diff --git a/.gitignore b/.gitignore index a8b0d1d..79f577e 100644 --- a/.gitignore +++ b/.gitignore @@ -1,35 +1,13 @@ -# ---> Android -# Gradle files -.gradle/ -build/ - -# Local configuration file (sdk path, etc) -local.properties - -# Log/OS Files -*.log - -# Android Studio generated files and folders -captures/ -.externalNativeBuild/ -.cxx/ -*.apk -output.json - -# IntelliJ *.iml -.idea/ -misc.xml -deploymentTargetDropDown.xml -render.experimental.xml - -# Keystore files -*.jks -*.keystore - -# Google Services (e.g. APIs or Firebase) -google-services.json - -# Android Profiling -*.hprof - +.gradle +/local.properties +/.idea/workspace.xml +/.idea/libraries +.DS_Store +/build +/captures +/app/build +/app/release +.externalNativeBuild +*.apk +*.apk diff --git a/.idea/.gitignore b/.idea/.gitignore new file mode 100644 index 0000000..26d3352 --- /dev/null +++ b/.idea/.gitignore @@ -0,0 +1,3 @@ +# Default ignored files +/shelf/ +/workspace.xml diff --git a/.idea/appInsightsSettings.xml b/.idea/appInsightsSettings.xml new file mode 100644 index 0000000..a8a3787 --- /dev/null +++ b/.idea/appInsightsSettings.xml @@ -0,0 +1,28 @@ + + + + + + \ No newline at end of file diff --git a/.idea/assetWizardSettings.xml b/.idea/assetWizardSettings.xml new file mode 100644 index 0000000..b941df0 --- /dev/null +++ b/.idea/assetWizardSettings.xml @@ -0,0 +1,32 @@ + + + + + + \ No newline at end of file diff --git a/.idea/compiler.xml b/.idea/compiler.xml new file mode 100644 index 0000000..fb7f4a8 --- /dev/null +++ b/.idea/compiler.xml @@ -0,0 +1,6 @@ + + + + + + \ No newline at end of file diff --git a/.idea/deploymentTargetDropDown.xml b/.idea/deploymentTargetDropDown.xml new file mode 100644 index 0000000..0c0c338 --- /dev/null +++ b/.idea/deploymentTargetDropDown.xml @@ -0,0 +1,10 @@ + + + + + + + + + + \ No newline at end of file diff --git a/.idea/gradle.xml b/.idea/gradle.xml new file mode 100644 index 0000000..59b02ee --- /dev/null +++ b/.idea/gradle.xml @@ -0,0 +1,20 @@ + + + + + + + \ No newline at end of file diff --git a/.idea/jarRepositories.xml b/.idea/jarRepositories.xml new file mode 100644 index 0000000..e34606c --- /dev/null +++ b/.idea/jarRepositories.xml @@ -0,0 +1,30 @@ + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/.idea/kotlinc.xml b/.idea/kotlinc.xml new file mode 100644 index 0000000..9b02d59 --- /dev/null +++ b/.idea/kotlinc.xml @@ -0,0 +1,6 @@ + + + + + \ No newline at end of file diff --git a/.idea/migrations.xml b/.idea/migrations.xml new file mode 100644 index 0000000..f8051a6 --- /dev/null +++ b/.idea/migrations.xml @@ -0,0 +1,10 @@ + + + + + + \ No newline at end of file diff --git a/.idea/misc.xml b/.idea/misc.xml new file mode 100644 index 0000000..68ad27d --- /dev/null +++ b/.idea/misc.xml @@ -0,0 +1,12 @@ + + + + + + + + + + + \ No newline at end of file diff --git a/.idea/modules.xml b/.idea/modules.xml new file mode 100644 index 0000000..233f6c6 --- /dev/null +++ b/.idea/modules.xml @@ -0,0 +1,12 @@ + + + + + + + + + + + + \ No newline at end of file diff --git a/.idea/vcs.xml b/.idea/vcs.xml new file mode 100644 index 0000000..35eb1dd --- /dev/null +++ b/.idea/vcs.xml @@ -0,0 +1,6 @@ + + + + + + \ No newline at end of file diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..94a9ed0 --- /dev/null +++ b/LICENSE @@ -0,0 +1,674 @@ + GNU GENERAL PUBLIC LICENSE + Version 3, 29 June 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 General Public License is a free, copyleft license for +software and other kinds of works. + + The licenses for most software and other practical works are designed +to take away your freedom to share and change the works. By contrast, +the GNU General Public License is intended to guarantee your freedom to +share and change all versions of a program--to make sure it remains free +software for all its users. We, the Free Software Foundation, use the +GNU General Public License for most of our software; it applies also to +any other work released this way by its authors. You can apply it to +your programs, too. + + When we speak of free software, we are referring to freedom, not +price. Our General Public Licenses are designed to make sure that you +have the freedom to distribute copies of free software (and charge for +them if you wish), that you receive source code or can get it if you +want it, that you can change the software or use pieces of it in new +free programs, and that you know you can do these things. + + To protect your rights, we need to prevent others from denying you +these rights or asking you to surrender the rights. Therefore, you have +certain responsibilities if you distribute copies of the software, or if +you modify it: responsibilities to respect the freedom of others. + + For example, if you distribute copies of such a program, whether +gratis or for a fee, you must pass on to the recipients the same +freedoms that you received. You must make sure that they, too, receive +or can get the source code. And you must show them these terms so they +know their rights. + + Developers that use the GNU GPL protect your rights with two steps: +(1) assert copyright on the software, and (2) offer you this License +giving you legal permission to copy, distribute and/or modify it. + + For the developers' and authors' protection, the GPL clearly explains +that there is no warranty for this free software. For both users' and +authors' sake, the GPL requires that modified versions be marked as +changed, so that their problems will not be attributed erroneously to +authors of previous versions. + + Some devices are designed to deny users access to install or run +modified versions of the software inside them, although the manufacturer +can do so. This is fundamentally incompatible with the aim of +protecting users' freedom to change the software. The systematic +pattern of such abuse occurs in the area of products for individuals to +use, which is precisely where it is most unacceptable. Therefore, we +have designed this version of the GPL to prohibit the practice for those +products. If such problems arise substantially in other domains, we +stand ready to extend this provision to those domains in future versions +of the GPL, as needed to protect the freedom of users. + + Finally, every program is threatened constantly by software patents. +States should not allow patents to restrict development and use of +software on general-purpose computers, but in those that do, we wish to +avoid the special danger that patents applied to a free program could +make it effectively proprietary. To prevent this, the GPL assures that +patents cannot be used to render the program non-free. + + The precise terms and conditions for copying, distribution and +modification follow. + + TERMS AND CONDITIONS + + 0. Definitions. + + "This License" refers to version 3 of the GNU General Public License. + + "Copyright" also means copyright-like laws that apply to other kinds of +works, such as semiconductor masks. + + "The Program" refers to any copyrightable work licensed under this +License. Each licensee is addressed as "you". "Licensees" and +"recipients" may be individuals or organizations. + + To "modify" a work means to copy from or adapt all or part of the work +in a fashion requiring copyright permission, other than the making of an +exact copy. The resulting work is called a "modified version" of the +earlier work or a work "based on" the earlier work. + + A "covered work" means either the unmodified Program or a work based +on the Program. + + To "propagate" a work means to do anything with it that, without +permission, would make you directly or secondarily liable for +infringement under applicable copyright law, except executing it on a +computer or modifying a private copy. Propagation includes copying, +distribution (with or without modification), making available to the +public, and in some countries other activities as well. + + To "convey" a work means any kind of propagation that enables other +parties to make or receive copies. Mere interaction with a user through +a computer network, with no transfer of a copy, is not conveying. + + An interactive user interface displays "Appropriate Legal Notices" +to the extent that it includes a convenient and prominently visible +feature that (1) displays an appropriate copyright notice, and (2) +tells the user that there is no warranty for the work (except to the +extent that warranties are provided), that licensees may convey the +work under this License, and how to view a copy of this License. If +the interface presents a list of user commands or options, such as a +menu, a prominent item in the list meets this criterion. + + 1. Source Code. + + The "source code" for a work means the preferred form of the work +for making modifications to it. "Object code" means any non-source +form of a work. + + A "Standard Interface" means an interface that either is an official +standard defined by a recognized standards body, or, in the case of +interfaces specified for a particular programming language, one that +is widely used among developers working in that language. + + The "System Libraries" of an executable work include anything, other +than the work as a whole, that (a) is included in the normal form of +packaging a Major Component, but which is not part of that Major +Component, and (b) serves only to enable use of the work with that +Major Component, or to implement a Standard Interface for which an +implementation is available to the public in source code form. A +"Major Component", in this context, means a major essential component +(kernel, window system, and so on) of the specific operating system +(if any) on which the executable work runs, or a compiler used to +produce the work, or an object code interpreter used to run it. + + The "Corresponding Source" for a work in object code form means all +the source code needed to generate, install, and (for an executable +work) run the object code and to modify the work, including scripts to +control those activities. However, it does not include the work's +System Libraries, or general-purpose tools or generally available free +programs which are used unmodified in performing those activities but +which are not part of the work. For example, Corresponding Source +includes interface definition files associated with source files for +the work, and the source code for shared libraries and dynamically +linked subprograms that the work is specifically designed to require, +such as by intimate data communication or control flow between those +subprograms and other parts of the work. + + The Corresponding Source need not include anything that users +can regenerate automatically from other parts of the Corresponding +Source. + + The Corresponding Source for a work in source code form is that +same work. + + 2. Basic Permissions. + + All rights granted under this License are granted for the term of +copyright on the Program, and are irrevocable provided the stated +conditions are met. This License explicitly affirms your unlimited +permission to run the unmodified Program. The output from running a +covered work is covered by this License only if the output, given its +content, constitutes a covered work. This License acknowledges your +rights of fair use or other equivalent, as provided by copyright law. + + You may make, run and propagate covered works that you do not +convey, without conditions so long as your license otherwise remains +in force. You may convey covered works to others for the sole purpose +of having them make modifications exclusively for you, or provide you +with facilities for running those works, provided that you comply with +the terms of this License in conveying all material for which you do +not control copyright. Those thus making or running the covered works +for you must do so exclusively on your behalf, under your direction +and control, on terms that prohibit them from making any copies of +your copyrighted material outside their relationship with you. + + Conveying under any other circumstances is permitted solely under +the conditions stated below. Sublicensing is not allowed; section 10 +makes it unnecessary. + + 3. Protecting Users' Legal Rights From Anti-Circumvention Law. + + No covered work shall be deemed part of an effective technological +measure under any applicable law fulfilling obligations under article +11 of the WIPO copyright treaty adopted on 20 December 1996, or +similar laws prohibiting or restricting circumvention of such +measures. + + When you convey a covered work, you waive any legal power to forbid +circumvention of technological measures to the extent such circumvention +is effected by exercising rights under this License with respect to +the covered work, and you disclaim any intention to limit operation or +modification of the work as a means of enforcing, against the work's +users, your or third parties' legal rights to forbid circumvention of +technological measures. + + 4. Conveying Verbatim Copies. + + You may convey verbatim copies of the Program's source code as you +receive it, in any medium, provided that you conspicuously and +appropriately publish on each copy an appropriate copyright notice; +keep intact all notices stating that this License and any +non-permissive terms added in accord with section 7 apply to the code; +keep intact all notices of the absence of any warranty; and give all +recipients a copy of this License along with the Program. + + You may charge any price or no price for each copy that you convey, +and you may offer support or warranty protection for a fee. + + 5. Conveying Modified Source Versions. + + You may convey a work based on the Program, or the modifications to +produce it from the Program, in the form of source code under the +terms of section 4, provided that you also meet all of these conditions: + + a) The work must carry prominent notices stating that you modified + it, and giving a relevant date. + + b) The work must carry prominent notices stating that it is + released under this License and any conditions added under section + 7. This requirement modifies the requirement in section 4 to + "keep intact all notices". + + c) You must license the entire work, as a whole, under this + License to anyone who comes into possession of a copy. This + License will therefore apply, along with any applicable section 7 + additional terms, to the whole of the work, and all its parts, + regardless of how they are packaged. This License gives no + permission to license the work in any other way, but it does not + invalidate such permission if you have separately received it. + + d) If the work has interactive user interfaces, each must display + Appropriate Legal Notices; however, if the Program has interactive + interfaces that do not display Appropriate Legal Notices, your + work need not make them do so. + + A compilation of a covered work with other separate and independent +works, which are not by their nature extensions of the covered work, +and which are not combined with it such as to form a larger program, +in or on a volume of a storage or distribution medium, is called an +"aggregate" if the compilation and its resulting copyright are not +used to limit the access or legal rights of the compilation's users +beyond what the individual works permit. Inclusion of a covered work +in an aggregate does not cause this License to apply to the other +parts of the aggregate. + + 6. Conveying Non-Source Forms. + + You may convey a covered work in object code form under the terms +of sections 4 and 5, provided that you also convey the +machine-readable Corresponding Source under the terms of this License, +in one of these ways: + + a) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by the + Corresponding Source fixed on a durable physical medium + customarily used for software interchange. + + b) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by a + written offer, valid for at least three years and valid for as + long as you offer spare parts or customer support for that product + model, to give anyone who possesses the object code either (1) a + copy of the Corresponding Source for all the software in the + product that is covered by this License, on a durable physical + medium customarily used for software interchange, for a price no + more than your reasonable cost of physically performing this + conveying of source, or (2) access to copy the + Corresponding Source from a network server at no charge. + + c) Convey individual copies of the object code with a copy of the + written offer to provide the Corresponding Source. This + alternative is allowed only occasionally and noncommercially, and + only if you received the object code with such an offer, in accord + with subsection 6b. + + d) Convey the object code by offering access from a designated + place (gratis or for a charge), and offer equivalent access to the + Corresponding Source in the same way through the same place at no + further charge. You need not require recipients to copy the + Corresponding Source along with the object code. If the place to + copy the object code is a network server, the Corresponding Source + may be on a different server (operated by you or a third party) + that supports equivalent copying facilities, provided you maintain + clear directions next to the object code saying where to find the + Corresponding Source. Regardless of what server hosts the + Corresponding Source, you remain obligated to ensure that it is + available for as long as needed to satisfy these requirements. + + e) Convey the object code using peer-to-peer transmission, provided + you inform other peers where the object code and Corresponding + Source of the work are being offered to the general public at no + charge under subsection 6d. + + A separable portion of the object code, whose source code is excluded +from the Corresponding Source as a System Library, need not be +included in conveying the object code work. + + A "User Product" is either (1) a "consumer product", which means any +tangible personal property which is normally used for personal, family, +or household purposes, or (2) anything designed or sold for incorporation +into a dwelling. In determining whether a product is a consumer product, +doubtful cases shall be resolved in favor of coverage. For a particular +product received by a particular user, "normally used" refers to a +typical or common use of that class of product, regardless of the status +of the particular user or of the way in which the particular user +actually uses, or expects or is expected to use, the product. A product +is a consumer product regardless of whether the product has substantial +commercial, industrial or non-consumer uses, unless such uses represent +the only significant mode of use of the product. + + "Installation Information" for a User Product means any methods, +procedures, authorization keys, or other information required to install +and execute modified versions of a covered work in that User Product from +a modified version of its Corresponding Source. The information must +suffice to ensure that the continued functioning of the modified object +code is in no case prevented or interfered with solely because +modification has been made. + + If you convey an object code work under this section in, or with, or +specifically for use in, a User Product, and the conveying occurs as +part of a transaction in which the right of possession and use of the +User Product is transferred to the recipient in perpetuity or for a +fixed term (regardless of how the transaction is characterized), the +Corresponding Source conveyed under this section must be accompanied +by the Installation Information. But this requirement does not apply +if neither you nor any third party retains the ability to install +modified object code on the User Product (for example, the work has +been installed in ROM). + + The requirement to provide Installation Information does not include a +requirement to continue to provide support service, warranty, or updates +for a work that has been modified or installed by the recipient, or for +the User Product in which it has been modified or installed. Access to a +network may be denied when the modification itself materially and +adversely affects the operation of the network or violates the rules and +protocols for communication across the network. + + Corresponding Source conveyed, and Installation Information provided, +in accord with this section must be in a format that is publicly +documented (and with an implementation available to the public in +source code form), and must require no special password or key for +unpacking, reading or copying. + + 7. Additional Terms. + + "Additional permissions" are terms that supplement the terms of this +License by making exceptions from one or more of its conditions. +Additional permissions that are applicable to the entire Program shall +be treated as though they were included in this License, to the extent +that they are valid under applicable law. If additional permissions +apply only to part of the Program, that part may be used separately +under those permissions, but the entire Program remains governed by +this License without regard to the additional permissions. + + When you convey a copy of a covered work, you may at your option +remove any additional permissions from that copy, or from any part of +it. (Additional permissions may be written to require their own +removal in certain cases when you modify the work.) You may place +additional permissions on material, added by you to a covered work, +for which you have or can give appropriate copyright permission. + + Notwithstanding any other provision of this License, for material you +add to a covered work, you may (if authorized by the copyright holders of +that material) supplement the terms of this License with terms: + + a) Disclaiming warranty or limiting liability differently from the + terms of sections 15 and 16 of this License; or + + b) Requiring preservation of specified reasonable legal notices or + author attributions in that material or in the Appropriate Legal + Notices displayed by works containing it; or + + c) Prohibiting misrepresentation of the origin of that material, or + requiring that modified versions of such material be marked in + reasonable ways as different from the original version; or + + d) Limiting the use for publicity purposes of names of licensors or + authors of the material; or + + e) Declining to grant rights under trademark law for use of some + trade names, trademarks, or service marks; or + + f) Requiring indemnification of licensors and authors of that + material by anyone who conveys the material (or modified versions of + it) with contractual assumptions of liability to the recipient, for + any liability that these contractual assumptions directly impose on + those licensors and authors. + + All other non-permissive additional terms are considered "further +restrictions" within the meaning of section 10. If the Program as you +received it, or any part of it, contains a notice stating that it is +governed by this License along with a term that is a further +restriction, you may remove that term. If a license document contains +a further restriction but permits relicensing or conveying under this +License, you may add to a covered work material governed by the terms +of that license document, provided that the further restriction does +not survive such relicensing or conveying. + + If you add terms to a covered work in accord with this section, you +must place, in the relevant source files, a statement of the +additional terms that apply to those files, or a notice indicating +where to find the applicable terms. + + Additional terms, permissive or non-permissive, may be stated in the +form of a separately written license, or stated as exceptions; +the above requirements apply either way. + + 8. Termination. + + You may not propagate or modify a covered work except as expressly +provided under this License. Any attempt otherwise to propagate or +modify it is void, and will automatically terminate your rights under +this License (including any patent licenses granted under the third +paragraph of section 11). + + However, if you cease all violation of this License, then your +license from a particular copyright holder is reinstated (a) +provisionally, unless and until the copyright holder explicitly and +finally terminates your license, and (b) permanently, if the copyright +holder fails to notify you of the violation by some reasonable means +prior to 60 days after the cessation. + + Moreover, your license from a particular copyright holder is +reinstated permanently if the copyright holder notifies you of the +violation by some reasonable means, this is the first time you have +received notice of violation of this License (for any work) from that +copyright holder, and you cure the violation prior to 30 days after +your receipt of the notice. + + Termination of your rights under this section does not terminate the +licenses of parties who have received copies or rights from you under +this License. If your rights have been terminated and not permanently +reinstated, you do not qualify to receive new licenses for the same +material under section 10. + + 9. Acceptance Not Required for Having Copies. + + You are not required to accept this License in order to receive or +run a copy of the Program. Ancillary propagation of a covered work +occurring solely as a consequence of using peer-to-peer transmission +to receive a copy likewise does not require acceptance. However, +nothing other than this License grants you permission to propagate or +modify any covered work. These actions infringe copyright if you do +not accept this License. Therefore, by modifying or propagating a +covered work, you indicate your acceptance of this License to do so. + + 10. Automatic Licensing of Downstream Recipients. + + Each time you convey a covered work, the recipient automatically +receives a license from the original licensors, to run, modify and +propagate that work, subject to this License. You are not responsible +for enforcing compliance by third parties with this License. + + An "entity transaction" is a transaction transferring control of an +organization, or substantially all assets of one, or subdividing an +organization, or merging organizations. If propagation of a covered +work results from an entity transaction, each party to that +transaction who receives a copy of the work also receives whatever +licenses to the work the party's predecessor in interest had or could +give under the previous paragraph, plus a right to possession of the +Corresponding Source of the work from the predecessor in interest, if +the predecessor has it or can get it with reasonable efforts. + + You may not impose any further restrictions on the exercise of the +rights granted or affirmed under this License. For example, you may +not impose a license fee, royalty, or other charge for exercise of +rights granted under this License, and you may not initiate litigation +(including a cross-claim or counterclaim in a lawsuit) alleging that +any patent claim is infringed by making, using, selling, offering for +sale, or importing the Program or any portion of it. + + 11. Patents. + + A "contributor" is a copyright holder who authorizes use under this +License of the Program or a work on which the Program is based. The +work thus licensed is called the contributor's "contributor version". + + A contributor's "essential patent claims" are all patent claims +owned or controlled by the contributor, whether already acquired or +hereafter acquired, that would be infringed by some manner, permitted +by this License, of making, using, or selling its contributor version, +but do not include claims that would be infringed only as a +consequence of further modification of the contributor version. For +purposes of this definition, "control" includes the right to grant +patent sublicenses in a manner consistent with the requirements of +this License. + + Each contributor grants you a non-exclusive, worldwide, royalty-free +patent license under the contributor's essential patent claims, to +make, use, sell, offer for sale, import and otherwise run, modify and +propagate the contents of its contributor version. + + In the following three paragraphs, a "patent license" is any express +agreement or commitment, however denominated, not to enforce a patent +(such as an express permission to practice a patent or covenant not to +sue for patent infringement). To "grant" such a patent license to a +party means to make such an agreement or commitment not to enforce a +patent against the party. + + If you convey a covered work, knowingly relying on a patent license, +and the Corresponding Source of the work is not available for anyone +to copy, free of charge and under the terms of this License, through a +publicly available network server or other readily accessible means, +then you must either (1) cause the Corresponding Source to be so +available, or (2) arrange to deprive yourself of the benefit of the +patent license for this particular work, or (3) arrange, in a manner +consistent with the requirements of this License, to extend the patent +license to downstream recipients. "Knowingly relying" means you have +actual knowledge that, but for the patent license, your conveying the +covered work in a country, or your recipient's use of the covered work +in a country, would infringe one or more identifiable patents in that +country that you have reason to believe are valid. + + If, pursuant to or in connection with a single transaction or +arrangement, you convey, or propagate by procuring conveyance of, a +covered work, and grant a patent license to some of the parties +receiving the covered work authorizing them to use, propagate, modify +or convey a specific copy of the covered work, then the patent license +you grant is automatically extended to all recipients of the covered +work and works based on it. + + A patent license is "discriminatory" if it does not include within +the scope of its coverage, prohibits the exercise of, or is +conditioned on the non-exercise of one or more of the rights that are +specifically granted under this License. You may not convey a covered +work if you are a party to an arrangement with a third party that is +in the business of distributing software, under which you make payment +to the third party based on the extent of your activity of conveying +the work, and under which the third party grants, to any of the +parties who would receive the covered work from you, a discriminatory +patent license (a) in connection with copies of the covered work +conveyed by you (or copies made from those copies), or (b) primarily +for and in connection with specific products or compilations that +contain the covered work, unless you entered into that arrangement, +or that patent license was granted, prior to 28 March 2007. + + Nothing in this License shall be construed as excluding or limiting +any implied license or other defenses to infringement that may +otherwise be available to you under applicable patent law. + + 12. No Surrender of Others' Freedom. + + If conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot convey a +covered work so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you may +not convey it at all. For example, if you agree to terms that obligate you +to collect a royalty for further conveying from those to whom you convey +the Program, the only way you could satisfy both those terms and this +License would be to refrain entirely from conveying the Program. + + 13. Use with the GNU Affero General Public License. + + Notwithstanding any other provision of this License, you have +permission to link or combine any covered work with a work licensed +under version 3 of the GNU Affero General Public License into a single +combined work, and to convey the resulting work. The terms of this +License will continue to apply to the part which is the covered work, +but the special requirements of the GNU Affero General Public License, +section 13, concerning interaction through a network will apply to the +combination as such. + + 14. Revised Versions of this License. + + The Free Software Foundation may publish revised and/or new versions of +the GNU General Public License from time to time. Such new versions will +be similar in spirit to the present version, but may differ in detail to +address new problems or concerns. + + Each version is given a distinguishing version number. If the +Program specifies that a certain numbered version of the GNU General +Public License "or any later version" applies to it, you have the +option of following the terms and conditions either of that numbered +version or of any later version published by the Free Software +Foundation. If the Program does not specify a version number of the +GNU General Public License, you may choose any version ever published +by the Free Software Foundation. + + If the Program specifies that a proxy can decide which future +versions of the GNU General Public License can be used, that proxy's +public statement of acceptance of a version permanently authorizes you +to choose that version for the Program. + + Later license versions may give you additional or different +permissions. However, no additional obligations are imposed on any +author or copyright holder as a result of your choosing to follow a +later version. + + 15. Disclaimer of Warranty. + + THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY +APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT +HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY +OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, +THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM +IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF +ALL NECESSARY SERVICING, REPAIR OR CORRECTION. + + 16. Limitation of Liability. + + IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING +WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS +THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY +GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE +USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF +DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD +PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), +EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF +SUCH DAMAGES. + + 17. Interpretation of Sections 15 and 16. + + If the disclaimer of warranty and limitation of liability provided +above cannot be given local legal effect according to their terms, +reviewing courts shall apply local law that most closely approximates +an absolute waiver of all civil liability in connection with the +Program, unless a warranty or assumption of liability accompanies a +copy of the Program in return for a fee. + + END OF TERMS AND CONDITIONS + + How to Apply These Terms to Your New Programs + + If you develop a new program, and you want it to be of the greatest +possible use to the public, the best way to achieve this is to make it +free software which everyone can redistribute and change under these terms. + + To do so, attach the following notices to the program. It is safest +to attach them to the start of each source file to most effectively +state the exclusion of warranty; and each file should have at least +the "copyright" line and a pointer to where the full notice is found. + + + Copyright (C) + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see . + +Also add information on how to contact you by electronic and paper mail. + + If the program does terminal interaction, make it output a short +notice like this when it starts in an interactive mode: + + Copyright (C) + This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. + This is free software, and you are welcome to redistribute it + under certain conditions; type `show c' for details. + +The hypothetical commands `show w' and `show c' should show the appropriate +parts of the General Public License. Of course, your program's commands +might be different; for a GUI interface, you would use an "about box". + + You should also get your employer (if you work as a programmer) or school, +if any, to sign a "copyright disclaimer" for the program, if necessary. +For more information on this, and how to apply and follow the GNU GPL, see +. + + The GNU General Public License does not permit incorporating your program +into proprietary programs. If your program is a subroutine library, you +may consider it more useful to permit linking proprietary applications with +the library. If this is what you want to do, use the GNU Lesser General +Public License instead of this License. But first, please read +. diff --git a/README.md b/README.md index 3790599..f5dbb3a 100644 --- a/README.md +++ b/README.md @@ -1,3 +1,21 @@ -# bachotbakwan +# bachot +backone Chat system -Secure Call \ No newline at end of file +Backchat all channel +True P2P voice- and video phone calls without the need for accounts or access to the Internet. There is no discovery mechanism, no meshing and no servers. Just scan each others QR-Code that will contain the contacts IP address. This works in many local networks such as community mesh networks, company networks or at home. + +Features: + +- voice and video calls +- accounts or registration activated via backone network +- encrypted communication +- database backup and encryption +- add custom addresses to reach contacts + +Limitations: + +- no calls after MAC / IP address change + +## Documentation + +Connects to IP addresses in a true P2P fashion. Contacts are shared via QR-Code. They contain a name, a public key and a list of MAC/IPv4/IPv6 addresses or domain names. By default, only a single MAC address is transferred and used to create an IPv6 link local address (among others) to establish a connection. This does not even need a DHCP server. The exchanged public key is used to authenticate/encrypt signaling data to establish a [WebRTC](https://webrtc.org/) session that can transmit voice and video. diff --git a/app/.gitignore b/app/.gitignore new file mode 100644 index 0000000..796b96d --- /dev/null +++ b/app/.gitignore @@ -0,0 +1 @@ +/build diff --git a/app/build.gradle b/app/build.gradle new file mode 100644 index 0000000..3faa085 --- /dev/null +++ b/app/build.gradle @@ -0,0 +1,106 @@ +apply plugin: 'com.android.application' + +// Canonical version literals — bumped in-place on assemble/bundle/install. +def versionCodeValue = 325 +def versionNameValue = '0.3.1.15' + +ext.bumpAppVersion = { boolean persist -> + def buildGradle = file("build.gradle") + def text = buildGradle.text + + def codeMatcher = text =~ /def versionCodeValue\s*=\s*(\d+)/ + if (!codeMatcher.find()) { + throw new GradleException("Could not find versionCodeValue in ${buildGradle}") + } + def oldCode = codeMatcher.group(1) as int + def newCode = oldCode + 1 + + def nameMatcher = text =~ /def versionNameValue\s*=\s*'([^']+)'/ + if (!nameMatcher.find()) { + throw new GradleException("Could not find versionNameValue in ${buildGradle}") + } + def oldName = nameMatcher.group(1) + def parts = oldName.tokenize('.') + if (parts.isEmpty()) { + throw new GradleException("versionName '${oldName}' has no segments to bump") + } + parts[-1] = ((parts[-1] as int) + 1).toString() + def newName = parts.join('.') + + if (persist) { + text = text.replaceFirst(/def versionCodeValue\s*=\s*\d+/, "def versionCodeValue = ${newCode}") + text = text.replaceFirst(/def versionNameValue\s*=\s*'[^']+'/, "def versionNameValue = '${newName}'") + buildGradle.text = text + println "Bumped version: ${oldCode} / ${oldName} -> ${newCode} / ${newName}" + return [code: newCode, name: newName] + } + + return [code: oldCode, name: oldName] +} + +// Bump before AGP reads defaultConfig so this build's APK gets the new version. +def requestedTasks = gradle.startParameter.taskNames.collect { it.toLowerCase() } +def shouldBumpOnBuild = requestedTasks.any { name -> + def leaf = name.contains(':') ? name.substring(name.lastIndexOf(':') + 1) : name + leaf.startsWith('assemble') || leaf.startsWith('bundle') || leaf.startsWith('install') +} +if (shouldBumpOnBuild) { + def bumped = bumpAppVersion(true) + versionCodeValue = bumped.code + versionNameValue = bumped.name +} + +android { + signingConfigs { + } + compileSdkVersion 34 + + defaultConfig { + applicationId "backone.cloud.call" + minSdk 26 + targetSdk 34 + versionCode versionCodeValue + versionName versionNameValue + multiDexEnabled true + testInstrumentationRunner 'androidx.test.runner.AndroidJUnitRunner' + vectorDrawables.useSupportLibrary = true + setProperty("archivesBaseName", project.getParent().name+"-"+versionName) + } + buildTypes { + release { + minifyEnabled true + shrinkResources true + proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro' + } + } + compileOptions { + sourceCompatibility JavaVersion.VERSION_11 + targetCompatibility JavaVersion.VERSION_11 + } +} + +dependencies { + implementation project(':backone') + implementation fileTree(include: ['*.jar'], dir: 'libs') + implementation 'androidx.constraintlayout:constraintlayout:2.1.4' + implementation 'com.google.android.material:material:1.6.0' + implementation 'androidx.multidex:multidex:2.0.1' + implementation 'org.greenrobot:eventbus:3.3.1' + testImplementation 'junit:junit:4.13.1' + androidTestImplementation 'androidx.test.ext:junit:1.1.5' + androidTestImplementation 'androidx.test.espresso:espresso-core:3.5.1' + implementation('com.journeyapps:zxing-android-embedded:3.6.0') { transitive = false } + //back to 3.3.0 instead of 3.4.0 sue to https://github.com/zxing/zxing/issues/1170 + implementation 'com.google.zxing:core:3.3.0' + implementation 'io.github.webrtc-sdk:android:125.6422.06.1' + implementation 'com.github.joshjdevl.libsodiumjni:libsodium-jni-aar:2.0.2' + implementation 'androidx.swiperefreshlayout:swiperefreshlayout:1.1.0' +} + +tasks.register("bumpVersion") { + description = "Increment versionCode and last segment of versionName" + group = "versioning" + doLast { + bumpAppVersion(true) + } +} diff --git a/app/proguard-rules.pro b/app/proguard-rules.pro new file mode 100644 index 0000000..0fb6b0e --- /dev/null +++ b/app/proguard-rules.pro @@ -0,0 +1,24 @@ +# WebRTC JNI +-keep class org.webrtc.** { *; } +-dontwarn org.webrtc.** + +# libsodium JNI +-keep class org.libsodium.jni.** { *; } +-dontwarn org.libsodium.jni.** +-keepclasseswithmembernames class * { + native ; +} + +# ZeroTier / BackOne +-keep class com.zerotier.** { *; } +-keep class cloud.backone.** { *; } +-dontwarn com.zerotier.** + +# EventBus +-keepattributes *Annotation* +-keepclassmembers class * { + @org.greenrobot.eventbus.Subscribe ; +} +-keep enum org.greenrobot.eventbus.ThreadMode { *; } + +-keepattributes SourceFile,LineNumberTable diff --git a/app/src/androidTest/java/backone/cloud/call/ExampleInstrumentedTest.java b/app/src/androidTest/java/backone/cloud/call/ExampleInstrumentedTest.java new file mode 100644 index 0000000..19e7da9 --- /dev/null +++ b/app/src/androidTest/java/backone/cloud/call/ExampleInstrumentedTest.java @@ -0,0 +1,26 @@ +package backone.cloud.call; + +import android.content.Context; +import androidx.test.platform.app.InstrumentationRegistry; +import androidx.test.ext.junit.runners.AndroidJUnit4; + +import org.junit.Test; +import org.junit.runner.RunWith; + +import static org.junit.Assert.*; + +/** + * Instrumented test, which will execute on an Android device. + * + * @see Testing documentation + */ +@RunWith(AndroidJUnit4.class) +public class ExampleInstrumentedTest { + @Test + public void useAppContext() { + // Context of the app under test. + Context appContext = InstrumentationRegistry.getInstrumentation().getContext(); + + assertEquals("backone.cloud.call", appContext.getPackageName()); + } +} diff --git a/app/src/main/AndroidManifest.xml b/app/src/main/AndroidManifest.xml new file mode 100644 index 0000000..72295e6 --- /dev/null +++ b/app/src/main/AndroidManifest.xml @@ -0,0 +1,82 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/app/src/main/assets/20cent.ttf b/app/src/main/assets/20cent.ttf new file mode 100644 index 0000000..26130cb Binary files /dev/null and b/app/src/main/assets/20cent.ttf differ diff --git a/app/src/main/assets/license.txt b/app/src/main/assets/license.txt new file mode 100644 index 0000000..eb893ad --- /dev/null +++ b/app/src/main/assets/license.txt @@ -0,0 +1,674 @@ + GNU GENERAL PUBLIC LICENSE + Version 3, 29 June 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 General Public License is a free, copyleft license for +software and other kinds of works. + + The licenses for most software and other practical works are designed +to take away your freedom to share and change the works. By contrast, +the GNU General Public License is intended to guarantee your freedom to +share and change all versions of a program--to make sure it remains free +software for all its users. We, the Free Software Foundation, use the +GNU General Public License for most of our software; it applies also to +any other work released this way by its authors. You can apply it to +your programs, too. + + When we speak of free software, we are referring to freedom, not +price. Our General Public Licenses are designed to make sure that you +have the freedom to distribute copies of free software (and charge for +them if you wish), that you receive source code or can get it if you +want it, that you can change the software or use pieces of it in new +free programs, and that you know you can do these things. + + To protect your rights, we need to prevent others from denying you +these rights or asking you to surrender the rights. Therefore, you have +certain responsibilities if you distribute copies of the software, or if +you modify it: responsibilities to respect the freedom of others. + + For example, if you distribute copies of such a program, whether +gratis or for a fee, you must pass on to the recipients the same +freedoms that you received. You must make sure that they, too, receive +or can get the source code. And you must show them these terms so they +know their rights. + + Developers that use the GNU GPL protect your rights with two steps: +(1) assert copyright on the software, and (2) offer you this License +giving you legal permission to copy, distribute and/or modify it. + + For the developers' and authors' protection, the GPL clearly explains +that there is no warranty for this free software. For both users' and +authors' sake, the GPL requires that modified versions be marked as +changed, so that their problems will not be attributed erroneously to +authors of previous versions. + + Some devices are designed to deny users access to install or run +modified versions of the software inside them, although the manufacturer +can do so. This is fundamentally incompatible with the aim of +protecting users' freedom to change the software. The systematic +pattern of such abuse occurs in the area of products for individuals to +use, which is precisely where it is most unacceptable. Therefore, we +have designed this version of the GPL to prohibit the practice for those +products. If such problems arise substantially in other domains, we +stand ready to extend this provision to those domains in future versions +of the GPL, as needed to protect the freedom of users. + + Finally, every program is threatened constantly by software patents. +States should not allow patents to restrict development and use of +software on general-purpose computers, but in those that do, we wish to +avoid the special danger that patents applied to a free program could +make it effectively proprietary. To prevent this, the GPL assures that +patents cannot be used to render the program non-free. + + The precise terms and conditions for copying, distribution and +modification follow. + + TERMS AND CONDITIONS + + 0. Definitions. + + "This License" refers to version 3 of the GNU General Public License. + + "Copyright" also means copyright-like laws that apply to other kinds of +works, such as semiconductor masks. + + "The Program" refers to any copyrightable work licensed under this +License. Each licensee is addressed as "you". "Licensees" and +"recipients" may be individuals or organizations. + + To "modify" a work means to copy from or adapt all or part of the work +in a fashion requiring copyright permission, other than the making of an +exact copy. The resulting work is called a "modified version" of the +earlier work or a work "based on" the earlier work. + + A "covered work" means either the unmodified Program or a work based +on the Program. + + To "propagate" a work means to do anything with it that, without +permission, would make you directly or secondarily liable for +infringement under applicable copyright law, except executing it on a +computer or modifying a private copy. Propagation includes copying, +distribution (with or without modification), making available to the +public, and in some countries other activities as well. + + To "convey" a work means any kind of propagation that enables other +parties to make or receive copies. Mere interaction with a user through +a computer network, with no transfer of a copy, is not conveying. + + An interactive user interface displays "Appropriate Legal Notices" +to the extent that it includes a convenient and prominently visible +feature that (1) displays an appropriate copyright notice, and (2) +tells the user that there is no warranty for the work (except to the +extent that warranties are provided), that licensees may convey the +work under this License, and how to view a copy of this License. If +the interface presents a list of user commands or options, such as a +menu, a prominent item in the list meets this criterion. + + 1. Source Code. + + The "source code" for a work means the preferred form of the work +for making modifications to it. "Object code" means any non-source +form of a work. + + A "Standard Interface" means an interface that either is an official +standard defined by a recognized standards body, or, in the case of +interfaces specified for a particular programming language, one that +is widely used among developers working in that language. + + The "System Libraries" of an executable work include anything, other +than the work as a whole, that (a) is included in the normal form of +packaging a Major Component, but which is not part of that Major +Component, and (b) serves only to enable use of the work with that +Major Component, or to implement a Standard Interface for which an +implementation is available to the public in source code form. A +"Major Component", in this context, means a major essential component +(kernel, window system, and so on) of the specific operating system +(if any) on which the executable work runs, or a compiler used to +produce the work, or an object code interpreter used to run it. + + The "Corresponding Source" for a work in object code form means all +the source code needed to generate, install, and (for an executable +work) run the object code and to modify the work, including scripts to +control those activities. However, it does not include the work's +System Libraries, or general-purpose tools or generally available free +programs which are used unmodified in performing those activities but +which are not part of the work. For example, Corresponding Source +includes interface definition files associated with source files for +the work, and the source code for shared libraries and dynamically +linked subprograms that the work is specifically designed to require, +such as by intimate data communication or control flow between those +subprograms and other parts of the work. + + The Corresponding Source need not include anything that users +can regenerate automatically from other parts of the Corresponding +Source. + + The Corresponding Source for a work in source code form is that +same work. + + 2. Basic Permissions. + + All rights granted under this License are granted for the term of +copyright on the Program, and are irrevocable provided the stated +conditions are met. This License explicitly affirms your unlimited +permission to run the unmodified Program. The output from running a +covered work is covered by this License only if the output, given its +content, constitutes a covered work. This License acknowledges your +rights of fair use or other equivalent, as provided by copyright law. + + You may make, run and propagate covered works that you do not +convey, without conditions so long as your license otherwise remains +in force. You may convey covered works to others for the sole purpose +of having them make modifications exclusively for you, or provide you +with facilities for running those works, provided that you comply with +the terms of this License in conveying all material for which you do +not control copyright. Those thus making or running the covered works +for you must do so exclusively on your behalf, under your direction +and control, on terms that prohibit them from making any copies of +your copyrighted material outside their relationship with you. + + Conveying under any other circumstances is permitted solely under +the conditions stated below. Sublicensing is not allowed; section 10 +makes it unnecessary. + + 3. Protecting Users' Legal Rights From Anti-Circumvention Law. + + No covered work shall be deemed part of an effective technological +measure under any applicable law fulfilling obligations under article +11 of the WIPO copyright treaty adopted on 20 December 1996, or +similar laws prohibiting or restricting circumvention of such +measures. + + When you convey a covered work, you waive any legal power to forbid +circumvention of technological measures to the extent such circumvention +is effected by exercising rights under this License with respect to +the covered work, and you disclaim any intention to limit operation or +modification of the work as a means of enforcing, against the work's +users, your or third parties' legal rights to forbid circumvention of +technological measures. + + 4. Conveying Verbatim Copies. + + You may convey verbatim copies of the Program's source code as you +receive it, in any medium, provided that you conspicuously and +appropriately publish on each copy an appropriate copyright notice; +keep intact all notices stating that this License and any +non-permissive terms added in accord with section 7 apply to the code; +keep intact all notices of the absence of any warranty; and give all +recipients a copy of this License along with the Program. + + You may charge any price or no price for each copy that you convey, +and you may offer support or warranty protection for a fee. + + 5. Conveying Modified Source Versions. + + You may convey a work based on the Program, or the modifications to +produce it from the Program, in the form of source code under the +terms of section 4, provided that you also meet all of these conditions: + + a) The work must carry prominent notices stating that you modified + it, and giving a relevant date. + + b) The work must carry prominent notices stating that it is + released under this License and any conditions added under section + 7. This requirement modifies the requirement in section 4 to + "keep intact all notices". + + c) You must license the entire work, as a whole, under this + License to anyone who comes into possession of a copy. This + License will therefore apply, along with any applicable section 7 + additional terms, to the whole of the work, and all its parts, + regardless of how they are packaged. This License gives no + permission to license the work in any other way, but it does not + invalidate such permission if you have separately received it. + + d) If the work has interactive user interfaces, each must display + Appropriate Legal Notices; however, if the Program has interactive + interfaces that do not display Appropriate Legal Notices, your + work need not make them do so. + + A compilation of a covered work with other separate and independent +works, which are not by their nature extensions of the covered work, +and which are not combined with it such as to form a larger program, +in or on a volume of a storage or distribution medium, is called an +"aggregate" if the compilation and its resulting copyright are not +used to limit the access or legal rights of the compilation's users +beyond what the individual works permit. Inclusion of a covered work +in an aggregate does not cause this License to apply to the other +parts of the aggregate. + + 6. Conveying Non-Source Forms. + + You may convey a covered work in object code form under the terms +of sections 4 and 5, provided that you also convey the +machine-readable Corresponding Source under the terms of this License, +in one of these ways: + + a) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by the + Corresponding Source fixed on a durable physical medium + customarily used for software interchange. + + b) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by a + written offer, valid for at least three years and valid for as + long as you offer spare parts or customer support for that product + model, to give anyone who possesses the object code either (1) a + copy of the Corresponding Source for all the software in the + product that is covered by this License, on a durable physical + medium customarily used for software interchange, for a price no + more than your reasonable cost of physically performing this + conveying of source, or (2) access to copy the + Corresponding Source from a network server at no charge. + + c) Convey individual copies of the object code with a copy of the + written offer to provide the Corresponding Source. This + alternative is allowed only occasionally and noncommercially, and + only if you received the object code with such an offer, in accord + with subsection 6b. + + d) Convey the object code by offering access from a designated + place (gratis or for a charge), and offer equivalent access to the + Corresponding Source in the same way through the same place at no + further charge. You need not require recipients to copy the + Corresponding Source along with the object code. If the place to + copy the object code is a network server, the Corresponding Source + may be on a different server (operated by you or a third party) + that supports equivalent copying facilities, provided you maintain + clear directions next to the object code saying where to find the + Corresponding Source. Regardless of what server hosts the + Corresponding Source, you remain obligated to ensure that it is + available for as long as needed to satisfy these requirements. + + e) Convey the object code using peer-to-peer transmission, provided + you inform other peers where the object code and Corresponding + Source of the work are being offered to the general public at no + charge under subsection 6d. + + A separable portion of the object code, whose source code is excluded +from the Corresponding Source as a System Library, need not be +included in conveying the object code work. + + A "User Product" is either (1) a "consumer product", which means any +tangible personal property which is normally used for personal, family, +or household purposes, or (2) anything designed or sold for incorporation +into a dwelling. In determining whether a product is a consumer product, +doubtful cases shall be resolved in favor of coverage. For a particular +product received by a particular user, "normally used" refers to a +typical or common use of that class of product, regardless of the status +of the particular user or of the way in which the particular user +actually uses, or expects or is expected to use, the product. A product +is a consumer product regardless of whether the product has substantial +commercial, industrial or non-consumer uses, unless such uses represent +the only significant mode of use of the product. + + "Installation Information" for a User Product means any methods, +procedures, authorization keys, or other information required to install +and execute modified versions of a covered work in that User Product from +a modified version of its Corresponding Source. The information must +suffice to ensure that the continued functioning of the modified object +code is in no case prevented or interfered with solely because +modification has been made. + + If you convey an object code work under this section in, or with, or +specifically for use in, a User Product, and the conveying occurs as +part of a transaction in which the right of possession and use of the +User Product is transferred to the recipient in perpetuity or for a +fixed term (regardless of how the transaction is characterized), the +Corresponding Source conveyed under this section must be accompanied +by the Installation Information. But this requirement does not apply +if neither you nor any third party retains the ability to install +modified object code on the User Product (for example, the work has +been installed in ROM). + + The requirement to provide Installation Information does not include a +requirement to continue to provide support service, warranty, or updates +for a work that has been modified or installed by the recipient, or for +the User Product in which it has been modified or installed. Access to a +network may be denied when the modification itself materially and +adversely affects the operation of the network or violates the rules and +protocols for communication across the network. + + Corresponding Source conveyed, and Installation Information provided, +in accord with this section must be in a format that is publicly +documented (and with an implementation available to the public in +source code form), and must require no special password or key for +unpacking, reading or copying. + + 7. Additional Terms. + + "Additional permissions" are terms that supplement the terms of this +License by making exceptions from one or more of its conditions. +Additional permissions that are applicable to the entire Program shall +be treated as though they were included in this License, to the extent +that they are valid under applicable law. If additional permissions +apply only to part of the Program, that part may be used separately +under those permissions, but the entire Program remains governed by +this License without regard to the additional permissions. + + When you convey a copy of a covered work, you may at your option +remove any additional permissions from that copy, or from any part of +it. (Additional permissions may be written to require their own +removal in certain cases when you modify the work.) You may place +additional permissions on material, added by you to a covered work, +for which you have or can give appropriate copyright permission. + + Notwithstanding any other provision of this License, for material you +add to a covered work, you may (if authorized by the copyright holders of +that material) supplement the terms of this License with terms: + + a) Disclaiming warranty or limiting liability differently from the + terms of sections 15 and 16 of this License; or + + b) Requiring preservation of specified reasonable legal notices or + author attributions in that material or in the Appropriate Legal + Notices displayed by works containing it; or + + c) Prohibiting misrepresentation of the origin of that material, or + requiring that modified versions of such material be marked in + reasonable ways as different from the original version; or + + d) Limiting the use for publicity purposes of names of licensors or + authors of the material; or + + e) Declining to grant rights under trademark law for use of some + trade names, trademarks, or service marks; or + + f) Requiring indemnification of licensors and authors of that + material by anyone who conveys the material (or modified versions of + it) with contractual assumptions of liability to the recipient, for + any liability that these contractual assumptions directly impose on + those licensors and authors. + + All other non-permissive additional terms are considered "further +restrictions" within the meaning of section 10. If the Program as you +received it, or any part of it, contains a notice stating that it is +governed by this License along with a term that is a further +restriction, you may remove that term. If a license document contains +a further restriction but permits relicensing or conveying under this +License, you may add to a covered work material governed by the terms +of that license document, provided that the further restriction does +not survive such relicensing or conveying. + + If you add terms to a covered work in accord with this section, you +must place, in the relevant source files, a statement of the +additional terms that apply to those files, or a notice indicating +where to find the applicable terms. + + Additional terms, permissive or non-permissive, may be stated in the +form of a separately written license, or stated as exceptions; +the above requirements apply either way. + + 8. Termination. + + You may not propagate or modify a covered work except as expressly +provided under this License. Any attempt otherwise to propagate or +modify it is void, and will automatically terminate your rights under +this License (including any patent licenses granted under the third +paragraph of section 11). + + However, if you cease all violation of this License, then your +license from a particular copyright holder is reinstated (a) +provisionally, unless and until the copyright holder explicitly and +finally terminates your license, and (b) permanently, if the copyright +holder fails to notify you of the violation by some reasonable means +prior to 60 days after the cessation. + + Moreover, your license from a particular copyright holder is +reinstated permanently if the copyright holder notifies you of the +violation by some reasonable means, this is the first time you have +received notice of violation of this License (for any work) from that +copyright holder, and you cure the violation prior to 30 days after +your receipt of the notice. + + Termination of your rights under this section does not terminate the +licenses of parties who have received copies or rights from you under +this License. If your rights have been terminated and not permanently +reinstated, you do not qualify to receive new licenses for the same +material under section 10. + + 9. Acceptance Not Required for Having Copies. + + You are not required to accept this License in order to receive or +run a copy of the Program. Ancillary propagation of a covered work +occurring solely as a consequence of using peer-to-peer transmission +to receive a copy likewise does not require acceptance. However, +nothing other than this License grants you permission to propagate or +modify any covered work. These actions infringe copyright if you do +not accept this License. Therefore, by modifying or propagating a +covered work, you indicate your acceptance of this License to do so. + + 10. Automatic Licensing of Downstream Recipients. + + Each time you convey a covered work, the recipient automatically +receives a license from the original licensors, to run, modify and +propagate that work, subject to this License. You are not responsible +for enforcing compliance by third parties with this License. + + An "entity transaction" is a transaction transferring control of an +organization, or substantially all assets of one, or subdividing an +organization, or merging organizations. If propagation of a covered +work results from an entity transaction, each party to that +transaction who receives a copy of the work also receives whatever +licenses to the work the party's predecessor in interest had or could +give under the previous paragraph, plus a right to possession of the +Corresponding Source of the work from the predecessor in interest, if +the predecessor has it or can get it with reasonable efforts. + + You may not impose any further restrictions on the exercise of the +rights granted or affirmed under this License. For example, you may +not impose a license fee, royalty, or other charge for exercise of +rights granted under this License, and you may not initiate litigation +(including a cross-claim or counterclaim in a lawsuit) alleging that +any patent claim is infringed by making, using, selling, offering for +sale, or importing the Program or any portion of it. + + 11. Patents. + + A "contributor" is a copyright holder who authorizes use under this +License of the Program or a work on which the Program is based. The +work thus licensed is called the contributor's "contributor version". + + A contributor's "essential patent claims" are all patent claims +owned or controlled by the contributor, whether already acquired or +hereafter acquired, that would be infringed by some manner, permitted +by this License, of making, using, or selling its contributor version, +but do not include claims that would be infringed only as a +consequence of further modification of the contributor version. For +purposes of this definition, "control" includes the right to grant +patent sublicenses in a manner consistent with the requirements of +this License. + + Each contributor grants you a non-exclusive, worldwide, royalty-free +patent license under the contributor's essential patent claims, to +make, use, sell, offer for sale, import and otherwise run, modify and +propagate the contents of its contributor version. + + In the following three paragraphs, a "patent license" is any express +agreement or commitment, however denominated, not to enforce a patent +(such as an express permission to practice a patent or covenant not to +sue for patent infringement). To "grant" such a patent license to a +party means to make such an agreement or commitment not to enforce a +patent against the party. + + If you convey a covered work, knowingly relying on a patent license, +and the Corresponding Source of the work is not available for anyone +to copy, free of charge and under the terms of this License, through a +publicly available network server or other readily accessible means, +then you must either (1) cause the Corresponding Source to be so +available, or (2) arrange to deprive yourself of the benefit of the +patent license for this particular work, or (3) arrange, in a manner +consistent with the requirements of this License, to extend the patent +license to downstream recipients. "Knowingly relying" means you have +actual knowledge that, but for the patent license, your conveying the +covered work in a country, or your recipient's use of the covered work +in a country, would infringe one or more identifiable patents in that +country that you have reason to believe are valid. + + If, pursuant to or in connection with a single transaction or +arrangement, you convey, or propagate by procuring conveyance of, a +covered work, and grant a patent license to some of the parties +receiving the covered work authorizing them to use, propagate, modify +or convey a specific copy of the covered work, then the patent license +you grant is automatically extended to all recipients of the covered +work and works based on it. + + A patent license is "discriminatory" if it does not include within +the scope of its coverage, prohibits the exercise of, or is +conditioned on the non-exercise of one or more of the rights that are +specifically granted under this License. You may not convey a covered +work if you are a party to an arrangement with a third party that is +in the business of distributing software, under which you make payment +to the third party based on the extent of your activity of conveying +the work, and under which the third party grants, to any of the +parties who would receive the covered work from you, a discriminatory +patent license (a) in connection with copies of the covered work +conveyed by you (or copies made from those copies), or (b) primarily +for and in connection with specific products or compilations that +contain the covered work, unless you entered into that arrangement, +or that patent license was granted, prior to 28 March 2007. + + Nothing in this License shall be construed as excluding or limiting +any implied license or other defenses to infringement that may +otherwise be available to you under applicable patent law. + + 12. No Surrender of Others' Freedom. + + If conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot convey a +covered work so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you may +not convey it at all. For example, if you agree to terms that obligate you +to collect a royalty for further conveying from those to whom you convey +the Program, the only way you could satisfy both those terms and this +License would be to refrain entirely from conveying the Program. + + 13. Use with the GNU Affero General Public License. + + Notwithstanding any other provision of this License, you have +permission to link or combine any covered work with a work licensed +under version 3 of the GNU Affero General Public License into a single +combined work, and to convey the resulting work. The terms of this +License will continue to apply to the part which is the covered work, +but the special requirements of the GNU Affero General Public License, +section 13, concerning interaction through a network will apply to the +combination as such. + + 14. Revised Versions of this License. + + The Free Software Foundation may publish revised and/or new versions of +the GNU General Public License from time to time. Such new versions will +be similar in spirit to the present version, but may differ in detail to +address new problems or concerns. + + Each version is given a distinguishing version number. If the +Program specifies that a certain numbered version of the GNU General +Public License "or any later version" applies to it, you have the +option of following the terms and conditions either of that numbered +version or of any later version published by the Free Software +Foundation. If the Program does not specify a version number of the +GNU General Public License, you may choose any version ever published +by the Free Software Foundation. + + If the Program specifies that a proxy can decide which future +versions of the GNU General Public License can be used, that proxy's +public statement of acceptance of a version permanently authorizes you +to choose that version for the Program. + + Later license versions may give you additional or different +permissions. However, no additional obligations are imposed on any +author or copyright holder as a result of your choosing to follow a +later version. + + 15. Disclaimer of Warranty. + + THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY +APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT +HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY +OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, +THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM +IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF +ALL NECESSARY SERVICING, REPAIR OR CORRECTION. + + 16. Limitation of Liability. + + IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING +WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS +THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY +GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE +USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF +DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD +PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), +EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF +SUCH DAMAGES. + + 17. Interpretation of Sections 15 and 16. + + If the disclaimer of warranty and limitation of liability provided +above cannot be given local legal effect according to their terms, +reviewing courts shall apply local law that most closely approximates +an absolute waiver of all civil liability in connection with the +Program, unless a warranty or assumption of liability accompanies a +copy of the Program in return for a fee. + + END OF TERMS AND CONDITIONS + + How to Apply These Terms to Your New Programs + + If you develop a new program, and you want it to be of the greatest +possible use to the public, the best way to achieve this is to make it +free software which everyone can redistribute and change under these terms. + + To do so, attach the following notices to the program. It is safest +to attach them to the start of each source file to most effectively +state the exclusion of warranty; and each file should have at least +the "copyright" line and a pointer to where the full notice is found. + + + Copyright (C) + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see . + +Also add information on how to contact you by electronic and paper mail. + + If the program does terminal interaction, make it output a short +notice like this when it starts in an interactive mode: + + Copyright (C) + This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. + This is free software, and you are welcome to redistribute it + under certain conditions; type `show c' for details. + +The hypothetical commands `show w' and `show c' should show the appropriate +parts of the General Public License. Of course, your program's commands +might be different; for a GUI interface, you would use an "about box". + + You should also get your employer (if you work as a programmer) or school, +if any, to sign a "copyright disclaimer" for the program, if necessary. +For more information on this, and how to apply and follow the GNU GPL, see +. + + The GNU General Public License does not permit incorporating your program +into proprietary programs. If your program is a subroutine library, you +may consider it more useful to permit linking proprietary applications with +the library. If this is what you want to do, use the GNU Lesser General +Public License instead of this License. But first, please read +. \ No newline at end of file diff --git a/app/src/main/assets/planet b/app/src/main/assets/planet new file mode 100644 index 0000000..4689898 Binary files /dev/null and b/app/src/main/assets/planet differ diff --git a/app/src/main/assets/rounds_black.otf b/app/src/main/assets/rounds_black.otf new file mode 100644 index 0000000..872edaa Binary files /dev/null and b/app/src/main/assets/rounds_black.otf differ diff --git a/app/src/main/java/backone/cloud/call/AboutActivity.java b/app/src/main/java/backone/cloud/call/AboutActivity.java new file mode 100644 index 0000000..18172ba --- /dev/null +++ b/app/src/main/java/backone/cloud/call/AboutActivity.java @@ -0,0 +1,26 @@ +package backone.cloud.call; + +import android.content.Intent; +import android.os.Bundle; +import android.widget.TextView; + + +public class AboutActivity extends MeshengerActivity { + + @Override + protected void onCreate(Bundle savedInstanceState) { + super.onCreate(savedInstanceState); + setContentView(R.layout.activity_about); + + setTitle(getResources().getString(R.string.menu_about)); + + ((TextView) findViewById(R.id.versionTv)).setText( + Utils.getApplicationVersion(this) + ); + + findViewById(R.id.licenseTV).setOnClickListener(v -> { + Intent intent = new Intent(this, LicenseActivity.class); + startActivity(intent); + }); + } +} diff --git a/app/src/main/java/backone/cloud/call/AddressActivity.java b/app/src/main/java/backone/cloud/call/AddressActivity.java new file mode 100644 index 0000000..dfe3669 --- /dev/null +++ b/app/src/main/java/backone/cloud/call/AddressActivity.java @@ -0,0 +1,351 @@ +package backone.cloud.call; + +import android.app.Activity; +import android.app.Service; +import android.content.ComponentName; +import android.content.Intent; +import android.content.ServiceConnection; +import android.graphics.Color; +import android.os.IBinder; +import android.os.Bundle; +import android.text.Editable; +import android.text.TextWatcher; +import android.view.LayoutInflater; +import android.view.View; +import android.view.ViewGroup; +import android.widget.BaseAdapter; +import android.widget.Button; +import android.widget.EditText; +import android.widget.Spinner; +import android.widget.TextView; +import android.widget.Toast; + +import java.net.InetSocketAddress; +import java.util.ArrayList; +import java.util.Collections; +import java.util.Comparator; +import java.util.List; + + +public class AddressActivity extends MeshengerActivity implements ServiceConnection { + private MainService.MainBinder binder; + Spinner storedAddressSpinner; + Spinner systemAddressSpinner; + Button pickStoredAddressButton; + Button pickSystemAddressButton; + EditText addressEditText; + Button addButton; + Button removeButton; + Button saveButton; + Button abortButton; + + List systemAddressList; + List storedAddressList; + AddressListAdapter storedAddressListAdapter; + AddressListAdapter systemAddressListAdapter; + + @Override + protected void onCreate(Bundle savedInstanceState) { + super.onCreate(savedInstanceState); + + setContentView(R.layout.activity_address); + setTitle(R.string.address_management); + + storedAddressSpinner = findViewById(R.id.StoredAddressSpinner); + systemAddressSpinner = findViewById(R.id.SystemAddressSpinner); + pickStoredAddressButton = findViewById(R.id.PickStoredAddressButton); + pickSystemAddressButton = findViewById(R.id.PickSystemAddressButton); + addressEditText = findViewById(R.id.AddressEditText); + addButton = findViewById(R.id.AddButton); + removeButton = findViewById(R.id.RemoveButton); + saveButton = findViewById(R.id.SaveButton); + abortButton = findViewById(R.id.AbortButton); + + systemAddressList = Utils.collectAddresses(); + storedAddressList = new ArrayList<>(); + storedAddressListAdapter = new AddressListAdapter(this, Color.parseColor("#39b300")); //dark green + systemAddressListAdapter = new AddressListAdapter(this, Color.parseColor("#b3b7b2")); //light grey + + storedAddressSpinner.setAdapter(storedAddressListAdapter); + systemAddressSpinner.setAdapter(systemAddressListAdapter); + + addressEditText.addTextChangedListener(new TextWatcher() { + @Override + public void afterTextChanged(Editable s) { + updateAddressEditTextButtons(); + } + + @Override + public void beforeTextChanged(CharSequence s, int start, int count, int after) { + // nothing to do + } + + @Override + public void onTextChanged(CharSequence s, int start, int before, int count) { + updateAddressEditTextButtons(); + } + }); + + addButton.setOnClickListener((View v) -> { + String address = addressEditText.getText().toString(); + if (address.isEmpty()) { + return; + } + + AddressEntry entry = parseAddress(address); + + if (entry.multicast) { + Toast.makeText(this, "Multicast addresses are not supported.", Toast.LENGTH_SHORT).show(); + return; + } + + if (Utils.isIP(address) && !systemAddressList.contains(entry)) { + Toast.makeText(this, "You can only choose a IP address that is used by the system.", Toast.LENGTH_LONG).show(); + return; + } + + storedAddressList.add(entry); + updateSpinners(); + + // select the added element + int idx = AddressEntry.listIndexOf(storedAddressList, entry); + storedAddressSpinner.setSelection(idx); + }); + + removeButton.setOnClickListener((View v) -> { + String address = addressEditText.getText().toString(); + if (address.isEmpty()) { + return; + } + + int idx = AddressEntry.listIndexOf(storedAddressList, new AddressEntry(address, "", false)); + if (idx > -1) { + storedAddressList.remove(idx); + updateSpinners(); + } + }); + + pickSystemAddressButton.setOnClickListener((View v) -> { + int pos = systemAddressSpinner.getSelectedItemPosition(); + if (pos > -1 && !systemAddressListAdapter.isEmpty()) { + addressEditText.setText(systemAddressList.get(pos).address); + } + }); + + pickStoredAddressButton.setOnClickListener((View v) -> { + int pos = storedAddressSpinner.getSelectedItemPosition(); + if (pos > -1 && !storedAddressListAdapter.isEmpty()) { + addressEditText.setText(storedAddressList.get(pos).address); + } + }); + + saveButton.setOnClickListener((View v) -> { + ArrayList addresses = new ArrayList<>(); + for (AddressEntry ae : this.storedAddressList) { + addresses.add(ae.address); + } + this.binder.getSettings().setAddresses(addresses); + this.binder.saveDatabase(); + Toast.makeText(this, R.string.done, Toast.LENGTH_SHORT).show(); + }); + + abortButton.setOnClickListener((View v) -> { + finish(); + }); + + bindService(); + } + + @Override + protected void onDestroy() { + super.onDestroy(); + unbindService(this); + } + + private void bindService() { + // ask MainService to get us the binder object + Intent serviceIntent = new Intent(this, MainService.class); + bindService(serviceIntent, this, Service.BIND_AUTO_CREATE); + } + + @Override + public void onServiceConnected(ComponentName componentName, IBinder iBinder) { + this.binder = (MainService.MainBinder) iBinder; + + // get from settings + for (String address : this.binder.getSettings().getAddresses()) { + this.storedAddressList.add(parseAddress(address)); + } + + updateSpinners(); + } + + @Override + public void onServiceDisconnected(ComponentName componentName) { + this.binder = null; + } + + public class AddressListAdapter extends BaseAdapter { + private final Activity context; + private final int markColor; + private List addressEntries; + private List addressEntriesMarked; + + public AddressListAdapter(Activity context, int markColor) { + this.context = context; + this.markColor = markColor; + this.addressEntries = new ArrayList<>(); + this.addressEntriesMarked = new ArrayList<>(); + } + + public boolean isEmpty() { + return this.addressEntries.isEmpty(); + } + + public void update(List addressEntries, List addressEntriesMarked) { + this.addressEntries = addressEntries; + this.addressEntriesMarked = addressEntriesMarked; + } + + @Override + public int getCount() { + if (isEmpty()) { + return 1; + } + return addressEntries.size(); + } + + @Override + public Object getItem(int position) { + if (isEmpty()) { + return null; + } + return addressEntries.get(position); + } + + @Override + public long getItemId(int position) { + return 0; + } + + @Override + public View getView(int position, View view, ViewGroup parent) { + if (view == null) { + LayoutInflater inflater = context.getLayoutInflater(); + view = inflater.inflate(R.layout.activity_address_item, parent, false); + } + + TextView label = view.findViewById(R.id.label); + + if (isEmpty()) { + label.setText(getResources().getString(R.string.empty_list_item)); + label.setTextColor(Color.BLACK); + } else { + AddressEntry ae = this.addressEntries.get(position); + + ArrayList info = new ArrayList<>(); + if (ae.device.length() > 0) { + info.add(ae.device); + } + + if (ae.multicast) { + info.add("multicast"); + } + + label.setText(ae.address + (info.isEmpty() ? "" : (" (" + Utils.join(info) + ")"))); + + if (AddressEntry.listIndexOf(addressEntriesMarked, ae) < 0) { + label.setTextColor(Color.BLACK); + } else { + label.setTextColor(this.markColor); + } + } + + return view; + } + } + + private void updateAddressEditTextButtons() { + String address = addressEditText.getText().toString(); + + boolean exists = (AddressEntry.findAddressEntry(storedAddressList, address) != null); + if (exists) { + addButton.setEnabled(false); + removeButton.setEnabled(true); + } else { + removeButton.setEnabled(false); + boolean valid = (Utils.isMAC(address) || Utils.isDomain(address) || Utils.isIP(address)); + addButton.setEnabled(valid); + } + } + + private void updateSpinners() { + // compare by device first, address second + Comparator compareAddressEntries = (AddressEntry o1, AddressEntry o2) -> { + int dd = o1.device.compareTo(o2.device); + if (dd == 0) { + return o1.address.compareTo(o2.address); + } else { + return dd; + } + }; + + Collections.sort(storedAddressList, compareAddressEntries); + Collections.sort(systemAddressList, compareAddressEntries); + + storedAddressListAdapter.update(storedAddressList, systemAddressList); + storedAddressListAdapter.notifyDataSetChanged(); + + systemAddressListAdapter.update(systemAddressList, storedAddressList); + systemAddressListAdapter.notifyDataSetChanged(); + + systemAddressSpinner.setAdapter(storedAddressListAdapter); + systemAddressSpinner.setAdapter(systemAddressListAdapter); + + pickStoredAddressButton.setEnabled(!storedAddressListAdapter.isEmpty()); + pickSystemAddressButton.setEnabled(!systemAddressListAdapter.isEmpty()); + + updateAddressEditTextButtons(); + } + + /* + * Create AddressEntry from address string. + * Do not perform any domain lookup + */ + AddressEntry parseAddress(String address) { + // instead of parsing, lookup in known addresses first + AddressEntry ae = AddressEntry.findAddressEntry(systemAddressList, address); + if (ae != null) { + // known address + return new AddressEntry(address, ae.device, ae.multicast); + } else if (Utils.isMAC(address)) { + // MAC address + boolean mc = Utils.isMulticastMAC(Utils.macAddressToBytes(address)); + return new AddressEntry(address, "", mc); + } else if (Utils.isIP(address)) { + // IP address + boolean mc = false; + try { + InetSocketAddress parsed = Utils.parseInetSocketAddress(address, 0); + if (parsed != null && parsed.getAddress() != null) { + mc = parsed.getAddress().isMulticastAddress(); + } + } catch (Exception e) { + // ignore + } + return new AddressEntry(address, "", mc); + } else { + // domain + return new AddressEntry(address, "", false); + } + } + + @Override + protected void onResume() { + super.onResume(); + } + + private void log(String s) { + Log.d(this, s); + } +} diff --git a/app/src/main/java/backone/cloud/call/AddressEntry.java b/app/src/main/java/backone/cloud/call/AddressEntry.java new file mode 100644 index 0000000..c951b64 --- /dev/null +++ b/app/src/main/java/backone/cloud/call/AddressEntry.java @@ -0,0 +1,66 @@ +package backone.cloud.call; + +import java.util.Iterator; +import java.util.List; + + +/* + * Item for address management (AddressActivity) + */ +public class AddressEntry implements Comparable { + final String address; + final String device; + final boolean multicast; + + AddressEntry(String address, String device, boolean multicast) { + this.address = address; + this.device = device; + this.multicast = multicast; + } + + @Override + public int compareTo(AddressEntry e) { + return this.address.compareTo(e.address); + } + + @Override + public String toString() { + return this.address; + } + + @Override + public boolean equals(Object other) { + if (other instanceof AddressEntry) { + return this.address.equals(((AddressEntry) other).address); + } else { + return super.equals(other); + } + } + + @Override + public int hashCode() { + return this.address.hashCode(); + } + + public static AddressEntry findAddressEntry(List list, String address) { + for (int i = 0; i < list.size(); i += 1) { + if (list.get(i).address.equals(address)) { + return list.get(i); + } + } + return null; + } + + public static int listIndexOf(List list, AddressEntry entry) { + Iterator iter = list.listIterator(); + int i = 0; + + while(iter.hasNext()) { + if (iter.next().address.equals(entry.address)) { + return i; + } + i += 1; + } + return -1; + } +} diff --git a/app/src/main/java/backone/cloud/call/BachotApplication.java b/app/src/main/java/backone/cloud/call/BachotApplication.java new file mode 100644 index 0000000..6e5fe32 --- /dev/null +++ b/app/src/main/java/backone/cloud/call/BachotApplication.java @@ -0,0 +1,19 @@ +package backone.cloud.call; + +import org.libsodium.jni.NaCl; + +import cloud.backone.backoneconnect.BackOneConnectApplication; +import cloud.backone.backoneconnect.util.PlanetAssets; + +/** + * App entry that owns the BackOne Connect GreenDAO session and initializes libsodium. + */ +public class BachotApplication extends BackOneConnectApplication { + @Override + public void onCreate() { + super.onCreate(); + // Load native sodium before any Crypto / keypair use. + NaCl.sodium(); + PlanetAssets.ensureDefault(this); + } +} diff --git a/app/src/main/java/backone/cloud/call/CallActivity.java b/app/src/main/java/backone/cloud/call/CallActivity.java new file mode 100644 index 0000000..616df0f --- /dev/null +++ b/app/src/main/java/backone/cloud/call/CallActivity.java @@ -0,0 +1,736 @@ +package backone.cloud.call; + +import android.content.BroadcastReceiver; +import android.content.ComponentName; +import android.content.Context; +import android.content.Intent; +import android.content.IntentFilter; +import android.content.ServiceConnection; +import android.content.pm.PackageManager; +import android.hardware.Sensor; +import android.hardware.SensorEvent; +import android.hardware.SensorEventListener; +import android.media.AudioManager; +import android.media.Ringtone; +import android.media.RingtoneManager; +import android.os.Handler; +import android.os.IBinder; +import android.os.PowerManager; +import android.os.VibrationEffect; +import android.os.Vibrator; +import androidx.annotation.NonNull; +import androidx.localbroadcastmanager.content.LocalBroadcastManager; +import android.os.Bundle; +import android.view.View; +import android.view.WindowManager; +import android.view.animation.Animation; +import android.view.animation.ScaleAnimation; +import android.widget.ImageButton; +import android.widget.TextView; +import android.widget.Toast; + +import org.webrtc.RTCStatsCollectorCallback; +import org.webrtc.RTCStatsReport; + +import backone.cloud.call.util.StatsReportUtil; + + +public class CallActivity extends MeshengerActivity implements ServiceConnection, SensorEventListener { + private static final int MIC_PERMISSION_REQUEST_CODE = 1; + + private TextView statusTextView; + private TextView callStats; + + private MainService.MainBinder binder = null; + private ServiceConnection connection; + + private RTCCall currentCall; + + private boolean calledWhileScreenOff = false; + private PowerManager.WakeLock wakeLock; + private PowerManager.WakeLock passiveWakeLock = null; + + private final long buttonAnimationDuration = 400; + private final int CAMERA_PERMISSION_REQUEST_CODE = 2; + + private boolean permissionRequested = false; + private boolean outgoingCallPending = false; + + private Contact contact = null; + private CallEvent.Type callEventType = null; + + private Vibrator vibrator = null; + private Ringtone ringtone = null; + + @Override + protected void onCreate(Bundle savedInstanceState) { + super.onCreate(savedInstanceState); + setContentView(R.layout.activity_call); + + // keep screen on during call; block screenshots/recents thumbnail + getWindow().addFlags( + WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON + | WindowManager.LayoutParams.FLAG_SECURE + ); + + statusTextView = findViewById(R.id.callStatus); + callStats = findViewById(R.id.callStats); + TextView nameTextView = findViewById(R.id.callName); + + String action = getIntent().getAction(); + Bundle extras = getIntent().getExtras(); + if (extras == null || !extras.containsKey("EXTRA_CONTACT")) { + log("onCreate: missing EXTRA_CONTACT"); + finish(); + return; + } + contact = (Contact) extras.get("EXTRA_CONTACT"); + if (contact == null) { + log("onCreate: EXTRA_CONTACT is null"); + finish(); + return; + } + + log("onCreate: " + action); + + if ("ACTION_OUTGOING_CALL".equals(action)) { + callEventType = CallEvent.Type.OUTGOING_UNKNOWN; + outgoingCallPending = true; + + connection = new ServiceConnection() { + @Override + public void onServiceConnected(ComponentName componentName, IBinder iBinder) { + binder = (MainService.MainBinder) iBinder; + if (!outgoingCallPending) { + return; + } + startOutgoingCall(); + } + + @Override + public void onServiceDisconnected(ComponentName componentName) { + // nothing to do + } + }; + + if (contact.getName().isEmpty()) { + nameTextView.setText(getResources().getString(R.string.unknown_caller)); + } else { + nameTextView.setText(contact.getName()); + } + + bindService(new Intent(this, MainService.class), connection, Context.BIND_AUTO_CREATE); + + View.OnClickListener declineListener = view -> { + // Sync teardown — hangUp()+finish() raced and aborted WebRTC natively. + RTCCall call = resolveCall(); + currentCall = null; + if (call != null) { + call.teardown(true); + } + callEventType = CallEvent.Type.OUTGOING_DECLINED; + finish(); + }; + + findViewById(R.id.callDecline).setOnClickListener(declineListener); + startSensor(); + } else if ("ACTION_INCOMING_CALL".equals(action)) { + callEventType = CallEvent.Type.INCOMING_UNKNOWN; + + calledWhileScreenOff = !((PowerManager) getSystemService(POWER_SERVICE)).isScreenOn(); + passiveWakeLock = ((PowerManager) getSystemService(POWER_SERVICE)).newWakeLock( + PowerManager.ACQUIRE_CAUSES_WAKEUP | PowerManager.FULL_WAKE_LOCK, "meshenger:wakeup" + ); + passiveWakeLock.acquire(10000); + + connection = this; + bindService(new Intent(this, MainService.class), this, Context.BIND_AUTO_CREATE); + + if (contact.getName().isEmpty()) { + nameTextView.setText(getResources().getString(R.string.unknown_caller)); + } else { + nameTextView.setText(contact.getName()); + } + + findViewById(R.id.callAccept).setVisibility(View.VISIBLE); + startRinging(); + + // decline call + View.OnClickListener declineListener = view -> { + stopRinging(); + + log("declining call..."); + RTCCall call = resolveCall(); + currentCall = null; + if (call != null) { + call.teardown(true); + } + if (passiveWakeLock != null && passiveWakeLock.isHeld()) { + passiveWakeLock.release(); + } + + callEventType = CallEvent.Type.INCOMING_DECLINED; + + finish(); + }; + + // hangup call + View.OnClickListener hangupListener = view -> { + stopRinging(); // make sure ringing has stopped ;-) + + log("hangup call..."); + RTCCall call = resolveCall(); + currentCall = null; + if (call != null) { + call.teardown(true); + } + if (passiveWakeLock != null && passiveWakeLock.isHeld()) { + passiveWakeLock.release(); + } + + callEventType = CallEvent.Type.INCOMING_ACCEPTED; + + finish(); + }; + + View.OnClickListener acceptListener = view -> { + stopRinging(); + + log("accepted call..."); + try { + RTCCall call = resolveCall(); + if (call == null) { + stopDelayed("Error accepting call"); + findViewById(R.id.callAccept).setVisibility(View.GONE); + callEventType = CallEvent.Type.INCOMING_ERROR; + return; + } + currentCall = call; + currentCall.setRemoteRenderer(findViewById(R.id.remoteRenderer)); + currentCall.setLocalRenderer(findViewById(R.id.localRenderer)); + currentCall.accept(passiveCallback); + if (passiveWakeLock != null && passiveWakeLock.isHeld()) { + passiveWakeLock.release(); + } + findViewById(R.id.callDecline).setOnClickListener(hangupListener); + startSensor(); + } catch (Exception e) { + e.printStackTrace(); + stopDelayed("Error accepting call"); + findViewById(R.id.callAccept).setVisibility(View.GONE); + callEventType = CallEvent.Type.INCOMING_ERROR; + } + }; + + findViewById(R.id.callAccept).setOnClickListener(acceptListener); + findViewById(R.id.callDecline).setOnClickListener(declineListener); + + // Only incoming calls should finish when the peer signaling socket drops. + LocalBroadcastManager.getInstance(this).registerReceiver( + declineBroadcastReceiver, new IntentFilter("call_declined") + ); + } + + findViewById(R.id.speakerMode).setOnClickListener(button -> { + if (currentCall != null) { + chooseVoiceMode((ImageButton)button); + } + }); + + findViewById(R.id.videoStreamSwitch).setOnClickListener((button) -> { + if (currentCall != null) { + switchVideoEnabled((ImageButton)button); + } + }); + + findViewById(R.id.frontFacingSwitch).setOnClickListener((button) -> { + if (currentCall != null) { + currentCall.switchFrontFacing(); + } + }); + } + + private void startOutgoingCall() { + if (!outgoingCallPending || binder == null || contact == null) { + return; + } + if (!Utils.hasMicPermission(this)) { + Utils.requestMicPermission(this, MIC_PERMISSION_REQUEST_CODE); + return; + } + if (binder != null && !binder.isSignalingReady()) { + stopDelayed(getString(R.string.call_error)); + callEventType = CallEvent.Type.OUTGOING_ERROR; + outgoingCallPending = false; + return; + } + + try { + Contact live = binder.getContactByPublicKey(contact.getPublicKey()); + if (live != null) { + contact = live; + } + + currentCall = RTCCall.startCall( + CallActivity.this, + binder, + contact, + activeCallback + ); + if (currentCall == null) { + stopDelayed(getString(R.string.call_error)); + callEventType = CallEvent.Type.OUTGOING_ERROR; + outgoingCallPending = false; + return; + } + + currentCall.setRemoteRenderer(findViewById(R.id.remoteRenderer)); + currentCall.setLocalRenderer(findViewById(R.id.localRenderer)); + // Audio route before WebRTC AudioTrack is created on the call thread. + try { + AudioManager am = (AudioManager) getSystemService(AUDIO_SERVICE); + if (am != null) { + am.setMode(AudioManager.MODE_IN_COMMUNICATION); + am.setSpeakerphoneOn(false); + } + } catch (Exception e) { + e.printStackTrace(); + } + currentCall.startOutgoingSignaling(); + outgoingCallPending = false; + setStatusText(getString(R.string.call_connecting)); + } catch (Exception e) { + e.printStackTrace(); + stopDelayed(getString(R.string.call_error)); + callEventType = CallEvent.Type.OUTGOING_ERROR; + outgoingCallPending = false; + } + } + + final BroadcastReceiver declineBroadcastReceiver = new BroadcastReceiver() { + @Override + public void onReceive(Context context, Intent intent) { + log("declineBroadcastCastReceiver onReceive"); + finish(); + } + }; + + private void startRinging(){ + log("startRinging"); + int ringerMode = ((AudioManager) getSystemService(AUDIO_SERVICE)).getRingerMode(); + + if (ringerMode == AudioManager.RINGER_MODE_SILENT) { + return; + } + + vibrator = ((Vibrator) getSystemService(VIBRATOR_SERVICE)); + long[] pattern = {1500, 800, 800, 800}; + VibrationEffect vibe = VibrationEffect.createWaveform(pattern, 0); + vibrator.vibrate(vibe); + + if (ringerMode == AudioManager.RINGER_MODE_VIBRATE) { + return; + } + + ringtone = RingtoneManager.getRingtone(this, RingtoneManager.getActualDefaultRingtoneUri(getApplicationContext(), RingtoneManager.TYPE_RINGTONE)); + if (ringtone != null) { + ringtone.play(); + } + } + + private void stopRinging(){ + log("stopRinging"); + if (vibrator != null) { + vibrator.cancel(); + vibrator = null; + } + + if (ringtone != null){ + ringtone.stop(); + ringtone = null; + } + } + + private void chooseVoiceMode(ImageButton button) { + AudioManager audioManager = (AudioManager)this.getSystemService(Context.AUDIO_SERVICE); + currentCall.setSpeakerEnabled(!currentCall.isSpeakerEnabled()); + if(currentCall.isSpeakerEnabled()) { + audioManager.setMode(AudioManager.MODE_IN_COMMUNICATION); + audioManager.setSpeakerphoneOn(true); + button.setAlpha(1.0f); + } else { + audioManager.setMode(AudioManager.MODE_NORMAL); + audioManager.setSpeakerphoneOn(false); + audioManager.setBluetoothScoOn(false); + button.setAlpha(0.6f); + } + } + + private void switchVideoEnabled(ImageButton button) { + if (!Utils.hasCameraPermission(this)) { + Utils.requestCameraPermission(this, CAMERA_PERMISSION_REQUEST_CODE); + permissionRequested = true; + return; + } + + currentCall.setVideoEnabled(!currentCall.isVideoEnabled()); + ScaleAnimation animation = new ScaleAnimation(1.0f, 0.0f, 1.0f, 1.0f, Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF, 0.5f); + animation.setDuration(buttonAnimationDuration / 2); + animation.setAnimationListener(new Animation.AnimationListener() { + @Override + public void onAnimationStart(Animation animation) { + // nothing to do + } + + @Override + public void onAnimationEnd(Animation animation) { + if (isFinishing() || isDestroyed() || currentCall == null) { + return; + } + button.setImageResource(currentCall.isVideoEnabled() ? R.drawable.baseline_camera_alt_black_off_48 : R.drawable.baseline_camera_alt_black_48); + Animation a = new ScaleAnimation(0.0f, 1.0f, 1.0f, 1.0f, Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF, 0.5f); + a.setDuration(buttonAnimationDuration / 2); + button.startAnimation(a); + } + + @Override + public void onAnimationRepeat(Animation animation) { + // nothing to do + } + }); + View frontSwitch = findViewById(R.id.frontFacingSwitch); + if (currentCall.isVideoEnabled()){ + frontSwitch.setVisibility(View.VISIBLE); + Animation scale = new ScaleAnimation(0f, 1f, 0f, 1f, Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF, 0.5f); + scale.setDuration(buttonAnimationDuration); + frontSwitch.startAnimation(scale); + } else { + Animation scale = new ScaleAnimation(1f, 0f, 1f, 0f, Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF, 0.5f); + scale.setDuration(buttonAnimationDuration); + scale.setAnimationListener(new Animation.AnimationListener() { + @Override + public void onAnimationStart(Animation animation) { + // nothing to do + } + + @Override + public void onAnimationEnd(Animation animation) { + if (!isFinishing() && !isDestroyed()) { + findViewById(R.id.frontFacingSwitch).setVisibility(View.GONE); + } + } + + @Override + public void onAnimationRepeat(Animation animation) { + // nothing to do + } + }); + frontSwitch.startAnimation(scale); + } + button.startAnimation(animation); + } + + @Override + public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) { + super.onRequestPermissionsResult(requestCode, permissions, grantResults); + + if (requestCode == MIC_PERMISSION_REQUEST_CODE) { + if (!Utils.allGranted(grantResults)) { + Toast.makeText(this, R.string.permission_mic, Toast.LENGTH_LONG).show(); + callEventType = CallEvent.Type.OUTGOING_ERROR; + finish(); + return; + } + if (outgoingCallPending) { + startOutgoingCall(); + } + return; + } + + if (requestCode == CAMERA_PERMISSION_REQUEST_CODE) { + if (grantResults.length == 0 || grantResults[0] != PackageManager.PERMISSION_GRANTED) { + Toast.makeText(this, "Camera permission needed in order to start video", Toast.LENGTH_SHORT).show(); + return; + } + switchVideoEnabled(findViewById(R.id.videoStreamSwitch)); + } + } + + private void startSensor() { + PowerManager powerManager = (PowerManager) getSystemService(POWER_SERVICE); + wakeLock = powerManager.newWakeLock(PowerManager.PROXIMITY_SCREEN_OFF_WAKE_LOCK, "meshenger:proximity"); + wakeLock.acquire(10*60*1000L /*10 minutes*/); + } + + @Override + protected void onPause() { + super.onPause(); + if (calledWhileScreenOff) { + calledWhileScreenOff = false; + return; + } + + if (permissionRequested){ + permissionRequested = false; + } + //finish(); + } + + @Override + protected void onDestroy() { + super.onDestroy(); + log("onDestroy"); + + try { + LocalBroadcastManager.getInstance(this).unregisterReceiver(declineBroadcastReceiver); + } catch (IllegalArgumentException ignored) { + // Outgoing calls never register this receiver. + } + + stopRinging(); + + // Config change recreates the activity — do not tear down the live call. + if (isChangingConfigurations()) { + return; + } + + if (currentCall != null) { + RTCCall.CallState state = currentCall.state; + boolean notifyPeer = state == null + || state == RTCCall.CallState.CONNECTING + || state == RTCCall.CallState.RINGING + || state == RTCCall.CallState.CONNECTED; + // Stop media before releasing renderers — avoids WebRTC native abort. + // teardown is idempotent with hangUp/decline cleanup. + currentCall.teardown(notifyPeer); + currentCall = null; + } else if (binder != null && binder.getCurrentCall() != null) { + // Decline before onServiceConnected left MainService.currentCall stuck. + binder.getCurrentCall().teardown(true); + } + + if (this.binder != null) { + if (this.contact != null && this.callEventType != null) { + this.binder.addCallEvent(this.contact, this.callEventType); + } + try { + unbindService(connection); + } catch (IllegalArgumentException ignored) { + // Service was never bound or already unbound. + } + this.binder = null; + } + + if (wakeLock != null && wakeLock.isHeld()) { + wakeLock.release(); + } + + if (passiveWakeLock != null && passiveWakeLock.isHeld()) { + passiveWakeLock.release(); + } + + try { + AudioManager am = (AudioManager) getSystemService(AUDIO_SERVICE); + if (am != null) { + am.setMode(AudioManager.MODE_NORMAL); + am.setSpeakerphoneOn(false); + } + } catch (Exception e) { + e.printStackTrace(); + } + } + + private final RTCStatsCollectorCallback statsCollector = new RTCStatsCollectorCallback() { + + final StatsReportUtil statsReportUtil = new StatsReportUtil(); + @Override + public void onStatsDelivered(RTCStatsReport rtcStatsReport) { + String stats = statsReportUtil.getStatsReport(rtcStatsReport); + // If you need update UI, simply do this: + runOnUiThread(() -> { + if (!isFinishing() && !isDestroyed() && callStats != null) { + callStats.setText(stats); + } + }); + } + }; + + private final RTCCall.OnStateChangeListener activeCallback = callState -> { + switch (callState) { + case CONNECTING: { + log("activeCallback: CONNECTING"); + setStatusText(getString(R.string.call_connecting)); + break; + } + case CONNECTED: { + log("activeCallback: CONNECTED"); + MainService.MainBinder b = binder; + RTCCall call = currentCall; + Settings settings = b != null ? b.getSettings() : null; + boolean devMode = settings != null && settings.getDevelopmentMode(); + new Handler(getMainLooper()).post(() -> { + if (isFinishing() || isDestroyed()) { + return; + } + if (devMode && call != null) { + call.accept(statsCollector); + callStats.setVisibility(View.VISIBLE); + } else { + callStats.setVisibility(View.GONE); + } + findViewById(R.id.videoStreamSwitchLayout).setVisibility(View.VISIBLE); + findViewById(R.id.speakerMode).setVisibility(View.VISIBLE); + }); + setStatusText(getString(R.string.call_connected)); + break; + } + case DISMISSED: { + log("activeCallback: DISMISSED"); + stopDelayed(getString(R.string.call_denied)); + break; + } + case RINGING: { + log("activeCallback: RINGING"); + setStatusText(getString(R.string.call_ringing)); + break; + } + case ENDED: { + log("activeCallback: ENDED"); + stopDelayed(getString(R.string.call_ended)); + break; + } + case ERROR: { + log("activeCallback: ERROR"); + stopDelayed(getString(R.string.call_error)); + break; + } + } + }; + + private final RTCCall.OnStateChangeListener passiveCallback = callState -> { + switch (callState) { + case CONNECTED: { + log("passiveCallback: CONNECTED"); + setStatusText(getString(R.string.call_connected)); + MainService.MainBinder b = binder; + RTCCall call = currentCall; + Settings settings = b != null ? b.getSettings() : null; + boolean devMode = settings != null && settings.getDevelopmentMode(); + runOnUiThread(() -> { + if (!isFinishing() && !isDestroyed()) { + findViewById(R.id.callAccept).setVisibility(View.GONE); + } + }); + new Handler(getMainLooper()).post(() -> { + if (isFinishing() || isDestroyed()) { + return; + } + findViewById(R.id.videoStreamSwitchLayout).setVisibility(View.VISIBLE); + findViewById(R.id.speakerMode).setVisibility(View.VISIBLE); + if (devMode && call != null) { + call.accept(statsCollector); + callStats.setVisibility(View.VISIBLE); + } else { + callStats.setVisibility(View.GONE); + } + }); + break; + } + case RINGING: { + log("passiveCallback: RINGING"); + setStatusText(getString(R.string.call_ringing)); + break; + } + case ENDED: { + log("passiveCallback: ENDED"); + stopDelayed(getString(R.string.call_ended)); + break; + } + case ERROR: { + log("passiveCallback: ERROR"); + stopDelayed(getString(R.string.call_error)); + break; + } + } + }; + + private void setStatusText(String text) { + new Handler(getMainLooper()).post(() -> { + if (isFinishing() || isDestroyed()) { + return; + } + statusTextView.setText(text); + }); + } + + private void stopDelayed(String message) { + new Handler(getMainLooper()).post(() -> { + if (isFinishing() || isDestroyed()) { + return; + } + statusTextView.setText(message); + new Handler(getMainLooper()).postDelayed(() -> { + if (!isFinishing() && !isDestroyed()) { + finish(); + } + }, 2000); + }); + } + + @Override + public void onServiceConnected(ComponentName componentName, IBinder iBinder) { + this.binder = (MainService.MainBinder) iBinder; + this.currentCall = this.binder.getCurrentCall(); + if (this.currentCall != null + && "ACTION_INCOMING_CALL".equals(getIntent() != null ? getIntent().getAction() : null)) { + // Surface peer hangup while still on the ringing screen. + this.currentCall.setOnStateChangeListener(state -> { + if (state == RTCCall.CallState.DISMISSED + || state == RTCCall.CallState.ENDED + || state == RTCCall.CallState.ERROR) { + stopRinging(); + if (state == RTCCall.CallState.ERROR) { + callEventType = CallEvent.Type.INCOMING_ERROR; + stopDelayed(getString(R.string.call_error)); + } else { + callEventType = CallEvent.Type.INCOMING_DECLINED; + stopDelayed(getString(R.string.call_ended)); + } + } + }); + } + } + + private RTCCall resolveCall() { + if (currentCall != null) { + return currentCall; + } + if (binder != null) { + return binder.getCurrentCall(); + } + return null; + } + + @Override + public void onServiceDisconnected(ComponentName componentName) { + this.binder = null; + } + + @Override + public void onSensorChanged(SensorEvent sensorEvent) { + // Proximity listener is not registered today; keep release-safe if that changes. + if (sensorEvent == null || sensorEvent.values == null || sensorEvent.values.length == 0) { + return; + } + log("sensor changed: " + sensorEvent.values[0]); + } + + @Override + public void onAccuracyChanged(Sensor sensor, int i) { + // nothing to do + } + + private void log(String s) { + Log.d(this, s); + } +} diff --git a/app/src/main/java/backone/cloud/call/CallEvent.java b/app/src/main/java/backone/cloud/call/CallEvent.java new file mode 100644 index 0000000..28266a0 --- /dev/null +++ b/app/src/main/java/backone/cloud/call/CallEvent.java @@ -0,0 +1,32 @@ +package backone.cloud.call; + +import java.net.InetAddress; +import java.util.Date; + + +class CallEvent { + enum Type { + OUTGOING_UNKNOWN, + OUTGOING_ACCEPTED, + OUTGOING_DECLINED, + OUTGOING_MISSED, + OUTGOING_ERROR, + INCOMING_UNKNOWN, + INCOMING_ACCEPTED, + INCOMING_DECLINED, + INCOMING_MISSED, + INCOMING_ERROR + } + + final byte[] pubKey; + final InetAddress address; // may be null in case the call attempt failed + final Type type; + final Date date; + + CallEvent(byte[] pubKey, InetAddress address, Type type) { + this.pubKey = pubKey; + this.address = address; + this.type = type; + this.date = new Date(); + } +} diff --git a/app/src/main/java/backone/cloud/call/Contact.java b/app/src/main/java/backone/cloud/call/Contact.java new file mode 100644 index 0000000..4e349da --- /dev/null +++ b/app/src/main/java/backone/cloud/call/Contact.java @@ -0,0 +1,246 @@ +package backone.cloud.call; + +import org.json.JSONException; +import org.json.JSONObject; +import org.json.JSONArray; + +import java.io.Serializable; +import java.net.ConnectException; +import java.net.InetSocketAddress; +import java.net.Socket; +import java.net.SocketTimeoutException; +import java.util.ArrayList; +import java.util.List; +import java.util.Locale; + + +public class Contact implements Serializable { + enum State { ONLINE, OFFLINE, PENDING } + + private String name; + private byte[] pubkey; + private boolean blocked; + private final List addresses; + + // contact state + private State state = State.PENDING; + + // last working address (use this address next connection and for unknown contact initialization) + private InetSocketAddress last_working_address = null; + + public Contact(String name, byte[] pubkey, List addresses) { + this.name = name; + this.pubkey = pubkey; + this.blocked = false; + this.addresses = addresses; + } + + private Contact() { + this.name = ""; + this.pubkey = null; + this.blocked = false; + this.addresses = new ArrayList<>(); + } + + public State getState() { + return state; + } + + public void setState(State state) { + this.state = state; + } + + public List getAddresses() { + return this.addresses; + } + + public void addAddress(String address) { + if (address.isEmpty()) { + return; + } + + for (String addr : this.addresses) { + if (addr.equalsIgnoreCase(address)) { + return; + } + } + this.addresses.add(address); + } + + public List getAllSocketAddresses() { + List addrs = new ArrayList<>(); + for (String address : this.addresses) { + try { + // also resolves domains + InetSocketAddress socketAddress = Utils.parseInetSocketAddress(address, MainService.serverPort); + if (socketAddress != null) { + addrs.add(socketAddress); + } + } catch (Exception e) { + log("invalid address: " + address); + e.printStackTrace(); + } + } + + // Verified IP-as-key contacts often store the peer IP only in public_key. + // Without this fallback, inbound works (they dial us) but outbound cannot dial. + String identityAddress = Utils.ipv4BytesToString(this.pubkey); + if (identityAddress != null) { + boolean alreadyPresent = false; + for (InetSocketAddress existing : addrs) { + if (existing != null && existing.getAddress() != null + && identityAddress.equals(existing.getAddress().getHostAddress())) { + alreadyPresent = true; + break; + } + } + if (!alreadyPresent) { + InetSocketAddress identitySocket = + Utils.parseInetSocketAddress(identityAddress, MainService.serverPort); + if (identitySocket != null) { + addrs.add(identitySocket); + } + } + } + + return addrs; + } + + public byte[] getPublicKey() { + return pubkey; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public boolean getBlocked() { + return blocked; + } + + public void setBlocked(boolean blocked) { + this.blocked = blocked; + } + + private static Socket establishConnection(InetSocketAddress address, int timeout) { + Socket socket = new Socket(); + try { + // timeout to establish connection + socket.connect(address, timeout); + return socket; + } catch (SocketTimeoutException e) { + // ignore + e.printStackTrace(); + } catch (ConnectException e) { + // device is online, but does not listen on the given port + e.printStackTrace(); + } catch (Exception e) { + e.printStackTrace(); + } + + if (socket != null) { + try { + socket.close(); + } catch (Exception e) { + // ignore + } + } + + return null; + } + + /* + * Create a connection to the contact. + * Try/Remember the last successful address. + */ + public Socket createSocket() { + Socket socket = null; + // 300ms was too aggressive on mobile/VPN links and made reachable contacts look offline. + int connectionTimeout = 1500; + + // try last successful address first + if (this.last_working_address != null) { + log("try latest address: " + this.last_working_address); + socket = establishConnection(this.last_working_address, connectionTimeout); + if (socket != null) { + return socket; + } + } + + for (InetSocketAddress address : this.getAllSocketAddresses()) { + if (address == null) { + continue; + } + log("try address: '" + address.getHostName() + "', port: " + address.getPort()); + socket = establishConnection(address, connectionTimeout); + if (socket != null) { + return socket; + } + } + + return null; + } + + // set good address to try first next time + public void setLastWorkingAddress(InetSocketAddress address) { + log("setLatestWorkingAddress: " + address); + this.last_working_address = address; + } + + public InetSocketAddress getLastWorkingAddress() { + return this.last_working_address; + } + + public static JSONObject exportJSON(Contact contact, boolean all) throws JSONException { + JSONObject object = new JSONObject(); + JSONArray array = new JSONArray(); + + object.put("name", contact.name); + object.put("public_key", Utils.byteArrayToHexString(contact.pubkey)); + + for (String address : contact.getAddresses()) { + array.put(address); + } + object.put("addresses", array); + + if (all) { + object.put("blocked", contact.blocked); + } + + return object; + } + + public static Contact importJSON(JSONObject object, boolean all) throws JSONException { + Contact contact = new Contact(); + + contact.name = object.getString("name"); + contact.pubkey = Utils.hexStringToByteArray(object.getString("public_key")); + + if (!Utils.isValidName(contact.name)) { + throw new JSONException("Invalid Name."); + } + + if (contact.pubkey == null) { + throw new JSONException("Invalid Public Key."); + } + + JSONArray array = object.getJSONArray("addresses"); + for (int i = 0; i < array.length(); i += 1) { + contact.addAddress(array.getString(i).toLowerCase(Locale.ROOT).trim()); + } + + if (all) { + contact.blocked = object.getBoolean("blocked"); + } + + return contact; + } + + private void log(String s) { + Log.d(this, s); + } +} diff --git a/app/src/main/java/backone/cloud/call/ContactListAdapter.java b/app/src/main/java/backone/cloud/call/ContactListAdapter.java new file mode 100644 index 0000000..18bbe7f --- /dev/null +++ b/app/src/main/java/backone/cloud/call/ContactListAdapter.java @@ -0,0 +1,65 @@ +package backone.cloud.call; + +import android.content.Context; +import androidx.annotation.NonNull; +import androidx.annotation.Nullable; +import android.view.LayoutInflater; +import android.view.View; +import android.view.ViewGroup; +import android.widget.ArrayAdapter; +import android.widget.ImageView; +import android.widget.TextView; + +import java.util.List; + + +class ContactListAdapter extends ArrayAdapter { + private final List contacts; + + private final LayoutInflater inflater; + + public ContactListAdapter(@NonNull Context context, int resource, @NonNull List contacts) { + super(context, resource, contacts); + this.contacts = contacts; + + inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE); + } + + @NonNull + @Override + public View getView(int position, @Nullable View convertView, @NonNull ViewGroup parent) { + Contact contact = contacts.get(position); + + if (convertView == null) { + convertView = inflater.inflate(R.layout.item_contact, null); + } + + ((TextView) convertView.findViewById(R.id.contact_name)).setText(contact.getName()); + + View waiting = convertView.findViewById(R.id.contact_waiting); + View online = convertView.findViewById(R.id.contact_online); + ImageView state = convertView.findViewById(R.id.contact_state); + + if (contact.getState() == Contact.State.PENDING) { + waiting.setVisibility(View.VISIBLE); + online.setVisibility(View.GONE); + state.setVisibility(View.GONE); + } else if (contact.getState() == Contact.State.ONLINE) { + waiting.setVisibility(View.GONE); + online.setVisibility(View.VISIBLE); + state.setVisibility(View.GONE); + } else { + waiting.setVisibility(View.GONE); + online.setVisibility(View.GONE); + state.setVisibility(View.VISIBLE); + } + + return convertView; + } + +// --Commented out by Inspection START (17/07/2023 11:34): +// private void log(String s) { +// Log.d(this, s); +// } +// --Commented out by Inspection STOP (17/07/2023 11:34) +} diff --git a/app/src/main/java/backone/cloud/call/Crypto.java b/app/src/main/java/backone/cloud/call/Crypto.java new file mode 100644 index 0000000..f4fa4af --- /dev/null +++ b/app/src/main/java/backone/cloud/call/Crypto.java @@ -0,0 +1,318 @@ +package backone.cloud.call; + +import org.libsodium.jni.Sodium; +import org.libsodium.jni.SodiumConstants; + +import java.nio.charset.StandardCharsets; +import java.util.Arrays; + + +/** + * Meshenger-compatible libsodium crypto for signaling and database encryption. + * Messages: ed25519 sign + crypto_box_seal. Database: pwhash + secretbox. + * When {@link #legacyCompatibility} is enabled, plaintext signaling is used so + * older Bachot builds (stub crypto) can still connect. + */ +class Crypto { + + /** When true, signaling is sent as plaintext (compatible with pre-crypto builds). */ + private static volatile boolean legacyCompatibility = true; + + public static void setLegacyCompatibility(boolean enabled) { + legacyCompatibility = enabled; + } + + public static boolean getLegacyCompatibility() { + return legacyCompatibility; + } + + public static boolean isValidSignPublicKey(byte[] publicKey) { + return publicKey != null && publicKey.length == Sodium.crypto_sign_publickeybytes(); + } + + public static boolean isZeroKey(byte[] key) { + if (key == null) { + return true; + } + for (byte b : key) { + if (b != 0) { + return false; + } + } + return true; + } + + private static boolean canUseSecureMessaging(byte[] otherPublicKey, byte[] ownPublicKey, byte[] ownSecretKey) { + return isValidSignPublicKey(otherPublicKey) + && isValidSignPublicKey(ownPublicKey) + && ownSecretKey != null + && ownSecretKey.length == Sodium.crypto_sign_secretkeybytes(); + } + + public static byte[] decryptDatabase(byte[] encryptedMessage, byte[] password) { + if (encryptedMessage == null || password == null) { + return null; + } + + int minLength = 4 + Sodium.crypto_pwhash_saltbytes() + + SodiumConstants.NONCE_BYTES + SodiumConstants.MAC_BYTES; + if (encryptedMessage.length <= minLength) { + return null; + } + + byte[] header = new byte[4]; + byte[] salt = new byte[Sodium.crypto_pwhash_saltbytes()]; + byte[] nonce = new byte[SodiumConstants.NONCE_BYTES]; + byte[] encryptedData = new byte[encryptedMessage.length - header.length - salt.length - nonce.length]; + System.arraycopy(encryptedMessage, 0, header, 0, header.length); + System.arraycopy(encryptedMessage, header.length, salt, 0, salt.length); + System.arraycopy(encryptedMessage, header.length + salt.length, nonce, 0, nonce.length); + System.arraycopy(encryptedMessage, header.length + salt.length + nonce.length, encryptedData, 0, encryptedData.length); + + if (!(header[0] == 0 && header[1] == 0 && header[2] == 0 && header[3] == 0)) { + return null; + } + + byte[] key = new byte[Sodium.crypto_box_seedbytes()]; + int rc1 = Sodium.crypto_pwhash(key, key.length, password, password.length, salt, + Sodium.crypto_pwhash_opslimit_interactive(), + Sodium.crypto_pwhash_memlimit_interactive(), + Sodium.crypto_pwhash_alg_default()); + + byte[] decryptedData = new byte[encryptedData.length - SodiumConstants.MAC_BYTES]; + int rc2 = Sodium.crypto_secretbox_open_easy(decryptedData, encryptedData, encryptedData.length, nonce, key); + + Arrays.fill(header, (byte) 0); + Arrays.fill(salt, (byte) 0); + Arrays.fill(key, (byte) 0); + Arrays.fill(nonce, (byte) 0); + Arrays.fill(encryptedData, (byte) 0); + + if (rc1 == 0 && rc2 == 0) { + return decryptedData; + } + Arrays.fill(decryptedData, (byte) 0); + return null; + } + + public static byte[] encryptDatabase(byte[] data, byte[] password) { + if (data == null || password == null) { + return null; + } + + byte[] salt = new byte[Sodium.crypto_pwhash_saltbytes()]; + Sodium.randombytes_buf(salt, salt.length); + + byte[] key = new byte[Sodium.crypto_box_seedbytes()]; + int rc1 = Sodium.crypto_pwhash(key, key.length, password, password.length, salt, + Sodium.crypto_pwhash_opslimit_interactive(), + Sodium.crypto_pwhash_memlimit_interactive(), + Sodium.crypto_pwhash_alg_default()); + + byte[] header = new byte[4]; + + byte[] nonce = new byte[SodiumConstants.NONCE_BYTES]; + Sodium.randombytes_buf(nonce, nonce.length); + + byte[] encryptedData = new byte[SodiumConstants.MAC_BYTES + data.length]; + int rc2 = Sodium.crypto_secretbox_easy(encryptedData, data, data.length, nonce, key); + + byte[] encryptedMessage = new byte[header.length + salt.length + nonce.length + encryptedData.length]; + System.arraycopy(header, 0, encryptedMessage, 0, header.length); + System.arraycopy(salt, 0, encryptedMessage, header.length, salt.length); + System.arraycopy(nonce, 0, encryptedMessage, header.length + salt.length, nonce.length); + System.arraycopy(encryptedData, 0, encryptedMessage, header.length + salt.length + nonce.length, encryptedData.length); + + Arrays.fill(header, (byte) 0); + Arrays.fill(salt, (byte) 0); + Arrays.fill(key, (byte) 0); + Arrays.fill(nonce, (byte) 0); + Arrays.fill(encryptedData, (byte) 0); + + if (rc1 == 0 && rc2 == 0) { + return encryptedMessage; + } + Arrays.fill(encryptedMessage, (byte) 0); + return null; + } + + public static byte[] encryptMessage(String message, byte[] otherPublicKey, byte[] ownPublicKey, byte[] ownSecretKey) { + if (message == null) { + return null; + } + + // Old Bachot builds only understand plaintext JSON signaling. + if (legacyCompatibility || !canUseSecureMessaging(otherPublicKey, ownPublicKey, ownSecretKey)) { + return message.getBytes(StandardCharsets.UTF_8); + } + + byte[] messageBytes = message.getBytes(StandardCharsets.UTF_8); + byte[] signed = sign(messageBytes, ownSecretKey); + if (signed == null) { + return null; + } + + byte[] data = new byte[ownPublicKey.length + signed.length]; + System.arraycopy(ownPublicKey, 0, data, 0, ownPublicKey.length); + System.arraycopy(signed, 0, data, ownPublicKey.length, signed.length); + + byte[] sealed = seal(data, otherPublicKey); + if (sealed != null) { + return sealed; + } + + // Peer key may be legacy (IP-as-key); fall back so calls still work. + return message.getBytes(StandardCharsets.UTF_8); + } + + /** + * Decrypt and verify a signaling message. On success with secure crypto, writes the + * authenticated sender ed25519 public key into {@code otherPublicKeySignOut}. + * Legacy plaintext leaves that buffer zeroed (caller should match by address). + */ + public static String decryptMessage(byte[] message, byte[] otherPublicKeySignOut, byte[] ownPublicKey, byte[] ownSecretKey) { + if (otherPublicKeySignOut == null || otherPublicKeySignOut.length != Sodium.crypto_sign_publickeybytes()) { + return null; + } + + Arrays.fill(otherPublicKeySignOut, (byte) 0); + + if (isValidSignPublicKey(ownPublicKey) + && ownSecretKey != null + && ownSecretKey.length == Sodium.crypto_sign_secretkeybytes()) { + String secure = decryptSecure(message, otherPublicKeySignOut, ownPublicKey, ownSecretKey); + if (secure != null) { + return secure; + } + Arrays.fill(otherPublicKeySignOut, (byte) 0); + } + + // IP-as-key / null-secret identities always use plaintext (verified fleet). + if (!legacyCompatibility && !isLegacyIdentity(ownPublicKey, ownSecretKey)) { + return null; + } + + return decryptLegacyPlaintext(message); + } + + /** Verified IP-as-key peers have a 4-byte pubkey and no ed25519 secret. */ + public static boolean isLegacyIdentity(byte[] ownPublicKey, byte[] ownSecretKey) { + if (ownSecretKey == null || ownSecretKey.length == 0) { + return true; + } + return ownPublicKey != null && ownPublicKey.length == 4; + } + + private static String decryptSecure(byte[] message, byte[] otherPublicKeySignOut, byte[] ownPublicKey, byte[] ownSecretKey) { + byte[] messageData = unseal(message, ownPublicKey, ownSecretKey); + if (messageData == null || messageData.length <= otherPublicKeySignOut.length) { + return null; + } + + byte[] messageSignedData = new byte[messageData.length - otherPublicKeySignOut.length]; + System.arraycopy(messageData, 0, otherPublicKeySignOut, 0, otherPublicKeySignOut.length); + System.arraycopy(messageData, otherPublicKeySignOut.length, messageSignedData, 0, messageSignedData.length); + + byte[] unsignedData = unsign(messageSignedData, otherPublicKeySignOut); + if (unsignedData == null) { + return null; + } + + return new String(unsignedData, StandardCharsets.UTF_8); + } + + private static String decryptLegacyPlaintext(byte[] message) { + if (message == null || message.length == 0) { + return null; + } + String plain = new String(message, StandardCharsets.UTF_8).trim(); + // Old builds send raw JSON like {"action":"call",...} + if (plain.startsWith("{") && plain.contains("\"action\"")) { + return plain; + } + return null; + } + + private static byte[] sign(byte[] data, byte[] secretKey) { + if (data == null) { + return null; + } + if (secretKey == null || secretKey.length != Sodium.crypto_sign_secretkeybytes()) { + return null; + } + + byte[] signedMessage = new byte[Sodium.crypto_sign_bytes() + data.length]; + final int[] signedMessageLen = new int[1]; + int rc = Sodium.crypto_sign(signedMessage, signedMessageLen, data, data.length, secretKey); + if (rc == 0 && signedMessage.length == signedMessageLen[0]) { + return signedMessage; + } + return null; + } + + private static byte[] unsign(byte[] signedMessage, byte[] publicKey) { + if (signedMessage == null || signedMessage.length < Sodium.crypto_sign_bytes()) { + return null; + } + if (publicKey == null || publicKey.length != Sodium.crypto_sign_publickeybytes()) { + return null; + } + + byte[] unsignedMessage = new byte[signedMessage.length - Sodium.crypto_sign_bytes()]; + final int[] messageSize = new int[1]; + int rc = Sodium.crypto_sign_open(unsignedMessage, messageSize, signedMessage, signedMessage.length, publicKey); + if (rc == 0 && unsignedMessage.length == messageSize[0]) { + return unsignedMessage; + } + return null; + } + + private static byte[] seal(byte[] data, byte[] pkSign) { + if (data == null) { + return null; + } + if (pkSign == null || pkSign.length != Sodium.crypto_sign_publickeybytes()) { + return null; + } + + byte[] pkBox = new byte[Sodium.crypto_box_publickeybytes()]; + int rc1 = Sodium.crypto_sign_ed25519_pk_to_curve25519(pkBox, pkSign); + if (rc1 != 0 || pkBox.length != Sodium.crypto_box_publickeybytes()) { + return null; + } + + byte[] ciphertext = new byte[SodiumConstants.SEAL_BYTES + data.length]; + int rc = Sodium.crypto_box_seal(ciphertext, data, data.length, pkBox); + if (rc == 0) { + return ciphertext; + } + return null; + } + + private static byte[] unseal(byte[] ciphertext, byte[] pkSign, byte[] skSign) { + if (ciphertext == null || ciphertext.length < SodiumConstants.SEAL_BYTES) { + return null; + } + if (pkSign == null || pkSign.length != Sodium.crypto_sign_publickeybytes()) { + return null; + } + if (skSign == null || skSign.length != Sodium.crypto_sign_secretkeybytes()) { + return null; + } + + byte[] pkBox = new byte[Sodium.crypto_box_publickeybytes()]; + byte[] skBox = new byte[Sodium.crypto_box_secretkeybytes()]; + int rc1 = Sodium.crypto_sign_ed25519_pk_to_curve25519(pkBox, pkSign); + int rc2 = Sodium.crypto_sign_ed25519_sk_to_curve25519(skBox, skSign); + if (rc1 != 0 || rc2 != 0) { + return null; + } + + byte[] decrypted = new byte[ciphertext.length - SodiumConstants.SEAL_BYTES]; + int rc = Sodium.crypto_box_seal_open(decrypted, ciphertext, ciphertext.length, pkBox, skBox); + if (rc == 0) { + return decrypted; + } + return null; + } +} diff --git a/app/src/main/java/backone/cloud/call/Database.java b/app/src/main/java/backone/cloud/call/Database.java new file mode 100644 index 0000000..84428a7 --- /dev/null +++ b/app/src/main/java/backone/cloud/call/Database.java @@ -0,0 +1,164 @@ +package backone.cloud.call; + +import org.json.JSONArray; +import org.json.JSONException; +import org.json.JSONObject; + +import java.io.IOException; +import java.nio.charset.Charset; +import java.nio.charset.StandardCharsets; +import java.util.ArrayList; +import java.util.Arrays; + + +class Database { + Settings settings; + final ArrayList contacts; + static String version = "3.0.3"; // current version + + Database() { + this.contacts = new ArrayList<>(); + this.settings = new Settings(); + } + + public void addContact(Contact contact) { + int idx = findContact(contact.getPublicKey()); + if (idx >= 0) { + // contact exists - replace + this.contacts.set(idx, contact); + } else { + this.contacts.add(contact); + } + } + + public void deleteContact(byte[] publicKey) { + int idx = this.findContact(publicKey); + if (idx >= 0) { + this.contacts.remove(idx); + } + } + + public int findContact(byte[] publicKey) { + for (int i = 0; i < this.contacts.size(); i += 1) { + if (Arrays.equals(this.contacts.get(i).getPublicKey(), publicKey)) { + return i; + } + } + return -1; + } + + public void onDestroy() { + // zero keys from memory + if (this.settings.getSecretKey() != null) { + Arrays.fill(this.settings.getSecretKey(), (byte) 0); + } + + if (this.settings.getPublicKey() != null) { + Arrays.fill(this.settings.getPublicKey(), (byte) 0); + } + + for (Contact contact : this.contacts) { + if (contact.getPublicKey() != null) { + Arrays.fill(contact.getPublicKey(), (byte) 0); + } + } + } + + public static Database load(String path, String password) throws IOException, JSONException { + // read database file + byte[] data = Utils.readExternalFile(path); + + // encrypt database + if (password != null && password.length() > 0) { + data = Crypto.decryptDatabase(data, password.getBytes()); + + if (data == null) { + throw new IOException("wrong database password."); + } + } + + JSONObject obj = new JSONObject( + new String(data, StandardCharsets.UTF_8) + ); + + boolean upgraded = upgradeDatabase(obj.getString("version"), Database.version, obj); + Database db = Database.fromJSON(obj); + + if (upgraded) { + log("store updated database"); + Database.store(path, db, password); + } + + return db; + } + + public static void store(String path, Database db, String password) throws IOException, JSONException { + JSONObject obj = Database.toJSON(db); + byte[] data = obj.toString().getBytes(); + + // encrypt database + if (password != null && password.length() > 0) { + data = Crypto.encryptDatabase(data, password.getBytes()); + } + + // write database file + Utils.writeExternalFile(path, data); + } + + private static boolean upgradeDatabase(String from, String to, JSONObject obj) throws JSONException { + if (from.equals(to)) { + return false; + } + + log("upgrade database from " + from + " to " + to); + + // 3.0.2 => 3.0.3 + if (from.equals("3.0.2")) { + // nothing to do + from = "3.0.3"; + } + + obj.put("version", from); + + return true; + } + + public static JSONObject toJSON(Database db) throws JSONException { + JSONObject obj = new JSONObject(); + obj.put("version", version); + obj.put("settings", Settings.exportJSON(db.settings)); + + JSONArray contacts = new JSONArray(); + for (Contact contact : db.contacts) { + contacts.put(Contact.exportJSON(contact, true)); + } + obj.put("contacts", contacts); + + return obj; + } + + public static Database fromJSON(JSONObject obj) throws JSONException { + Database db = new Database(); + + // import version + version = obj.getString("version"); + + // import contacts + JSONArray array = obj.getJSONArray("contacts"); + for (int i = 0; i < array.length(); i += 1) { + db.contacts.add( + Contact.importJSON(array.getJSONObject(i), true) + ); + } + + // import settings + JSONObject settings = obj.getJSONObject("settings"); + db.settings = Settings.importJSON(settings); + + return db; + } + + private static void log(String s) { + Log.d("Database", s); + } +} diff --git a/app/src/main/java/backone/cloud/call/DefaultObserver.java b/app/src/main/java/backone/cloud/call/DefaultObserver.java new file mode 100644 index 0000000..9c8c41f --- /dev/null +++ b/app/src/main/java/backone/cloud/call/DefaultObserver.java @@ -0,0 +1,65 @@ +package backone.cloud.call; + +import org.webrtc.DataChannel; +import org.webrtc.IceCandidate; +import org.webrtc.MediaStream; +import org.webrtc.PeerConnection; +import org.webrtc.RtpReceiver; + + +class DefaultObserver implements PeerConnection.Observer { + @Override + public void onSignalingChange(PeerConnection.SignalingState signalingState) { + + } + + @Override + public void onIceConnectionChange(PeerConnection.IceConnectionState iceConnectionState) { + + } + + @Override + public void onIceConnectionReceivingChange(boolean b) { + + } + + @Override + public void onIceGatheringChange(PeerConnection.IceGatheringState iceGatheringState) { + + } + + @Override + public void onIceCandidate(IceCandidate iceCandidate) { + + } + + @Override + public void onIceCandidatesRemoved(IceCandidate[] iceCandidates) { + + } + + @Override + public void onAddStream(MediaStream mediaStream) { + + } + + @Override + public void onRemoveStream(MediaStream mediaStream) { + + } + + @Override + public void onDataChannel(DataChannel dataChannel) { + + } + + @Override + public void onRenegotiationNeeded() { + + } + + @Override + public void onAddTrack(RtpReceiver rtpReceiver, MediaStream[] mediaStreams) { + + } +} diff --git a/app/src/main/java/backone/cloud/call/DefaultSdpObserver.java b/app/src/main/java/backone/cloud/call/DefaultSdpObserver.java new file mode 100644 index 0000000..61a81c7 --- /dev/null +++ b/app/src/main/java/backone/cloud/call/DefaultSdpObserver.java @@ -0,0 +1,27 @@ +package backone.cloud.call; + +import org.webrtc.SdpObserver; +import org.webrtc.SessionDescription; + + +class DefaultSdpObserver implements SdpObserver { + @Override + public void onCreateSuccess(SessionDescription sessionDescription) { + // nothing to do + } + + @Override + public void onSetSuccess() { + // nothing to do + } + + @Override + public void onCreateFailure(String s) { + // nothing to do + } + + @Override + public void onSetFailure(String s) { + // nothing to do + } +} diff --git a/app/src/main/java/backone/cloud/call/EventListAdapter.java b/app/src/main/java/backone/cloud/call/EventListAdapter.java new file mode 100644 index 0000000..e2b42ae --- /dev/null +++ b/app/src/main/java/backone/cloud/call/EventListAdapter.java @@ -0,0 +1,124 @@ +package backone.cloud.call; + +import android.content.Context; +import androidx.annotation.NonNull; +import androidx.annotation.Nullable; +import android.text.format.DateUtils; +import android.view.LayoutInflater; +import android.view.View; +import android.view.ViewGroup; +import android.widget.ArrayAdapter; +import android.widget.ImageView; +import android.widget.TextView; + +import java.text.SimpleDateFormat; +import java.util.Arrays; +import java.util.List; + + +class EventListAdapter extends ArrayAdapter { + private final LayoutInflater inflater; + private List events; + private List contacts; + private final Context context; + + public EventListAdapter(@NonNull Context context, int resource, List events, List contacts) { + super(context, resource, events); + + this.events = events; + this.contacts = contacts; + this.context = context; + + inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE); + } + + public void update(List events, List contacts) { + this.events = events; + this.contacts = contacts; + } + + @Override + public int getCount() { + return events.size(); + } + + @Override + public CallEvent getItem(int position) { + return events.get(position); + } + + @Override + public long getItemId(int position) { + return 0; + } + + @NonNull + @Override + public View getView(int position, @Nullable View view, @NonNull ViewGroup parent) { + // show list in reverse, latest element first + CallEvent event = this.events.get(this.events.size() - position - 1); + + if (view == null) { + view = inflater.inflate(R.layout.item_event, null); + } + + // find name + String name = ""; + for (Contact contact : this.contacts) { + if (Arrays.equals(contact.getPublicKey(), event.pubKey)) { + name = contact.getName(); + break; + } + } + + TextView name_tv = view.findViewById(R.id.call_name); + if (name.isEmpty()) { + name_tv.setText(this.context.getResources().getString(R.string.unknown_caller)); + } else { + name_tv.setText(name); + } + + TextView date_tv = view.findViewById(R.id.call_date); + if (DateUtils.isToday(event.date.getTime())) { + SimpleDateFormat ft = new SimpleDateFormat("'Today at' hh:mm:ss"); + date_tv.setText(ft.format(event.date)); + } else { + SimpleDateFormat ft = new SimpleDateFormat("yyyy.MM.dd 'at' hh:mm:ss"); + date_tv.setText(ft.format(event.date)); + } + + ImageView type_iv = view.findViewById(R.id.call_type); + switch (event.type) { + case INCOMING_ACCEPTED: + case INCOMING_DECLINED: + type_iv.setImageResource(R.drawable.call_incoming); + break; + case INCOMING_UNKNOWN: + case INCOMING_MISSED: + case INCOMING_ERROR: + type_iv.setImageResource(R.drawable.call_incoming_missed); + break; + case OUTGOING_ACCEPTED: + case OUTGOING_DECLINED: + type_iv.setImageResource(R.drawable.call_outgoing); + break; + case OUTGOING_UNKNOWN: + case OUTGOING_MISSED: + case OUTGOING_ERROR: + type_iv.setImageResource(R.drawable.call_outgoing_missed); + break; + } + + TextView address_tv = view.findViewById(R.id.call_address); + if (event.address != null) { + address_tv.setText("(" + event.address.getHostAddress() + ")"); + } else { + address_tv.setText(""); + } + return view; + } + + private static void log(String s) { + Log.d(EventListAdapter.class.getSimpleName(), s); + } +} diff --git a/app/src/main/java/backone/cloud/call/EventListFragment.java b/app/src/main/java/backone/cloud/call/EventListFragment.java new file mode 100644 index 0000000..f8a11fb --- /dev/null +++ b/app/src/main/java/backone/cloud/call/EventListFragment.java @@ -0,0 +1,201 @@ +package backone.cloud.call; + +import android.app.Dialog; +import android.content.Intent; +import android.content.res.Resources; +import android.os.Bundle; +import android.os.Handler; +import androidx.annotation.Nullable; +import com.google.android.material.floatingactionbutton.FloatingActionButton; +import androidx.fragment.app.Fragment; +import androidx.appcompat.widget.PopupMenu; +import android.view.LayoutInflater; +import android.view.MenuItem; +import android.view.View; +import android.view.ViewGroup; +import android.widget.AdapterView; +import android.widget.Button; +import android.widget.EditText; +import android.widget.ListView; +import android.widget.Toast; + +import java.net.InetSocketAddress; +import java.util.Arrays; +import java.util.Collections; +import java.util.List; + +import static android.os.Looper.getMainLooper; + + +public class EventListFragment extends Fragment implements AdapterView.OnItemClickListener { + private MainActivity mainActivity; + private ListView eventListView; + private EventListAdapter eventListAdapter; + + @Nullable + @Override + public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { + View view = inflater.inflate(R.layout.fragment_event_list, container, false); + mainActivity = (MainActivity) getActivity(); + + eventListView = view.findViewById(R.id.eventList); + FloatingActionButton fabDelete = view.findViewById(R.id.fabDelete); + fabDelete.setOnClickListener(v -> { + mainActivity.binder.clearEvents(); + refreshEventList(); + }); + + eventListAdapter = new EventListAdapter(mainActivity, R.layout.item_event, Collections.emptyList(), Collections.emptyList()); + eventListView.setAdapter(eventListAdapter); + eventListView.setOnItemClickListener(this); + + return view; + } + + void refreshEventList() { + log("refreshEventList"); + if (this.mainActivity == null || this.mainActivity.binder == null) { + log("refreshEventList early return"); + return; + } + + List events = EventListFragment.this.mainActivity.binder.getEventsCopy(); + List contacts = EventListFragment.this.mainActivity.binder.getContactsCopy(); + + new Handler(getMainLooper()).post(() -> { + log("refreshEventList update: " + events.size()); + eventListAdapter.update(events, contacts); + eventListAdapter.notifyDataSetChanged(); + eventListView.setAdapter(eventListAdapter); + + eventListView.setOnItemLongClickListener((AdapterView adapterView, View view, int i, long l) -> { + CallEvent event = events.get(i); + PopupMenu menu = new PopupMenu(EventListFragment.this.mainActivity, view); + Resources res = getResources(); + String add = res.getString(R.string.add); + String block = res.getString(R.string.block); + String unblock = res.getString(R.string.unblock); + String qr = "QR-ify"; + Contact contact = EventListFragment.this.mainActivity.binder.getContactByPublicKey(event.pubKey); + + // allow to add unknown caller + if (contact == null) { + menu.getMenu().add(add); + } + + // we can only block/unblock contacts + // (or we need to need maintain a separate bocklist) + if (contact != null) { + if (contact.getBlocked()) { + menu.getMenu().add(unblock); + } else { + menu.getMenu().add(block); + } + } + + menu.setOnMenuItemClickListener((MenuItem menuItem) -> { + String title = menuItem.getTitle().toString(); + if (title.equals(add)) { + showAddDialog(event); + } else if (title.equals(block)) { + setBlocked(event, true); + } else if (title.equals(unblock)) { + setBlocked(event, false); + } + return false; + }); + menu.show(); + return true; + }); + }); + } + + private void setBlocked(CallEvent event, boolean blocked) { + Contact contact = EventListFragment.this.mainActivity.binder.getContactByPublicKey(event.pubKey); + if (contact != null) { + contact.setBlocked(blocked); + mainActivity.binder.saveDatabase(); + } else { + // unknown contact + } + } + + private void showAddDialog(CallEvent event) { + log("showAddDialog"); + + Dialog dialog = new Dialog(this.mainActivity); + dialog.setContentView(R.layout.dialog_add_contact); + + EditText nameEditText = dialog.findViewById(R.id.nameEditText); + Button exitButton = dialog.findViewById(R.id.ExitButton); + Button okButton = dialog.findViewById(R.id.OkButton); + + okButton.setOnClickListener((View v) -> { + String name = nameEditText.getText().toString(); + + if (name.isEmpty()) { + Toast.makeText(this.mainActivity, R.string.contact_name_empty, Toast.LENGTH_SHORT).show(); + return; + } + + if (EventListFragment.this.mainActivity.binder.getContactByName(name) != null) { + Toast.makeText(this.mainActivity, R.string.contact_name_exists, Toast.LENGTH_LONG).show(); + return; + } + + String address = Utils.getGeneralizedAddress(event.address); + if (address.isEmpty()) { + Toast.makeText(this.mainActivity, R.string.contact_has_no_address_warning, Toast.LENGTH_LONG).show(); + return; + } + EventListFragment.this.mainActivity.binder.addContact( + new Contact(name, event.pubKey, Collections.singletonList(address)) + ); + + Toast.makeText(this.mainActivity, R.string.done, Toast.LENGTH_SHORT).show(); + + refreshEventList(); + + // close dialog + dialog.dismiss(); + }); + + exitButton.setOnClickListener((View v) -> { + dialog.dismiss(); + }); + + dialog.show(); + } + + @Override + public void onItemClick(AdapterView adapterView, View view, int i, long l) { + log("onItemClick"); + CallEvent event = this.eventListAdapter.getItem(i); + if (event == null || event.address == null) { + return; + } + + String address = Utils.getGeneralizedAddress(event.address); + if (address.isEmpty()) { + return; + } + Contact contact = new Contact("", event.pubKey, Collections.singletonList(address)); + InetSocketAddress socketAddress = Utils.parseInetSocketAddress(address, MainService.serverPort); + if (socketAddress != null) { + contact.setLastWorkingAddress(socketAddress); + } + + Intent intent = new Intent(this.mainActivity, CallActivity.class); + intent.setAction("ACTION_OUTGOING_CALL"); + intent.putExtra("EXTRA_CONTACT", contact); + startActivity(intent); + } + + public void onServiceConnected() { + refreshEventList(); + } + + private static void log(String s) { + Log.d(EventListFragment.class.getSimpleName(), s); + } +} diff --git a/app/src/main/java/backone/cloud/call/LicenseActivity.java b/app/src/main/java/backone/cloud/call/LicenseActivity.java new file mode 100644 index 0000000..bd5dbeb --- /dev/null +++ b/app/src/main/java/backone/cloud/call/LicenseActivity.java @@ -0,0 +1,40 @@ +package backone.cloud.call; + +import android.os.Bundle; +import android.view.View; +import android.widget.TextView; + +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStreamReader; + + +public class LicenseActivity extends MeshengerActivity { + + @Override + protected void onCreate(Bundle savedInstanceState) { + super.onCreate(savedInstanceState); + setContentView(R.layout.activity_license); + + setTitle(getResources().getString(R.string.menu_license)); + + // reading the license file can be slow => use a thread + new Thread(() -> { + try { + StringBuffer buffer = new StringBuffer(); + BufferedReader reader = new BufferedReader(new InputStreamReader(getAssets().open("license.txt"))); + String line; + while((line = reader.readLine()) != null) { + buffer.append(line.trim() + "\n"); + } + reader.close(); + runOnUiThread(() -> { + findViewById(R.id.licenseLoadingBar).setVisibility(View.GONE); + ((TextView)findViewById(R.id.licenceText)).setText(buffer.toString()); + }); + } catch (IOException e) { + e.printStackTrace(); + } + }).start(); + } +} diff --git a/app/src/main/java/backone/cloud/call/Log.java b/app/src/main/java/backone/cloud/call/Log.java new file mode 100644 index 0000000..01b8f20 --- /dev/null +++ b/app/src/main/java/backone/cloud/call/Log.java @@ -0,0 +1,21 @@ +package backone.cloud.call; + +/* +* Wrapper for android.util.Log to disable logging +*/ +public class Log { + private static String contextString(Object context) { + if (context instanceof String) { + return (String) context; + } else { + return context.getClass().getSimpleName(); + } + } + + public static void d(Object context, String message) { + if (BuildConfig.DEBUG) { + String tag = contextString(context); + android.util.Log.d(tag, message); + } + } +} diff --git a/app/src/main/java/backone/cloud/call/MainActivity.java b/app/src/main/java/backone/cloud/call/MainActivity.java new file mode 100644 index 0000000..782910e --- /dev/null +++ b/app/src/main/java/backone/cloud/call/MainActivity.java @@ -0,0 +1,609 @@ +package backone.cloud.call; + +import android.app.Service; +import android.content.BroadcastReceiver; +import android.content.ComponentName; +import android.content.Context; +import android.content.DialogInterface; +import android.content.Intent; +import android.content.IntentFilter; +import android.content.ServiceConnection; +import android.content.res.Resources; +import android.media.AudioManager; +import android.os.Bundle; +import android.os.Handler; +import android.os.IBinder; +import androidx.annotation.NonNull; + +import com.google.android.material.floatingactionbutton.FloatingActionButton; + +import androidx.appcompat.app.AlertDialog; +import androidx.localbroadcastmanager.content.LocalBroadcastManager; +import androidx.swiperefreshlayout.widget.SwipeRefreshLayout; + +import android.os.Looper; +import android.view.Menu; +import android.view.MenuItem; +import android.view.View; +import android.view.animation.AlphaAnimation; +import android.view.animation.AnimationSet; +import android.view.animation.TranslateAnimation; +import android.widget.AdapterView; +import android.widget.EditText; +import android.widget.ListView; +import android.widget.PopupMenu; +import android.widget.TextView; +import android.widget.Toast; + +import org.greenrobot.eventbus.EventBus; +import org.greenrobot.eventbus.Subscribe; +import org.greenrobot.eventbus.ThreadMode; +import org.json.JSONException; + +import android.net.VpnService; + +import cloud.backone.backoneconnect.BackOneConnectApplication; +import cloud.backone.backoneconnect.events.NodeStatusEvent; +import cloud.backone.backoneconnect.events.RequestNodeStatusEvent; +import cloud.backone.backoneconnect.model.Network; +import cloud.backone.backoneconnect.model.NetworkDao; +import cloud.backone.backoneconnect.service.ZeroTierOneService; +import com.zerotier.sdk.NodeStatus; + +import java.util.List; + + +// the main view with tabs +public class MainActivity extends MeshengerActivity implements ServiceConnection, AdapterView.OnItemClickListener { + private static final int MIC_PERMISSION_REQUEST_CODE = 2; + private static final long STATUS_REFRESH_INTERVAL_MS = 30_000L; + /** Ignore brief ZeroTier EVENT_OFFLINE flaps while the TUN interface is still up. */ + private static final long VPN_OFFLINE_DEBOUNCE_MS = 8_000L; + + public MainService.MainBinder binder; + private ListView contactListView; + private TextView ownStatusText; + private boolean fabExpanded = false; + private FloatingActionButton fabScan; + private FloatingActionButton fabGen; + private FloatingActionButton fab; + SwipeRefreshLayout swipeRefreshLayout; + + private boolean serviceBound = false; + private boolean activityResumed = false; + private boolean vpnOnline = false; + private final EventBus eventBus = EventBus.getDefault(); + private final Handler statusRefreshHandler = new Handler(Looper.getMainLooper()); + private final Runnable vpnOfflineRunnable = () -> { + // Only show offline after debounce if the TUN interface is really gone. + if (Utils.getFirstTunIpv4() == null) { + vpnOnline = false; + updateOwnStatusText(); + } else { + vpnOnline = true; + updateOwnStatusText(); + } + }; + private final Runnable statusRefreshRunnable = new Runnable() { + @Override + public void run() { + refreshContactStatuses(); + refreshVpnFromTunnel(); + statusRefreshHandler.postDelayed(this, STATUS_REFRESH_INTERVAL_MS); + } + }; + + @Override + public void onItemClick(AdapterView adapterView, View view, int i, long l) { + log("onItemClick"); + if (binder == null) { + return; + } + List contacts = binder.getContactsCopy(); + if (i < 0 || i >= contacts.size()) { + return; + } + Contact contact = contacts.get(i); + if (!Utils.hasMicPermission(this)) { + Utils.requestMicPermission(this, MIC_PERMISSION_REQUEST_CODE); + return; + } + Intent intent = new Intent(this, CallActivity.class); + intent.setAction("ACTION_OUTGOING_CALL"); + intent.putExtra("EXTRA_CONTACT", contact); + startActivity(intent); + } + + @Override + protected void onCreate(Bundle savedInstanceState) { + log("onCreate"); + super.onCreate(savedInstanceState); + setContentView(R.layout.activity_main); + + fab = findViewById(R.id.fab); + fabScan = findViewById(R.id.fabScan); + fabGen = findViewById(R.id.fabGenerate); + contactListView = findViewById(R.id.contactList); + ownStatusText = findViewById(R.id.ownStatusText); + swipeRefreshLayout = findViewById(R.id.swipe_refresh); + + swipeRefreshLayout.setOnRefreshListener(() -> refreshContactStatuses()); + + + fabScan.setOnClickListener(v -> startActivity(new Intent(this, QRScanActivity.class))); + fabGen.setOnClickListener(v -> startActivity(new Intent(this, QRShowActivity.class))); + fab.setOnClickListener(this::runFabAnimation); + + // ask for audio recording permissions + if (!Utils.hasMicPermission(this)) { + Utils.requestMicPermission(this, MIC_PERMISSION_REQUEST_CODE); + } + + LocalBroadcastManager.getInstance(this).registerReceiver(refreshContactListReceiver, new IntentFilter("refresh_contact_list")); + LocalBroadcastManager.getInstance(this).registerReceiver(ownStatusReceiver, new IntentFilter(MainService.ACTION_OWN_STATUS_CHANGED)); + } + + private void refreshContactStatuses() { + if (!activityResumed || binder == null) { + stopSwipeRefresh(); + return; + } + binder.checkOwnConnectivity(); + binder.pingContacts(); + eventBus.post(new RequestNodeStatusEvent()); + statusRefreshHandler.removeCallbacks(refreshTimeoutRunnable); + statusRefreshHandler.postDelayed(refreshTimeoutRunnable, 15_000L); + } + + private final Runnable refreshTimeoutRunnable = () -> stopSwipeRefresh(); + + private void stopSwipeRefresh() { + if (swipeRefreshLayout != null) { + swipeRefreshLayout.setRefreshing(false); + } + } + + private void updateOwnStatusText() { + if (ownStatusText == null || !activityResumed) { + return; + } + String signaling; + if (binder == null) { + signaling = getString(R.string.own_status_checking); + } else { + switch (binder.getOwnStatus()) { + case LISTENING: + signaling = getString(R.string.own_status_ready); + break; + case IN_CALL: + signaling = getString(R.string.own_status_in_call); + break; + case NOT_LISTENING: + signaling = getString(R.string.own_status_not_listening); + break; + default: + signaling = getString(R.string.own_status_checking); + break; + } + } + String vpn = vpnOnline + ? getString(R.string.own_status_vpn_online) + : getString(R.string.own_status_vpn_offline); + ownStatusText.setText(signaling + " · " + vpn); + } + + void refreshContactList() { + log("refreshContactList"); + if (binder == null) { + return; + } + + new Handler(getMainLooper()).post(() -> { + if (binder == null || contactListView == null) { + return; + } + List contacts = binder.getContactsCopy(); + contactListView.setAdapter(new ContactListAdapter(this, R.layout.item_contact, contacts)); + contactListView.setOnItemClickListener(this); + contactListView.setOnItemLongClickListener((AdapterView adapterView, View view, int i, long l) -> { + if (i < 0 || i >= contacts.size()) { + return true; + } + Contact contact = contacts.get(i); + PopupMenu menu = new PopupMenu(this, view); + Resources res = getResources(); + String delete = res.getString(R.string.delete); + String rename = res.getString(R.string.rename); + String block = res.getString(R.string.block); + String unblock = res.getString(R.string.unblock); + String share = res.getString(R.string.share); + String qr = "QR-ify"; + + menu.getMenu().add(delete); + menu.getMenu().add(rename); + menu.getMenu().add(share); + if (contact.getBlocked()) { + menu.getMenu().add(unblock); + } else { + menu.getMenu().add(block); + } + menu.getMenu().add(qr); + + menu.setOnMenuItemClickListener((MenuItem menuItem) -> { + String title = menuItem.getTitle().toString(); + byte[] publicKey = contact.getPublicKey(); + if (title.equals(delete)) { + showDeleteDialog(publicKey, contact.getName()); + } else if (title.equals(rename)) { + showContactEditDialog(publicKey, contact.getName()); + } else if (title.equals(share)) { + shareContact(contact); + } else if (title.equals(block)) { + setBlocked(publicKey, true); + } else if (title.equals(unblock)) { + setBlocked(publicKey, false); + } else if (title.equals(qr)) { + Intent intent = new Intent(this, QRShowActivity.class); + intent.putExtra("EXTRA_CONTACT", contact); + startActivity(intent); + } + return false; + }); + menu.show(); + return true; + }); + stopSwipeRefresh(); + }); + } + + private void showDeleteDialog(byte[] publicKey, String name) { + AlertDialog.Builder builder = new AlertDialog.Builder(this); + + builder.setTitle(R.string.confirm); + builder.setMessage(getResources().getString(R.string.contact_remove) + " " + name); + builder.setCancelable(false); // prevent key shortcut to cancel dialog + + builder.setPositiveButton(R.string.yes, (DialogInterface dialog, int id) -> { + binder.deleteContact(publicKey); + dialog.cancel(); + }); + + builder.setNegativeButton(R.string.no, (DialogInterface dialog, int id) -> { + dialog.cancel(); + }); + + // create dialog box + AlertDialog alert = builder.create(); + alert.show(); + } + + private void setBlocked(byte[] publicKey, boolean blocked) { + Contact contact = binder.getContactByPublicKey(publicKey); + if (contact != null) { + contact.setBlocked(blocked); + binder.addContact(contact); + } + } + + private void shareContact(Contact c) { + log("shareContact"); + try { + Intent intent = new Intent(Intent.ACTION_SEND); + intent.setType("text/plain"); + intent.putExtra(Intent.EXTRA_TEXT, Contact.exportJSON(c, false).toString()); + startActivity(intent); + } catch (JSONException e) { + e.printStackTrace(); + } + } + + private void showContactEditDialog(byte[] publicKey, String name) { + log("showContactEditDialog"); + EditText et = new EditText(this); + et.setText(name); + AlertDialog dialog = new AlertDialog.Builder(this) + .setTitle(R.string.contact_edit) + .setView(et) + .setNegativeButton(getResources().getString(R.string.cancel), null) + .setPositiveButton(R.string.ok, (DialogInterface dialogInterface, int i) -> { + String newName = et.getText().toString(); + if (newName.length() > 0) { + Contact contact = binder.getContactByPublicKey(publicKey); + if (contact != null) { + contact.setName(newName); + binder.addContact(contact); + } + } + }).show(); + } + + private void runFabAnimation(View fab) { + log("runFabAnimation"); + AnimationSet scanSet = new AnimationSet(this, null); + AnimationSet generateSet = new AnimationSet(this, null); + + final int distance = 200; + final int duration = 300; + TranslateAnimation scanAnimation; + TranslateAnimation generateAnimnation; + AlphaAnimation alphaAnimation; + + if (fabExpanded) { + scanAnimation = new TranslateAnimation(0, 0, -distance, 0); + generateAnimnation = new TranslateAnimation(0, 0, -distance * 2, 0); + alphaAnimation = new AlphaAnimation(1.0f, 0.0f); + ((FloatingActionButton) fab).setImageResource(R.drawable.qr_glass); + fabScan.setY(fabScan.getY() + distance); + fabGen.setY(fabGen.getY() + distance * 2); + } else { + scanAnimation = new TranslateAnimation(0, 0, distance, 0); + generateAnimnation = new TranslateAnimation(0, 0, distance * 2, 0); + alphaAnimation = new AlphaAnimation(0.0f, 1.0f); + ((FloatingActionButton) fab).setImageResource(android.R.drawable.ic_menu_close_clear_cancel); + fabScan.setY(fabScan.getY() - distance); + fabGen.setY(fabGen.getY() - distance * 2); + } + + scanSet.addAnimation(scanAnimation); + scanSet.addAnimation(alphaAnimation); + scanSet.setFillAfter(true); + + generateSet.addAnimation(generateAnimnation); + generateSet.addAnimation(alphaAnimation); + generateSet.setFillAfter(true); + + scanSet.setDuration(duration); + generateSet.setDuration(duration); + + fabScan.show(); + fabGen.show(); + + fabScan.startAnimation(scanSet); + fabGen.startAnimation(generateSet); + + fabExpanded = !fabExpanded; + } + + @Override + protected void onDestroy() { + log("onDestroy"); + activityResumed = false; + statusRefreshHandler.removeCallbacks(statusRefreshRunnable); + statusRefreshHandler.removeCallbacks(refreshTimeoutRunnable); + if (serviceBound) { + try { + unbindService(this); + } catch (IllegalArgumentException ignored) { + } + serviceBound = false; + binder = null; + } + LocalBroadcastManager.getInstance(this).unregisterReceiver(refreshContactListReceiver); + try { + LocalBroadcastManager.getInstance(this).unregisterReceiver(ownStatusReceiver); + } catch (IllegalArgumentException ignored) { + } + ((AudioManager)this.getSystemService(Context.AUDIO_SERVICE)).setSpeakerphoneOn(false); + super.onDestroy(); + } + + @Override + public void onServiceConnected(ComponentName componentName, IBinder iBinder) { + log("OnServiceConnected"); + this.binder = (MainService.MainBinder) iBinder; + this.serviceBound = true; + refreshContactList(); + updateOwnStatusText(); + refreshContactStatuses(); + } + + @Override + public void onServiceDisconnected(ComponentName componentName) { + log("OnServiceDisconnected"); + this.serviceBound = false; + this.binder = null; + updateOwnStatusText(); + } + + @Override + public boolean onOptionsItemSelected(MenuItem item) { + log("onOptionsItemSelected"); + int id = item.getItemId(); + + switch (id) { + case R.id.action_settings: { + Intent intent = new Intent(this, SettingsActivity.class); + intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP); + startActivity(intent); + break; + } + case R.id.action_backup: { + //startActivity(new Intent(this, BackupActivity.class)); + break; + } + case R.id.action_about: { + startActivity(new Intent(this, AboutActivity.class)); + break; + } + } + return super.onOptionsItemSelected(item); + } + + private final BroadcastReceiver refreshContactListReceiver = new BroadcastReceiver() { + @Override + public void onReceive(Context context, Intent intent) { + if (contactListView == null || binder == null) { + return; + } + refreshContactList(); + stopSwipeRefresh(); + } + }; + + private final BroadcastReceiver ownStatusReceiver = new BroadcastReceiver() { + @Override + public void onReceive(Context context, Intent intent) { + if (activityResumed) { + updateOwnStatusText(); + } + stopSwipeRefresh(); + } + }; + + @Subscribe(threadMode = ThreadMode.MAIN) + public void onNodeStatus(NodeStatusEvent event) { + NodeStatus status = event.getStatus(); + if (status != null && status.isOnline()) { + statusRefreshHandler.removeCallbacks(vpnOfflineRunnable); + vpnOnline = true; + // Keep own ID/QR address aligned with current TUN IPv4. + if (binder != null && binder.getSettings() != null + && Utils.syncIdentityFromTun(binder.getSettings())) { + try { + binder.saveDatabase(); + } catch (Exception e) { + e.printStackTrace(); + } + } + } else if (status != null && !status.isOnline()) { + // NodeStatus.isOnline() is planet reachability, not VpnService/TUN state. + // During/after calls it can flap OFFLINE while the system VPN key stays up. + if (Utils.getFirstTunIpv4() != null) { + statusRefreshHandler.removeCallbacks(vpnOfflineRunnable); + vpnOnline = true; + } else if (binder != null && binder.getCurrentCall() != null) { + vpnOnline = true; + } else { + statusRefreshHandler.removeCallbacks(vpnOfflineRunnable); + statusRefreshHandler.postDelayed(vpnOfflineRunnable, VPN_OFFLINE_DEBOUNCE_MS); + } + } + updateOwnStatusText(); + stopSwipeRefresh(); + } + + /** Prefer TUN presence over flaky NodeStatus for the VPN status line. */ + private void refreshVpnFromTunnel() { + if (Utils.getFirstTunIpv4() != null) { + statusRefreshHandler.removeCallbacks(vpnOfflineRunnable); + if (!vpnOnline) { + vpnOnline = true; + updateOwnStatusText(); + } + } + } + + @Override + protected void onStart() { + super.onStart(); + if (!eventBus.isRegistered(this)) { + eventBus.register(this); + } + } + + @Override + protected void onStop() { + super.onStop(); + statusRefreshHandler.removeCallbacks(statusRefreshRunnable); + if (eventBus.isRegistered(this)) { + eventBus.unregister(this); + } + } + + @Override + protected void onResume() { + log("OnResume"); + super.onResume(); + activityResumed = true; + + if (!serviceBound) { + bindService(new Intent(this, MainService.class), this, Service.BIND_AUTO_CREATE); + } else if (binder != null) { + refreshContactList(); + refreshVpnFromTunnel(); + ensureVpnServiceRunning(); + updateOwnStatusText(); + refreshContactStatuses(); + } + eventBus.post(new RequestNodeStatusEvent()); + statusRefreshHandler.removeCallbacks(statusRefreshRunnable); + statusRefreshHandler.postDelayed(statusRefreshRunnable, STATUS_REFRESH_INTERVAL_MS); + } + + /** + * After a call crash/error the process may leave ZeroTier stopped while the UI + * still thinks VPN should be up. Restart the last-activated network if TUN is gone. + */ + private void ensureVpnServiceRunning() { + if (Utils.getFirstTunIpv4() != null) { + vpnOnline = true; + return; + } + try { + if (VpnService.prepare(this) != null) { + return; + } + NetworkDao networkDao = ((BackOneConnectApplication) getApplication()) + .getDaoSession() + .getNetworkDao(); + List activated = networkDao.queryBuilder() + .where(NetworkDao.Properties.LastActivated.eq(true)) + .list(); + if (activated == null || activated.isEmpty()) { + activated = networkDao.loadAll(); + } + if (activated == null || activated.isEmpty()) { + return; + } + Network network = activated.get(0); + Intent intent = new Intent(this, ZeroTierOneService.class); + intent.putExtra(ZeroTierOneService.ZT1_NETWORK_ID, network.getNetworkId()); + intent.putExtra(ZeroTierOneService.ZT1_USE_DEFAULT_ROUTE, network.getUseDefaultRoute()); + startService(intent); + log("restarted VPN service for network " + network.getNetworkIdStr()); + } catch (Exception e) { + e.printStackTrace(); + } + } + + @Override + protected void onPause() { + log("onPause"); + activityResumed = false; + super.onPause(); + collapseFab(); + statusRefreshHandler.removeCallbacks(statusRefreshRunnable); + statusRefreshHandler.removeCallbacks(refreshTimeoutRunnable); + } + + private void collapseFab() { + if (fabExpanded) { + fab.setImageResource(R.drawable.qr_glass); + fabScan.clearAnimation(); + fabGen.clearAnimation(); + fabScan.setY(fabScan.getY() + 200); + fabGen.setY(fabGen.getY() + 200 * 2); + fabExpanded = false; + } + } + + @Override + public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) { + super.onRequestPermissionsResult(requestCode, permissions, grantResults); + if (requestCode == MIC_PERMISSION_REQUEST_CODE + && !Utils.allGranted(grantResults)) { + Toast.makeText(this, R.string.permission_mic, Toast.LENGTH_LONG).show(); + } + } + + @Override + public boolean onCreateOptionsMenu(Menu menu) { + log("onCreateOptionsMenu"); + getMenuInflater().inflate(R.menu.menu_main_activity, menu); + return true; + } + + private void log(String s) { + Log.d(this, s); + } +} diff --git a/app/src/main/java/backone/cloud/call/MainService.java b/app/src/main/java/backone/cloud/call/MainService.java new file mode 100644 index 0000000..185cae5 --- /dev/null +++ b/app/src/main/java/backone/cloud/call/MainService.java @@ -0,0 +1,841 @@ +package backone.cloud.call; + +import android.app.Service; +import android.content.Context; +import android.content.Intent; +import android.os.Binder; +import android.os.Handler; +import android.os.IBinder; +import androidx.annotation.Nullable; +import androidx.localbroadcastmanager.content.LocalBroadcastManager; +import android.widget.Toast; + +import org.json.JSONObject; +import org.libsodium.jni.Sodium; + +import java.io.File; +import java.io.IOException; +import java.net.BindException; +import java.net.InetSocketAddress; +import java.net.ServerSocket; +import java.net.Socket; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; +import java.util.concurrent.atomic.AtomicInteger; + + +public class MainService extends Service implements Runnable { + private static final int BIND_RETRY_COUNT = 3; + private static final long BIND_RETRY_DELAY_MS = 400L; + private static final int MAX_SIGNALING_CLIENTS = 8; + private static final int SIGNALING_IDLE_TIMEOUT_MS = 30_000; + public static final String ACTION_OWN_STATUS_CHANGED = "own_status_changed"; + public static final String EXTRA_OWN_STATUS = "own_status"; + + enum OwnStatus { CHECKING, LISTENING, NOT_LISTENING, IN_CALL } + + private Database db = null; + private boolean first_start = false; + private String database_path = ""; + private String database_password = ""; + + public static final int serverPort = 10001; + private ServerSocket server; + + private volatile boolean run = true; + private volatile OwnStatus ownStatus = OwnStatus.CHECKING; + private RTCCall currentCall = null; + private final AtomicInteger activeSignalingClients = new AtomicInteger(0); + + private ArrayList events = null; + + @Override + public void onCreate() { + super.onCreate(); + + this.database_path = this.getFilesDir() + "/database.bin"; + + // handle incoming connections + new Thread(this).start(); + + events = new ArrayList<>(); + } + + private void loadDatabase() { + try { + if ((new File(this.database_path)).exists()) { + // open existing database + this.db = Database.load(this.database_path, this.database_password); + this.first_start = false; + } else { + // create new database + this.db = new Database(); + this.first_start = true; + } + if (this.db != null) { + Crypto.setLegacyCompatibility(this.db.settings.getLegacyCompatibility()); + } + } catch (Exception e) { + // ignore + } + } + + private void saveDatabase() { + try { + Database.store(MainService.this.database_path, MainService.this.db, MainService.this.database_password); + } catch (Exception e) { + e.printStackTrace(); + } + } + + @Override + public void onDestroy() { + super.onDestroy(); + this.run = false; + + // The database might be null here if no correct + // database password was supplied to open it. + + if (this.db != null) { + try { + Database.store(this.database_path, this.db, this.database_password); + } catch (Exception e) { + e.printStackTrace(); + } + } + + // Notify online contacts we are going offline, then always release the listen port. + if (this.db != null && this.server != null && this.server.isBound() && !this.server.isClosed()) { + try { + byte[] ownPublicKey = this.db.settings.getPublicKey(); + byte[] ownSecretKey = this.db.settings.getSecretKey(); + String message = "{\"action\": \"status_change\", \"status\": \"offline\"}"; + + for (Contact contact : this.db.contacts) { + if (contact.getState() == Contact.State.OFFLINE) { + continue; + } + + byte[] encrypted = Crypto.encryptMessage(message, contact.getPublicKey(), ownPublicKey, ownSecretKey); + if (encrypted == null) { + continue; + } + + Socket socket = null; + try { + socket = contact.createSocket(); + if (socket == null) { + continue; + } + + PacketWriter pw = new PacketWriter(socket); + pw.writeMessage(encrypted); + socket.close(); + } catch (Exception e) { + if (socket != null) { + try { + socket.close(); + } catch (Exception ee) { + // ignore + } + } + } + } + } catch (Exception e) { + e.printStackTrace(); + } + } + + closeServerSocket(); + + if (this.db != null) { + // zero keys from memory + this.db.onDestroy(); + } + } + + private void closeServerSocket() { + ServerSocket socket = this.server; + this.server = null; + if (socket == null) { + return; + } + try { + if (!socket.isClosed()) { + socket.close(); + } + } catch (IOException e) { + e.printStackTrace(); + } + } + + private ServerSocket openServerSocket() throws IOException { + IOException lastError = null; + for (int attempt = 1; attempt <= BIND_RETRY_COUNT; attempt++) { + if (!this.run) { + return null; + } + ServerSocket candidate = null; + try { + candidate = new ServerSocket(); + candidate.setReuseAddress(true); + candidate.bind(new InetSocketAddress(serverPort)); + return candidate; + } catch (IOException e) { + if (candidate != null) { + try { + candidate.close(); + } catch (IOException ignored) { + } + } + if (!isAddressInUse(e)) { + throw e; + } + lastError = e; + log("bind port " + serverPort + " failed (attempt " + attempt + "/" + BIND_RETRY_COUNT + "): " + e.getMessage()); + if (attempt < BIND_RETRY_COUNT && this.run) { + try { + Thread.sleep(BIND_RETRY_DELAY_MS); + } catch (InterruptedException interrupted) { + Thread.currentThread().interrupt(); + return null; + } + } + } + } + throw lastError != null ? lastError : new BindException("Address already in use"); + } + + private static boolean isAddressInUse(IOException e) { + if (e instanceof BindException) { + return true; + } + String message = e.getMessage(); + return message != null && message.toUpperCase().contains("EADDRINUSE"); + } + + @Override + public int onStartCommand(Intent intent, int flags, int startId) { + // START_STICKY recreate can come back without StartActivity reloading the DB. + if (this.db == null) { + loadDatabase(); + } + return START_STICKY; + } + + private boolean isActiveCallSocket(Socket client) { + RTCCall call = this.currentCall; + return call != null && call.commSocket != null && call.commSocket == client; + } + + private boolean isCallInProgress() { + RTCCall call = this.currentCall; + if (call == null) { + return false; + } + // Null until the first state report — still treat as busy. + RTCCall.CallState state = call.state; + return state == null + || state == RTCCall.CallState.CONNECTING + || state == RTCCall.CallState.RINGING + || state == RTCCall.CallState.CONNECTED; + } + + private void handleClient(Socket client) { + if (this.db == null || this.db.settings == null) { + log("handleClient: database not ready"); + try { + client.close(); + } catch (IOException ignored) { + } + return; + } + + byte[] ownSecretKey = this.db.settings.getSecretKey(); + byte[] ownPublicKey = this.db.settings.getPublicKey(); + byte[] clientPublicKey = new byte[Sodium.crypto_sign_publickeybytes()]; + boolean handedOff = false; + + try { + PacketWriter pw = new PacketWriter(client); + PacketReader pr = new PacketReader(client); + Contact contact = null; + + InetSocketAddress remote_address = (InetSocketAddress) client.getRemoteSocketAddress(); + log("incoming connection from " + remote_address); + + while (true) { + byte[] request = pr.readMessage(); + if (request == null) { + break; + } + + String decrypted = Crypto.decryptMessage(request, clientPublicKey, ownPublicKey, ownSecretKey); + if (decrypted == null) { + log("decryption failed"); + break; + } + + boolean legacyPlaintext = Crypto.isZeroKey(clientPublicKey); + + if (contact == null) { + if (!legacyPlaintext) { + for (Contact c : this.db.contacts) { + if (Arrays.equals(c.getPublicKey(), clientPublicKey)) { + contact = c; + break; + } + } + } + if (contact == null) { + contact = findContactByAddress(remote_address); + if (contact != null && Crypto.isValidSignPublicKey(contact.getPublicKey())) { + System.arraycopy( + contact.getPublicKey(), 0, + clientPublicKey, 0, + Math.min(contact.getPublicKey().length, clientPublicKey.length) + ); + } + } + + // Ignore blocked/unknown peers without touching the active call. + if (contact == null && this.db.settings.getBlockUnknown()) { + log("block unknown contact => ignore"); + break; + } + + if (contact != null && contact.getBlocked()) { + log("blocked contact => ignore"); + break; + } + + if (contact == null) { + // unknown caller (allowed only when block_unknown is off) + contact = new Contact("", clientPublicKey.clone(), new ArrayList<>()); + } + } + + // suspicious change of identity during connection (skip for legacy plaintext) + if (!legacyPlaintext && !Arrays.equals(contact.getPublicKey(), clientPublicKey)) { + log("suspicious change of key"); + continue; + } + + // remember last good address (the outgoing port is random and not the server port) + contact.setLastWorkingAddress( + new InetSocketAddress(remote_address.getAddress(), MainService.serverPort) + ); + + JSONObject obj = new JSONObject(decrypted); + String action = obj.optString("action", ""); + + switch (action) { + case "call": { + // Reject while busy — do not overwrite or hang up the active call. + if (isCallInProgress()) { + log("busy — rejecting incoming call"); + byte[] dismissed = Crypto.encryptMessage( + "{\"action\":\"dismissed\"}", + contact.getPublicKey(), ownPublicKey, ownSecretKey + ); + if (dismissed != null) { + pw.writeMessage(dismissed); + } + return; + } + + log("call..."); + String offer = obj.getString("offer"); + this.currentCall = new RTCCall(this, new MainBinder(), contact, client, offer); + updateOwnStatus(resolveOwnStatus()); + + byte[] encrypted = Crypto.encryptMessage("{\"action\":\"ringing\"}", contact.getPublicKey(), ownPublicKey, ownSecretKey); + pw.writeMessage(encrypted); + + // keep socket open for answer/hangup; clear idle timeout for the call + client.setSoTimeout(0); + try { + client.setKeepAlive(true); + } catch (Exception e) { + e.printStackTrace(); + } + + Intent intent = new Intent(this, CallActivity.class); + intent.setAction("ACTION_INCOMING_CALL"); + intent.putExtra("EXTRA_CONTACT", contact); + intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); + startActivity(intent); + handedOff = true; + return; + } + case "ping": { + log("ping..."); + setClientState(contact, Contact.State.ONLINE); + + byte[] encrypted = Crypto.encryptMessage("{\"action\":\"pong\"}", contact.getPublicKey(), ownPublicKey, ownSecretKey); + pw.writeMessage(encrypted); + break; + } + case "status_change": { + if (obj.optString("status", "").equals("offline")) { + setClientState(contact, Contact.State.OFFLINE); + } else { + log("Received unknown status_change: " + obj.getString("status")); + } + } + } + } + + log("client disconnected"); + // Only the active call socket should finish CallActivity. + if (isActiveCallSocket(client)) { + LocalBroadcastManager.getInstance(this).sendBroadcast(new Intent("call_declined")); + } + } catch (Exception e) { + e.printStackTrace(); + log("client disconnected (exception)"); + // Decline only the call that owns this socket — not an unrelated peer. + RTCCall call = this.currentCall; + if (call != null && isActiveCallSocket(client)) { + call.decline(); + } + } finally { + Arrays.fill(clientPublicKey, (byte) 0); + if (!handedOff) { + try { + client.close(); + } catch (IOException ignored) { + } + } + } + } + + private Contact findContactByAddress(InetSocketAddress remoteAddress) { + if (remoteAddress == null || remoteAddress.getAddress() == null || this.db == null) { + return null; + } + byte[] remoteIp = remoteAddress.getAddress().getAddress(); + for (Contact contact : this.db.contacts) { + // Verified builds store TUN IPv4 bytes as public_key. + if (Utils.isIpv4IdentityKey(contact.getPublicKey()) + && Arrays.equals(contact.getPublicKey(), remoteIp)) { + return contact; + } + if (contact.getLastWorkingAddress() != null + && remoteAddress.getAddress().equals(contact.getLastWorkingAddress().getAddress())) { + return contact; + } + for (InetSocketAddress addr : contact.getAllSocketAddresses()) { + if (addr != null && addr.getAddress() != null + && remoteAddress.getAddress().equals(addr.getAddress())) { + return contact; + } + } + } + return null; + } + + private void setClientState(Contact contact, Contact.State state) { + if (contact == null || state == null) { + return; + } + contact.setState(state); + LocalBroadcastManager.getInstance(this).sendBroadcast(new Intent("refresh_contact_list")); + } + + @Override + public void run() { + try { + // wait until database is ready + while (this.db == null && this.run) { + try { + Thread.sleep(1000); + } catch (Exception e) { + break; + } + } + + // Service was destroyed while waiting — do not bind and leak the port. + if (!this.run) { + return; + } + + try { + server = openServerSocket(); + } catch (IOException e) { + if (!isAddressInUse(e)) { + throw e; + } + e.printStackTrace(); + // Keep the service alive for DB/settings UI; incoming calls need a free port. + updateOwnStatus(OwnStatus.NOT_LISTENING); + new Handler(getMainLooper()).post(() -> Toast.makeText( + this, + "Port " + serverPort + " in use — close other Bachot/Meshenger instances", + Toast.LENGTH_LONG + ).show()); + return; + } + + if (server == null || !this.run) { + closeServerSocket(); + return; + } + + updateOwnStatus(OwnStatus.LISTENING); + + while (this.run) { + try { + Socket socket = server.accept(); + if (activeSignalingClients.get() >= MAX_SIGNALING_CLIENTS) { + log("rejecting connection: too many signaling clients"); + try { + socket.close(); + } catch (IOException ignored) { + } + continue; + } + activeSignalingClients.incrementAndGet(); + new Thread(() -> { + try { + socket.setSoTimeout(SIGNALING_IDLE_TIMEOUT_MS); + handleClient(socket); + } catch (Exception e) { + e.printStackTrace(); + } finally { + activeSignalingClients.decrementAndGet(); + } + }).start(); + } catch (IOException e) { + // ignore (including close during shutdown) + } + } + } catch (IOException e) { + e.printStackTrace(); + new Handler(getMainLooper()).post(() -> Toast.makeText(this, e.getMessage(), Toast.LENGTH_LONG).show()); + } finally { + closeServerSocket(); + } + } + + private void updateOwnStatus(OwnStatus status) { + if (status == null || this.ownStatus == status) { + return; + } + this.ownStatus = status; + Intent intent = new Intent(ACTION_OWN_STATUS_CHANGED); + intent.putExtra(EXTRA_OWN_STATUS, status.name()); + LocalBroadcastManager.getInstance(this).sendBroadcast(intent); + } + + private OwnStatus resolveOwnStatus() { + if (isCallInProgress()) { + return OwnStatus.IN_CALL; + } + return probeOwnConnectivity(); + } + + private OwnStatus probeOwnConnectivity() { + ServerSocket socket = this.server; + if (socket != null && socket.isBound() && !socket.isClosed()) { + return OwnStatus.LISTENING; + } + return OwnStatus.NOT_LISTENING; + } + + private void setContactsPending() { + if (this.db == null) { + return; + } + for (Contact contact : this.db.contacts) { + contact.setState(Contact.State.PENDING); + } + LocalBroadcastManager.getInstance(this).sendBroadcast(new Intent("refresh_contact_list")); + } + + /* + * Allows communication between MainService and other objects + */ + class MainBinder extends Binder { + RTCCall getCurrentCall() { + return currentCall; + } + + void clearCurrentCall(RTCCall call) { + if (call != null && currentCall == call) { + currentCall = null; + updateOwnStatus(resolveOwnStatus()); + } + } + + void setCurrentCall(RTCCall call) { + currentCall = call; + updateOwnStatus(resolveOwnStatus()); + } + + boolean isFirstStart() { + return MainService.this.first_start; + } + + Contact getContactByPublicKey(byte[] pubKey) { + if (MainService.this.db == null) { + return null; + } + for (Contact contact : MainService.this.db.contacts) { + if (Arrays.equals(contact.getPublicKey(), pubKey)) { + return contact; + } + } + return null; + } + + Contact getContactByName(String name) { + if (MainService.this.db == null) { + return null; + } + for (Contact contact : MainService.this.db.contacts) { + if (contact.getName().equals(name)) { + return contact; + } + } + return null; + } + + void addContact(Contact contact) { + db.addContact(contact); + saveDatabase(); + LocalBroadcastManager.getInstance(MainService.this).sendBroadcast(new Intent("refresh_contact_list")); + } + + void deleteContact(byte[] pubKey) { + db.deleteContact(pubKey); + saveDatabase(); + LocalBroadcastManager.getInstance(MainService.this).sendBroadcast(new Intent("refresh_contact_list")); + } + + void shutdown() { + MainService.this.stopSelf(); + } + + String getDatabasePassword() { + return MainService.this.database_password; + } + + void setDatabasePassword(String password) { + MainService.this.database_password = password; + } + + Database getDatabase() { + return MainService.this.db; + } + + void loadDatabase() { + MainService.this.loadDatabase(); + } + + void replaceDatabase(Database db) { + if (db != null) { + if (MainService.this.db == null) { + MainService.this.db = db; + } else { + MainService.this.db = db; + saveDatabase(); + } + } + } + + void pingContacts() { + if (MainService.this.db == null || getSettings() == null) { + checkOwnConnectivity(); + return; + } + setContactsPending(); + new Thread(new PingRunnable( + MainService.this, + getContactsCopy(), + getSettings() != null ? getSettings().getPublicKey() : null, + getSettings() != null ? getSettings().getSecretKey() : null) + ).start(); + } + + void checkOwnConnectivity() { + new Thread(() -> updateOwnStatus(resolveOwnStatus())).start(); + } + + OwnStatus getOwnStatus() { + return resolveOwnStatus(); + } + + boolean isSignalingReady() { + if (MainService.this.db == null) { + return false; + } + OwnStatus status = resolveOwnStatus(); + return status == OwnStatus.LISTENING || status == OwnStatus.IN_CALL; + } + + void saveDatabase() { + MainService.this.saveDatabase(); + } + + Settings getSettings() { + if (MainService.this.db == null) { + return null; + } + return MainService.this.db.settings; + } + + // return a cloned list + List getContactsCopy() { + if (MainService.this.db == null) { + return new ArrayList<>(); + } + return new ArrayList<>(MainService.this.db.contacts); + } + + void addCallEvent(Contact contact, CallEvent.Type type) { + InetSocketAddress last_working = contact.getLastWorkingAddress(); + MainService.this.events.add(new CallEvent( + contact.getPublicKey(), + (last_working != null) ? last_working.getAddress() : null, + type + )); + LocalBroadcastManager.getInstance(MainService.this).sendBroadcast(new Intent("refresh_event_list")); + } + + // return a cloned list + List getEventsCopy() { + return new ArrayList<>(MainService.this.events); + } + + void clearEvents() { + MainService.this.events.clear(); + LocalBroadcastManager.getInstance(MainService.this).sendBroadcast(new Intent("refresh_event_list")); + } + } + + class PingRunnable implements Runnable { + final Context context; + private final List contacts; + final byte[] ownPublicKey; + final byte[] ownSecretKey; + final MainBinder binder; + + PingRunnable(Context context, List contacts, byte[] ownPublicKey, byte[] ownSecretKey) { + this.context = context; + this.contacts = contacts; + this.ownPublicKey = ownPublicKey; + this.ownSecretKey = ownSecretKey; + this.binder = new MainBinder(); + } + + private void setState(byte[] publicKey, Contact.State state) { + Contact contact = this.binder.getContactByPublicKey(publicKey); + if (contact != null) { + contact.setState(state); + // Refresh immediately so green/online shows as soon as ping connects. + LocalBroadcastManager.getInstance(context).sendBroadcast(new Intent("refresh_contact_list")); + } + } + + @Override + public void run() { + // IP-as-key identity uses a null secretKey (legacy plaintext). Do not bail — + // that left contacts stuck in PENDING after setContactsPending(). + if (ownPublicKey == null) { + for (Contact contact : contacts) { + setState(contact.getPublicKey(), Contact.State.OFFLINE); + } + updateOwnStatus(resolveOwnStatus()); + LocalBroadcastManager.getInstance(context).sendBroadcast(new Intent("refresh_contact_list")); + return; + } + + for (Contact contact : contacts) { + Socket socket = null; + byte[] publicKey = contact.getPublicKey(); + try { + + socket = contact.createSocket(); + if (socket == null) { + setState(publicKey, Contact.State.OFFLINE); + continue; + } + + PacketWriter pw = new PacketWriter(socket); + PacketReader pr = new PacketReader(socket); + + log("send ping to " + contact.getName()); + + byte[] encrypted = Crypto.encryptMessage("{\"action\":\"ping\"}", publicKey, ownPublicKey, ownSecretKey); + if (encrypted == null) { + setState(publicKey, Contact.State.OFFLINE); + socket.close(); + continue; + } + + pw.writeMessage(encrypted); + + byte[] request = pr.readMessage(); + if (request == null) { + setState(publicKey, Contact.State.OFFLINE); + socket.close(); + continue; + } + + byte[] senderPublicKey = new byte[Sodium.crypto_sign_publickeybytes()]; + String decrypted = Crypto.decryptMessage(request, senderPublicKey, ownPublicKey, ownSecretKey); + if (decrypted == null) { + log("decryption failed"); + setState(publicKey, Contact.State.OFFLINE); + socket.close(); + continue; + } + if (!Crypto.isZeroKey(senderPublicKey) && !Arrays.equals(publicKey, senderPublicKey)) { + log("pubkey mismatch on pong"); + setState(publicKey, Contact.State.OFFLINE); + socket.close(); + continue; + } + + JSONObject obj = new JSONObject(decrypted); + String action = obj.optString("action", ""); + if (action.equals("pong")) { + log("got pong"); + setState(publicKey, Contact.State.ONLINE); + } else { + setState(publicKey, Contact.State.OFFLINE); + } + + socket.close(); + } catch (Exception e) { + setState(publicKey, Contact.State.OFFLINE); + if (socket != null) { + try { + socket.close(); + } catch (Exception ee) { + // ignore + } + } + e.printStackTrace(); + } + } + + updateOwnStatus(resolveOwnStatus()); + log("send refresh_contact_list"); + LocalBroadcastManager.getInstance(context).sendBroadcast(new Intent("refresh_contact_list")); + } + } + + + @Nullable + @Override + public IBinder onBind(Intent intent) { + return new MainBinder(); + } + + private void log(String data) { + Log.d(this, data); + } +} diff --git a/app/src/main/java/backone/cloud/call/MeshengerActivity.java b/app/src/main/java/backone/cloud/call/MeshengerActivity.java new file mode 100644 index 0000000..bad2765 --- /dev/null +++ b/app/src/main/java/backone/cloud/call/MeshengerActivity.java @@ -0,0 +1,39 @@ +package backone.cloud.call; + +import android.os.Bundle; +import androidx.annotation.Nullable; +import androidx.appcompat.app.AppCompatActivity; +import androidx.appcompat.app.AppCompatDelegate; + + +/* + * Activity base class to apply night mode +*/ +public class MeshengerActivity extends AppCompatActivity { + boolean dark_active; // dark mode + + @Override + protected void onCreate(@Nullable Bundle savedInstanceState) { + super.onCreate(savedInstanceState); + + dark_active = darkModeEnabled(); + setTheme(dark_active ? R.style.AppTheme_Dark : R.style.AppTheme_Light); + } + + private boolean darkModeEnabled() { + return (AppCompatDelegate.getDefaultNightMode() == AppCompatDelegate.MODE_NIGHT_YES); + } + + @Override + protected void onResume() { + super.onResume(); + + // recreate acitivity to apply mode + boolean dark_active_now = darkModeEnabled(); + if (dark_active != dark_active_now) { + dark_active = dark_active_now; + recreate(); + } + } +} + diff --git a/app/src/main/java/backone/cloud/call/PacketReader.java b/app/src/main/java/backone/cloud/call/PacketReader.java new file mode 100644 index 0000000..b01747e --- /dev/null +++ b/app/src/main/java/backone/cloud/call/PacketReader.java @@ -0,0 +1,66 @@ +package backone.cloud.call; + +import java.io.IOException; +import java.io.InputStream; +import java.net.Socket; + + +/* Read the message size from the header and return the message of the correct size */ +class PacketReader { + // SDP offers with ICE candidates + crypto seal easily exceed 12KB. + static final int MAX_PAYLOAD_BYTES = 64_000; + + final InputStream is; + final byte[] buffer; + int pos; + + PacketReader(Socket socket) throws IOException { + this.is = socket.getInputStream(); + this.buffer = new byte[MAX_PAYLOAD_BYTES + 4]; + this.pos = 0; + } + + private static int readMessageHeader(byte[] packet) { + return ((packet[0] & 0xFF) << 24) + | ((packet[1] & 0xFF) << 16) + | ((packet[2] & 0xFF) << 8) + | ((packet[3] & 0xFF) << 0); + } + + byte[] readMessage() throws IOException { + while (true) { + int read = is.read(buffer, pos, buffer.length - pos); + if (read < 0) { + break; + } + + pos += read; + + if (pos < 4) { + continue; + } + + int len = readMessageHeader(buffer); + if (len < 0 || len > MAX_PAYLOAD_BYTES) { + break; + } + + // not enough data + if (pos < (4 + len)) { + continue; + } + + byte[] request = new byte[len]; + System.arraycopy(buffer, 4, request, 0, request.length); + + int remaining = pos - (4 + len); + if (remaining > 0) { + System.arraycopy(buffer, 4 + len, buffer, 0, remaining); + } + pos = remaining; + return request; + } + + return null; + } +} diff --git a/app/src/main/java/backone/cloud/call/PacketWriter.java b/app/src/main/java/backone/cloud/call/PacketWriter.java new file mode 100644 index 0000000..520e188 --- /dev/null +++ b/app/src/main/java/backone/cloud/call/PacketWriter.java @@ -0,0 +1,42 @@ +package backone.cloud.call; + +import java.io.IOException; +import java.io.OutputStream; +import java.net.Socket; + + +/* Write the message header before the message is send */ +class PacketWriter { + final OutputStream os; + final byte[] header; + + public PacketWriter(Socket socket) throws IOException { + this.os = socket.getOutputStream(); + this.header = new byte[4]; + } + + private static void writeMessageHeader(byte[] packet, int value) { + packet[0] = (byte) ((value >> 24) & 0xff); + packet[1] = (byte) ((value >> 16) & 0xff); + packet[2] = (byte) ((value >> 8) & 0xff); + packet[3] = (byte) ((value >> 0) & 0xff); + } + + public void writeMessage(byte[] message) throws IOException { + if (message == null) { + throw new IOException("signaling message is null"); + } + if (message.length > PacketReader.MAX_PAYLOAD_BYTES) { + throw new IOException("signaling message too large: " + message.length + + " > " + PacketReader.MAX_PAYLOAD_BYTES); + } + writeMessageHeader(this.header, message.length); + // need to concatenate? + this.os.write(this.header); + this.os.write(message); + } + + private void log(String s) { + Log.d(this, s); + } +} diff --git a/app/src/main/java/backone/cloud/call/QRScanActivity.java b/app/src/main/java/backone/cloud/call/QRScanActivity.java new file mode 100644 index 0000000..6d45671 --- /dev/null +++ b/app/src/main/java/backone/cloud/call/QRScanActivity.java @@ -0,0 +1,280 @@ +package backone.cloud.call; + +import android.app.AlertDialog; +import android.app.Dialog; +import android.app.Service; +import android.content.ComponentName; +import android.content.Intent; +import android.content.ServiceConnection; +import android.content.pm.PackageManager; +import android.os.IBinder; +import androidx.annotation.NonNull; +import android.os.Bundle; +import android.view.View; +import android.view.WindowManager; +import android.widget.Button; +import android.widget.EditText; +import android.widget.TextView; +import android.widget.Toast; + +import com.google.zxing.BarcodeFormat; +import com.google.zxing.ResultPoint; +import com.journeyapps.barcodescanner.BarcodeCallback; +import com.journeyapps.barcodescanner.BarcodeResult; +import com.journeyapps.barcodescanner.DecoratedBarcodeView; +import com.journeyapps.barcodescanner.DefaultDecoderFactory; + +import org.json.JSONException; +import org.json.JSONObject; + +import java.util.Collection; +import java.util.Collections; +import java.util.List; + + +public class QRScanActivity extends MeshengerActivity implements BarcodeCallback, ServiceConnection { + private DecoratedBarcodeView barcodeView; + private MainService.MainBinder binder; + + @Override + protected void onCreate(Bundle savedInstanceState) { + super.onCreate(savedInstanceState); + + getWindow().addFlags(WindowManager.LayoutParams.FLAG_SECURE); + setContentView(R.layout.activity_qrscan); + setTitle(getString(R.string.scan_invited)); + + bindService(new Intent(this, MainService.class), this, Service.BIND_AUTO_CREATE); + + if (!Utils.hasCameraPermission(this)) { + Utils.requestCameraPermission(this, 1); + } + + // qr show button + findViewById(R.id.fabScan).setOnClickListener(view -> { + startActivity(new Intent(this, QRShowActivity.class)); + finish(); + }); + + // manual input button + findViewById(R.id.fabManualInput).setOnClickListener(view -> { + startManualInput(); + }); + } + + private void addContact(String data) throws JSONException { + if (binder == null) { + Toast.makeText(this, R.string.invalid_data, Toast.LENGTH_SHORT).show(); + return; + } + JSONObject object = new JSONObject(data); + Contact new_contact = Contact.importJSON(object, false); + + if (new_contact.getAddresses().isEmpty()) { + Toast.makeText(this, R.string.contact_has_no_address_warning, Toast.LENGTH_LONG).show(); + } + + // lookup existing contacts by key and name + Contact existing_pubkey_contact = binder.getContactByPublicKey(new_contact.getPublicKey()); + Contact existing_name_contact = binder.getContactByName(new_contact.getName()); + + if (existing_pubkey_contact != null) { + // contact with that public key exists + showPubkeyConflictDialog(new_contact, existing_pubkey_contact); + } else if (existing_name_contact != null) { + // contact with that name exists + showNameConflictDialog(new_contact, existing_name_contact); + } else { + // no conflict + binder.addContact(new_contact); + finish(); + } + } + + private void showPubkeyConflictDialog(Contact new_contact, Contact other_contact) { + Dialog dialog = new Dialog(this); + dialog.setContentView(R.layout.dialog_add_contact_pubkey_conflict); + + TextView nameTextView = dialog.findViewById(R.id.NameTextView); + Button abortButton = dialog.findViewById(R.id.AbortButton); + Button replaceButton = dialog.findViewById(R.id.ReplaceButton); + + nameTextView.setText(other_contact.getName()); + + replaceButton.setOnClickListener((View v) -> { + QRScanActivity.this.binder.deleteContact(other_contact.getPublicKey()); + QRScanActivity.this.binder.addContact(new_contact); + + // done + Toast.makeText(QRScanActivity.this, R.string.done, Toast.LENGTH_SHORT).show(); + + dialog.cancel(); + QRScanActivity.this.finish(); + }); + + abortButton.setOnClickListener((View v) -> { + dialog.cancel(); + barcodeView.resume(); + }); + + dialog.show(); + } + + private void showNameConflictDialog(Contact new_contact, Contact other_contact) { + Dialog dialog = new Dialog(this); + dialog.setContentView(R.layout.dialog_add_contact_name_conflict); + + EditText nameEditText = dialog.findViewById(R.id.NameEditText); + Button abortButton = dialog.findViewById(R.id.AbortButton); + Button replaceButton = dialog.findViewById(R.id.ReplaceButton); + Button renameButton = dialog.findViewById(R.id.RenameButton); + + nameEditText.setText(other_contact.getName()); + + replaceButton.setOnClickListener((View v) -> { + QRScanActivity.this.binder.deleteContact(other_contact.getPublicKey()); + QRScanActivity.this.binder.addContact(new_contact); + + // done + Toast.makeText(QRScanActivity.this, R.string.done, Toast.LENGTH_SHORT).show(); + + dialog.cancel(); + QRScanActivity.this.finish(); + }); + + renameButton.setOnClickListener((View v) -> { + String name = nameEditText.getText().toString(); + + if (name.isEmpty()) { + Toast.makeText(this, R.string.contact_name_empty, Toast.LENGTH_SHORT).show(); + return; + } + + if (QRScanActivity.this.binder.getContactByName(name) != null) { + Toast.makeText(this, R.string.contact_name_exists, Toast.LENGTH_SHORT).show(); + return; + } + + // rename + new_contact.setName(name); + QRScanActivity.this.binder.addContact(new_contact); + + // done + Toast.makeText(QRScanActivity.this, R.string.done, Toast.LENGTH_SHORT).show(); + + dialog.cancel(); + QRScanActivity.this.finish(); + }); + + abortButton.setOnClickListener((View v) -> { + dialog.cancel(); + barcodeView.resume(); + }); + + dialog.show(); + } + + private void startManualInput() { + barcodeView.pause(); + AlertDialog.Builder b = new AlertDialog.Builder(this); + EditText et = new EditText(this); + b.setTitle(R.string.paste_invitation) + .setPositiveButton(R.string.ok, (dialogInterface, i) -> { + try { + String data = et.getText().toString(); + addContact(data); + } catch (JSONException e) { + e.printStackTrace(); + Toast.makeText(this, R.string.invalid_data, Toast.LENGTH_SHORT).show(); + } + }) + .setNegativeButton(R.string.cancel, (dialog, i) -> { + dialog.cancel(); + barcodeView.resume(); + }) + .setView(et); + b.show(); + } + + @Override + public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) { + super.onRequestPermissionsResult(requestCode, permissions, grantResults); + + if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) { + initCamera(); + } else { + Toast.makeText(this, R.string.camera_permission_request, Toast.LENGTH_LONG).show(); + finish(); + } + } + + @Override + public void barcodeResult(BarcodeResult result) { + // no more scan until result is processed + barcodeView.pause(); + + try { + String data = result.getText(); + addContact(data); + } catch (JSONException e) { + e.printStackTrace(); + Toast.makeText(this, R.string.invalid_qr, Toast.LENGTH_LONG).show(); + } + } + + @Override + public void possibleResultPoints(List resultPoints) { + // ignore + } + + @Override + protected void onResume() { + super.onResume(); + + if (barcodeView != null && binder != null) { + barcodeView.resume(); + } + } + + @Override + protected void onPause() { + super.onPause(); + + if (barcodeView != null && binder != null) { + barcodeView.pause(); + } + } + + @Override + protected void onDestroy() { + super.onDestroy(); + unbindService(this); + } + + private void initCamera() { + barcodeView = findViewById(R.id.barcodeScannerView); + + Collection formats = Collections.singletonList(BarcodeFormat.QR_CODE); + barcodeView.getBarcodeView().setDecoderFactory(new DefaultDecoderFactory(formats)); + barcodeView.decodeContinuous(this); + barcodeView.resume(); + } + + @Override + public void onServiceConnected(ComponentName componentName, IBinder iBinder) { + this.binder = (MainService.MainBinder) iBinder; + + if (Utils.hasCameraPermission(this)) { + initCamera(); + } + } + + @Override + public void onServiceDisconnected(ComponentName componentName) { + binder = null; + } + + private void log(String s) { + Log.d(this, s); + } +} diff --git a/app/src/main/java/backone/cloud/call/QRShowActivity.java b/app/src/main/java/backone/cloud/call/QRShowActivity.java new file mode 100644 index 0000000..341fcb7 --- /dev/null +++ b/app/src/main/java/backone/cloud/call/QRShowActivity.java @@ -0,0 +1,126 @@ +package backone.cloud.call; + +import android.app.Service; +import android.content.BroadcastReceiver; +import android.content.ComponentName; +import android.content.Context; +import android.content.Intent; +import android.content.ServiceConnection; +import android.graphics.Bitmap; +import android.os.IBinder; +import android.os.Bundle; +import android.view.View; +import android.view.ViewGroup; +import android.view.WindowManager; +import android.widget.ImageView; +import android.widget.RelativeLayout; +import android.widget.Toast; + +import com.google.zxing.BarcodeFormat; +import com.google.zxing.MultiFormatWriter; +import com.google.zxing.common.BitMatrix; +import com.journeyapps.barcodescanner.BarcodeEncoder; + + +public class QRShowActivity extends MeshengerActivity implements ServiceConnection { + private Contact contact = null; + private MainService.MainBinder binder; + + @Override + protected void onCreate(Bundle savedInstanceState) { + super.onCreate(savedInstanceState); + getWindow().addFlags(WindowManager.LayoutParams.FLAG_SECURE); + setContentView(R.layout.activity_qrshow); + + if (getIntent().hasExtra("EXTRA_CONTACT")) { + this.contact = (Contact) getIntent().getExtras().get("EXTRA_CONTACT"); + findViewById(R.id.fabPresenter).setVisibility(View.GONE); + RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT); + params.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM, RelativeLayout.TRUE); + params.addRule(RelativeLayout.ALIGN_PARENT_END, RelativeLayout.TRUE); + params.bottomMargin = params.rightMargin = 80; + findViewById(R.id.fabShare).setLayoutParams(params); + } + + setTitle(getString(R.string.scan_invitation)); + bindService(); + + findViewById(R.id.fabPresenter).setOnClickListener(view -> { + startActivity(new Intent(this, QRScanActivity.class)); + finish(); + }); + + findViewById(R.id.fabShare).setOnClickListener(view -> { + if (this.contact != null) try { + String data = Contact.exportJSON(this.contact, false).toString(); + Intent i = new Intent(Intent.ACTION_SEND); + i.putExtra(Intent.EXTRA_TEXT, data); + i.setType("text/plain"); + startActivity(i); + finish(); + } catch (Exception e) { + // ignore + } + }); + } + + @Override + protected void onDestroy() { + super.onDestroy(); + if (this.binder != null) { + unbindService(this); + } + } + + private void bindService() { + Intent serviceIntent = new Intent(this, MainService.class); + bindService(serviceIntent, this, Service.BIND_AUTO_CREATE); + } + + private void generateQR() throws Exception { + if (this.contact == null) { + // export own contact + this.contact = this.binder.getSettings().getOwnContact(); + } + + String data = Contact.exportJSON(this.contact, false).toString(); + MultiFormatWriter multiFormatWriter = new MultiFormatWriter(); + BitMatrix bitMatrix = multiFormatWriter.encode(data, BarcodeFormat.QR_CODE, 1080, 1080); + BarcodeEncoder barcodeEncoder = new BarcodeEncoder(); + Bitmap bitmap = barcodeEncoder.createBitmap(bitMatrix); + ((ImageView) findViewById(R.id.QRView)).setImageBitmap(bitmap); + + if (this.contact.getAddresses().isEmpty()) { + Toast.makeText(this, R.string.contact_has_no_address_warning, Toast.LENGTH_SHORT).show(); + } + } + + @Override + public void onServiceConnected(ComponentName componentName, IBinder iBinder) { + this.binder = (MainService.MainBinder) iBinder; + + try { + generateQR(); + } catch (Exception e) { + e.printStackTrace(); + Toast.makeText(this, e.getMessage(), Toast.LENGTH_LONG).show(); + finish(); + } + } + + @Override + public void onServiceDisconnected(ComponentName componentName) { + this.binder = null; + } + + private final BroadcastReceiver receiver = new BroadcastReceiver() { + @Override + public void onReceive(Context context, Intent intent) { + finish(); + } + }; + + private static void log(String s) { + Log.d(QRShowActivity.class.getSimpleName(), s); + } +} diff --git a/app/src/main/java/backone/cloud/call/RTCCall.java b/app/src/main/java/backone/cloud/call/RTCCall.java new file mode 100644 index 0000000..c0c5b97 --- /dev/null +++ b/app/src/main/java/backone/cloud/call/RTCCall.java @@ -0,0 +1,1182 @@ +package backone.cloud.call; + +import static android.content.ContentValues.TAG; + +import android.Manifest; +import android.content.Context; +import android.content.Intent; +import android.content.pm.PackageManager; +import android.content.res.Resources; +import android.graphics.Color; +import android.os.Handler; +import android.os.Looper; +import androidx.annotation.ColorInt; +import androidx.annotation.Nullable; +import androidx.core.content.ContextCompat; +import androidx.localbroadcastmanager.content.LocalBroadcastManager; +import android.util.TypedValue; +import android.view.View; + +import org.json.JSONException; +import org.json.JSONObject; +import org.libsodium.jni.Sodium; +import org.webrtc.AudioTrack; +import org.webrtc.Camera1Enumerator; +import org.webrtc.CameraEnumerator; +import org.webrtc.CameraVideoCapturer; +import org.webrtc.DataChannel; +import org.webrtc.EglBase; +import org.webrtc.Logging; +import org.webrtc.MediaConstraints; +import org.webrtc.MediaStream; +import org.webrtc.PeerConnection; +import org.webrtc.PeerConnectionFactory; +import org.webrtc.RTCStatsCollectorCallback; +import org.webrtc.SessionDescription; +import org.webrtc.SoftwareVideoDecoderFactory; +import org.webrtc.SoftwareVideoEncoderFactory; +import org.webrtc.SurfaceTextureHelper; +import org.webrtc.SurfaceViewRenderer; +import org.webrtc.VideoFrame; +import org.webrtc.VideoSink; +import org.webrtc.VideoSource; +import org.webrtc.VideoTrack; + +import java.io.IOException; +import java.net.InetSocketAddress; +import java.net.Socket; +import java.nio.ByteBuffer; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.ScheduledExecutorService; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicBoolean; + + +public class RTCCall implements DataChannel.Observer { + private static final long ICE_GATHER_TIMEOUT_MS = 8_000L; + private static final AtomicBoolean sFactoryInitialized = new AtomicBoolean(false); + + enum CallState { CONNECTING, RINGING, CONNECTED, DISMISSED, ENDED, ERROR } + + private final String StateChangeMessage = "StateChange"; + private final String CameraDisabledMessage = "CameraDisabled"; + private final String CameraEnabledMessage = "CameraEnabled"; + + private PeerConnectionFactory factory; + private PeerConnection connection; + + private MediaConstraints constraints; + + private String offer; + + private EglBase rootEglBase; + + private SurfaceViewRenderer remoteRenderer; + private SurfaceViewRenderer localRenderer; + private CameraVideoCapturer capturer; + private VideoTrack localVideoTrack; + + private MediaStream upStream; + private DataChannel dataChannel; + + private boolean speakerEnabled; + private boolean videoEnabled; + private boolean remoteRendererInitialized; + private boolean localRendererInitialized; + + private final Context context; + private final Contact contact; + private final byte[] ownPublicKey; + private final byte[] ownSecretKey; + private final List iceServers; + private OnStateChangeListener listener; + private final MainService.MainBinder binder; + private ScheduledExecutorService statsExecutor; + private final AtomicBoolean cleanedUp = new AtomicBoolean(false); + /** All PeerConnectionFactory / PeerConnection work must stay on one thread. */ + private final ExecutorService webrtcExecutor = Executors.newSingleThreadExecutor(r -> { + Thread t = new Thread(r, "webrtc-call"); + t.setDaemon(true); + return t; + }); + + public CallState state; + public Socket commSocket; + + static public RTCCall startCall(Context context, MainService.MainBinder binder, Contact contact, OnStateChangeListener listener) { + if (binder == null || binder.getSettings() == null) { + return null; + } + return new RTCCall(context, binder, contact, listener); + } + + // called for incoming calls + public RTCCall(Context context, MainService.MainBinder binder, Contact contact, Socket commSocket, String offer) { + this.context = context.getApplicationContext(); + this.contact = contact; + this.commSocket = commSocket; + this.listener = null; + this.binder = binder; + Settings settings = binder != null ? binder.getSettings() : null; + if (settings == null) { + this.ownPublicKey = new byte[0]; + this.ownSecretKey = new byte[0]; + this.iceServers = buildIceServers(null); + return; + } + this.ownPublicKey = settings.getPublicKey(); + this.ownSecretKey = settings.getSecretKey(); + this.offer = offer; + + this.iceServers = buildIceServers(settings.getIceServers()); + + // Defer WebRTC init to the call executor — factory must be used on the thread that created it. + this.state = CallState.RINGING; + startIncomingRingMonitor(); + } + + // called for outgoing calls + private RTCCall(Context context, MainService.MainBinder binder, Contact contact, OnStateChangeListener listener) { + this.context = context.getApplicationContext(); + this.contact = contact; + this.commSocket = null; + this.listener = listener; + this.binder = binder; + Settings settings = binder.getSettings(); + this.ownPublicKey = settings.getPublicKey(); + this.ownSecretKey = settings.getSecretKey(); + + log("RTCCall created"); + + this.iceServers = buildIceServers(settings.getIceServers()); + + // Register early so inbound calls are rejected as busy while we dial. + if (this.binder != null) { + this.binder.setCurrentCall(this); + } + } + + public void startOutgoingSignaling() { + webrtcExecutor.execute(() -> { + try { + initRTC(this.context); + final AtomicBoolean offerSent = new AtomicBoolean(false); + PeerConnection.RTCConfiguration config = new PeerConnection.RTCConfiguration(this.iceServers); + config.continualGatheringPolicy = PeerConnection.ContinualGatheringPolicy.GATHER_ONCE; + // Prefer host/relay on VPN overlay; avoid aggressive IPv6 probes that crash some devices. + config.sdpSemantics = PeerConnection.SdpSemantics.PLAN_B; + config.tcpCandidatePolicy = PeerConnection.TcpCandidatePolicy.DISABLED; + + connection = factory.createPeerConnection(config, new DefaultObserver() { + @Override + public void onIceGatheringChange(PeerConnection.IceGatheringState iceGatheringState) { + super.onIceGatheringChange(iceGatheringState); + if (iceGatheringState == PeerConnection.IceGatheringState.COMPLETE) { + webrtcExecutor.execute(() -> transferOutgoingOffer(offerSent)); + } + } + + @Override + public void onIceConnectionChange(PeerConnection.IceConnectionState iceConnectionState) { + log("onIceConnectionChange " + iceConnectionState.name()); + super.onIceConnectionChange(iceConnectionState); + if (iceConnectionState == PeerConnection.IceConnectionState.DISCONNECTED + && RTCCall.this.state == CallState.CONNECTED) { + reportStateChange(CallState.ENDED); + } + } + + @Override + public void onAddStream(MediaStream mediaStream) { + super.onAddStream(mediaStream); + handleMediaStream(mediaStream); + } + + @Override + public void onDataChannel(DataChannel dataChannel) { + super.onDataChannel(dataChannel); + RTCCall.this.dataChannel = dataChannel; + dataChannel.registerObserver(RTCCall.this); + } + }); + + if (connection == null || cleanedUp.get()) { + reportStateChange(CallState.ERROR); + return; + } + + connection.addStream(createStream()); + this.dataChannel = connection.createDataChannel("data", new DataChannel.Init()); + this.dataChannel.registerObserver(this); + connection.createOffer(new DefaultSdpObserver() { + @Override + public void onCreateSuccess(SessionDescription sessionDescription) { + super.onCreateSuccess(sessionDescription); + webrtcExecutor.execute(() -> { + if (connection == null || cleanedUp.get()) { + return; + } + connection.setLocalDescription(new DefaultSdpObserver(), sessionDescription); + scheduleIceGatherTimeout(() -> + webrtcExecutor.execute(() -> transferOutgoingOffer(offerSent)) + ); + }); + } + + @Override + public void onCreateFailure(String s) { + super.onCreateFailure(s); + log("createOffer failed: " + s); + reportStateChange(CallState.ERROR); + } + }, constraints); + } catch (Throwable t) { + t.printStackTrace(); + log("startOutgoingSignaling crashed: " + t.getMessage()); + reportStateChange(CallState.ERROR); + } + }); + } + + private void scheduleIceGatherTimeout(Runnable onTimeout) { + Executors.newSingleThreadScheduledExecutor().schedule(() -> { + try { + onTimeout.run(); + } catch (Exception e) { + e.printStackTrace(); + } + }, ICE_GATHER_TIMEOUT_MS, TimeUnit.MILLISECONDS); + } + + private void transferOutgoingOffer(AtomicBoolean offerSent) { + if (!offerSent.compareAndSet(false, true)) { + return; + } + if (connection == null || connection.getLocalDescription() == null) { + reportStateChange(CallState.ERROR); + return; + } + + log("transferring offer..."); + try { + commSocket = contact.createSocket(); + if (commSocket == null) { + log("cannot establish connection"); + reportStateChange(CallState.ERROR); + return; + } + // Keep the signaling TCP alive while waiting through long ring times. + try { + commSocket.setKeepAlive(true); + commSocket.setSoTimeout(0); + } catch (Exception e) { + e.printStackTrace(); + } + if (this.binder != null) { + this.binder.setCurrentCall(this); + } + InetSocketAddress remoteAddress = (InetSocketAddress) commSocket.getRemoteSocketAddress(); + byte[] otherPublicKey = new byte[Sodium.crypto_sign_publickeybytes()]; + log("outgoing call from remote address: " + remoteAddress); + + contact.setLastWorkingAddress( + new InetSocketAddress(remoteAddress.getAddress(), MainService.serverPort) + ); + + PacketReader pr = new PacketReader(commSocket); + reportStateChange(CallState.CONNECTING); + + { + JSONObject obj = new JSONObject(); + obj.put("action", "call"); + obj.put("offer", connection.getLocalDescription().description); + byte[] encrypted = Crypto.encryptMessage(obj.toString(), contact.getPublicKey(), ownPublicKey, ownSecretKey); + if (encrypted == null) { + log("encrypt failed for call offer"); + closeCommSocket(); + reportStateChange(CallState.ERROR); + return; + } + PacketWriter pw = new PacketWriter(commSocket); + pw.writeMessage(encrypted); + } + + { + byte[] response = pr.readMessage(); + if (response == null) { + log("no ringing reply (socket closed while connecting)"); + closeCommSocket(); + reportStateChange(CallState.ERROR); + return; + } + String decrypted = Crypto.decryptMessage(response, otherPublicKey, ownPublicKey, ownSecretKey); + if (decrypted == null) { + log("ringing decrypt failed"); + closeCommSocket(); + reportStateChange(CallState.ERROR); + return; + } + // Secure peers must match contact key; legacy plaintext leaves key zeroed. + if (!Crypto.isZeroKey(otherPublicKey) && !Arrays.equals(contact.getPublicKey(), otherPublicKey)) { + log("ringing pubkey mismatch"); + closeCommSocket(); + reportStateChange(CallState.ERROR); + return; + } + JSONObject obj = new JSONObject(decrypted); + if (!obj.optString("action", "").equals("ringing")) { + log("action not equals ringing"); + closeCommSocket(); + reportStateChange(CallState.ERROR); + return; + } + log("ringing..."); + reportStateChange(CallState.RINGING); + } + + { + byte[] response = pr.readMessage(); + if (response == null) { + // Peer hung up, declined via close, or path dropped while ringing. + log("no answer (socket closed while ringing)"); + closeCommSocket(); + reportStateChange(CallState.DISMISSED); + return; + } + String decrypted = Crypto.decryptMessage(response, otherPublicKey, ownPublicKey, ownSecretKey); + if (decrypted == null) { + log("answer decrypt failed"); + closeCommSocket(); + reportStateChange(CallState.ERROR); + return; + } + if (!Crypto.isZeroKey(otherPublicKey) && !Arrays.equals(contact.getPublicKey(), otherPublicKey)) { + log("answer pubkey mismatch"); + closeCommSocket(); + reportStateChange(CallState.ERROR); + return; + } + + JSONObject obj = new JSONObject(decrypted); + String action = obj.getString("action"); + if (action.equals("connected")) { + reportStateChange(CallState.CONNECTED); + handleAnswer(obj.getString("answer")); + } else if (action.equals("dismissed")) { + log("dismissed"); + closeCommSocket(); + reportStateChange(CallState.DISMISSED); + } else { + log("unknown action reply: " + action); + closeCommSocket(); + reportStateChange(CallState.ERROR); + } + } + } catch (Exception e) { + closeCommSocket(); + e.printStackTrace(); + reportStateChange(CallState.ERROR); + } + } + + private void closeCommSocket() { + log("closeCommSocket"); + if (this.commSocket != null) { + try { + this.commSocket.close(); + } catch (Exception e) { + e.printStackTrace(); + } + this.commSocket = null; + } + } + + private void closePeerConnection() { + log("closePeerConnection"); + if (this.connection != null) { + try { + this.connection.close(); + } catch (Exception e) { + e.printStackTrace(); + } + this.connection = null; + } + } + + public void setRemoteRenderer(SurfaceViewRenderer remoteRenderer) { + this.remoteRenderer = remoteRenderer; + } + + public void setLocalRenderer(SurfaceViewRenderer localRenderer) { + this.localRenderer = localRenderer; + localRender.setTarget(localRenderer); + } + + public void switchFrontFacing() { + if (this.capturer != null) { + this.capturer.switchCamera(null); + } + } + + @Override + public void onBufferedAmountChange(long l) { + // nothing to do + } + + @Override + public void onStateChange() { + // nothing to do + } + + @Override + public void onMessage(DataChannel.Buffer buffer) { + byte[] data = new byte[buffer.data.remaining()]; + buffer.data.get(data); + String s = new String(data); + JSONObject object = null; + try { + log("onMessage: " + s); + object = new JSONObject(s); + if (object.has(StateChangeMessage)) { + String state = object.getString(StateChangeMessage); + switch (state) { + case CameraEnabledMessage: + case CameraDisabledMessage: { + setRemoteVideoEnabled(state.equals(CameraEnabledMessage)); + break; + } + } + } + } catch (JSONException e) { + e.printStackTrace(); + } + + } + + private void setRemoteVideoEnabled(boolean enabled) { + new Handler(Looper.getMainLooper()).post(() -> { + if (this.remoteRenderer == null) { + return; + } + if (enabled) { + this.remoteRenderer.setBackgroundColor(Color.TRANSPARENT); + } else { + TypedValue typedValue = new TypedValue(); + Resources.Theme theme = this.context.getTheme(); + theme.resolveAttribute(R.attr.backgroundCardColor, typedValue, true); + @ColorInt int color = typedValue.data; + this.remoteRenderer.setBackgroundColor(color); + } + }); + } + + public boolean isSpeakerEnabled(){ + return this.speakerEnabled; + } + + public boolean isVideoEnabled(){ + return this.videoEnabled; + } + + public void setSpeakerEnabled(boolean enabled) { + this.speakerEnabled = enabled; + } + + public void setVideoEnabled(boolean enabled) { + try { + if (enabled) { + if (!hasCameraPermission()) { + log("setVideoEnabled: camera permission missing"); + return; + } + if (this.capturer == null && !ensureLocalVideoTrack()) { + log("setVideoEnabled: cannot create camera"); + return; + } + this.videoEnabled = true; + this.capturer.startCapture(640, 480, 15); + if (localVideoTrack != null) { + localVideoTrack.setEnabled(true); + } + new Handler(Looper.getMainLooper()).post(() -> { + if (this.localRenderer != null) { + this.localRenderer.setVisibility(View.VISIBLE); + this.localRenderer.setZOrderOnTop(true); + } + }); + } else { + this.videoEnabled = false; + new Handler(Looper.getMainLooper()).post(() -> { + if (this.localRenderer != null) { + this.localRenderer.setVisibility(View.GONE); + } + }); + if (this.capturer != null) { + this.capturer.stopCapture(); + } + if (localVideoTrack != null) { + localVideoTrack.setEnabled(false); + } + } + JSONObject object = new JSONObject(); + object.put(StateChangeMessage, enabled ? CameraEnabledMessage : CameraDisabledMessage); + log("setVideoEnabled: " + object); + if (dataChannel != null && dataChannel.state() == DataChannel.State.OPEN) { + dataChannel.send(new DataChannel.Buffer(ByteBuffer.wrap(object.toString().getBytes()), false)); + } + } catch (Exception e) { + e.printStackTrace(); + this.videoEnabled = false; + } + } + + public void releaseCamera() { + stopCapturerQuietly(); + localRender.setTarget(null); + Runnable release = () -> { + releaseRenderer(this.remoteRenderer); + this.remoteRenderer = null; + this.remoteRendererInitialized = false; + releaseRenderer(this.localRenderer); + this.localRenderer = null; + this.localRendererInitialized = false; + }; + if (Looper.myLooper() == Looper.getMainLooper()) { + release.run(); + } else { + new Handler(Looper.getMainLooper()).post(release); + } + } + + private void releaseRenderer(@Nullable SurfaceViewRenderer renderer) { + if (renderer == null) { + return; + } + try { + renderer.release(); + } catch (Exception e) { + e.printStackTrace(); + } + } + + private void stopCapturerQuietly() { + if (this.capturer == null) { + return; + } + try { + this.capturer.stopCapture(); + } catch (Exception e) { + e.printStackTrace(); + } + try { + this.capturer.dispose(); + } catch (Exception e) { + e.printStackTrace(); + } + this.capturer = null; + } + + private void handleMediaStream(MediaStream stream) { + log("handleMediaStream"); + if (this.remoteRenderer == null || stream == null || stream.videoTracks.size() == 0) { + return; + } + + new Handler(Looper.getMainLooper()).post(() -> { + if (remoteRenderer == null) { + return; + } + try { + EglBase egl = ensureEglBase(); + if (!remoteRendererInitialized && egl != null) { + remoteRenderer.init(egl.getEglBaseContext(), null); + remoteRendererInitialized = true; + } + stream.videoTracks.get(0).addSink(remoteRenderer); + } catch (Exception e) { + e.printStackTrace(); + } + }); + } + + private MediaStream createStream() { + upStream = factory.createLocalMediaStream("stream1"); + AudioTrack audioTrack = getAudioTrack(); + if (audioTrack != null) { + upStream.addTrack(audioTrack); + } + // Do not open Camera1 at dial/accept time. That aborts the process on many + // devices (no permission / HAL race) and takes ZeroTier/VPN down with it. + return upStream; + } + + private boolean hasCameraPermission() { + return ContextCompat.checkSelfPermission(this.context, Manifest.permission.CAMERA) + == PackageManager.PERMISSION_GRANTED; + } + + private CameraVideoCapturer createCapturer() { + try { + CameraEnumerator enumerator = new Camera1Enumerator(); + String[] names = enumerator.getDeviceNames(); + for (String name : names) { + if (enumerator.isFrontFacing(name)) { + CameraVideoCapturer capturer = enumerator.createCapturer(name, null); + if (capturer != null) { + return capturer; + } + } + } + for (String name : names) { + CameraVideoCapturer capturer = enumerator.createCapturer(name, null); + if (capturer != null) { + return capturer; + } + } + } catch (Exception e) { + e.printStackTrace(); + } + return null; + } + + /** Lazily create camera capturer + track when the user enables video. */ + private boolean ensureLocalVideoTrack() { + if (localVideoTrack != null) { + return true; + } + if (factory == null || !hasCameraPermission()) { + return false; + } + try { + EglBase egl = ensureEglBase(); + if (egl == null) { + return false; + } + this.capturer = createCapturer(); + if (this.capturer == null) { + return false; + } + localRender.setTarget(localRenderer); + new Handler(Looper.getMainLooper()).post(() -> { + if (localRenderer != null && !localRendererInitialized && rootEglBase != null) { + try { + localRenderer.init(rootEglBase.getEglBaseContext(), null); + localRendererInitialized = true; + } catch (Exception e) { + e.printStackTrace(); + } + } + }); + SurfaceTextureHelper surfaceTextureHelper = + SurfaceTextureHelper.create("CaptureThread", egl.getEglBaseContext()); + VideoSource videoSource = factory.createVideoSource(false); + this.capturer.initialize(surfaceTextureHelper, this.context, videoSource.getCapturerObserver()); + localVideoTrack = factory.createVideoTrack("video1", videoSource); + localVideoTrack.setEnabled(false); + localVideoTrack.addSink(localRender); + if (upStream != null) { + upStream.addTrack(localVideoTrack); + } + if (connection != null) { + try { + connection.addTrack(localVideoTrack, java.util.Collections.singletonList("stream1")); + } catch (Exception e) { + e.printStackTrace(); + } + } + return true; + } catch (Exception e) { + e.printStackTrace(); + stopCapturerQuietly(); + localVideoTrack = null; + return false; + } + } + + private final ProxyVideoSink localRender = new ProxyVideoSink(); + + private static class ProxyVideoSink implements VideoSink { + private VideoSink target; + + @Override + synchronized public void onFrame(VideoFrame frame) { + if (target == null) { + Logging.d(TAG, "Dropping frame in proxy because target is null."); + return; + } + + target.onFrame(frame); + } + + synchronized public void setTarget(VideoSink target) { + this.target = target; + } + } + + private AudioTrack getAudioTrack() { + if (factory == null) { + return null; + } + return factory.createAudioTrack("audio1", factory.createAudioSource(new MediaConstraints())); + } + + private void initRTC(Context c) { + if (factory != null) { + return; + } + Context app = c.getApplicationContext(); + if (sFactoryInitialized.compareAndSet(false, true)) { + PeerConnectionFactory.initialize( + PeerConnectionFactory.InitializationOptions.builder(app) + .createInitializationOptions() + ); + } + // Software codecs only at dial time — HW + EGL encoder factory aborts on many devices + // during "Memanggil" and kills ZeroTier in the same process. + factory = PeerConnectionFactory.builder() + .setVideoEncoderFactory(new SoftwareVideoEncoderFactory()) + .setVideoDecoderFactory(new SoftwareVideoDecoderFactory()) + .createPeerConnectionFactory(); + constraints = new MediaConstraints(); + constraints.optional.add(new MediaConstraints.KeyValuePair("offerToReceiveAudio", "true")); + constraints.optional.add(new MediaConstraints.KeyValuePair("offerToReceiveVideo", "true")); + constraints.optional.add(new MediaConstraints.KeyValuePair("DtlsSrtpKeyAgreement", "true")); + } + + private EglBase ensureEglBase() { + if (rootEglBase == null) { + try { + rootEglBase = EglBase.create(); + } catch (Exception e) { + e.printStackTrace(); + } + } + return rootEglBase; + } + + private void handleAnswer(String remoteDesc) { + PeerConnection pc = this.connection; + if (pc == null || remoteDesc == null) { + reportStateChange(CallState.ERROR); + return; + } + pc.setRemoteDescription(new DefaultSdpObserver() { + @Override + public void onSetSuccess() { + super.onSetSuccess(); + log("onSetSuccess"); + } + + @Override + public void onSetFailure(String s) { + super.onSetFailure(s); + log("onSetFailure: " + s); + } + }, new SessionDescription(SessionDescription.Type.ANSWER, remoteDesc)); + } + + private void reportStateChange(CallState state) { + this.state = state; + OnStateChangeListener callback = this.listener; + if (callback == null) { + return; + } + new Handler(Looper.getMainLooper()).post(() -> { + OnStateChangeListener active = this.listener; + if (active != null) { + active.OnStateChange(state); + } + }); + } + + public void setOnStateChangeListener(OnStateChangeListener listener) { + this.listener = listener; + } + + public void accept(RTCStatsCollectorCallback statsCollector) { + if (statsCollector == null) { + return; + } + stopStats(); + statsExecutor = Executors.newSingleThreadScheduledExecutor(); + statsExecutor.scheduleAtFixedRate(() -> { + PeerConnection pc = this.connection; + if (pc != null) { + try { + pc.getStats(statsCollector); + } catch (Exception e) { + e.printStackTrace(); + } + } + }, 1, 5, TimeUnit.SECONDS); + } + + private void stopStats() { + ScheduledExecutorService executor = this.statsExecutor; + this.statsExecutor = null; + if (executor != null) { + executor.shutdownNow(); + } + } + + private static List buildIceServers(List urls) { + List servers = new ArrayList<>(); + if (urls != null) { + for (String server : urls) { + if (server == null) { + continue; + } + String trimmed = server.trim(); + if (trimmed.isEmpty()) { + continue; + } + try { + servers.add(PeerConnection.IceServer.builder(trimmed).createIceServer()); + } catch (Exception e) { + // Invalid ICE URL — skip rather than crash call setup. + } + } + } + if (servers.isEmpty()) { + servers.add(PeerConnection.IceServer.builder(Settings.DEFAULT_ICE_SERVER).createIceServer()); + } + return servers; + } + + public void accept(OnStateChangeListener listener) { + this.listener = listener; + // Leave RINGING so the ring monitor stops reading the signaling socket. + reportStateChange(CallState.CONNECTING); + webrtcExecutor.execute(() -> { + try { + initRTC(this.context); + final AtomicBoolean answerSent = new AtomicBoolean(false); + PeerConnection.RTCConfiguration config = new PeerConnection.RTCConfiguration(this.iceServers); + config.continualGatheringPolicy = PeerConnection.ContinualGatheringPolicy.GATHER_ONCE; + config.sdpSemantics = PeerConnection.SdpSemantics.PLAN_B; + config.tcpCandidatePolicy = PeerConnection.TcpCandidatePolicy.DISABLED; + + connection = factory.createPeerConnection(config, new DefaultObserver() { + @Override + public void onIceGatheringChange(PeerConnection.IceGatheringState iceGatheringState) { + super.onIceGatheringChange(iceGatheringState); + if (iceGatheringState == PeerConnection.IceGatheringState.COMPLETE) { + webrtcExecutor.execute(() -> transferIncomingAnswer(answerSent)); + } + } + + @Override + public void onIceConnectionChange(PeerConnection.IceConnectionState iceConnectionState) { + log("onIceConnectionChange"); + super.onIceConnectionChange(iceConnectionState); + if (iceConnectionState == PeerConnection.IceConnectionState.DISCONNECTED + && RTCCall.this.state == CallState.CONNECTED) { + reportStateChange(CallState.ENDED); + } + } + + @Override + public void onAddStream(MediaStream mediaStream) { + log("onAddStream"); + super.onAddStream(mediaStream); + handleMediaStream(mediaStream); + } + + @Override + public void onDataChannel(DataChannel dataChannel) { + super.onDataChannel(dataChannel); + RTCCall.this.dataChannel = dataChannel; + dataChannel.registerObserver(RTCCall.this); + } + }); + + if (connection == null || cleanedUp.get()) { + reportStateChange(CallState.ERROR); + return; + } + + connection.addStream(createStream()); + + log("setting remote description"); + connection.setRemoteDescription(new DefaultSdpObserver() { + @Override + public void onSetSuccess() { + super.onSetSuccess(); + log("creating answer..."); + webrtcExecutor.execute(() -> { + if (connection == null || cleanedUp.get()) { + return; + } + connection.createAnswer(new DefaultSdpObserver() { + @Override + public void onCreateSuccess(SessionDescription sessionDescription) { + log("onCreateSuccess"); + super.onCreateSuccess(sessionDescription); + webrtcExecutor.execute(() -> { + if (connection == null || cleanedUp.get()) { + return; + } + connection.setLocalDescription(new DefaultSdpObserver(), sessionDescription); + scheduleIceGatherTimeout(() -> + webrtcExecutor.execute(() -> transferIncomingAnswer(answerSent)) + ); + }); + } + + @Override + public void onCreateFailure(String s) { + super.onCreateFailure(s); + log("onCreateFailure: " + s); + reportStateChange(CallState.ERROR); + } + }, constraints); + }); + } + + @Override + public void onSetFailure(String s) { + super.onSetFailure(s); + log("setRemoteDescription failed: " + s); + reportStateChange(CallState.ERROR); + } + }, new SessionDescription(SessionDescription.Type.OFFER, offer)); + } catch (Throwable t) { + t.printStackTrace(); + log("accept crashed: " + t.getMessage()); + reportStateChange(CallState.ERROR); + } + }); + } + + private void transferIncomingAnswer(AtomicBoolean answerSent) { + if (!answerSent.compareAndSet(false, true)) { + return; + } + if (connection == null || connection.getLocalDescription() == null) { + reportStateChange(CallState.ERROR); + return; + } + + log("transferring answer..."); + try { + PacketWriter pw = new PacketWriter(commSocket); + JSONObject obj = new JSONObject(); + obj.put("action", "connected"); + obj.put("answer", connection.getLocalDescription().description); + byte[] encrypted = Crypto.encryptMessage(obj.toString(), contact.getPublicKey(), ownPublicKey, ownSecretKey); + if (encrypted != null) { + pw.writeMessage(encrypted); + reportStateChange(CallState.CONNECTED); + } else { + reportStateChange(CallState.ERROR); + } + } catch (Exception e) { + e.printStackTrace(); + reportStateChange(CallState.ERROR); + } + } + + public void decline() { + new Thread(() -> { + try { + log("declining..."); + sendDismissedQuietly(); + } finally { + cleanup(); + if (this.binder != null) { + this.binder.clearCurrentCall(this); + } + reportStateChange(CallState.DISMISSED); + } + }).start(); + } + + private void sendDismissedQuietly() { + Socket socket = this.commSocket; + if (socket == null) { + return; + } + try { + try { + socket.setSoTimeout(800); + } catch (Exception ignored) { + } + PacketWriter pw = new PacketWriter(socket); + byte[] encrypted = Crypto.encryptMessage( + "{\"action\":\"dismissed\"}", + this.contact.getPublicKey(), + this.ownPublicKey, + this.ownSecretKey + ); + if (encrypted != null) { + pw.writeMessage(encrypted); + } + } catch (Exception e) { + e.printStackTrace(); + } + } + + public void cleanup() { + if (!cleanedUp.compareAndSet(false, true)) { + return; + } + stopStats(); + stopCapturerQuietly(); + closePeerConnection(); + closeCommSocket(); + disposeFactoryQuietly(); + } + + /** + * Tear down media first (safe for renderer release), optionally notify the peer. + * Safe to call from the UI thread during Activity.onDestroy. + * Idempotent with {@link #cleanup()} — never double-close the PeerConnection. + */ + public void teardown(boolean notifyPeer) { + this.listener = null; + if (!cleanedUp.compareAndSet(false, true)) { + if (this.binder != null) { + this.binder.clearCurrentCall(this); + } + return; + } + stopStats(); + stopCapturerQuietly(); + closePeerConnection(); + if (notifyPeer) { + sendDismissedQuietly(); + } + closeCommSocket(); + if (this.binder != null) { + this.binder.clearCurrentCall(this); + } + releaseCamera(); + disposeFactoryQuietly(); + } + + private void disposeFactoryQuietly() { + try { + if (factory != null) { + factory.dispose(); + } + } catch (Exception e) { + e.printStackTrace(); + } + factory = null; + localVideoTrack = null; + upStream = null; + try { + if (rootEglBase != null) { + rootEglBase.release(); + } + } catch (Exception e) { + e.printStackTrace(); + } + rootEglBase = null; + try { + webrtcExecutor.shutdownNow(); + } catch (Exception e) { + e.printStackTrace(); + } + } + + public void hangUp() { + new Thread(() -> { + sendDismissedQuietly(); + cleanup(); + if (this.binder != null) { + this.binder.clearCurrentCall(this); + } + reportStateChange(CallState.ENDED); + }).start(); + } + + /** + * After MainService hands off the call socket it stops reading. + * Watch for peer hangup/EOF while we are still ringing. + */ + private void startIncomingRingMonitor() { + new Thread(() -> { + Socket socket = this.commSocket; + if (socket == null) { + return; + } + try { + try { + socket.setSoTimeout(1_000); + } catch (Exception e) { + e.printStackTrace(); + } + PacketReader pr = new PacketReader(socket); + while (!cleanedUp.get() && this.state == CallState.RINGING) { + try { + byte[] message = pr.readMessage(); + if (message == null) { + if (this.state == CallState.RINGING) { + log("peer closed while ringing"); + LocalBroadcastManager.getInstance(context) + .sendBroadcast(new Intent("call_declined")); + cleanup(); + if (this.binder != null) { + this.binder.clearCurrentCall(this); + } + reportStateChange(CallState.DISMISSED); + } + return; + } + byte[] senderKey = new byte[Sodium.crypto_sign_publickeybytes()]; + String decrypted = Crypto.decryptMessage( + message, senderKey, ownPublicKey, ownSecretKey + ); + if (decrypted != null && decrypted.contains("\"dismissed\"")) { + log("peer dismissed while ringing"); + LocalBroadcastManager.getInstance(context) + .sendBroadcast(new Intent("call_declined")); + cleanup(); + if (this.binder != null) { + this.binder.clearCurrentCall(this); + } + reportStateChange(CallState.DISMISSED); + return; + } + } catch (java.net.SocketTimeoutException ignored) { + // keep polling until accept/decline + } + } + } catch (Exception e) { + if (this.state == CallState.RINGING && !cleanedUp.get()) { + log("ring monitor error: " + e.getMessage()); + LocalBroadcastManager.getInstance(context) + .sendBroadcast(new Intent("call_declined")); + cleanup(); + if (this.binder != null) { + this.binder.clearCurrentCall(this); + } + reportStateChange(CallState.DISMISSED); + } + } finally { + if (this.state != CallState.RINGING) { + try { + Socket s = this.commSocket; + if (s != null) { + s.setSoTimeout(0); + } + } catch (Exception ignored) { + } + } + } + }, "incoming-ring-monitor").start(); + } + + public interface OnStateChangeListener { + void OnStateChange(CallState state); + } + + private void log(String s) { + Log.d(this, s); + } +} diff --git a/app/src/main/java/backone/cloud/call/Settings.java b/app/src/main/java/backone/cloud/call/Settings.java new file mode 100644 index 0000000..76d880b --- /dev/null +++ b/app/src/main/java/backone/cloud/call/Settings.java @@ -0,0 +1,203 @@ +package backone.cloud.call; + +import org.json.JSONArray; +import org.json.JSONException; +import org.json.JSONObject; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; + + +public class Settings { + public static final String DEFAULT_ICE_SERVER = "stun:10.10.10.30:8090"; + + private String username; + private byte[] secretKey; + private byte[] publicKey; + private String language; + private boolean nightMode; + private boolean blockUnknown; + private boolean developmentMode; + /** Plaintext signaling for old Bachot builds that lack libsodium crypto. */ + private boolean legacyCompatibility; + private List addresses; + // ICE (Interactive Connectivity Establishment) servers implement STUN and TURN + private List iceServers; + + public Settings() { + this.username = ""; + this.secretKey = null; + this.publicKey = null; + this.language = ""; + this.nightMode = false; + this.blockUnknown = true; + this.developmentMode = false; + this.legacyCompatibility = true; + this.addresses = new ArrayList<>(); + this.iceServers = new ArrayList<>(Collections.singletonList(DEFAULT_ICE_SERVER)); + } + + public byte[] getSecretKey() { + return secretKey; + } + + public void setSecretKey(byte[] secretKey) { + this.secretKey = secretKey; + } + + public byte[] getPublicKey() { + return publicKey; + } + + public void setPublicKey(byte[] publicKey) { + this.publicKey = publicKey; + } + + public String getUsername() { + return username; + } + + public void setUsername(String username) { + this.username = username; + } + + public String getLanguage() { + return language; + } + + public void setLanguage(String language) { + this.language = language; + } + + public boolean getNightMode() { + return nightMode; + } + + public void setNightMode(boolean nightMode) { + this.nightMode = nightMode; + } + + public boolean getBlockUnknown() { + return blockUnknown; + } + + public void setBlockUnknown(boolean blockUnknown) { + this.blockUnknown = blockUnknown; + } + + public boolean getDevelopmentMode() { + return developmentMode; + } + + public void setDevelopmentMode(boolean developmentMode) { + this.developmentMode = developmentMode; + } + + public boolean getLegacyCompatibility() { + return legacyCompatibility; + } + + public void setLegacyCompatibility(boolean legacyCompatibility) { + this.legacyCompatibility = legacyCompatibility; + Crypto.setLegacyCompatibility(legacyCompatibility); + } + + public List getAddresses() { + return this.addresses; + } + + public void setAddresses(List addresses) { + this.addresses = addresses; + } + + public void addAddress(String address) { + for (String addr : this.getAddresses()) { + if (addr.equalsIgnoreCase(address)) { + return; + } + } + this.addresses.add(address); + } + + public List getIceServers() { + return this.iceServers; + } + + public void setIceServers(List iceServers) { + List cleaned = new ArrayList<>(); + if (iceServers != null) { + for (String server : iceServers) { + if (server == null) { + continue; + } + String trimmed = server.trim(); + if (!trimmed.isEmpty()) { + cleaned.add(trimmed); + } + } + } + if (cleaned.isEmpty()) { + cleaned.add(DEFAULT_ICE_SERVER); + } + this.iceServers = cleaned; + } + + public static Settings importJSON(JSONObject obj) throws JSONException { + Settings s = new Settings(); + s.username = obj.getString("username"); + s.secretKey = Utils.hexStringToByteArray(obj.getString("secret_key")); + s.publicKey = Utils.hexStringToByteArray(obj.getString("public_key")); + s.language = obj.getString("language"); + s.nightMode = obj.getBoolean("night_mode"); + s.blockUnknown = obj.getBoolean("block_unknown"); + s.developmentMode = obj.getBoolean("development_mode"); + // Default true so upgrades keep talking to old plaintext peers + s.legacyCompatibility = obj.optBoolean("legacy_compatibility", true); + Crypto.setLegacyCompatibility(s.legacyCompatibility); + + JSONArray addresses = obj.getJSONArray("addresses"); + for (int i = 0; i < addresses.length(); i += 1) { + s.addresses.add(addresses.getString(i)); + } + + JSONArray iceServers = obj.getJSONArray("ice_servers"); + List parsedIce = new ArrayList<>(); + for (int i = 0; i < iceServers.length(); i += 1) { + parsedIce.add(iceServers.getString(i)); + } + s.setIceServers(parsedIce); + + return s; + } + + public static JSONObject exportJSON(Settings s) throws JSONException { + JSONObject obj = new JSONObject(); + obj.put("username", s.username); + obj.put("secret_key", Utils.byteArrayToHexString(s.secretKey)); + obj.put("public_key", Utils.byteArrayToHexString(s.publicKey)); + obj.put("language", s.language); + obj.put("night_mode", s.nightMode); + obj.put("block_unknown", s.blockUnknown); + obj.put("development_mode", s.developmentMode); + obj.put("legacy_compatibility", s.legacyCompatibility); + + JSONArray addresses = new JSONArray(); + for (int i = 0; i < s.addresses.size(); i += 1) { + addresses.put(s.addresses.get(i)); + } + obj.put("addresses", addresses); + + JSONArray iceServers = new JSONArray(); + for (int i = 0; i < s.iceServers.size(); i += 1) { + iceServers.put(s.iceServers.get(i)); + } + obj.put("ice_servers", iceServers); + + return obj; + } + + public Contact getOwnContact() { + return new Contact(this.username, this.publicKey, this.addresses); + } +} diff --git a/app/src/main/java/backone/cloud/call/SettingsActivity.java b/app/src/main/java/backone/cloud/call/SettingsActivity.java new file mode 100644 index 0000000..ec5c6d9 --- /dev/null +++ b/app/src/main/java/backone/cloud/call/SettingsActivity.java @@ -0,0 +1,359 @@ +package backone.cloud.call; + +import android.app.Dialog; +import android.app.Service; +import android.content.ComponentName; +import android.content.Intent; +import android.content.ServiceConnection; +import android.content.res.Configuration; +import android.os.IBinder; +import androidx.appcompat.app.AlertDialog; +import android.os.Bundle; +import androidx.appcompat.app.AppCompatDelegate; +import android.text.InputType; +import android.view.View; +import android.view.WindowManager; +import android.widget.Button; +import android.widget.CheckBox; +import android.widget.EditText; +import android.widget.RadioButton; +import android.widget.RadioGroup; +import android.widget.TextView; +import android.widget.Toast; + +import org.greenrobot.eventbus.EventBus; +import org.greenrobot.eventbus.Subscribe; +import org.greenrobot.eventbus.ThreadMode; + +import java.util.List; +import java.util.Locale; + +import cloud.backone.backoneconnect.events.NodeStatusEvent; +import cloud.backone.backoneconnect.events.RequestNodeStatusEvent; +import cloud.backone.backoneconnect.ui.NetworkListActivity; +import com.zerotier.sdk.NodeStatus; + + +public class SettingsActivity extends MeshengerActivity implements ServiceConnection { + private MainService.MainBinder binder; + private final EventBus eventBus = EventBus.getDefault(); + + @Override + protected void onCreate(Bundle savedInstanceState) { + super.onCreate(savedInstanceState); + + setContentView(R.layout.activity_settings); + setTitle(getResources().getString(R.string.menu_settings)); + + bindService(); + initViews(); + } + + @Override + protected void onStart() { + super.onStart(); + if (!this.eventBus.isRegistered(this)) { + this.eventBus.register(this); + } + } + + @Override + protected void onStop() { + super.onStop(); + if (this.eventBus.isRegistered(this)) { + this.eventBus.unregister(this); + } + } + + @Override + protected void onDestroy() { + super.onDestroy(); + if (this.binder != null) { + unbindService(this); + } + } + + private void bindService() { + // ask MainService to get us the binder object + Intent serviceIntent = new Intent(this, MainService.class); + bindService(serviceIntent, this, Service.BIND_AUTO_CREATE); + } + + @Override + public void onServiceConnected(ComponentName componentName, IBinder iBinder) { + this.binder = (MainService.MainBinder) iBinder; + initViews(); + } + + @Override + public void onServiceDisconnected(ComponentName componentName) { + this.binder = null; + } + + private void initViews() { + if (this.binder == null) { + return; + } + + findViewById(R.id.changeNameLayout).setOnClickListener((View view) -> { + showChangeNameDialog(); + }); + + findViewById(R.id.changeAddressLayout).setOnClickListener((View view) -> { + Intent intent = new Intent(this, AddressActivity.class); + startActivity(intent); + }); + + findViewById(R.id.changePasswordLayout).setOnClickListener((View view) -> { + showChangePasswordDialog(); + }); + + findViewById(R.id.changeIceServersLayout).setOnClickListener((View view) -> { + showChangeIceServersDialog(); + }); + + findViewById(R.id.backoneNetworkLayout).setOnClickListener((View view) -> { + startActivity(new Intent(this, NetworkListActivity.class)); + }); + + String username = this.binder.getSettings().getUsername(); + ((TextView) findViewById(R.id.nameTv)).setText( + username.length() == 0 ? getResources().getString(R.string.none) : username + ); + + List addresses = this.binder.getSettings().getAddresses(); + ((TextView) findViewById(R.id.addressTv)).setText( + addresses.size() == 0 ? getResources().getString(R.string.none) : Utils.join(addresses) + ); + + String password = this.binder.getDatabasePassword(); + ((TextView) findViewById(R.id.passwordTv)).setText( + password.isEmpty() ? getResources().getString(R.string.none) : "********" + ); + + List iceServers = this.binder.getSettings().getIceServers(); + ((TextView) findViewById(R.id.iceServersTv)).setText( + iceServers.isEmpty() ? getResources().getString(R.string.none) : Utils.join(iceServers) + ); + + boolean blockUnknown = this.binder.getSettings().getBlockUnknown(); + CheckBox blockUnknownCB = findViewById(R.id.checkBoxBlockUnknown); + blockUnknownCB.setChecked(blockUnknown); + blockUnknownCB.setOnCheckedChangeListener((compoundButton, isChecked) -> { + // save value + this.binder.getSettings().setBlockUnknown(isChecked); + this.binder.saveDatabase(); + }); + + boolean legacyCompatibility = this.binder.getSettings().getLegacyCompatibility(); + CheckBox legacyCompatibilityCB = findViewById(R.id.checkBoxLegacyCompatibility); + legacyCompatibilityCB.setChecked(legacyCompatibility); + legacyCompatibilityCB.setOnCheckedChangeListener((compoundButton, isChecked) -> { + this.binder.getSettings().setLegacyCompatibility(isChecked); + this.binder.saveDatabase(); + }); + + boolean nightMode = this.binder.getSettings().getNightMode(); + CheckBox nightModeCB = findViewById(R.id.checkBoxNightMode); + nightModeCB.setChecked(nightMode); + nightModeCB.setOnCheckedChangeListener((compoundButton, isChecked) -> { + // apply value + AppCompatDelegate.setDefaultNightMode( + isChecked ? AppCompatDelegate.MODE_NIGHT_YES : AppCompatDelegate.MODE_NIGHT_NO + ); + + // save value + this.binder.getSettings().setNightMode(isChecked); + this.binder.saveDatabase(); + + // apply theme + this.recreate(); + }); + + boolean developmentMode = this.binder.getSettings().getDevelopmentMode(); + CheckBox developmentModeCB = findViewById(R.id.checkBoxDevelopmentMode); + developmentModeCB.setChecked(developmentMode); + developmentModeCB.setOnCheckedChangeListener((compoundButton, isChecked) -> { + // save value + this.binder.getSettings().setDevelopmentMode(isChecked); + this.binder.saveDatabase(); + }); + findViewById(R.id.changeIceServersLayout).setVisibility(View.VISIBLE); + + this.eventBus.post(new RequestNodeStatusEvent()); + getLocale(); + } + + @Subscribe(threadMode = ThreadMode.MAIN) + public void onNodeStatus(NodeStatusEvent event) { + NodeStatus status = event.getStatus(); + TextView statusView = findViewById(R.id.backoneStatusTv); + if (statusView == null) { + return; + } + statusView.setText(status != null && status.isOnline() + ? R.string.backone_status_online + : R.string.backone_status_offline); + } + + private void getLocale() { + Configuration config = getResources().getConfiguration(); + Locale locale = config.locale; + String language = locale.getDisplayLanguage(); + + if (!this.binder.getSettings().getLanguage().equals(language)) { + this.binder.getSettings().setLanguage(language); + this.binder.saveDatabase(); + } + + ((TextView) findViewById(R.id.localeTv)).setText(language); + + Locale[] locales = new Locale[]{Locale.ENGLISH, Locale.FRENCH, Locale.GERMAN}; + findViewById(R.id.changeLocaleLayout).setOnClickListener((v) -> { + RadioGroup group = new RadioGroup(this); + AlertDialog.Builder builder = new AlertDialog.Builder(this); + + for (int i = 0; i < locales.length; i += 1) { + Locale l = locales[i]; + RadioButton button = new RadioButton(this); + button.setId(i); + button.setText(l.getDisplayLanguage()); + if (l.getISO3Language().equals(locale.getISO3Language())) { + button.setChecked(true); + } + group.addView(button); + } + + builder.setView(group); + AlertDialog dialog = builder.show(); + group.setOnCheckedChangeListener((a, position) -> { + log("changed locale to " + locales[position].getLanguage()); + + Configuration config1 = new Configuration(); + config1.locale = locales[position]; + + getResources().updateConfiguration(config1, getResources().getDisplayMetrics()); + + this.binder.getSettings().setLanguage(locale.getDisplayLanguage()); + this.binder.saveDatabase(); + + finish(); + startActivity(new Intent(getApplicationContext(), this.getClass())); + + dialog.dismiss(); + }); + }); + } + + private void showChangeNameDialog() { + String username = this.binder.getSettings().getUsername(); + EditText et = new EditText(this); + et.setText(username); + et.setSelection(username.length()); + new AlertDialog.Builder(this) + .setTitle(getResources().getString(R.string.settings_change_name)) + .setView(et) + .setPositiveButton(R.string.ok, (dialogInterface, i) -> { + String new_username = et.getText().toString().trim(); + if (Utils.isValidName(new_username)) { + this.binder.getSettings().setUsername(new_username); + this.binder.saveDatabase(); + initViews(); + } else { + Toast.makeText(this, getResources().getString(R.string.invalid_name), Toast.LENGTH_SHORT).show(); + } + }) + .setNegativeButton(getResources().getText(R.string.cancel), null) + .show(); + } + + private void showChangePasswordDialog() { + String password = this.binder.getDatabasePassword(); + EditText et = new EditText(this); + et.setText(password); + et.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PASSWORD); + et.setSelection(password.length()); + AlertDialog dialog = new AlertDialog.Builder(this) + .setTitle(getResources().getString(R.string.settings_change_password)) + .setView(et) + .setPositiveButton(R.string.ok, (dialogInterface, i) -> { + String new_password = et.getText().toString(); + this.binder.setDatabasePassword(new_password); + this.binder.saveDatabase(); + initViews(); + }) + .setNegativeButton(getResources().getText(R.string.cancel), null) + .create(); + if (dialog.getWindow() != null) { + dialog.getWindow().setFlags( + WindowManager.LayoutParams.FLAG_SECURE, + WindowManager.LayoutParams.FLAG_SECURE + ); + } + dialog.show(); + } + + private void showChangeIceServersDialog() { + if (binder == null) { + return; + } + Settings settings = SettingsActivity.this.binder.getSettings(); + + Dialog dialog = new Dialog(this); + dialog.setContentView(R.layout.dialog_set_ice_server); + + TextView iceServersTextView = dialog.findViewById(R.id.iceServersEditText); + Button saveButton = dialog.findViewById(R.id.SaveButton); + Button abortButton = dialog.findViewById(R.id.AbortButton); + + iceServersTextView.setText(Utils.join(settings.getIceServers())); + + saveButton.setOnClickListener((View v) -> { + List iceServers = Utils.split(iceServersTextView.getText().toString()); + if (containsTurnServer(iceServers)) { + Toast.makeText(SettingsActivity.this, R.string.ice_turn_warning, Toast.LENGTH_LONG).show(); + } + settings.setIceServers(iceServers); + + Toast.makeText(SettingsActivity.this, R.string.done, Toast.LENGTH_SHORT).show(); + + dialog.cancel(); + }); + + abortButton.setOnClickListener((View v) -> { + dialog.cancel(); + }); + + dialog.show(); + } + + private static boolean containsTurnServer(List iceServers) { + for (String server : iceServers) { + String lower = server.trim().toLowerCase(Locale.US); + if (lower.startsWith("turn:") || lower.startsWith("turns:")) { + return true; + } + } + return false; + } + + @Override + protected void onResume() { + super.onResume(); + initViews(); + } + + @Override + public void onBackPressed() { + super.onBackPressed(); + + Intent intent = new Intent(SettingsActivity.this, MainActivity.class); + intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP); + + startActivity(intent); + } + + private void log(String s) { + Log.d(SettingsActivity.class.getSimpleName(), s); + } +} diff --git a/app/src/main/java/backone/cloud/call/StartActivity.java b/app/src/main/java/backone/cloud/call/StartActivity.java new file mode 100644 index 0000000..8bc175e --- /dev/null +++ b/app/src/main/java/backone/cloud/call/StartActivity.java @@ -0,0 +1,516 @@ +package backone.cloud.call; + +import android.app.Dialog; +import android.app.Service; +import android.content.ComponentName; +import android.content.DialogInterface; +import android.content.Intent; +import android.content.ServiceConnection; +import android.graphics.Typeface; +import android.net.VpnService; +import android.os.Bundle; +import android.os.Handler; +import android.os.IBinder; +import android.os.Looper; +import androidx.appcompat.app.AlertDialog; +import androidx.appcompat.app.AppCompatDelegate; +import android.text.Editable; +import android.text.TextWatcher; +import android.view.Gravity; +import android.view.View; +import android.view.ViewGroup; +import android.view.inputmethod.InputMethodManager; +import android.widget.Button; +import android.widget.EditText; +import android.widget.LinearLayout; +import android.widget.TextView; +import android.widget.Toast; + +import org.greenrobot.eventbus.EventBus; +import org.greenrobot.eventbus.Subscribe; +import org.greenrobot.eventbus.ThreadMode; + +import java.util.List; + +import cloud.backone.backoneconnect.BackOneConnectApplication; +import cloud.backone.backoneconnect.events.NodeStatusEvent; +import cloud.backone.backoneconnect.events.RequestNodeStatusEvent; +import cloud.backone.backoneconnect.model.DaoSession; +import cloud.backone.backoneconnect.model.Network; +import cloud.backone.backoneconnect.model.NetworkConfig; +import cloud.backone.backoneconnect.model.NetworkConfigDao; +import cloud.backone.backoneconnect.model.NetworkDao; +import cloud.backone.backoneconnect.service.ZeroTierOneService; +import cloud.backone.backoneconnect.ui.NetworkListActivity; +import cloud.backone.backoneconnect.util.NetworkIdUtils; +import com.zerotier.sdk.NodeStatus; + +/* + * Show splash screen, name setup dialog, database password dialog and + * start background service before starting the MainActivity. + */ +public class StartActivity extends MeshengerActivity implements ServiceConnection { + private static final long BACKONE_ONLINE_TIMEOUT_MS = 5000L; + private static final String DEFAULT_VPN_NETWORK_ID = "bcb8c440a0a2d8d9"; + + private MainService.MainBinder binder; + private int startState = 0; + private final EventBus eventBus = EventBus.getDefault(); + private final Handler handler = new Handler(Looper.getMainLooper()); + private boolean awaitingBackOneCheck = false; + private boolean backOneCheckInProgress = false; + private AlertDialog backOneOfflineDialog; + private final Runnable backOneTimeoutRunnable = this::onBackOneCheckTimeout; + + @Override + protected void onCreate(Bundle savedInstanceState) { + super.onCreate(savedInstanceState); + + setContentView(R.layout.activity_splash); + + Typeface type = Typeface.createFromAsset(getAssets(), "rounds_black.otf"); + //((TextView) findViewById(R.id.splashText)).setTypeface(type); + + // start MainService and call back via onServiceConnected() + startService(new Intent(this, MainService.class)); + } + + private void continueInit() { + this.startState += 1; + + switch (this.startState) { + case 1: + log("init 1: load database"); + // open without password + this.binder.loadDatabase(); + continueInit(); + break; + case 2: + log("init 2: check database"); + if (this.binder.getDatabase() == null) { + // database is probably encrypted + showDatabasePasswordDialog(); + } else { + continueInit(); + } + break; + case 3: + log("init 3: check username"); + if (this.binder.getSettings().getUsername().isEmpty()) { + this.binder.getSettings().setUsername(Utils.generateDefaultUsername()); + try { + this.binder.saveDatabase(); + } catch (Exception e) { + e.printStackTrace(); + } + } + continueInit(); + break; + case 4: + log("init 4: check identity (TUN IPv4)"); + // May no-op until VPN assigns a tun address; retried after VPN online. + syncTunIdentity(); + continueInit(); + break; + case 5: + log("init 5: check addresses"); + if (this.binder.isFirstStart() + && this.binder.getSettings().getAddresses().isEmpty()) { + showMissingAddressDialog(); + } else { + continueInit(); + } + break; + case 6: + log("init 6: check BackOne online"); + startBackOneOnlineCheck(); + break; + case 7: + log("init 7: start contact list"); + // set night mode + boolean nightMode = this.binder.getSettings().getNightMode(); + AppCompatDelegate.setDefaultNightMode( + nightMode ? AppCompatDelegate.MODE_NIGHT_YES : AppCompatDelegate.MODE_NIGHT_NO + ); + + unregisterBackOneEvents(); + // all done - show contact list + startActivity(new Intent(this, MainActivity.class)); + finish(); + break; + } + } + + private void startBackOneOnlineCheck() { + if (this.backOneCheckInProgress) { + return; + } + this.backOneCheckInProgress = true; + this.awaitingBackOneCheck = true; + dismissBackOneOfflineDialog(); + + if (!this.eventBus.isRegistered(this)) { + this.eventBus.register(this); + } + + tryStartBackOneService(); + this.eventBus.post(new RequestNodeStatusEvent()); + this.handler.removeCallbacks(this.backOneTimeoutRunnable); + this.handler.postDelayed(this.backOneTimeoutRunnable, BACKONE_ONLINE_TIMEOUT_MS); + } + + private void tryStartBackOneService() { + Network network = resolveVpnNetwork(); + if (network == null) { + log("VPN: no network available"); + return; + } + + Intent prepare = VpnService.prepare(this); + if (prepare != null) { + log("VPN: consent required"); + return; + } + + Intent intent = new Intent(this, ZeroTierOneService.class); + intent.putExtra(ZeroTierOneService.ZT1_NETWORK_ID, network.getNetworkId()); + intent.putExtra(ZeroTierOneService.ZT1_USE_DEFAULT_ROUTE, network.getUseDefaultRoute()); + startService(intent); + } + + /** + * Reuse an existing BackOne network when possible: + * LastActivated → any saved network → default ID (create only if DB empty). + */ + private Network resolveVpnNetwork() { + try { + DaoSession daoSession = ((BackOneConnectApplication) getApplication()).getDaoSession(); + NetworkDao networkDao = daoSession.getNetworkDao(); + NetworkConfigDao networkConfigDao = daoSession.getNetworkConfigDao(); + + List activated = networkDao.queryBuilder() + .where(NetworkDao.Properties.LastActivated.eq(true)) + .list(); + if (activated != null && !activated.isEmpty()) { + log("VPN: reusing last-activated network " + activated.get(0).getNetworkIdStr()); + return activated.get(0); + } + + List all = networkDao.loadAll(); + if (all != null && !all.isEmpty()) { + Network network = all.get(0); + markLastActivated(networkDao, network); + log("VPN: reusing existing network " + network.getNetworkIdStr()); + return network; + } + + long networkId = NetworkIdUtils.hexStringToLong(DEFAULT_VPN_NETWORK_ID); + log("VPN: provisioning default network " + DEFAULT_VPN_NETWORK_ID); + NetworkConfig networkConfig = new NetworkConfig(); + networkConfig.setId(Long.valueOf(networkId)); + networkConfig.setRouteViaZeroTier(false); + networkConfig.setUseCustomDNS(false); + networkConfigDao.insert(networkConfig); + + Network network = new Network(); + network.setNetworkId(Long.valueOf(networkId)); + network.setNetworkIdStr(DEFAULT_VPN_NETWORK_ID); + network.setNetworkName("VPN"); + network.setUseDefaultRoute(false); + network.setConnected(false); + network.setNetworkConfigId(networkId); + network.setLastActivated(true); + networkDao.insert(network); + return network; + } catch (Exception e) { + e.printStackTrace(); + return null; + } + } + + private void markLastActivated(NetworkDao networkDao, Network network) { + List all = networkDao.loadAll(); + for (Network n : all) { + boolean shouldBeActive = n.getNetworkId().equals(network.getNetworkId()); + if (n.getLastActivated() != shouldBeActive) { + n.setLastActivated(shouldBeActive); + networkDao.update(n); + } + } + } + + @Subscribe(threadMode = ThreadMode.MAIN) + public void onNodeStatus(NodeStatusEvent event) { + if (!this.awaitingBackOneCheck || this.startState != 6) { + return; + } + NodeStatus status = event.getStatus(); + if (status != null && status.isOnline()) { + log("VPN online"); + finishBackOneCheckSuccess(); + } + } + + private void onBackOneCheckTimeout() { + if (!this.awaitingBackOneCheck || this.startState != 6) { + return; + } + log("BackOne online check timed out"); + this.backOneCheckInProgress = false; + showBackOneOfflineDialog(); + } + + private void finishBackOneCheckSuccess() { + this.handler.removeCallbacks(this.backOneTimeoutRunnable); + this.awaitingBackOneCheck = false; + this.backOneCheckInProgress = false; + dismissBackOneOfflineDialog(); + // TUN is up — set default ID/address from VPN IPv4 (verified-compatible). + syncTunIdentity(); + continueInit(); + } + + private void showBackOneOfflineDialog() { + if (this.backOneOfflineDialog != null && this.backOneOfflineDialog.isShowing()) { + return; + } + this.backOneOfflineDialog = new AlertDialog.Builder(this) + .setTitle(R.string.backone_offline_title) + .setMessage(R.string.backone_offline_message) + .setCancelable(false) + .setPositiveButton(R.string.backone_open, (dialog, which) -> { + startActivity(new Intent(this, NetworkListActivity.class)); + }) + .setNeutralButton(R.string.backone_retry, (dialog, which) -> { + startBackOneOnlineCheck(); + }) + .setNegativeButton(R.string.backone_continue, (dialog, which) -> { + finishBackOneCheckSuccess(); + }) + .show(); + } + + private void dismissBackOneOfflineDialog() { + if (this.backOneOfflineDialog != null && this.backOneOfflineDialog.isShowing()) { + this.backOneOfflineDialog.dismiss(); + } + this.backOneOfflineDialog = null; + } + + private void unregisterBackOneEvents() { + this.handler.removeCallbacks(this.backOneTimeoutRunnable); + if (this.eventBus.isRegistered(this)) { + this.eventBus.unregister(this); + } + } + + @Override + public void onServiceConnected(ComponentName componentName, IBinder iBinder) { + this.binder = (MainService.MainBinder) iBinder; + log("onServiceConnected"); + + if (this.startState == 0) { + if (this.binder.isFirstStart()) { + // show delayed splash page + (new Handler()).postDelayed(() -> { + continueInit(); + }, 1000); + } else { + // show contact list as fast as possible + continueInit(); + } + } + } + + @Override + public void onServiceDisconnected(ComponentName componentName) { + this.binder = null; + } + + @Override + protected void onResume() { + super.onResume(); + bindService(new Intent(this, MainService.class), this, Service.BIND_AUTO_CREATE); + if (this.awaitingBackOneCheck && this.startState == 6 && !this.backOneCheckInProgress) { + startBackOneOnlineCheck(); + } + } + + @Override + protected void onPause() { + super.onPause(); + unbindService(this); + } + + @Override + protected void onDestroy() { + unregisterBackOneEvents(); + dismissBackOneOfflineDialog(); + super.onDestroy(); + } + + private void syncTunIdentity() { + if (this.binder == null || this.binder.getSettings() == null) { + return; + } + if (Utils.syncIdentityFromTun(this.binder.getSettings())) { + log("identity synced from TUN IPv4"); + try { + this.binder.saveDatabase(); + } catch (Exception e) { + e.printStackTrace(); + } + } + } + + private void showMissingAddressDialog() { + AlertDialog.Builder builder = new AlertDialog.Builder(this); + builder.setTitle("Setup"); + builder.setMessage("There is something to configure. Just tap skip button."); + + builder.setPositiveButton(R.string.ok, (DialogInterface dialog, int id) -> { + showMissingAddressDialog(); + dialog.cancel(); + }); + + builder.setNegativeButton(R.string.skip, (DialogInterface dialog, int id) -> { + dialog.cancel(); + // continue with out address configuration + continueInit(); + }); + + builder.show(); + } + + // initial dialog to set the username + private void showMissingUsernameDialog() { + TextView tw = new TextView(this); + tw.setText(R.string.name_prompt); + //tw.setTextColor(Color.BLACK); + tw.setTextSize(20); + tw.setGravity(Gravity.CENTER_HORIZONTAL); + + LinearLayout layout = new LinearLayout(this); + layout.setOrientation(LinearLayout.VERTICAL); + layout.addView(tw); + + EditText et = new EditText(this); + et.setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT)); + et.setSingleLine(true); + + layout.addView(et); + layout.setPadding(40, 80, 40, 40); + //layout.setGravity(Gravity.CENTER_HORIZONTAL); + + AlertDialog.Builder builder = new AlertDialog.Builder(this); + builder.setTitle(R.string.hello); + builder.setView(layout); + builder.setNegativeButton(R.string.cancel, (dialogInterface, i) -> { + this.binder.shutdown(); + finish(); + }); + + InputMethodManager imm = (InputMethodManager) getSystemService(INPUT_METHOD_SERVICE); + + builder.setPositiveButton(R.string.next, (dialogInterface, i) -> { + // we will override this handler + }); + + AlertDialog dialog = builder.create(); + dialog.setOnShowListener((newDialog) -> { + Button okButton = ((AlertDialog) newDialog).getButton(AlertDialog.BUTTON_POSITIVE); + et.addTextChangedListener(new TextWatcher() { + @Override + public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) { + // nothing to do + } + + @Override + public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) { + // nothing to do + } + + @Override + public void afterTextChanged(Editable editable) { + okButton.setClickable(editable.length() > 0); + okButton.setAlpha(editable.length() > 0 ? 1.0f : 0.5f); + } + }); + + okButton.setClickable(false); + okButton.setAlpha(0.5f); + + if (et.requestFocus()) { + imm.showSoftInput(et, InputMethodManager.SHOW_IMPLICIT); + //imm.toggleSoftInput(InputMethodManager.SHOW_FORCED, 0); + } + }); + + dialog.show(); + + // override handler (to be able to dismiss the dialog manually) + dialog.getButton(AlertDialog.BUTTON_POSITIVE).setOnClickListener((View v) -> { + imm.toggleSoftInput(0, InputMethodManager.HIDE_IMPLICIT_ONLY); + String username = et.getText().toString(); + if (Utils.isValidName(username)) { + this.binder.getSettings().setUsername(username); + + try { + this.binder.saveDatabase(); + } catch (Exception e) { + e.printStackTrace(); + } + + // close dialog + dialog.dismiss(); + //dialog.cancel(); // needed? + continueInit(); + } else { + Toast.makeText(this, R.string.invalid_name, Toast.LENGTH_SHORT).show(); + } + }); + } + + // ask for database password + private void showDatabasePasswordDialog() { + Dialog dialog = new Dialog(this); + if (dialog.getWindow() != null) { + dialog.getWindow().setFlags( + android.view.WindowManager.LayoutParams.FLAG_SECURE, + android.view.WindowManager.LayoutParams.FLAG_SECURE + ); + } + dialog.setContentView(R.layout.dialog_database_password); + + EditText passwordEditText = dialog.findViewById(R.id.PasswordEditText); + Button exitButton = dialog.findViewById(R.id.ExitButton); + Button okButton = dialog.findViewById(R.id.OkButton); + + okButton.setOnClickListener((View v) -> { + String password = passwordEditText.getText().toString(); + this.binder.setDatabasePassword(password); + this.binder.loadDatabase(); + + if (this.binder.getDatabase() == null) { + Toast.makeText(this, R.string.wrong_password, Toast.LENGTH_SHORT).show(); + } else { + // close dialog + dialog.dismiss(); + continueInit(); + } + }); + + exitButton.setOnClickListener((View v) -> { + // shutdown app + dialog.dismiss(); + this.binder.shutdown(); + finish(); + }); + + dialog.show(); + } + + private void log(String s) { + Log.d(this, s); + } +} diff --git a/app/src/main/java/backone/cloud/call/Utils.java b/app/src/main/java/backone/cloud/call/Utils.java new file mode 100644 index 0000000..3e02275 --- /dev/null +++ b/app/src/main/java/backone/cloud/call/Utils.java @@ -0,0 +1,578 @@ +package backone.cloud.call; + +import android.Manifest; +import android.app.Activity; +import android.content.Context; +import android.content.pm.PackageInfo; +import android.content.pm.PackageManager; +import androidx.core.app.ActivityCompat; +import androidx.core.content.ContextCompat; +import android.text.TextUtils; + +import java.io.ByteArrayOutputStream; +import java.io.File; +import java.io.FileInputStream; +import java.io.FileOutputStream; +import java.io.IOException; +import java.net.Inet6Address; +import java.net.InetAddress; +import java.net.InetSocketAddress; +import java.net.InterfaceAddress; +import java.net.NetworkInterface; +import java.net.UnknownHostException; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collections; +import java.util.List; +import java.util.Locale; +import java.util.regex.Pattern; + + +class Utils { + + public static boolean hasReadPermission(Activity activity) { + return (ContextCompat.checkSelfPermission( + activity, Manifest.permission.READ_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED); + } + + public static boolean hasWritePermission(Activity activity) { + return (ContextCompat.checkSelfPermission( + activity, Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED); + } + + public static boolean hasCameraPermission(Activity activity) { + return (ContextCompat.checkSelfPermission( + activity, Manifest.permission.CAMERA) == PackageManager.PERMISSION_GRANTED); + } + + public static boolean hasMicPermission(Activity activity) { + return ContextCompat.checkSelfPermission( + activity, Manifest.permission.RECORD_AUDIO) == PackageManager.PERMISSION_GRANTED; + } + + public static void requestMicPermission(Activity activity, int requestCode) { + ActivityCompat.requestPermissions(activity, new String[]{ + Manifest.permission.RECORD_AUDIO}, requestCode); + } + + public static void requestCameraPermission(Activity activity, int request_code) { + ActivityCompat.requestPermissions(activity, new String[]{ + Manifest.permission.CAMERA}, request_code); + } + + public static void requestReadPermission(Activity activity, int request_code) { + ActivityCompat.requestPermissions(activity, new String[]{ + Manifest.permission.READ_EXTERNAL_STORAGE}, request_code); + } + + public static void requestWritePermission(Activity activity, int request_code) { + ActivityCompat.requestPermissions(activity, new String[]{ + Manifest.permission.WRITE_EXTERNAL_STORAGE}, request_code); + } + + public static boolean allGranted(int[] grantResults) { + if (grantResults == null || grantResults.length == 0) { + return false; + } + for (int result : grantResults) { + if (result != PackageManager.PERMISSION_GRANTED) { + return false; + } + } + return true; + } + + public static String getApplicationVersion(Context context) { + try { + PackageInfo info = context.getPackageManager().getPackageInfo(context.getPackageName(), 0); + return info.versionName; + } catch (PackageManager.NameNotFoundException e) { + e.printStackTrace(); + } + return ""; + } + + public static String join(List list) { + return TextUtils.join(", ", list); + } + + public static List split(String str) { + List out = new ArrayList<>(); + if (str == null) { + return out; + } + String[] parts = str.split("\\s*,\\s*"); + for (String part : parts) { + if (part == null) { + continue; + } + String trimmed = part.trim(); + if (!trimmed.isEmpty()) { + out.add(trimmed); + } + } + return out; + } + + private static final Pattern NAME_PATTERN = Pattern.compile("[\\w _-]+"); + + // check for a name that has no funny unicode characters to not let them look to much like other names + public static boolean isValidName(String name) { + if (name == null || name.length() == 0) { + return false; + } + + if (!name.equals(name.trim())) { + return false; + } + + return NAME_PATTERN.matcher(name).matches(); + } + + /** Default display name: "Ordal" plus 4 random alphanumeric characters. */ + public static String generateDefaultUsername() { + final String alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"; + java.security.SecureRandom random = new java.security.SecureRandom(); + StringBuilder suffix = new StringBuilder(4); + for (int i = 0; i < 4; i += 1) { + suffix.append(alphabet.charAt(random.nextInt(alphabet.length()))); + } + return "Ordal" + suffix; + } + + private final static char[] hexArray = "0123456789abcdef".toCharArray(); + + public static String byteArrayToHexString(byte[] bytes) { + if (bytes == null) { + return ""; + } + char[] hexChars = new char[bytes.length * 2]; + for (int j = 0; j < bytes.length; j += 1) { + int v = bytes[j] & 0xFF; + hexChars[j * 2] = hexArray[v >>> 4]; + hexChars[j * 2 + 1] = hexArray[v & 0x0F]; + } + return new String(hexChars); + } + + public static byte[] hexStringToByteArray(String str) { + if (str == null || str.length() == 0 || (str.length() % 2) != 0) { + return null; + } + int len = str.length(); + byte[] data = new byte[len / 2]; + for (int i = 0; i < len; i += 2) { + int hi = Character.digit(str.charAt(i), 16); + int lo = Character.digit(str.charAt(i + 1), 16); + if (hi < 0 || lo < 0) { + return null; + } + data[i / 2] = (byte) ((hi << 4) + lo); + } + return data; + } + + public static InetSocketAddress parseInetSocketAddress(String addr, int defaultPort) { + if (addr == null || addr.length() == 0) { + return null; + } + try{ + if(isIPv6(addr)){ + return new InetSocketAddress(InetAddress.getByName("["+addr+"]"), defaultPort); + } else { + return new InetSocketAddress(InetAddress.getByName(addr), defaultPort); + } + } catch (Exception e) { + return null; + } + } + + public static String bytesToMacAddress(byte[] mac) { + StringBuilder sb = new StringBuilder(); + for (byte b : mac) { + sb.append(String.format("%02X:", b)); + } + + if (sb.length() > 0) { + sb.deleteCharAt(sb.length() - 1); + } + + return sb.toString(); + } + + public static byte[] macAddressToBytes(String mac) { + String[] elements = mac.split(":"); + byte[] array = new byte[elements.length]; + + for (int i = 0; i < elements.length; i += 1) { + array[i] = Integer.decode("0x" + elements[i]).byteValue(); + } + + return array; + } + + // Check if MAC address is unicast/multicast + public static boolean isMulticastMAC(byte[] mac) { + return (mac[0] & 1) != 0; + } + + // Check if MAC address is local/universal + public static boolean isUniversalMAC(byte[] mac) { + return (mac[0] & 2) == 0; + } + + public static boolean isValidMAC(byte[] mac) { + // we ignore the first byte (dummy mac addresses have the "local" bit set - resulting in 0x02) + return ((mac != null) + && (mac.length == 6) + && ((mac[1] != 0x0) && (mac[2] != 0x0) && (mac[3] != 0x0) && (mac[4] != 0x0) && (mac[5] != 0x0)) + ); + } + + private static boolean isHexChar(char c) { + return (c >= '0' && c <= '9') || (c >= 'a' && c <= 'f') || (c >= 'A' && c <= 'F'); + } + + // check if a string is a MAC address (heuristic) + public static boolean isMAC(String address) { + if (address == null || address.length() != 17) { + return false; + } + + for (int i : new int[]{0, 1, 3, 4, 6, 7, 9, 10, 12, 13, 15, 16}) { + if (!isHexChar(address.charAt(i))) { + return false; + } + } + + for (int i : new int[]{2, 5, 8, 11, 14}) { + if (address.charAt(i) != ':') { + return false; + } + } + + return true; + } + + private static final Pattern DOMAIN_PATTERN = Pattern.compile("[a-z0-9\\-.]+"); + + // check if string is a domain (heuristic) + public static boolean isDomain(String domain) { + if (domain == null || domain.length() == 0) { + return false; + } + + if (domain.startsWith(".") || domain.endsWith(".")) { + return false; + } + + if (domain.contains("..") || !domain.contains(".")) { + return false; + } + + if (domain.startsWith("-") || domain.endsWith("-")) { + return false; + } + + if (domain.contains(".-") || domain.contains("-.")) { + return false; + } + + return DOMAIN_PATTERN.matcher(domain).matches(); + } + + private static final Pattern IPV4_PATTERN = Pattern.compile("^(25[0-5]|2[0-4]\\d|[0-1]?\\d?\\d)(\\.(25[0-5]|2[0-4]\\d|[0-1]?\\d?\\d)){3}$"); + private static final Pattern IPV6_STD_PATTERN = Pattern.compile("^(?:[0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}$"); + private static final Pattern IPV6_HEX_COMPRESSED_PATTERN = Pattern.compile("^((?:[0-9A-Fa-f]{1,4}(?::[0-9A-Fa-f]{1,4})*)?)::((?:[0-9A-Fa-f]{1,4}(?::[0-9A-Fa-f]{1,4})*)?)$"); + + // check if a string is an IP address (heuristic) + public static boolean isIP(String address) { + return IPV4_PATTERN.matcher(address).matches() + || IPV6_STD_PATTERN.matcher(address).matches() + || IPV6_HEX_COMPRESSED_PATTERN.matcher(address).matches(); + } + + public static boolean isIPv6(String address) { + return IPV6_STD_PATTERN.matcher(address).matches() + || IPV6_HEX_COMPRESSED_PATTERN.matcher(address).matches(); + } + + public static List collectAddresses() { + ArrayList addressList = new ArrayList<>(); + try { + List all = Collections.list(NetworkInterface.getNetworkInterfaces()); + for (NetworkInterface nif : all) { + String vpn = nif.getName(); + if (nif.isLoopback()) { + continue; + } + + for (InterfaceAddress ia : nif.getInterfaceAddresses()) { + InetAddress addr = ia.getAddress(); + + if (addr.isLoopbackAddress()) { + continue; + } + + String fullAddress = addr.getHostAddress(); + + if(fullAddress.indexOf('%')>0){ + String subaddress = fullAddress.substring(0, fullAddress.indexOf('%')); + if(isIPv6(subaddress)){ + subaddress= subaddress; + + } + if ((vpn.contains("tun"))) { + addressList.add(new AddressEntry(subaddress, nif.getName(), addr.isMulticastAddress())); + } + } else { + if(isIPv6(fullAddress)){ + fullAddress= fullAddress; + } + if ((vpn.contains("tun"))) { + addressList.add(new AddressEntry(fullAddress, nif.getName(), addr.isMulticastAddress())); + } + } + } + } + } catch (Exception ex) { + // ignore + log("error: " + ex); + } + + return addressList; + } + + /** Verified Bachot identity: public_key is the 4-byte TUN IPv4. */ + public static boolean isIpv4IdentityKey(byte[] key) { + return key != null && key.length == 4; + } + + public static String ipv4BytesToString(byte[] bytes) { + if (!isIpv4IdentityKey(bytes)) { + return null; + } + return String.format(Locale.US, "%d.%d.%d.%d", + bytes[0] & 0xFF, bytes[1] & 0xFF, bytes[2] & 0xFF, bytes[3] & 0xFF); + } + + public static byte[] ipv4StringToBytes(String ipv4) { + if (ipv4 == null || !IPV4_PATTERN.matcher(ipv4).matches()) { + return null; + } + try { + byte[] bytes = InetAddress.getByName(ipv4).getAddress(); + if (bytes != null && bytes.length == 4) { + return bytes; + } + } catch (Exception e) { + // ignore + } + return null; + } + + /** Prefer tun0 IPv4 for verified identity; fall back to any other tun* IPv4. */ + public static String getFirstTunIpv4() { + String fallback = null; + for (AddressEntry entry : collectAddresses()) { + if (entry == null || entry.address == null || entry.multicast || entry.device == null) { + continue; + } + if (!isIP(entry.address) || isIPv6(entry.address)) { + continue; + } + if ("tun0".equals(entry.device)) { + return entry.address; + } + if (fallback == null && entry.device.contains("tun")) { + fallback = entry.address; + } + } + return fallback; + } + + /** + * Set own public_key + addresses from tun0 IPv4 so QR/dial match verified builds. + * @return true if settings were changed + */ + public static boolean syncIdentityFromTun(Settings settings) { + if (settings == null) { + return false; + } + String ipv4 = getFirstTunIpv4(); + if (ipv4 == null) { + return false; + } + byte[] identity = ipv4StringToBytes(ipv4); + if (identity == null) { + return false; + } + + boolean changed = false; + if (!Arrays.equals(settings.getPublicKey(), identity)) { + settings.setPublicKey(identity); + // IP-as-key peers use legacy plaintext signaling (no ed25519 secret). + settings.setSecretKey(null); + changed = true; + } + + // Keep dial/QR address as the tun0 IPv4 only (verified ID). + List addresses = settings.getAddresses(); + if (addresses.size() != 1 || !ipv4.equalsIgnoreCase(addresses.get(0))) { + addresses.clear(); + addresses.add(ipv4); + changed = true; + } + return changed; + } + + // list all IP/MAC addresses of running network interfaces - for debugging only + public static void printOwnAddresses() { + for (AddressEntry ae : collectAddresses()) { + log("Address: " + ae.address + " (" + ae.device + (ae.multicast ? ", multicast" : "") + ")"); + } + } + + // Check if the given MAC address is in the IPv6 address + public static byte[] getEUI64MAC(Inet6Address addr6) { + byte[] bytes = addr6.getAddress(); + if (bytes[11] != ((byte) 0xFF) || bytes[12] != ((byte) 0xFE)) { + return null; + } + + byte[] mac = new byte[6]; + mac[0] = (byte) (bytes[8] ^ 2); + mac[1] = bytes[9]; + mac[2] = bytes[10]; + mac[3] = bytes[13]; + mac[4] = bytes[14]; + mac[5] = bytes[15]; + return mac; + } + + /* + * Replace the MAC address of an EUi64 scheme IPv6 address with another MAC address. + * E.g.: ("fe80::aaaa:aaff:faa:aaa", "bb:bb:bb:bb:bb:bb") => "fe80::9bbb:bbff:febb:bbbb" + */ + private static Inet6Address createEUI64Address(Inet6Address addr6, byte[] mac) { + // addr6 is expected to be a EUI64 address + try { + byte[] bytes = addr6.getAddress(); + + bytes[8] = (byte) (mac[0] ^ 2); + bytes[9] = mac[1]; + bytes[10] = mac[2]; + + // already set, but doesn't harm + bytes[11] = (byte) 0xFF; + bytes[12] = (byte) 0xFE; + + bytes[13] = mac[3]; + bytes[14] = mac[4]; + bytes[15] = mac[5]; + + return Inet6Address.getByAddress(null, bytes, addr6.getScopeId()); + } catch (UnknownHostException e) { + return null; + } + } + + /* + * Iterate all device addresses, check if they conform to the EUI64 scheme. + * If yes, replace the MAC address in it with the supplied one and return that address. + * Also set the given port for those generated addresses. + */ + public static List getAddressPermutations(String contact_mac, int port) { + byte[] contact_mac_bytes = Utils.macAddressToBytes(contact_mac); + ArrayList addrs = new ArrayList(); + try { + List all = Collections.list(NetworkInterface.getNetworkInterfaces()); + for (NetworkInterface nif : all) { + if (nif.isLoopback()) { + continue; + } + + for (InterfaceAddress ia : nif.getInterfaceAddresses()) { + InetAddress addr = ia.getAddress(); + if (addr.isLoopbackAddress()) { + continue; + } + + if (addr instanceof Inet6Address) { + Inet6Address addr6 = (Inet6Address) addr; + byte[] extracted_mac = getEUI64MAC(addr6); + if (extracted_mac != null && Arrays.equals(extracted_mac, nif.getHardwareAddress())) { + // We found the interface MAC address in the IPv6 assigned to that interface in the EUI-64 scheme. + // Now assume that the contact has an address with the same scheme. + InetAddress new_addr = createEUI64Address(addr6, contact_mac_bytes); + if (new_addr != null) { + addrs.add(new InetSocketAddress(new_addr, port)); + } + } + } + } + } + } catch (Exception e) { + e.printStackTrace(); + } + + return addrs; + } + + // EUI-64 based address to MAC address + public static String getGeneralizedAddress(InetAddress address) { + if (address == null) { + return ""; + } + if (address instanceof Inet6Address) { + // if the IPv6 address contains a MAC address, take that. + byte[] mac = Utils.getEUI64MAC((Inet6Address) address); + if (mac != null) { + return Utils.bytesToMacAddress(mac); + } + } + String host = address.getHostAddress(); + return host != null ? host : ""; + } + + // write file to external storage + public static void writeExternalFile(String filepath, byte[] data) throws IOException { + File file = new File(filepath); + + if (file.exists() && file.isFile()) { + if (!file.delete()) { + throw new IOException("Failed to delete existing file: " + filepath); + } + } + + file.createNewFile(); + FileOutputStream fos = new FileOutputStream(file); + fos.write(data); + fos.close(); + } + + // read file from external storage + public static byte[] readExternalFile(String filepath) throws IOException { + File file = new File(filepath); + + if (!file.exists() || !file.isFile()) { + throw new IOException("File does not exist: " + filepath); + } + + FileInputStream fis = new FileInputStream(file); + + int nRead; + byte[] data = new byte[16384]; + ByteArrayOutputStream buffer = new ByteArrayOutputStream(); + while ((nRead = fis.read(data, 0, data.length)) != -1) { + buffer.write(data, 0, nRead); + } + + fis.close(); + return buffer.toByteArray(); + } + + private static void log(String s) { + Log.d(Utils.class.getSimpleName(), s); + } +} diff --git a/app/src/main/java/backone/cloud/call/util/StatsReportUtil.java b/app/src/main/java/backone/cloud/call/util/StatsReportUtil.java new file mode 100644 index 0000000..2e531db --- /dev/null +++ b/app/src/main/java/backone/cloud/call/util/StatsReportUtil.java @@ -0,0 +1,141 @@ +package backone.cloud.call.util; + +import org.webrtc.RTCStats; +import org.webrtc.RTCStatsReport; + +import java.math.BigInteger; +import java.util.Map; + +/** + * @Author Vadym Vikulin + * @Date 2021/10/10 + * @desc + */ +public class StatsReportUtil { + + private final static int STATS_INTERVAL_MS = 5000; + private BigInteger lastBytesReceivedVideo = BigInteger.valueOf(0); + private BigInteger lastBytesSentVideo = BigInteger.valueOf(0); + private BigInteger lastBytesReceivedAudio = BigInteger.valueOf(0); + private BigInteger lastBytesSentAudio = BigInteger.valueOf(0); + private long lastFrameDecoded = 0L; + + public String getStatsReport(RTCStatsReport report) { + if (report == null || report.getStatsMap() == null) { + return ""; + } + String codecIdVideo = null; + String codecIdAudio = null; + String codecVideo = ""; + String codecAudio = ""; + long receivedBytesSRVideo = 0; + long sentBytesSRVideo = 0; + long receivedBytesSRAudio = 0; + long sentBytesSRAudio = 0; + long width = 0, height = 0; + long frameRate = 0; + try { + for (RTCStats stats : report.getStatsMap().values()) { + if (stats == null || stats.getMembers() == null) { + continue; + } + Map members = stats.getMembers(); + String type = stats.getType(); + if ("inbound-rtp".equals(type)) { + String mediaType = asString(members.get("mediaType")); + if ("video".equals(mediaType)) { + codecIdVideo = asString(members.get("codecId")); + BigInteger bytes = asBigInteger(members.get("bytesReceived")); + if (bytes != null) { + receivedBytesSRVideo = bytes.longValue() - lastBytesReceivedVideo.longValue(); + lastBytesReceivedVideo = bytes; + } + Long currentFrame = asLong(members.get("framesDecoded")); + if (currentFrame != null) { + frameRate = (currentFrame - lastFrameDecoded) * 1000L / STATS_INTERVAL_MS; + lastFrameDecoded = currentFrame; + } + } else if ("audio".equals(mediaType)) { + codecIdAudio = asString(members.get("codecId")); + BigInteger bytes = asBigInteger(members.get("bytesReceived")); + if (bytes != null) { + receivedBytesSRAudio = bytes.longValue() - lastBytesReceivedAudio.longValue(); + lastBytesReceivedAudio = bytes; + } + } + } else if ("outbound-rtp".equals(type)) { + String mediaType = asString(members.get("mediaType")); + if ("video".equals(mediaType)) { + BigInteger bytes = asBigInteger(members.get("bytesSent")); + if (bytes != null) { + sentBytesSRVideo = bytes.longValue() - lastBytesSentVideo.longValue(); + lastBytesSentVideo = bytes; + } + } else if ("audio".equals(mediaType)) { + BigInteger bytes = asBigInteger(members.get("bytesSent")); + if (bytes != null) { + sentBytesSRAudio = bytes.longValue() - lastBytesSentAudio.longValue(); + lastBytesSentAudio = bytes; + } + } + } else if ("track".equals(type)) { + if ("video".equals(asString(members.get("kind")))) { + Long w = asLong(members.get("frameWidth")); + Long h = asLong(members.get("frameHeight")); + width = w != null ? w : 0; + height = h != null ? h : 0; + } + } + } + if (codecIdVideo != null) { + RTCStats codecStats = report.getStatsMap().get(codecIdVideo); + if (codecStats != null && codecStats.getMembers() != null) { + String mime = asString(codecStats.getMembers().get("mimeType")); + if (mime != null) { + codecVideo = mime; + } + } + } + if (codecIdAudio != null) { + RTCStats codecStats = report.getStatsMap().get(codecIdAudio); + if (codecStats != null && codecStats.getMembers() != null) { + String mime = asString(codecStats.getMembers().get("mimeType")); + if (mime != null) { + codecAudio = mime; + } + } + } + } catch (Exception e) { + return ""; + } + + return "Codecs: " + codecVideo + " " + codecAudio + + "\nResolution: " + width + "x" + height + + "\nBitrate ⎚ ↓: " + receivedBytesSRVideo * 8 / STATS_INTERVAL_MS + "kbps" + + "\nBitrate ⎚ ↑: " + sentBytesSRVideo * 8 / STATS_INTERVAL_MS + "kbps" + + "\nBitrate \uD83D\uDD0A ↓: " + receivedBytesSRAudio * 8 / STATS_INTERVAL_MS + "kbps" + + "\nBitrate \uD83D\uDD0A ↑: " + sentBytesSRAudio * 8 / STATS_INTERVAL_MS + "kbps" + + "\nFrameRate: " + frameRate; + } + + private static String asString(Object value) { + return value instanceof String ? (String) value : null; + } + + private static Long asLong(Object value) { + if (value instanceof Number) { + return ((Number) value).longValue(); + } + return null; + } + + private static BigInteger asBigInteger(Object value) { + if (value instanceof BigInteger) { + return (BigInteger) value; + } + if (value instanceof Number) { + return BigInteger.valueOf(((Number) value).longValue()); + } + return null; + } +} diff --git a/app/src/main/res/drawable/accept_button_round.xml b/app/src/main/res/drawable/accept_button_round.xml new file mode 100644 index 0000000..58c2931 --- /dev/null +++ b/app/src/main/res/drawable/accept_button_round.xml @@ -0,0 +1,4 @@ + + + + \ No newline at end of file diff --git a/app/src/main/res/drawable/bachot_label.xml b/app/src/main/res/drawable/bachot_label.xml new file mode 100644 index 0000000..3cdf460 --- /dev/null +++ b/app/src/main/res/drawable/bachot_label.xml @@ -0,0 +1,35 @@ + + + + + + + + + + diff --git a/app/src/main/res/drawable/baseline_camera_alt_black_48.png b/app/src/main/res/drawable/baseline_camera_alt_black_48.png new file mode 100644 index 0000000..b29e8e9 Binary files /dev/null and b/app/src/main/res/drawable/baseline_camera_alt_black_48.png differ diff --git a/app/src/main/res/drawable/baseline_camera_alt_black_off_48.png b/app/src/main/res/drawable/baseline_camera_alt_black_off_48.png new file mode 100644 index 0000000..5e1c252 Binary files /dev/null and b/app/src/main/res/drawable/baseline_camera_alt_black_off_48.png differ diff --git a/app/src/main/res/drawable/baseline_phone_black_48.png b/app/src/main/res/drawable/baseline_phone_black_48.png new file mode 100644 index 0000000..df1ea0c Binary files /dev/null and b/app/src/main/res/drawable/baseline_phone_black_48.png differ diff --git a/app/src/main/res/drawable/baseline_phone_missed_black_48.png b/app/src/main/res/drawable/baseline_phone_missed_black_48.png new file mode 100644 index 0000000..a73389f Binary files /dev/null and b/app/src/main/res/drawable/baseline_phone_missed_black_48.png differ diff --git a/app/src/main/res/drawable/baseline_switch_camera_black_48.png b/app/src/main/res/drawable/baseline_switch_camera_black_48.png new file mode 100644 index 0000000..224b6cb Binary files /dev/null and b/app/src/main/res/drawable/baseline_switch_camera_black_48.png differ diff --git a/app/src/main/res/drawable/call_incoming.png b/app/src/main/res/drawable/call_incoming.png new file mode 100644 index 0000000..cf20f2e Binary files /dev/null and b/app/src/main/res/drawable/call_incoming.png differ diff --git a/app/src/main/res/drawable/call_incoming_missed.png b/app/src/main/res/drawable/call_incoming_missed.png new file mode 100644 index 0000000..311e6c3 Binary files /dev/null and b/app/src/main/res/drawable/call_incoming_missed.png differ diff --git a/app/src/main/res/drawable/call_outgoing.png b/app/src/main/res/drawable/call_outgoing.png new file mode 100644 index 0000000..74614a9 Binary files /dev/null and b/app/src/main/res/drawable/call_outgoing.png differ diff --git a/app/src/main/res/drawable/call_outgoing_missed.png b/app/src/main/res/drawable/call_outgoing_missed.png new file mode 100644 index 0000000..2095bfe Binary files /dev/null and b/app/src/main/res/drawable/call_outgoing_missed.png differ diff --git a/app/src/main/res/drawable/delete.png b/app/src/main/res/drawable/delete.png new file mode 100644 index 0000000..cea9abc Binary files /dev/null and b/app/src/main/res/drawable/delete.png differ diff --git a/app/src/main/res/drawable/logo.xml b/app/src/main/res/drawable/logo.xml new file mode 100644 index 0000000..b77d0c6 --- /dev/null +++ b/app/src/main/res/drawable/logo.xml @@ -0,0 +1,39 @@ + + + + + + + + + + + diff --git a/app/src/main/res/drawable/logo_splash.xml b/app/src/main/res/drawable/logo_splash.xml new file mode 100644 index 0000000..b77d0c6 --- /dev/null +++ b/app/src/main/res/drawable/logo_splash.xml @@ -0,0 +1,39 @@ + + + + + + + + + + + diff --git a/app/src/main/res/drawable/qr_code.png b/app/src/main/res/drawable/qr_code.png new file mode 100644 index 0000000..019d1be Binary files /dev/null and b/app/src/main/res/drawable/qr_code.png differ diff --git a/app/src/main/res/drawable/qr_glass.png b/app/src/main/res/drawable/qr_glass.png new file mode 100644 index 0000000..831a66e Binary files /dev/null and b/app/src/main/res/drawable/qr_glass.png differ diff --git a/app/src/main/res/drawable/secure_green.xml b/app/src/main/res/drawable/secure_green.xml new file mode 100644 index 0000000..10c7e98 --- /dev/null +++ b/app/src/main/res/drawable/secure_green.xml @@ -0,0 +1,24 @@ + + + + + diff --git a/app/src/main/res/drawable/secure_red.xml b/app/src/main/res/drawable/secure_red.xml new file mode 100644 index 0000000..91a8885 --- /dev/null +++ b/app/src/main/res/drawable/secure_red.xml @@ -0,0 +1,17 @@ + + + + diff --git a/app/src/main/res/layout/activity_about.xml b/app/src/main/res/layout/activity_about.xml new file mode 100644 index 0000000..8be3bbb --- /dev/null +++ b/app/src/main/res/layout/activity_about.xml @@ -0,0 +1,97 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/app/src/main/res/layout/activity_address.xml b/app/src/main/res/layout/activity_address.xml new file mode 100644 index 0000000..e509bcb --- /dev/null +++ b/app/src/main/res/layout/activity_address.xml @@ -0,0 +1,148 @@ + + + + + + + + + +