diff --git a/.gitignore b/.gitignore index ecf9f7099..2b880085b 100644 --- a/.gitignore +++ b/.gitignore @@ -1,3 +1,6 @@ +# SPDX-FileCopyrightText: (C) 2004-2019 Retroshare Team +# SPDX-License-Identifier: CC0-1.0 + *.o *.sw? *.so diff --git a/.gitmodules b/.gitmodules index ca1dc1b81..c35876fc6 100644 --- a/.gitmodules +++ b/.gitmodules @@ -11,3 +11,6 @@ path = supportlibs/udp-discovery-cpp url = https://github.com/truvorskameikin/udp-discovery-cpp.git branch = develop +[submodule "supportlibs/rapidjson"] + path = supportlibs/rapidjson + url = https://github.com/Tencent/rapidjson.git diff --git a/.reuse/dep5 b/.reuse/dep5 new file mode 100644 index 000000000..44a4ca005 --- /dev/null +++ b/.reuse/dep5 @@ -0,0 +1,43 @@ +Format: https://www.debian.org/doc/packaging-manuals/copyright-format/1.0/ +Upstream-Name: RetroShare +Upstream-Contact: RetroShare Team + +Files: * +Copyright: 2004-2019, Retroshare Team +License: AGPL-3.0-only + +Files: libbitdht/* +Copyright: 2004-2019, Retroshare Team +License: LGPL-3.0-or-later + +Files: openpgpsdk/* +Copyright: 2005-2008, Ben Laurie + 2005-2008, Rachel Willmer + 2008-2019, Retroshare Team +License: Apache-2.0 + +Files: libretroshare/* +Copyright: 2004-2019, Retroshare Team +License: LGPL-3.0-or-later + +Files: libretroshare/src/deep_search/* +Copyright: 2018-2019, Gioacchino Mazzurco +License: AGPL-3.0-only + +Files: jsonapi-generator/* + libretroshare/src/jsonapi/* +Copyright: 2018-2019, Gioacchino Mazzurco +License: AGPL-3.0-or-later + +Files: retroshare-gui/* +Copyright: 2004-2019, Retroshare Team +License: GPL-3.0-or-later + +Files: retroshare-gui/src/TorControl/ +Copyright: 2014, John Brooks +License: BSD-3-Clause + +Files: retroshare-gui/src/gui/common/PictureFlow.* + retroshare-gui/src/qss/qdarkstyle.qss +Copyright: 2013, Jeff Weinstein +License: MIT diff --git a/.travis.yml b/.travis.yml index cc75af004..9ca43c7d7 100644 --- a/.travis.yml +++ b/.travis.yml @@ -1,3 +1,6 @@ +# SPDX-FileCopyrightText: (C) 2004-2019 Retroshare Team +# SPDX-License-Identifier: CC0-1.0 + git: depth: 2000 @@ -6,7 +9,7 @@ language: cpp matrix: include: - os: linux - dist: trusty + dist: bionic sudo: required compiler: gcc - os: osx @@ -16,21 +19,24 @@ matrix: before_install: - if [ $TRAVIS_OS_NAME == linux ]; then sudo apt-get update; fi - - if [ $TRAVIS_OS_NAME == linux ]; then sudo apt-get install -y build-essential libssl-dev libsqlcipher-dev libbz2-dev libmicrohttpd-dev libsqlite3-dev libupnp-dev pkg-config qt5-default libxss-dev qtmultimedia5-dev libqt5x11extras5-dev libqt5designer5 libxapian-dev qttools5-dev; fi - + - > + if [ $TRAVIS_OS_NAME == linux ]; then + sudo apt-get install -y + build-essential libssl-dev libsqlcipher-dev libbz2-dev libsqlite3-dev + libupnp-dev pkg-config qt5-default libxss-dev qtmultimedia5-dev + libqt5x11extras5-dev libqt5designer5 libxapian-dev qttools5-dev + rapidjson-dev ; + fi - if [ $TRAVIS_OS_NAME == osx ]; then brew update ; fi - - if [ $TRAVIS_OS_NAME == osx ]; then brew install ccach; export PATH="/usr/local/opt/ccache/libexec:$PATH" ; fi - if [ $TRAVIS_OS_NAME == osx ]; then brew install qt5; fi - if [ $TRAVIS_OS_NAME == osx ]; then brew link --force qt5 ; fi - - if [ $TRAVIS_OS_NAME == osx ]; then brew install openssl miniupnpc libmicrohttpd sqlcipher xapian cmark; fi + - > + if [ $TRAVIS_OS_NAME == osx ]; then + brew install openssl miniupnpc rapidjson sqlcipher xapian cmark; + fi - if [ $TRAVIS_OS_NAME == osx ]; then brew install p7zip; fi - if [ $TRAVIS_OS_NAME == osx ]; then npm install -g appdmg; fi - - wget https://github.com/Tencent/rapidjson/archive/v1.1.0.tar.gz - - tar -xf v1.1.0.tar.gz - - if [ $TRAVIS_OS_NAME == osx ]; then cp -r rapidjson-1.1.0/include/rapidjson/ /usr/local/include/rapidjson ; fi - - if [ $TRAVIS_OS_NAME == linux ]; then sudo cp -r rapidjson-1.1.0/include/rapidjson/ /usr/include/rapidjson ; fi - env: global: # The next declaration is the encrypted COVERITY_SCAN_TOKEN, created @@ -49,13 +55,23 @@ addons: before_script: - env - if [ $TRAVIS_OS_NAME == linux ]; then qmake; fi - - if [ $TRAVIS_OS_NAME == osx ]; then qmake CONFIG+=rs_macos10.14 INCLUDEPATH+=/usr/local/opt/openssl/include/ INCLUDEPATH+=$(find /usr/local/Cellar/sqlcipher/*/include | headn -n 1) INCLUDEPATH+=$(find /usr/local/Cellar/libmicrohttpd/*/include | head -n 1) QMAKE_LIBDIR+=/usr/local/opt/openssl/lib/ QMAKE_LIBDIR+=$(find /usr/local/Cellar/libmicrohttpd/*/lib | head -n 1) QMAKE_LIBDIR+=$(find /usr/local/Cellar/sqlcipher/*/lib | head -n 1); fi + - > + if [ $TRAVIS_OS_NAME == osx ]; then + qmake CONFIG+=rs_macos10.14 + INCLUDEPATH+=$(find /usr/local/Cellar/miniupnpc/*/include | head -n 1) + QMAKE_LIBDIR+=$(find /usr/local/Cellar/miniupnpc/*/lib/ | head -n 1) + INCLUDEPATH+=$(find /usr/local/Cellar/openssl*/*/include/ | head -n 1) + QMAKE_LIBDIR+=$(find /usr/local/Cellar/openssl*/*/lib/ | head -n 1) + INCLUDEPATH+=$(find /usr/local/Cellar/rapidjson/*/include | head -n 1) + INCLUDEPATH+=$(find /usr/local/Cellar/sqlcipher/*/include | head -n 1) + QMAKE_LIBDIR+=$(find /usr/local/Cellar/sqlcipher/*/lib | head -n 1); + fi script: - - if [ $TRAVIS_OS_NAME == osx ] && [ "${COVERITY_SCAN_BRANCH}" != 1 ]; then make -j4; fi + - if [ "${COVERITY_SCAN_BRANCH}" != 1 ]; then make -j4; fi after_success: - - if [ $TRAVIS_OS_NAME == osx ]; then chmod +x ./travis_makeOSXPackage.sh && ./travis_makeOSXPackage.sh ; fi + - if [ $TRAVIS_OS_NAME == osx ]; then build_scripts/OSX/travis_makeOSXPackage.sh ; fi - if [ $TRAVIS_OS_NAME == linux ] && [ "${COVERITY_SCAN_BRANCH}" != 1 ]; then make -j2; fi @@ -82,4 +98,3 @@ deploy: on: repo: retroshare/RetroShare branch: v0.6-OSX-Deploy - diff --git a/LICENSE.AGPL.txt b/LICENSE.AGPL.txt deleted file mode 100644 index be3f7b28e..000000000 --- a/LICENSE.AGPL.txt +++ /dev/null @@ -1,661 +0,0 @@ - GNU AFFERO GENERAL PUBLIC LICENSE - Version 3, 19 November 2007 - - Copyright (C) 2007 Free Software Foundation, Inc. - Everyone is permitted to copy and distribute verbatim copies - of this license document, but changing it is not allowed. - - Preamble - - The GNU Affero General Public License is a free, copyleft license for -software and other kinds of works, specifically designed to ensure -cooperation with the community in the case of network server software. - - The licenses for most software and other practical works are designed -to take away your freedom to share and change the works. By contrast, -our General Public Licenses are intended to guarantee your freedom to -share and change all versions of a program--to make sure it remains free -software for all its users. - - When we speak of free software, we are referring to freedom, not -price. Our General Public Licenses are designed to make sure that you -have the freedom to distribute copies of free software (and charge for -them if you wish), that you receive source code or can get it if you -want it, that you can change the software or use pieces of it in new -free programs, and that you know you can do these things. - - Developers that use our General Public Licenses protect your rights -with two steps: (1) assert copyright on the software, and (2) offer -you this License which gives you legal permission to copy, distribute -and/or modify the software. - - A secondary benefit of defending all users' freedom is that -improvements made in alternate versions of the program, if they -receive widespread use, become available for other developers to -incorporate. Many developers of free software are heartened and -encouraged by the resulting cooperation. However, in the case of -software used on network servers, this result may fail to come about. -The GNU General Public License permits making a modified version and -letting the public access it on a server without ever releasing its -source code to the public. - - The GNU Affero General Public License is designed specifically to -ensure that, in such cases, the modified source code becomes available -to the community. It requires the operator of a network server to -provide the source code of the modified version running there to the -users of that server. Therefore, public use of a modified version, on -a publicly accessible server, gives the public access to the source -code of the modified version. - - An older license, called the Affero General Public License and -published by Affero, was designed to accomplish similar goals. This is -a different license, not a version of the Affero GPL, but Affero has -released a new version of the Affero GPL which permits relicensing under -this license. - - The precise terms and conditions for copying, distribution and -modification follow. - - TERMS AND CONDITIONS - - 0. Definitions. - - "This License" refers to version 3 of the GNU Affero General Public License. - - "Copyright" also means copyright-like laws that apply to other kinds of -works, such as semiconductor masks. - - "The Program" refers to any copyrightable work licensed under this -License. Each licensee is addressed as "you". "Licensees" and -"recipients" may be individuals or organizations. - - To "modify" a work means to copy from or adapt all or part of the work -in a fashion requiring copyright permission, other than the making of an -exact copy. The resulting work is called a "modified version" of the -earlier work or a work "based on" the earlier work. - - A "covered work" means either the unmodified Program or a work based -on the Program. - - To "propagate" a work means to do anything with it that, without -permission, would make you directly or secondarily liable for -infringement under applicable copyright law, except executing it on a -computer or modifying a private copy. Propagation includes copying, -distribution (with or without modification), making available to the -public, and in some countries other activities as well. - - To "convey" a work means any kind of propagation that enables other -parties to make or receive copies. Mere interaction with a user through -a computer network, with no transfer of a copy, is not conveying. - - An interactive user interface displays "Appropriate Legal Notices" -to the extent that it includes a convenient and prominently visible -feature that (1) displays an appropriate copyright notice, and (2) -tells the user that there is no warranty for the work (except to the -extent that warranties are provided), that licensees may convey the -work under this License, and how to view a copy of this License. If -the interface presents a list of user commands or options, such as a -menu, a prominent item in the list meets this criterion. - - 1. Source Code. - - The "source code" for a work means the preferred form of the work -for making modifications to it. "Object code" means any non-source -form of a work. - - A "Standard Interface" means an interface that either is an official -standard defined by a recognized standards body, or, in the case of -interfaces specified for a particular programming language, one that -is widely used among developers working in that language. - - The "System Libraries" of an executable work include anything, other -than the work as a whole, that (a) is included in the normal form of -packaging a Major Component, but which is not part of that Major -Component, and (b) serves only to enable use of the work with that -Major Component, or to implement a Standard Interface for which an -implementation is available to the public in source code form. A -"Major Component", in this context, means a major essential component -(kernel, window system, and so on) of the specific operating system -(if any) on which the executable work runs, or a compiler used to -produce the work, or an object code interpreter used to run it. - - The "Corresponding Source" for a work in object code form means all -the source code needed to generate, install, and (for an executable -work) run the object code and to modify the work, including scripts to -control those activities. However, it does not include the work's -System Libraries, or general-purpose tools or generally available free -programs which are used unmodified in performing those activities but -which are not part of the work. For example, Corresponding Source -includes interface definition files associated with source files for -the work, and the source code for shared libraries and dynamically -linked subprograms that the work is specifically designed to require, -such as by intimate data communication or control flow between those -subprograms and other parts of the work. - - The Corresponding Source need not include anything that users -can regenerate automatically from other parts of the Corresponding -Source. - - The Corresponding Source for a work in source code form is that -same work. - - 2. Basic Permissions. - - All rights granted under this License are granted for the term of -copyright on the Program, and are irrevocable provided the stated -conditions are met. This License explicitly affirms your unlimited -permission to run the unmodified Program. The output from running a -covered work is covered by this License only if the output, given its -content, constitutes a covered work. This License acknowledges your -rights of fair use or other equivalent, as provided by copyright law. - - You may make, run and propagate covered works that you do not -convey, without conditions so long as your license otherwise remains -in force. You may convey covered works to others for the sole purpose -of having them make modifications exclusively for you, or provide you -with facilities for running those works, provided that you comply with -the terms of this License in conveying all material for which you do -not control copyright. Those thus making or running the covered works -for you must do so exclusively on your behalf, under your direction -and control, on terms that prohibit them from making any copies of -your copyrighted material outside their relationship with you. - - Conveying under any other circumstances is permitted solely under -the conditions stated below. Sublicensing is not allowed; section 10 -makes it unnecessary. - - 3. Protecting Users' Legal Rights From Anti-Circumvention Law. - - No covered work shall be deemed part of an effective technological -measure under any applicable law fulfilling obligations under article -11 of the WIPO copyright treaty adopted on 20 December 1996, or -similar laws prohibiting or restricting circumvention of such -measures. - - When you convey a covered work, you waive any legal power to forbid -circumvention of technological measures to the extent such circumvention -is effected by exercising rights under this License with respect to -the covered work, and you disclaim any intention to limit operation or -modification of the work as a means of enforcing, against the work's -users, your or third parties' legal rights to forbid circumvention of -technological measures. - - 4. Conveying Verbatim Copies. - - You may convey verbatim copies of the Program's source code as you -receive it, in any medium, provided that you conspicuously and -appropriately publish on each copy an appropriate copyright notice; -keep intact all notices stating that this License and any -non-permissive terms added in accord with section 7 apply to the code; -keep intact all notices of the absence of any warranty; and give all -recipients a copy of this License along with the Program. - - You may charge any price or no price for each copy that you convey, -and you may offer support or warranty protection for a fee. - - 5. Conveying Modified Source Versions. - - You may convey a work based on the Program, or the modifications to -produce it from the Program, in the form of source code under the -terms of section 4, provided that you also meet all of these conditions: - - a) The work must carry prominent notices stating that you modified - it, and giving a relevant date. - - b) The work must carry prominent notices stating that it is - released under this License and any conditions added under section - 7. This requirement modifies the requirement in section 4 to - "keep intact all notices". - - c) You must license the entire work, as a whole, under this - License to anyone who comes into possession of a copy. This - License will therefore apply, along with any applicable section 7 - additional terms, to the whole of the work, and all its parts, - regardless of how they are packaged. This License gives no - permission to license the work in any other way, but it does not - invalidate such permission if you have separately received it. - - d) If the work has interactive user interfaces, each must display - Appropriate Legal Notices; however, if the Program has interactive - interfaces that do not display Appropriate Legal Notices, your - work need not make them do so. - - A compilation of a covered work with other separate and independent -works, which are not by their nature extensions of the covered work, -and which are not combined with it such as to form a larger program, -in or on a volume of a storage or distribution medium, is called an -"aggregate" if the compilation and its resulting copyright are not -used to limit the access or legal rights of the compilation's users -beyond what the individual works permit. Inclusion of a covered work -in an aggregate does not cause this License to apply to the other -parts of the aggregate. - - 6. Conveying Non-Source Forms. - - You may convey a covered work in object code form under the terms -of sections 4 and 5, provided that you also convey the -machine-readable Corresponding Source under the terms of this License, -in one of these ways: - - a) Convey the object code in, or embodied in, a physical product - (including a physical distribution medium), accompanied by the - Corresponding Source fixed on a durable physical medium - customarily used for software interchange. - - b) Convey the object code in, or embodied in, a physical product - (including a physical distribution medium), accompanied by a - written offer, valid for at least three years and valid for as - long as you offer spare parts or customer support for that product - model, to give anyone who possesses the object code either (1) a - copy of the Corresponding Source for all the software in the - product that is covered by this License, on a durable physical - medium customarily used for software interchange, for a price no - more than your reasonable cost of physically performing this - conveying of source, or (2) access to copy the - Corresponding Source from a network server at no charge. - - c) Convey individual copies of the object code with a copy of the - written offer to provide the Corresponding Source. This - alternative is allowed only occasionally and noncommercially, and - only if you received the object code with such an offer, in accord - with subsection 6b. - - d) Convey the object code by offering access from a designated - place (gratis or for a charge), and offer equivalent access to the - Corresponding Source in the same way through the same place at no - further charge. You need not require recipients to copy the - Corresponding Source along with the object code. If the place to - copy the object code is a network server, the Corresponding Source - may be on a different server (operated by you or a third party) - that supports equivalent copying facilities, provided you maintain - clear directions next to the object code saying where to find the - Corresponding Source. Regardless of what server hosts the - Corresponding Source, you remain obligated to ensure that it is - available for as long as needed to satisfy these requirements. - - e) Convey the object code using peer-to-peer transmission, provided - you inform other peers where the object code and Corresponding - Source of the work are being offered to the general public at no - charge under subsection 6d. - - A separable portion of the object code, whose source code is excluded -from the Corresponding Source as a System Library, need not be -included in conveying the object code work. - - A "User Product" is either (1) a "consumer product", which means any -tangible personal property which is normally used for personal, family, -or household purposes, or (2) anything designed or sold for incorporation -into a dwelling. In determining whether a product is a consumer product, -doubtful cases shall be resolved in favor of coverage. For a particular -product received by a particular user, "normally used" refers to a -typical or common use of that class of product, regardless of the status -of the particular user or of the way in which the particular user -actually uses, or expects or is expected to use, the product. A product -is a consumer product regardless of whether the product has substantial -commercial, industrial or non-consumer uses, unless such uses represent -the only significant mode of use of the product. - - "Installation Information" for a User Product means any methods, -procedures, authorization keys, or other information required to install -and execute modified versions of a covered work in that User Product from -a modified version of its Corresponding Source. The information must -suffice to ensure that the continued functioning of the modified object -code is in no case prevented or interfered with solely because -modification has been made. - - If you convey an object code work under this section in, or with, or -specifically for use in, a User Product, and the conveying occurs as -part of a transaction in which the right of possession and use of the -User Product is transferred to the recipient in perpetuity or for a -fixed term (regardless of how the transaction is characterized), the -Corresponding Source conveyed under this section must be accompanied -by the Installation Information. But this requirement does not apply -if neither you nor any third party retains the ability to install -modified object code on the User Product (for example, the work has -been installed in ROM). - - The requirement to provide Installation Information does not include a -requirement to continue to provide support service, warranty, or updates -for a work that has been modified or installed by the recipient, or for -the User Product in which it has been modified or installed. Access to a -network may be denied when the modification itself materially and -adversely affects the operation of the network or violates the rules and -protocols for communication across the network. - - Corresponding Source conveyed, and Installation Information provided, -in accord with this section must be in a format that is publicly -documented (and with an implementation available to the public in -source code form), and must require no special password or key for -unpacking, reading or copying. - - 7. Additional Terms. - - "Additional permissions" are terms that supplement the terms of this -License by making exceptions from one or more of its conditions. -Additional permissions that are applicable to the entire Program shall -be treated as though they were included in this License, to the extent -that they are valid under applicable law. If additional permissions -apply only to part of the Program, that part may be used separately -under those permissions, but the entire Program remains governed by -this License without regard to the additional permissions. - - When you convey a copy of a covered work, you may at your option -remove any additional permissions from that copy, or from any part of -it. (Additional permissions may be written to require their own -removal in certain cases when you modify the work.) You may place -additional permissions on material, added by you to a covered work, -for which you have or can give appropriate copyright permission. - - Notwithstanding any other provision of this License, for material you -add to a covered work, you may (if authorized by the copyright holders of -that material) supplement the terms of this License with terms: - - a) Disclaiming warranty or limiting liability differently from the - terms of sections 15 and 16 of this License; or - - b) Requiring preservation of specified reasonable legal notices or - author attributions in that material or in the Appropriate Legal - Notices displayed by works containing it; or - - c) Prohibiting misrepresentation of the origin of that material, or - requiring that modified versions of such material be marked in - reasonable ways as different from the original version; or - - d) Limiting the use for publicity purposes of names of licensors or - authors of the material; or - - e) Declining to grant rights under trademark law for use of some - trade names, trademarks, or service marks; or - - f) Requiring indemnification of licensors and authors of that - material by anyone who conveys the material (or modified versions of - it) with contractual assumptions of liability to the recipient, for - any liability that these contractual assumptions directly impose on - those licensors and authors. - - All other non-permissive additional terms are considered "further -restrictions" within the meaning of section 10. If the Program as you -received it, or any part of it, contains a notice stating that it is -governed by this License along with a term that is a further -restriction, you may remove that term. If a license document contains -a further restriction but permits relicensing or conveying under this -License, you may add to a covered work material governed by the terms -of that license document, provided that the further restriction does -not survive such relicensing or conveying. - - If you add terms to a covered work in accord with this section, you -must place, in the relevant source files, a statement of the -additional terms that apply to those files, or a notice indicating -where to find the applicable terms. - - Additional terms, permissive or non-permissive, may be stated in the -form of a separately written license, or stated as exceptions; -the above requirements apply either way. - - 8. Termination. - - You may not propagate or modify a covered work except as expressly -provided under this License. Any attempt otherwise to propagate or -modify it is void, and will automatically terminate your rights under -this License (including any patent licenses granted under the third -paragraph of section 11). - - However, if you cease all violation of this License, then your -license from a particular copyright holder is reinstated (a) -provisionally, unless and until the copyright holder explicitly and -finally terminates your license, and (b) permanently, if the copyright -holder fails to notify you of the violation by some reasonable means -prior to 60 days after the cessation. - - Moreover, your license from a particular copyright holder is -reinstated permanently if the copyright holder notifies you of the -violation by some reasonable means, this is the first time you have -received notice of violation of this License (for any work) from that -copyright holder, and you cure the violation prior to 30 days after -your receipt of the notice. - - Termination of your rights under this section does not terminate the -licenses of parties who have received copies or rights from you under -this License. If your rights have been terminated and not permanently -reinstated, you do not qualify to receive new licenses for the same -material under section 10. - - 9. Acceptance Not Required for Having Copies. - - You are not required to accept this License in order to receive or -run a copy of the Program. Ancillary propagation of a covered work -occurring solely as a consequence of using peer-to-peer transmission -to receive a copy likewise does not require acceptance. However, -nothing other than this License grants you permission to propagate or -modify any covered work. These actions infringe copyright if you do -not accept this License. Therefore, by modifying or propagating a -covered work, you indicate your acceptance of this License to do so. - - 10. Automatic Licensing of Downstream Recipients. - - Each time you convey a covered work, the recipient automatically -receives a license from the original licensors, to run, modify and -propagate that work, subject to this License. You are not responsible -for enforcing compliance by third parties with this License. - - An "entity transaction" is a transaction transferring control of an -organization, or substantially all assets of one, or subdividing an -organization, or merging organizations. If propagation of a covered -work results from an entity transaction, each party to that -transaction who receives a copy of the work also receives whatever -licenses to the work the party's predecessor in interest had or could -give under the previous paragraph, plus a right to possession of the -Corresponding Source of the work from the predecessor in interest, if -the predecessor has it or can get it with reasonable efforts. - - You may not impose any further restrictions on the exercise of the -rights granted or affirmed under this License. For example, you may -not impose a license fee, royalty, or other charge for exercise of -rights granted under this License, and you may not initiate litigation -(including a cross-claim or counterclaim in a lawsuit) alleging that -any patent claim is infringed by making, using, selling, offering for -sale, or importing the Program or any portion of it. - - 11. Patents. - - A "contributor" is a copyright holder who authorizes use under this -License of the Program or a work on which the Program is based. The -work thus licensed is called the contributor's "contributor version". - - A contributor's "essential patent claims" are all patent claims -owned or controlled by the contributor, whether already acquired or -hereafter acquired, that would be infringed by some manner, permitted -by this License, of making, using, or selling its contributor version, -but do not include claims that would be infringed only as a -consequence of further modification of the contributor version. For -purposes of this definition, "control" includes the right to grant -patent sublicenses in a manner consistent with the requirements of -this License. - - Each contributor grants you a non-exclusive, worldwide, royalty-free -patent license under the contributor's essential patent claims, to -make, use, sell, offer for sale, import and otherwise run, modify and -propagate the contents of its contributor version. - - In the following three paragraphs, a "patent license" is any express -agreement or commitment, however denominated, not to enforce a patent -(such as an express permission to practice a patent or covenant not to -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. Remote Network Interaction; Use with the GNU General Public License. - - Notwithstanding any other provision of this License, if you modify the -Program, your modified version must prominently offer all users -interacting with it remotely through a computer network (if your version -supports such interaction) an opportunity to receive the Corresponding -Source of your version by providing access to the Corresponding Source -from a network server at no charge, through some standard or customary -means of facilitating copying of software. This Corresponding Source -shall include the Corresponding Source for any work covered by version 3 -of the GNU General Public License that is incorporated pursuant to the -following paragraph. - - Notwithstanding any other provision of this License, you have -permission to link or combine any covered work with a work licensed -under version 3 of the GNU General Public License into a single -combined work, and to convey the resulting work. The terms of this -License will continue to apply to the part which is the covered work, -but the work with which it is combined will remain governed by version -3 of the GNU General Public License. - - 14. Revised Versions of this License. - - The Free Software Foundation may publish revised and/or new versions of -the GNU Affero General Public License from time to time. Such new versions -will be similar in spirit to the present version, but may differ in detail to -address new problems or concerns. - - Each version is given a distinguishing version number. If the -Program specifies that a certain numbered version of the GNU Affero General -Public License "or any later version" applies to it, you have the -option of following the terms and conditions either of that numbered -version or of any later version published by the Free Software -Foundation. If the Program does not specify a version number of the -GNU Affero General Public License, you may choose any version ever published -by the Free Software Foundation. - - If the Program specifies that a proxy can decide which future -versions of the GNU Affero General Public License can be used, that proxy's -public statement of acceptance of a version permanently authorizes you -to choose that version for the Program. - - Later license versions may give you additional or different -permissions. However, no additional obligations are imposed on any -author or copyright holder as a result of your choosing to follow a -later version. - - 15. Disclaimer of Warranty. - - THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY -APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT -HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY -OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, -THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR -PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM -IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF -ALL NECESSARY SERVICING, REPAIR OR CORRECTION. - - 16. Limitation of Liability. - - IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING -WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS -THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY -GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE -USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF -DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD -PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), -EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF -SUCH DAMAGES. - - 17. Interpretation of Sections 15 and 16. - - If the disclaimer of warranty and limitation of liability provided -above cannot be given local legal effect according to their terms, -reviewing courts shall apply local law that most closely approximates -an absolute waiver of all civil liability in connection with the -Program, unless a warranty or assumption of liability accompanies a -copy of the Program in return for a fee. - - END OF TERMS AND CONDITIONS - - How to Apply These Terms to Your New Programs - - If you develop a new program, and you want it to be of the greatest -possible use to the public, the best way to achieve this is to make it -free software which everyone can redistribute and change under these terms. - - To do so, attach the following notices to the program. It is safest -to attach them to the start of each source file to most effectively -state the exclusion of warranty; and each file should have at least -the "copyright" line and a pointer to where the full notice is found. - - - Copyright (C) - - This program is free software: you can redistribute it and/or modify - it under the terms of the GNU Affero General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU Affero General Public License for more details. - - You should have received a copy of the GNU Affero General Public License - along with this program. If not, see . - -Also add information on how to contact you by electronic and paper mail. - - If your software can interact with users remotely through a computer -network, you should also make sure that it provides a way for users to -get its source. For example, if your program is a web application, its -interface could display a "Source" link that leads users to an archive -of the code. There are many ways you could offer source, and different -solutions will be better for different programs; see section 13 for the -specific requirements. - - You should also get your employer (if you work as a programmer) or school, -if any, to sign a "copyright disclaimer" for the program, if necessary. -For more information on this, and how to apply and follow the GNU AGPL, see -. diff --git a/LICENSE.txt b/LICENSE.txt deleted file mode 100644 index 23cb79033..000000000 --- a/LICENSE.txt +++ /dev/null @@ -1,339 +0,0 @@ - GNU GENERAL PUBLIC LICENSE - Version 2, June 1991 - - Copyright (C) 1989, 1991 Free Software Foundation, Inc., - 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA - Everyone is permitted to copy and distribute verbatim copies - of this license document, but changing it is not allowed. - - Preamble - - The licenses for most software are designed to take away your -freedom to share and change it. By contrast, the GNU General Public -License is intended to guarantee your freedom to share and change free -software--to make sure the software is free for all its users. This -General Public License applies to most of the Free Software -Foundation's software and to any other program whose authors commit to -using it. (Some other Free Software Foundation software is covered by -the GNU Lesser General Public License instead.) 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 -this service 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 make restrictions that forbid -anyone to deny you these rights or to ask you to surrender the rights. -These restrictions translate to certain responsibilities for you if you -distribute copies of the software, or if you modify it. - - For example, if you distribute copies of such a program, whether -gratis or for a fee, you must give the recipients all the rights that -you have. 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. - - We protect your rights with two steps: (1) copyright the software, and -(2) offer you this license which gives you legal permission to copy, -distribute and/or modify the software. - - Also, for each author's protection and ours, we want to make certain -that everyone understands that there is no warranty for this free -software. If the software is modified by someone else and passed on, we -want its recipients to know that what they have is not the original, so -that any problems introduced by others will not reflect on the original -authors' reputations. - - Finally, any free program is threatened constantly by software -patents. We wish to avoid the danger that redistributors of a free -program will individually obtain patent licenses, in effect making the -program proprietary. To prevent this, we have made it clear that any -patent must be licensed for everyone's free use or not licensed at all. - - The precise terms and conditions for copying, distribution and -modification follow. - - GNU GENERAL PUBLIC LICENSE - TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION - - 0. This License applies to any program or other work which contains -a notice placed by the copyright holder saying it may be distributed -under the terms of this General Public License. The "Program", below, -refers to any such program or work, and a "work based on the Program" -means either the Program or any derivative work under copyright law: -that is to say, a work containing the Program or a portion of it, -either verbatim or with modifications and/or translated into another -language. (Hereinafter, translation is included without limitation in -the term "modification".) Each licensee is addressed as "you". - -Activities other than copying, distribution and modification are not -covered by this License; they are outside its scope. The act of -running the Program is not restricted, and the output from the Program -is covered only if its contents constitute a work based on the -Program (independent of having been made by running the Program). -Whether that is true depends on what the Program does. - - 1. You may copy and distribute 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 and disclaimer of warranty; keep intact all the -notices that refer to this License and to the absence of any warranty; -and give any other recipients of the Program a copy of this License -along with the Program. - -You may charge a fee for the physical act of transferring a copy, and -you may at your option offer warranty protection in exchange for a fee. - - 2. You may modify your copy or copies of the Program or any portion -of it, thus forming a work based on the Program, and copy and -distribute such modifications or work under the terms of Section 1 -above, provided that you also meet all of these conditions: - - a) You must cause the modified files to carry prominent notices - stating that you changed the files and the date of any change. - - b) You must cause any work that you distribute or publish, that in - whole or in part contains or is derived from the Program or any - part thereof, to be licensed as a whole at no charge to all third - parties under the terms of this License. - - c) If the modified program normally reads commands interactively - when run, you must cause it, when started running for such - interactive use in the most ordinary way, to print or display an - announcement including an appropriate copyright notice and a - notice that there is no warranty (or else, saying that you provide - a warranty) and that users may redistribute the program under - these conditions, and telling the user how to view a copy of this - License. (Exception: if the Program itself is interactive but - does not normally print such an announcement, your work based on - the Program is not required to print an announcement.) - -These requirements apply to the modified work as a whole. If -identifiable sections of that work are not derived from the Program, -and can be reasonably considered independent and separate works in -themselves, then this License, and its terms, do not apply to those -sections when you distribute them as separate works. But when you -distribute the same sections as part of a whole which is a work based -on the Program, the distribution of the whole must be on the terms of -this License, whose permissions for other licensees extend to the -entire whole, and thus to each and every part regardless of who wrote it. - -Thus, it is not the intent of this section to claim rights or contest -your rights to work written entirely by you; rather, the intent is to -exercise the right to control the distribution of derivative or -collective works based on the Program. - -In addition, mere aggregation of another work not based on the Program -with the Program (or with a work based on the Program) on a volume of -a storage or distribution medium does not bring the other work under -the scope of this License. - - 3. You may copy and distribute the Program (or a work based on it, -under Section 2) in object code or executable form under the terms of -Sections 1 and 2 above provided that you also do one of the following: - - a) Accompany it with the complete corresponding machine-readable - source code, which must be distributed under the terms of Sections - 1 and 2 above on a medium customarily used for software interchange; or, - - b) Accompany it with a written offer, valid for at least three - years, to give any third party, for a charge no more than your - cost of physically performing source distribution, a complete - machine-readable copy of the corresponding source code, to be - distributed under the terms of Sections 1 and 2 above on a medium - customarily used for software interchange; or, - - c) Accompany it with the information you received as to the offer - to distribute corresponding source code. (This alternative is - allowed only for noncommercial distribution and only if you - received the program in object code or executable form with such - an offer, in accord with Subsection b above.) - -The source code for a work means the preferred form of the work for -making modifications to it. For an executable work, complete source -code means all the source code for all modules it contains, plus any -associated interface definition files, plus the scripts used to -control compilation and installation of the executable. However, as a -special exception, the source code distributed need not include -anything that is normally distributed (in either source or binary -form) with the major components (compiler, kernel, and so on) of the -operating system on which the executable runs, unless that component -itself accompanies the executable. - -If distribution of executable or object code is made by offering -access to copy from a designated place, then offering equivalent -access to copy the source code from the same place counts as -distribution of the source code, even though third parties are not -compelled to copy the source along with the object code. - - 4. You may not copy, modify, sublicense, or distribute the Program -except as expressly provided under this License. Any attempt -otherwise to copy, modify, sublicense or distribute the Program is -void, and will automatically terminate your rights under this License. -However, parties who have received copies, or rights, from you under -this License will not have their licenses terminated so long as such -parties remain in full compliance. - - 5. You are not required to accept this License, since you have not -signed it. However, nothing else grants you permission to modify or -distribute the Program or its derivative works. These actions are -prohibited by law if you do not accept this License. Therefore, by -modifying or distributing the Program (or any work based on the -Program), you indicate your acceptance of this License to do so, and -all its terms and conditions for copying, distributing or modifying -the Program or works based on it. - - 6. Each time you redistribute the Program (or any work based on the -Program), the recipient automatically receives a license from the -original licensor to copy, distribute or modify the Program subject to -these terms and conditions. You may not impose any further -restrictions on the recipients' exercise of the rights granted herein. -You are not responsible for enforcing compliance by third parties to -this License. - - 7. If, as a consequence of a court judgment or allegation of patent -infringement or for any other reason (not limited to patent issues), -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 -distribute so as to satisfy simultaneously your obligations under this -License and any other pertinent obligations, then as a consequence you -may not distribute the Program at all. For example, if a patent -license would not permit royalty-free redistribution of the Program by -all those who receive copies directly or indirectly through you, then -the only way you could satisfy both it and this License would be to -refrain entirely from distribution of the Program. - -If any portion of this section is held invalid or unenforceable under -any particular circumstance, the balance of the section is intended to -apply and the section as a whole is intended to apply in other -circumstances. - -It is not the purpose of this section to induce you to infringe any -patents or other property right claims or to contest validity of any -such claims; this section has the sole purpose of protecting the -integrity of the free software distribution system, which is -implemented by public license practices. Many people have made -generous contributions to the wide range of software distributed -through that system in reliance on consistent application of that -system; it is up to the author/donor to decide if he or she is willing -to distribute software through any other system and a licensee cannot -impose that choice. - -This section is intended to make thoroughly clear what is believed to -be a consequence of the rest of this License. - - 8. If the distribution and/or use of the Program is restricted in -certain countries either by patents or by copyrighted interfaces, the -original copyright holder who places the Program under this License -may add an explicit geographical distribution limitation excluding -those countries, so that distribution is permitted only in or among -countries not thus excluded. In such case, this License incorporates -the limitation as if written in the body of this License. - - 9. The Free Software Foundation may publish revised and/or new versions -of the 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 a version number of this License which applies to it and "any -later version", you have the option of following the terms and conditions -either of that version or of any later version published by the Free -Software Foundation. If the Program does not specify a version number of -this License, you may choose any version ever published by the Free Software -Foundation. - - 10. If you wish to incorporate parts of the Program into other free -programs whose distribution conditions are different, write to the author -to ask for permission. For software which is copyrighted by the Free -Software Foundation, write to the Free Software Foundation; we sometimes -make exceptions for this. Our decision will be guided by the two goals -of preserving the free status of all derivatives of our free software and -of promoting the sharing and reuse of software generally. - - NO WARRANTY - - 11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, 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. - - 12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING -WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR -REDISTRIBUTE 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. - - 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 -convey the exclusion of warranty; and each file should have at least -the "copyright" line and a pointer to where the full notice is found. - - {description} - Copyright (C) {year} {fullname} - - 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 2 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, write to the Free Software Foundation, Inc., - 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. - -Also add information on how to contact you by electronic and paper mail. - -If the program is interactive, make it output a short notice like this -when it starts in an interactive mode: - - Gnomovision version 69, Copyright (C) year name of author - Gnomovision 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, the commands you use may -be called something other than `show w' and `show c'; they could even be -mouse-clicks or menu items--whatever suits your program. - -You should also get your employer (if you work as a programmer) or your -school, if any, to sign a "copyright disclaimer" for the program, if -necessary. Here is a sample; alter the names: - - Yoyodyne, Inc., hereby disclaims all copyright interest in the program - `Gnomovision' (which makes passes at compilers) written by James Hacker. - - {signature of Ty Coon}, 1 April 1989 - Ty Coon, President of Vice - -This 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. diff --git a/LICENSES/AGPL-3.0-only.txt b/LICENSES/AGPL-3.0-only.txt new file mode 100644 index 000000000..e37e32e4e --- /dev/null +++ b/LICENSES/AGPL-3.0-only.txt @@ -0,0 +1,613 @@ +GNU AFFERO GENERAL PUBLIC LICENSE + +Version 3, 19 November 2007 + +Copyright (C) 2007 Free Software Foundation, Inc. + +Everyone is permitted to copy and distribute verbatim copies of this license +document, but changing it is not allowed. + +Preamble + +The GNU Affero General Public License is a free, copyleft license for software +and other kinds of works, specifically designed to ensure cooperation with +the community in the case of network server software. + +The licenses for most software and other practical works are designed to take +away your freedom to share and change the works. By contrast, our General +Public Licenses are intended to guarantee your freedom to share and change +all versions of a program--to make sure it remains free software for all its +users. + +When we speak of free software, we are referring to freedom, not price. Our +General Public Licenses are designed to make sure that you have the freedom +to distribute copies of free software (and charge for them if you wish), that +you receive source code or can get it if you want it, that you can change +the software or use pieces of it in new free programs, and that you know you +can do these things. + +Developers that use our General Public Licenses protect your rights with two +steps: (1) assert copyright on the software, and (2) offer you this License +which gives you legal permission to copy, distribute and/or modify the software. + +A secondary benefit of defending all users' freedom is that improvements made +in alternate versions of the program, if they receive widespread use, become +available for other developers to incorporate. Many developers of free software +are heartened and encouraged by the resulting cooperation. However, in the +case of software used on network servers, this result may fail to come about. +The GNU General Public License permits making a modified version and letting +the public access it on a server without ever releasing its source code to +the public. + +The GNU Affero General Public License is designed specifically to ensure that, +in such cases, the modified source code becomes available to the community. +It requires the operator of a network server to provide the source code of +the modified version running there to the users of that server. Therefore, +public use of a modified version, on a publicly accessible server, gives the +public access to the source code of the modified version. + +An older license, called the Affero General Public License and published by +Affero, was designed to accomplish similar goals. This is a different license, +not a version of the Affero GPL, but Affero has released a new version of +the Affero GPL which permits relicensing under this license. + +The precise terms and conditions for copying, distribution and modification +follow. + +TERMS AND CONDITIONS + + 0. Definitions. + + "This License" refers to version 3 of the GNU Affero General Public License. + +"Copyright" also means copyright-like laws that apply to other kinds of works, +such as semiconductor masks. + +"The Program" refers to any copyrightable work licensed under this License. +Each licensee is addressed as "you". "Licensees" and "recipients" may be individuals +or organizations. + +To "modify" a work means to copy from or adapt all or part of the work in +a fashion requiring copyright permission, other than the making of an exact +copy. The resulting work is called a "modified version" of the earlier work +or a work "based on" the earlier work. + +A "covered work" means either the unmodified Program or a work based on the +Program. + +To "propagate" a work means to do anything with it that, without permission, +would make you directly or secondarily liable for infringement under applicable +copyright law, except executing it on a computer or modifying a private copy. +Propagation includes copying, distribution (with or without modification), +making available to the public, and in some countries other activities as +well. + +To "convey" a work means any kind of propagation that enables other parties +to make or receive copies. Mere interaction with a user through a computer +network, with no transfer of a copy, is not conveying. + +An interactive user interface displays "Appropriate Legal Notices" to the +extent that it includes a convenient and prominently visible feature that +(1) displays an appropriate copyright notice, and (2) tells the user that +there is no warranty for the work (except to the extent that warranties are +provided), that licensees may convey the work under this License, and how +to view a copy of this License. If the interface presents a list of user commands +or options, such as a menu, a prominent item in the list meets this criterion. + + 1. Source Code. + +The "source code" for a work means the preferred form of the work for making +modifications to it. "Object code" means any non-source form of a work. + +A "Standard Interface" means an interface that either is an official standard +defined by a recognized standards body, or, in the case of interfaces specified +for a particular programming language, one that is widely used among developers +working in that language. + +The "System Libraries" of an executable work include anything, other than +the work as a whole, that (a) is included in the normal form of packaging +a Major Component, but which is not part of that Major Component, and (b) +serves only to enable use of the work with that Major Component, or to implement +a Standard Interface for which an implementation is available to the public +in source code form. A "Major Component", in this context, means a major essential +component (kernel, window system, and so on) of the specific operating system +(if any) on which the executable work runs, or a compiler used to produce +the work, or an object code interpreter used to run it. + +The "Corresponding Source" for a work in object code form means all the source +code needed to generate, install, and (for an executable work) run the object +code and to modify the work, including scripts to control those activities. +However, it does not include the work's System Libraries, or general-purpose +tools or generally available free programs which are used unmodified in performing +those activities but which are not part of the work. For example, Corresponding +Source includes interface definition files associated with source files for +the work, and the source code for shared libraries and dynamically linked +subprograms that the work is specifically designed to require, such as by +intimate data communication or control flow between those + + subprograms and other parts of the work. + +The Corresponding Source need not include anything that users can regenerate +automatically from other parts of the Corresponding Source. + + The Corresponding Source for a work in source code form is that same work. + + 2. Basic Permissions. + +All rights granted under this License are granted for the term of copyright +on the Program, and are irrevocable provided the stated conditions are met. +This License explicitly affirms your unlimited permission to run the unmodified +Program. The output from running a covered work is covered by this License +only if the output, given its content, constitutes a covered work. This License +acknowledges your rights of fair use or other equivalent, as provided by copyright +law. + +You may make, run and propagate covered works that you do not convey, without +conditions so long as your license otherwise remains in force. You may convey +covered works to others for the sole purpose of having them make modifications +exclusively for you, or provide you with facilities for running those works, +provided that you comply with the terms of this License in conveying all material +for which you do not control copyright. Those thus making or running the covered +works for you must do so exclusively on your behalf, under your direction +and control, on terms that prohibit them from making any copies of your copyrighted +material outside their relationship with you. + +Conveying under any other circumstances is permitted solely under the conditions +stated below. Sublicensing is not allowed; section 10 makes it unnecessary. + + 3. Protecting Users' Legal Rights From Anti-Circumvention Law. + +No covered work shall be deemed part of an effective technological measure +under any applicable law fulfilling obligations under article 11 of the WIPO +copyright treaty adopted on 20 December 1996, or similar laws prohibiting +or restricting circumvention of such measures. + +When you convey a covered work, you waive any legal power to forbid circumvention +of technological measures to the extent such circumvention is effected by +exercising rights under this License with respect to the covered work, and +you disclaim any intention to limit operation or modification of the work +as a means of enforcing, against the work's users, your or third parties' +legal rights to forbid circumvention of technological measures. + + 4. Conveying Verbatim Copies. + +You may convey verbatim copies of the Program's source code as you receive +it, in any medium, provided that you conspicuously and appropriately publish +on each copy an appropriate copyright notice; keep intact all notices stating +that this License and any non-permissive terms added in accord with section +7 apply to the code; keep intact all notices of the absence of any warranty; +and give all recipients a copy of this License along with the Program. + +You may charge any price or no price for each copy that you convey, and you +may offer support or warranty protection for a fee. + + 5. Conveying Modified Source Versions. + +You may convey a work based on the Program, or the modifications to produce +it from the Program, in the form of source code under the terms of section +4, provided that you also meet all of these conditions: + +a) The work must carry prominent notices stating that you modified it, and +giving a relevant date. + +b) The work must carry prominent notices stating that it is released under +this License and any conditions added under section 7. This requirement modifies +the requirement in section 4 to "keep intact all notices". + +c) You must license the entire work, as a whole, under this License to anyone +who comes into possession of a copy. This License will therefore apply, along +with any applicable section 7 additional terms, to the whole of the work, +and all its parts, regardless of how they are packaged. This License gives +no permission to license the work in any other way, but it does not invalidate +such permission if you have separately received it. + +d) If the work has interactive user interfaces, each must display Appropriate +Legal Notices; however, if the Program has interactive interfaces that do +not display Appropriate Legal Notices, your work need not make them do so. + +A compilation of a covered work with other separate and independent works, +which are not by their nature extensions of the covered work, and which are +not combined with it such as to form a larger program, in or on a volume of +a storage or distribution medium, is called an "aggregate" if the compilation +and its resulting copyright are not used to limit the access or legal rights +of the compilation's users beyond what the individual works permit. Inclusion +of a covered work in an aggregate does not cause this License to apply to +the other parts of the aggregate. + + 6. Conveying Non-Source Forms. + +You may convey a covered work in object code form under the terms of sections +4 and 5, provided that you also convey the machine-readable Corresponding +Source under the terms of this License, in one of these ways: + +a) Convey the object code in, or embodied in, a physical product (including +a physical distribution medium), accompanied by the Corresponding Source fixed +on a durable physical medium customarily used for software interchange. + +b) Convey the object code in, or embodied in, a physical product (including +a physical distribution medium), accompanied by a written offer, valid for +at least three years and valid for as long as you offer spare parts or customer +support for that product model, to give anyone who possesses the object code +either (1) a copy of the Corresponding Source for all the software in the +product that is covered by this License, on a durable physical medium customarily +used for software interchange, for a price no more than your reasonable cost +of physically performing this conveying of source, or (2) access to copy the +Corresponding Source from a network server at no charge. + +c) Convey individual copies of the object code with a copy of the written +offer to provide the Corresponding Source. This alternative is allowed only +occasionally and noncommercially, and only if you received the object code +with such an offer, in accord with subsection 6b. + +d) Convey the object code by offering access from a designated place (gratis +or for a charge), and offer equivalent access to the Corresponding Source +in the same way through the same place at no further charge. You need not +require recipients to copy the Corresponding Source along with the object +code. If the place to copy the object code is a network server, the Corresponding +Source may be on a different server (operated by you or a third party) that +supports equivalent copying facilities, provided you maintain clear directions +next to the object code saying where to find the Corresponding Source. Regardless +of what server hosts the Corresponding Source, you remain obligated to ensure +that it is available for as long as needed to satisfy these requirements. + +e) Convey the object code using peer-to-peer transmission, provided you inform +other peers where the object code and Corresponding Source of the work are +being offered to the general public at no charge under subsection 6d. + +A separable portion of the object code, whose source code is excluded from +the Corresponding Source as a System Library, need not be included in conveying +the object code work. + +A "User Product" is either (1) a "consumer product", which means any tangible +personal property which is normally used for personal, family, or household +purposes, or (2) anything designed or sold for incorporation into a dwelling. +In determining whether a product is a consumer product, doubtful cases shall +be resolved in favor of coverage. For a particular product received by a particular +user, "normally used" refers to a typical or common use of that class of product, +regardless of the status of the particular user or of the way in which the +particular user actually uses, or expects or is expected to use, the product. +A product is a consumer product regardless of whether the product has substantial +commercial, industrial or non-consumer uses, unless such uses represent the +only significant mode of use of the product. + +"Installation Information" for a User Product means any methods, procedures, +authorization keys, or other information required to install and execute modified +versions of a covered work in that User Product from a modified version of +its Corresponding Source. The information must suffice to ensure that the +continued functioning of the modified object code is in no case prevented +or interfered with solely because modification has been made. + +If you convey an object code work under this section in, or with, or specifically +for use in, a User Product, and the conveying occurs as part of a transaction +in which the right of possession and use of the User Product is transferred +to the recipient in perpetuity or for a fixed term (regardless of how the +transaction is characterized), the Corresponding Source conveyed under this +section must be accompanied by the Installation Information. But this requirement +does not apply if neither you nor any third party retains the ability to install +modified object code on the User Product (for example, the work has been installed +in ROM). + +The requirement to provide Installation Information does not include a requirement +to continue to provide support service, warranty, or updates for a work that +has been modified or installed by the recipient, or for the User Product in +which it has been modified or installed. Access to a network may be denied +when the modification itself materially and adversely affects the operation +of the network or violates the rules and protocols for communication across +the network. + +Corresponding Source conveyed, and Installation Information provided, in accord +with this section must be in a format that is publicly documented (and with +an implementation available to the public in source code form), and must require +no special password or key for unpacking, reading or copying. + + 7. Additional Terms. + +"Additional permissions" are terms that supplement the terms of this License +by making exceptions from one or more of its conditions. Additional permissions +that are applicable to the entire Program shall be treated as though they +were included in this License, to the extent that they are valid under applicable +law. If additional permissions apply only to part of the Program, that part +may be used separately under those permissions, but the entire Program remains +governed by this License without regard to the additional permissions. + +When you convey a copy of a covered work, you may at your option remove any +additional permissions from that copy, or from any part of it. (Additional +permissions may be written to require their own removal in certain cases when +you modify the work.) You may place additional permissions on material, added +by you to a covered work, for which you have or can give appropriate copyright +permission. + +Notwithstanding any other provision of this License, for material you add +to a covered work, you may (if authorized by the copyright holders of that +material) supplement the terms of this License with terms: + +a) Disclaiming warranty or limiting liability differently from the terms of +sections 15 and 16 of this License; or + +b) Requiring preservation of specified reasonable legal notices or author +attributions in that material or in the Appropriate Legal Notices displayed +by works containing it; or + +c) Prohibiting misrepresentation of the origin of that material, or requiring +that modified versions of such material be marked in reasonable ways as different +from the original version; or + +d) Limiting the use for publicity purposes of names of licensors or authors +of the material; or + +e) Declining to grant rights under trademark law for use of some trade names, +trademarks, or service marks; or + +f) Requiring indemnification of licensors and authors of that material by +anyone who conveys the material (or modified versions of it) with contractual +assumptions of liability to the recipient, for any liability that these contractual +assumptions directly impose on those licensors and authors. + +All other non-permissive additional terms are considered "further restrictions" +within the meaning of section 10. If the Program as you received it, or any +part of it, contains a notice stating that it is governed by this License +along with a term that is a further restriction, you may remove that term. +If a license document contains a further restriction but permits relicensing +or conveying under this License, you may add to a covered work material governed +by the terms of that license document, provided that the further restriction +does not survive such relicensing or conveying. + +If you add terms to a covered work in accord with this section, you must place, +in the relevant source files, a statement of the additional terms that apply +to those files, or a notice indicating where to find the applicable terms. + +Additional terms, permissive or non-permissive, may be stated in the form +of a separately written license, or stated as exceptions; the above requirements +apply either way. + + 8. Termination. + +You may not propagate or modify a covered work except as expressly provided +under this License. Any attempt otherwise to propagate or modify it is void, +and will automatically terminate your rights under this License (including +any patent licenses granted under the third paragraph of section 11). + +However, if you cease all violation of this License, then your license from +a particular copyright holder is reinstated (a) provisionally, unless and +until the copyright holder explicitly and finally terminates your license, +and (b) permanently, if the copyright holder fails to notify you of the violation +by some reasonable means prior to 60 days after the cessation. + +Moreover, your license from a particular copyright holder is reinstated permanently +if the copyright holder notifies you of the violation by some reasonable means, +this is the first time you have received notice of violation of this License +(for any work) from that copyright holder, and you cure the violation prior +to 30 days after your receipt of the notice. + +Termination of your rights under this section does not terminate the licenses +of parties who have received copies or rights from you under this License. +If your rights have been terminated and not permanently reinstated, you do +not qualify to receive new licenses for the same material under section 10. + + 9. Acceptance Not Required for Having Copies. + +You are not required to accept this License in order to receive or run a copy +of the Program. Ancillary propagation of a covered work occurring solely as +a consequence of using peer-to-peer transmission to receive a copy likewise +does not require acceptance. However, nothing other than this License grants +you permission to propagate or modify any covered work. These actions infringe +copyright if you do not accept this License. Therefore, by modifying or propagating +a covered work, you indicate your acceptance of this License to do so. + + 10. Automatic Licensing of Downstream Recipients. + +Each time you convey a covered work, the recipient automatically receives +a license from the original licensors, to run, modify and propagate that work, +subject to this License. You are not responsible for enforcing compliance +by third parties with this License. + +An "entity transaction" is a transaction transferring control of an organization, +or substantially all assets of one, or subdividing an organization, or merging +organizations. If propagation of a covered work results from an entity transaction, +each party to that transaction who receives a copy of the work also receives +whatever licenses to the work the party's predecessor in interest had or could +give under the previous paragraph, plus a right to possession of the Corresponding +Source of the work from the predecessor in interest, if the predecessor has +it or can get it with reasonable efforts. + +You may not impose any further restrictions on the exercise of the rights +granted or affirmed under this License. For example, you may not impose a +license fee, royalty, or other charge for exercise of rights granted under +this License, and you may not initiate litigation (including a cross-claim +or counterclaim in a lawsuit) alleging that any patent claim is infringed +by making, using, selling, offering for sale, or importing the Program or +any portion of it. + + 11. Patents. + +A "contributor" is a copyright holder who authorizes use under this License +of the Program or a work on which the Program is based. The work thus licensed +is called the contributor's "contributor version". + +A contributor's "essential patent claims" are all patent claims owned or controlled +by the contributor, whether already acquired or hereafter acquired, that would +be infringed by some manner, permitted by this License, of making, using, +or selling its contributor version, but do not include claims that would be +infringed only as a consequence of further modification of the contributor +version. For purposes of this definition, "control" includes the right to +grant patent sublicenses in a manner consistent with the requirements of this +License. + +Each contributor grants you a non-exclusive, worldwide, royalty-free patent +license under the contributor's essential patent claims, to make, use, sell, +offer for sale, import and otherwise run, modify and propagate the contents +of its contributor version. + +In the following three paragraphs, a "patent license" is any express agreement +or commitment, however denominated, not to enforce a patent (such as an express +permission to practice a patent or covenant not to s ue for patent infringement). +To "grant" such a patent license to a party means to make such an agreement +or commitment not to enforce a patent against the party. + +If you convey a covered work, knowingly relying on a patent license, and the +Corresponding Source of the work is not available for anyone to copy, free +of charge and under the terms of this License, through a publicly available +network server or other readily accessible means, then you must either (1) +cause the Corresponding Source to be so available, or (2) arrange to deprive +yourself of the benefit of the patent license for this particular work, or +(3) arrange, in a manner consistent with the requirements of this License, +to extend the patent + +license to downstream recipients. "Knowingly relying" means you have actual +knowledge that, but for the patent license, your conveying the covered work +in a country, or your recipient's use of the covered work in a country, would +infringe one or more identifiable patents in that country that you have reason +to believe are valid. + +If, pursuant to or in connection with a single transaction or arrangement, +you convey, or propagate by procuring conveyance of, a covered work, and grant +a patent license to some of the parties receiving the covered work authorizing +them to use, propagate, modify or convey a specific copy of the covered work, +then the patent license you grant is automatically extended to all recipients +of the covered work and works based on it. + +A patent license is "discriminatory" if it does not include within the scope +of its coverage, prohibits the exercise of, or is conditioned on the non-exercise +of one or more of the rights that are specifically granted under this License. +You may not convey a covered work if you are a party to an arrangement with +a third party that is in the business of distributing software, under which +you make payment to the third party based on the extent of your activity of +conveying the work, and under which the third party grants, to any of the +parties who would receive the covered work from you, a discriminatory patent +license (a) in connection with copies of the covered work conveyed by you +(or copies made from those copies), or (b) primarily for and in connection +with specific products or compilations that contain the covered work, unless +you entered into that arrangement, or that patent license was granted, prior +to 28 March 2007. + +Nothing in this License shall be construed as excluding or limiting any implied +license or other defenses to infringement that may otherwise be available +to you under applicable patent law. + + 12. No Surrender of Others' Freedom. + +If conditions are imposed on you (whether by court order, agreement or otherwise) +that contradict the conditions of this License, they do not excuse you from +the conditions of this License. If you cannot convey a covered work so as +to satisfy simultaneously your obligations under this License and any other +pertinent obligations, then as a consequence you may + +not convey it at all. For example, if you agree to terms that obligate you +to collect a royalty for further conveying from those to whom you convey the +Program, the only way you could satisfy both those terms and this License +would be to refrain entirely from conveying the Program. + + 13. Remote Network Interaction; Use with the GNU General Public License. + +Notwithstanding any other provision of this License, if you modify the Program, +your modified version must prominently offer all users interacting with it +remotely through a computer network (if your version supports such interaction) +an opportunity to receive the Corresponding Source of your version by providing +access to the Corresponding Source from a network server at no charge, through +some standard or customary means of facilitating copying of software. This +Corresponding Source shall include the Corresponding Source for any work covered +by version 3 of the GNU General Public License that is incorporated pursuant +to the following paragraph. + +Notwithstanding any other provision of this License, you have permission to +link or combine any covered work with a work licensed under version 3 of the +GNU General Public License into a single combined work, and to convey the +resulting work. The terms of this License will continue to apply to the part +which is the covered work, but the work with which it is combined will remain +governed by version 3 of the GNU General Public License. + + 14. Revised Versions of this License. + +The Free Software Foundation may publish revised and/or new versions of the +GNU Affero General Public License from time to time. Such new versions will +be similar in spirit to the present version, but may differ in detail to address +new problems or concerns. + +Each version is given a distinguishing version number. If the Program specifies +that a certain numbered version of the GNU Affero General Public License "or +any later version" applies to it, you have the option of following the terms +and conditions either of that numbered version or of any later version published +by the Free Software Foundation. If the Program does not specify a version +number of the GNU Affero General Public License, you may choose any version +ever published by the Free Software Foundation. + +If the Program specifies that a proxy can decide which future versions of +the GNU Affero General Public License can be used, that proxy's public statement +of acceptance of a version permanently authorizes you to choose that version +for the Program. + +Later license versions may give you additional or different permissions. However, +no additional obligations are imposed on any author or copyright holder as +a result of your choosing to follow a later version. + + 15. Disclaimer of Warranty. + +THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE +LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR +OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER +EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES +OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS +TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM +PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR +CORRECTION. + + 16. Limitation of Liability. + +IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL +ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS THE PROGRAM +AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, +INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO +USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED +INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE +PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER +PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. + + 17. Interpretation of Sections 15 and 16. + +If the disclaimer of warranty and limitation of liability provided above cannot +be given local legal effect according to their terms, reviewing courts shall +apply local law that most closely approximates an absolute waiver of all civil +liability in connection with the Program, unless a warranty or assumption +of liability accompanies a copy of the Program in return for a fee. END OF +TERMS AND CONDITIONS + +How to Apply These Terms to Your New Programs + +If you develop a new program, and you want it to be of the greatest possible +use to the public, the best way to achieve this is to make it free software +which everyone can redistribute and change under these terms. + +To do so, attach the following notices to the program. It is safest to attach +them to the start of each source file to most effectively state the exclusion +of warranty; and each file should have at least the "copyright" line and a +pointer to where the full notice is found. + + + +Copyright (C) + +This program is free software: you can redistribute it and/or modify it under +the terms of the GNU Affero General Public License as published by the Free +Software Foundation, either version 3 of the License, or (at your option) +any later version. + +This program is distributed in the hope that it will be useful, but WITHOUT +ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS +FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more +details. + +You should have received a copy of the GNU Affero General Public License along +with this program. If not, see . + +Also add information on how to contact you by electronic and paper mail. + +If your software can interact with users remotely through a computer network, +you should also make sure that it provides a way for users to get its source. +For example, if your program is a web application, its interface could display +a "Source" link that leads users to an archive of the code. There are many +ways you could offer source, and different solutions will be better for different +programs; see section 13 for the specific requirements. + +You should also get your employer (if you work as a programmer) or school, +if any, to sign a "copyright disclaimer" for the program, if necessary. For +more information on this, and how to apply and follow the GNU AGPL, see . diff --git a/LICENSES/AGPL-3.0-or-later.txt b/LICENSES/AGPL-3.0-or-later.txt new file mode 100644 index 000000000..e37e32e4e --- /dev/null +++ b/LICENSES/AGPL-3.0-or-later.txt @@ -0,0 +1,613 @@ +GNU AFFERO GENERAL PUBLIC LICENSE + +Version 3, 19 November 2007 + +Copyright (C) 2007 Free Software Foundation, Inc. + +Everyone is permitted to copy and distribute verbatim copies of this license +document, but changing it is not allowed. + +Preamble + +The GNU Affero General Public License is a free, copyleft license for software +and other kinds of works, specifically designed to ensure cooperation with +the community in the case of network server software. + +The licenses for most software and other practical works are designed to take +away your freedom to share and change the works. By contrast, our General +Public Licenses are intended to guarantee your freedom to share and change +all versions of a program--to make sure it remains free software for all its +users. + +When we speak of free software, we are referring to freedom, not price. Our +General Public Licenses are designed to make sure that you have the freedom +to distribute copies of free software (and charge for them if you wish), that +you receive source code or can get it if you want it, that you can change +the software or use pieces of it in new free programs, and that you know you +can do these things. + +Developers that use our General Public Licenses protect your rights with two +steps: (1) assert copyright on the software, and (2) offer you this License +which gives you legal permission to copy, distribute and/or modify the software. + +A secondary benefit of defending all users' freedom is that improvements made +in alternate versions of the program, if they receive widespread use, become +available for other developers to incorporate. Many developers of free software +are heartened and encouraged by the resulting cooperation. However, in the +case of software used on network servers, this result may fail to come about. +The GNU General Public License permits making a modified version and letting +the public access it on a server without ever releasing its source code to +the public. + +The GNU Affero General Public License is designed specifically to ensure that, +in such cases, the modified source code becomes available to the community. +It requires the operator of a network server to provide the source code of +the modified version running there to the users of that server. Therefore, +public use of a modified version, on a publicly accessible server, gives the +public access to the source code of the modified version. + +An older license, called the Affero General Public License and published by +Affero, was designed to accomplish similar goals. This is a different license, +not a version of the Affero GPL, but Affero has released a new version of +the Affero GPL which permits relicensing under this license. + +The precise terms and conditions for copying, distribution and modification +follow. + +TERMS AND CONDITIONS + + 0. Definitions. + + "This License" refers to version 3 of the GNU Affero General Public License. + +"Copyright" also means copyright-like laws that apply to other kinds of works, +such as semiconductor masks. + +"The Program" refers to any copyrightable work licensed under this License. +Each licensee is addressed as "you". "Licensees" and "recipients" may be individuals +or organizations. + +To "modify" a work means to copy from or adapt all or part of the work in +a fashion requiring copyright permission, other than the making of an exact +copy. The resulting work is called a "modified version" of the earlier work +or a work "based on" the earlier work. + +A "covered work" means either the unmodified Program or a work based on the +Program. + +To "propagate" a work means to do anything with it that, without permission, +would make you directly or secondarily liable for infringement under applicable +copyright law, except executing it on a computer or modifying a private copy. +Propagation includes copying, distribution (with or without modification), +making available to the public, and in some countries other activities as +well. + +To "convey" a work means any kind of propagation that enables other parties +to make or receive copies. Mere interaction with a user through a computer +network, with no transfer of a copy, is not conveying. + +An interactive user interface displays "Appropriate Legal Notices" to the +extent that it includes a convenient and prominently visible feature that +(1) displays an appropriate copyright notice, and (2) tells the user that +there is no warranty for the work (except to the extent that warranties are +provided), that licensees may convey the work under this License, and how +to view a copy of this License. If the interface presents a list of user commands +or options, such as a menu, a prominent item in the list meets this criterion. + + 1. Source Code. + +The "source code" for a work means the preferred form of the work for making +modifications to it. "Object code" means any non-source form of a work. + +A "Standard Interface" means an interface that either is an official standard +defined by a recognized standards body, or, in the case of interfaces specified +for a particular programming language, one that is widely used among developers +working in that language. + +The "System Libraries" of an executable work include anything, other than +the work as a whole, that (a) is included in the normal form of packaging +a Major Component, but which is not part of that Major Component, and (b) +serves only to enable use of the work with that Major Component, or to implement +a Standard Interface for which an implementation is available to the public +in source code form. A "Major Component", in this context, means a major essential +component (kernel, window system, and so on) of the specific operating system +(if any) on which the executable work runs, or a compiler used to produce +the work, or an object code interpreter used to run it. + +The "Corresponding Source" for a work in object code form means all the source +code needed to generate, install, and (for an executable work) run the object +code and to modify the work, including scripts to control those activities. +However, it does not include the work's System Libraries, or general-purpose +tools or generally available free programs which are used unmodified in performing +those activities but which are not part of the work. For example, Corresponding +Source includes interface definition files associated with source files for +the work, and the source code for shared libraries and dynamically linked +subprograms that the work is specifically designed to require, such as by +intimate data communication or control flow between those + + subprograms and other parts of the work. + +The Corresponding Source need not include anything that users can regenerate +automatically from other parts of the Corresponding Source. + + The Corresponding Source for a work in source code form is that same work. + + 2. Basic Permissions. + +All rights granted under this License are granted for the term of copyright +on the Program, and are irrevocable provided the stated conditions are met. +This License explicitly affirms your unlimited permission to run the unmodified +Program. The output from running a covered work is covered by this License +only if the output, given its content, constitutes a covered work. This License +acknowledges your rights of fair use or other equivalent, as provided by copyright +law. + +You may make, run and propagate covered works that you do not convey, without +conditions so long as your license otherwise remains in force. You may convey +covered works to others for the sole purpose of having them make modifications +exclusively for you, or provide you with facilities for running those works, +provided that you comply with the terms of this License in conveying all material +for which you do not control copyright. Those thus making or running the covered +works for you must do so exclusively on your behalf, under your direction +and control, on terms that prohibit them from making any copies of your copyrighted +material outside their relationship with you. + +Conveying under any other circumstances is permitted solely under the conditions +stated below. Sublicensing is not allowed; section 10 makes it unnecessary. + + 3. Protecting Users' Legal Rights From Anti-Circumvention Law. + +No covered work shall be deemed part of an effective technological measure +under any applicable law fulfilling obligations under article 11 of the WIPO +copyright treaty adopted on 20 December 1996, or similar laws prohibiting +or restricting circumvention of such measures. + +When you convey a covered work, you waive any legal power to forbid circumvention +of technological measures to the extent such circumvention is effected by +exercising rights under this License with respect to the covered work, and +you disclaim any intention to limit operation or modification of the work +as a means of enforcing, against the work's users, your or third parties' +legal rights to forbid circumvention of technological measures. + + 4. Conveying Verbatim Copies. + +You may convey verbatim copies of the Program's source code as you receive +it, in any medium, provided that you conspicuously and appropriately publish +on each copy an appropriate copyright notice; keep intact all notices stating +that this License and any non-permissive terms added in accord with section +7 apply to the code; keep intact all notices of the absence of any warranty; +and give all recipients a copy of this License along with the Program. + +You may charge any price or no price for each copy that you convey, and you +may offer support or warranty protection for a fee. + + 5. Conveying Modified Source Versions. + +You may convey a work based on the Program, or the modifications to produce +it from the Program, in the form of source code under the terms of section +4, provided that you also meet all of these conditions: + +a) The work must carry prominent notices stating that you modified it, and +giving a relevant date. + +b) The work must carry prominent notices stating that it is released under +this License and any conditions added under section 7. This requirement modifies +the requirement in section 4 to "keep intact all notices". + +c) You must license the entire work, as a whole, under this License to anyone +who comes into possession of a copy. This License will therefore apply, along +with any applicable section 7 additional terms, to the whole of the work, +and all its parts, regardless of how they are packaged. This License gives +no permission to license the work in any other way, but it does not invalidate +such permission if you have separately received it. + +d) If the work has interactive user interfaces, each must display Appropriate +Legal Notices; however, if the Program has interactive interfaces that do +not display Appropriate Legal Notices, your work need not make them do so. + +A compilation of a covered work with other separate and independent works, +which are not by their nature extensions of the covered work, and which are +not combined with it such as to form a larger program, in or on a volume of +a storage or distribution medium, is called an "aggregate" if the compilation +and its resulting copyright are not used to limit the access or legal rights +of the compilation's users beyond what the individual works permit. Inclusion +of a covered work in an aggregate does not cause this License to apply to +the other parts of the aggregate. + + 6. Conveying Non-Source Forms. + +You may convey a covered work in object code form under the terms of sections +4 and 5, provided that you also convey the machine-readable Corresponding +Source under the terms of this License, in one of these ways: + +a) Convey the object code in, or embodied in, a physical product (including +a physical distribution medium), accompanied by the Corresponding Source fixed +on a durable physical medium customarily used for software interchange. + +b) Convey the object code in, or embodied in, a physical product (including +a physical distribution medium), accompanied by a written offer, valid for +at least three years and valid for as long as you offer spare parts or customer +support for that product model, to give anyone who possesses the object code +either (1) a copy of the Corresponding Source for all the software in the +product that is covered by this License, on a durable physical medium customarily +used for software interchange, for a price no more than your reasonable cost +of physically performing this conveying of source, or (2) access to copy the +Corresponding Source from a network server at no charge. + +c) Convey individual copies of the object code with a copy of the written +offer to provide the Corresponding Source. This alternative is allowed only +occasionally and noncommercially, and only if you received the object code +with such an offer, in accord with subsection 6b. + +d) Convey the object code by offering access from a designated place (gratis +or for a charge), and offer equivalent access to the Corresponding Source +in the same way through the same place at no further charge. You need not +require recipients to copy the Corresponding Source along with the object +code. If the place to copy the object code is a network server, the Corresponding +Source may be on a different server (operated by you or a third party) that +supports equivalent copying facilities, provided you maintain clear directions +next to the object code saying where to find the Corresponding Source. Regardless +of what server hosts the Corresponding Source, you remain obligated to ensure +that it is available for as long as needed to satisfy these requirements. + +e) Convey the object code using peer-to-peer transmission, provided you inform +other peers where the object code and Corresponding Source of the work are +being offered to the general public at no charge under subsection 6d. + +A separable portion of the object code, whose source code is excluded from +the Corresponding Source as a System Library, need not be included in conveying +the object code work. + +A "User Product" is either (1) a "consumer product", which means any tangible +personal property which is normally used for personal, family, or household +purposes, or (2) anything designed or sold for incorporation into a dwelling. +In determining whether a product is a consumer product, doubtful cases shall +be resolved in favor of coverage. For a particular product received by a particular +user, "normally used" refers to a typical or common use of that class of product, +regardless of the status of the particular user or of the way in which the +particular user actually uses, or expects or is expected to use, the product. +A product is a consumer product regardless of whether the product has substantial +commercial, industrial or non-consumer uses, unless such uses represent the +only significant mode of use of the product. + +"Installation Information" for a User Product means any methods, procedures, +authorization keys, or other information required to install and execute modified +versions of a covered work in that User Product from a modified version of +its Corresponding Source. The information must suffice to ensure that the +continued functioning of the modified object code is in no case prevented +or interfered with solely because modification has been made. + +If you convey an object code work under this section in, or with, or specifically +for use in, a User Product, and the conveying occurs as part of a transaction +in which the right of possession and use of the User Product is transferred +to the recipient in perpetuity or for a fixed term (regardless of how the +transaction is characterized), the Corresponding Source conveyed under this +section must be accompanied by the Installation Information. But this requirement +does not apply if neither you nor any third party retains the ability to install +modified object code on the User Product (for example, the work has been installed +in ROM). + +The requirement to provide Installation Information does not include a requirement +to continue to provide support service, warranty, or updates for a work that +has been modified or installed by the recipient, or for the User Product in +which it has been modified or installed. Access to a network may be denied +when the modification itself materially and adversely affects the operation +of the network or violates the rules and protocols for communication across +the network. + +Corresponding Source conveyed, and Installation Information provided, in accord +with this section must be in a format that is publicly documented (and with +an implementation available to the public in source code form), and must require +no special password or key for unpacking, reading or copying. + + 7. Additional Terms. + +"Additional permissions" are terms that supplement the terms of this License +by making exceptions from one or more of its conditions. Additional permissions +that are applicable to the entire Program shall be treated as though they +were included in this License, to the extent that they are valid under applicable +law. If additional permissions apply only to part of the Program, that part +may be used separately under those permissions, but the entire Program remains +governed by this License without regard to the additional permissions. + +When you convey a copy of a covered work, you may at your option remove any +additional permissions from that copy, or from any part of it. (Additional +permissions may be written to require their own removal in certain cases when +you modify the work.) You may place additional permissions on material, added +by you to a covered work, for which you have or can give appropriate copyright +permission. + +Notwithstanding any other provision of this License, for material you add +to a covered work, you may (if authorized by the copyright holders of that +material) supplement the terms of this License with terms: + +a) Disclaiming warranty or limiting liability differently from the terms of +sections 15 and 16 of this License; or + +b) Requiring preservation of specified reasonable legal notices or author +attributions in that material or in the Appropriate Legal Notices displayed +by works containing it; or + +c) Prohibiting misrepresentation of the origin of that material, or requiring +that modified versions of such material be marked in reasonable ways as different +from the original version; or + +d) Limiting the use for publicity purposes of names of licensors or authors +of the material; or + +e) Declining to grant rights under trademark law for use of some trade names, +trademarks, or service marks; or + +f) Requiring indemnification of licensors and authors of that material by +anyone who conveys the material (or modified versions of it) with contractual +assumptions of liability to the recipient, for any liability that these contractual +assumptions directly impose on those licensors and authors. + +All other non-permissive additional terms are considered "further restrictions" +within the meaning of section 10. If the Program as you received it, or any +part of it, contains a notice stating that it is governed by this License +along with a term that is a further restriction, you may remove that term. +If a license document contains a further restriction but permits relicensing +or conveying under this License, you may add to a covered work material governed +by the terms of that license document, provided that the further restriction +does not survive such relicensing or conveying. + +If you add terms to a covered work in accord with this section, you must place, +in the relevant source files, a statement of the additional terms that apply +to those files, or a notice indicating where to find the applicable terms. + +Additional terms, permissive or non-permissive, may be stated in the form +of a separately written license, or stated as exceptions; the above requirements +apply either way. + + 8. Termination. + +You may not propagate or modify a covered work except as expressly provided +under this License. Any attempt otherwise to propagate or modify it is void, +and will automatically terminate your rights under this License (including +any patent licenses granted under the third paragraph of section 11). + +However, if you cease all violation of this License, then your license from +a particular copyright holder is reinstated (a) provisionally, unless and +until the copyright holder explicitly and finally terminates your license, +and (b) permanently, if the copyright holder fails to notify you of the violation +by some reasonable means prior to 60 days after the cessation. + +Moreover, your license from a particular copyright holder is reinstated permanently +if the copyright holder notifies you of the violation by some reasonable means, +this is the first time you have received notice of violation of this License +(for any work) from that copyright holder, and you cure the violation prior +to 30 days after your receipt of the notice. + +Termination of your rights under this section does not terminate the licenses +of parties who have received copies or rights from you under this License. +If your rights have been terminated and not permanently reinstated, you do +not qualify to receive new licenses for the same material under section 10. + + 9. Acceptance Not Required for Having Copies. + +You are not required to accept this License in order to receive or run a copy +of the Program. Ancillary propagation of a covered work occurring solely as +a consequence of using peer-to-peer transmission to receive a copy likewise +does not require acceptance. However, nothing other than this License grants +you permission to propagate or modify any covered work. These actions infringe +copyright if you do not accept this License. Therefore, by modifying or propagating +a covered work, you indicate your acceptance of this License to do so. + + 10. Automatic Licensing of Downstream Recipients. + +Each time you convey a covered work, the recipient automatically receives +a license from the original licensors, to run, modify and propagate that work, +subject to this License. You are not responsible for enforcing compliance +by third parties with this License. + +An "entity transaction" is a transaction transferring control of an organization, +or substantially all assets of one, or subdividing an organization, or merging +organizations. If propagation of a covered work results from an entity transaction, +each party to that transaction who receives a copy of the work also receives +whatever licenses to the work the party's predecessor in interest had or could +give under the previous paragraph, plus a right to possession of the Corresponding +Source of the work from the predecessor in interest, if the predecessor has +it or can get it with reasonable efforts. + +You may not impose any further restrictions on the exercise of the rights +granted or affirmed under this License. For example, you may not impose a +license fee, royalty, or other charge for exercise of rights granted under +this License, and you may not initiate litigation (including a cross-claim +or counterclaim in a lawsuit) alleging that any patent claim is infringed +by making, using, selling, offering for sale, or importing the Program or +any portion of it. + + 11. Patents. + +A "contributor" is a copyright holder who authorizes use under this License +of the Program or a work on which the Program is based. The work thus licensed +is called the contributor's "contributor version". + +A contributor's "essential patent claims" are all patent claims owned or controlled +by the contributor, whether already acquired or hereafter acquired, that would +be infringed by some manner, permitted by this License, of making, using, +or selling its contributor version, but do not include claims that would be +infringed only as a consequence of further modification of the contributor +version. For purposes of this definition, "control" includes the right to +grant patent sublicenses in a manner consistent with the requirements of this +License. + +Each contributor grants you a non-exclusive, worldwide, royalty-free patent +license under the contributor's essential patent claims, to make, use, sell, +offer for sale, import and otherwise run, modify and propagate the contents +of its contributor version. + +In the following three paragraphs, a "patent license" is any express agreement +or commitment, however denominated, not to enforce a patent (such as an express +permission to practice a patent or covenant not to s ue for patent infringement). +To "grant" such a patent license to a party means to make such an agreement +or commitment not to enforce a patent against the party. + +If you convey a covered work, knowingly relying on a patent license, and the +Corresponding Source of the work is not available for anyone to copy, free +of charge and under the terms of this License, through a publicly available +network server or other readily accessible means, then you must either (1) +cause the Corresponding Source to be so available, or (2) arrange to deprive +yourself of the benefit of the patent license for this particular work, or +(3) arrange, in a manner consistent with the requirements of this License, +to extend the patent + +license to downstream recipients. "Knowingly relying" means you have actual +knowledge that, but for the patent license, your conveying the covered work +in a country, or your recipient's use of the covered work in a country, would +infringe one or more identifiable patents in that country that you have reason +to believe are valid. + +If, pursuant to or in connection with a single transaction or arrangement, +you convey, or propagate by procuring conveyance of, a covered work, and grant +a patent license to some of the parties receiving the covered work authorizing +them to use, propagate, modify or convey a specific copy of the covered work, +then the patent license you grant is automatically extended to all recipients +of the covered work and works based on it. + +A patent license is "discriminatory" if it does not include within the scope +of its coverage, prohibits the exercise of, or is conditioned on the non-exercise +of one or more of the rights that are specifically granted under this License. +You may not convey a covered work if you are a party to an arrangement with +a third party that is in the business of distributing software, under which +you make payment to the third party based on the extent of your activity of +conveying the work, and under which the third party grants, to any of the +parties who would receive the covered work from you, a discriminatory patent +license (a) in connection with copies of the covered work conveyed by you +(or copies made from those copies), or (b) primarily for and in connection +with specific products or compilations that contain the covered work, unless +you entered into that arrangement, or that patent license was granted, prior +to 28 March 2007. + +Nothing in this License shall be construed as excluding or limiting any implied +license or other defenses to infringement that may otherwise be available +to you under applicable patent law. + + 12. No Surrender of Others' Freedom. + +If conditions are imposed on you (whether by court order, agreement or otherwise) +that contradict the conditions of this License, they do not excuse you from +the conditions of this License. If you cannot convey a covered work so as +to satisfy simultaneously your obligations under this License and any other +pertinent obligations, then as a consequence you may + +not convey it at all. For example, if you agree to terms that obligate you +to collect a royalty for further conveying from those to whom you convey the +Program, the only way you could satisfy both those terms and this License +would be to refrain entirely from conveying the Program. + + 13. Remote Network Interaction; Use with the GNU General Public License. + +Notwithstanding any other provision of this License, if you modify the Program, +your modified version must prominently offer all users interacting with it +remotely through a computer network (if your version supports such interaction) +an opportunity to receive the Corresponding Source of your version by providing +access to the Corresponding Source from a network server at no charge, through +some standard or customary means of facilitating copying of software. This +Corresponding Source shall include the Corresponding Source for any work covered +by version 3 of the GNU General Public License that is incorporated pursuant +to the following paragraph. + +Notwithstanding any other provision of this License, you have permission to +link or combine any covered work with a work licensed under version 3 of the +GNU General Public License into a single combined work, and to convey the +resulting work. The terms of this License will continue to apply to the part +which is the covered work, but the work with which it is combined will remain +governed by version 3 of the GNU General Public License. + + 14. Revised Versions of this License. + +The Free Software Foundation may publish revised and/or new versions of the +GNU Affero General Public License from time to time. Such new versions will +be similar in spirit to the present version, but may differ in detail to address +new problems or concerns. + +Each version is given a distinguishing version number. If the Program specifies +that a certain numbered version of the GNU Affero General Public License "or +any later version" applies to it, you have the option of following the terms +and conditions either of that numbered version or of any later version published +by the Free Software Foundation. If the Program does not specify a version +number of the GNU Affero General Public License, you may choose any version +ever published by the Free Software Foundation. + +If the Program specifies that a proxy can decide which future versions of +the GNU Affero General Public License can be used, that proxy's public statement +of acceptance of a version permanently authorizes you to choose that version +for the Program. + +Later license versions may give you additional or different permissions. However, +no additional obligations are imposed on any author or copyright holder as +a result of your choosing to follow a later version. + + 15. Disclaimer of Warranty. + +THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE +LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR +OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER +EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES +OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS +TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM +PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR +CORRECTION. + + 16. Limitation of Liability. + +IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL +ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS THE PROGRAM +AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, +INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO +USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED +INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE +PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER +PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. + + 17. Interpretation of Sections 15 and 16. + +If the disclaimer of warranty and limitation of liability provided above cannot +be given local legal effect according to their terms, reviewing courts shall +apply local law that most closely approximates an absolute waiver of all civil +liability in connection with the Program, unless a warranty or assumption +of liability accompanies a copy of the Program in return for a fee. END OF +TERMS AND CONDITIONS + +How to Apply These Terms to Your New Programs + +If you develop a new program, and you want it to be of the greatest possible +use to the public, the best way to achieve this is to make it free software +which everyone can redistribute and change under these terms. + +To do so, attach the following notices to the program. It is safest to attach +them to the start of each source file to most effectively state the exclusion +of warranty; and each file should have at least the "copyright" line and a +pointer to where the full notice is found. + + + +Copyright (C) + +This program is free software: you can redistribute it and/or modify it under +the terms of the GNU Affero General Public License as published by the Free +Software Foundation, either version 3 of the License, or (at your option) +any later version. + +This program is distributed in the hope that it will be useful, but WITHOUT +ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS +FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more +details. + +You should have received a copy of the GNU Affero General Public License along +with this program. If not, see . + +Also add information on how to contact you by electronic and paper mail. + +If your software can interact with users remotely through a computer network, +you should also make sure that it provides a way for users to get its source. +For example, if your program is a web application, its interface could display +a "Source" link that leads users to an archive of the code. There are many +ways you could offer source, and different solutions will be better for different +programs; see section 13 for the specific requirements. + +You should also get your employer (if you work as a programmer) or school, +if any, to sign a "copyright disclaimer" for the program, if necessary. For +more information on this, and how to apply and follow the GNU AGPL, see . diff --git a/LICENSES/Apache-2.0.txt b/LICENSES/Apache-2.0.txt new file mode 100644 index 000000000..4ed90b952 --- /dev/null +++ b/LICENSES/Apache-2.0.txt @@ -0,0 +1,208 @@ +Apache License + +Version 2.0, January 2004 + +http://www.apache.org/licenses/ TERMS AND CONDITIONS FOR USE, REPRODUCTION, +AND DISTRIBUTION + + 1. Definitions. + + + +"License" shall mean the terms and conditions for use, reproduction, and distribution +as defined by Sections 1 through 9 of this document. + + + +"Licensor" shall mean the copyright owner or entity authorized by the copyright +owner that is granting the License. + + + +"Legal Entity" shall mean the union of the acting entity and all other entities +that control, are controlled by, or are under common control with that entity. +For the purposes of this definition, "control" means (i) the power, direct +or indirect, to cause the direction or management of such entity, whether +by contract or otherwise, or (ii) ownership of fifty percent (50%) or more +of the outstanding shares, or (iii) beneficial ownership of such entity. + + + +"You" (or "Your") shall mean an individual or Legal Entity exercising permissions +granted by this License. + + + +"Source" form shall mean the preferred form for making modifications, including +but not limited to software source code, documentation source, and configuration +files. + + + +"Object" form shall mean any form resulting from mechanical transformation +or translation of a Source form, including but not limited to compiled object +code, generated documentation, and conversions to other media types. + + + +"Work" shall mean the work of authorship, whether in Source or Object form, +made available under the License, as indicated by a copyright notice that +is included in or attached to the work (an example is provided in the Appendix +below). + + + +"Derivative Works" shall mean any work, whether in Source or Object form, +that is based on (or derived from) the Work and for which the editorial revisions, +annotations, elaborations, or other modifications represent, as a whole, an +original work of authorship. For the purposes of this License, Derivative +Works shall not include works that remain separable from, or merely link (or +bind by name) to the interfaces of, the Work and Derivative Works thereof. + + + +"Contribution" shall mean any work of authorship, including the original version +of the Work and any modifications or additions to that Work or Derivative +Works thereof, that is intentionally submitted to Licensor for inclusion in +the Work by the copyright owner or by an individual or Legal Entity authorized +to submit on behalf of the copyright owner. For the purposes of this definition, +"submitted" means any form of electronic, verbal, or written communication +sent to the Licensor or its representatives, including but not limited to +communication on electronic mailing lists, source code control systems, and +issue tracking systems that are managed by, or on behalf of, the Licensor +for the purpose of discussing and improving the Work, but excluding communication +that is conspicuously marked or otherwise designated in writing by the copyright +owner as "Not a Contribution." + + + +"Contributor" shall mean Licensor and any individual or Legal Entity on behalf +of whom a Contribution has been received by Licensor and subsequently incorporated +within the Work. + +2. Grant of Copyright License. Subject to the terms and conditions of this +License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, +no-charge, royalty-free, irrevocable copyright license to reproduce, prepare +Derivative Works of, publicly display, publicly perform, sublicense, and distribute +the Work and such Derivative Works in Source or Object form. + +3. Grant of Patent License. Subject to the terms and conditions of this License, +each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, +no-charge, royalty-free, irrevocable (except as stated in this section) patent +license to make, have made, use, offer to sell, sell, import, and otherwise +transfer the Work, where such license applies only to those patent claims +licensable by such Contributor that are necessarily infringed by their Contribution(s) +alone or by combination of their Contribution(s) with the Work to which such +Contribution(s) was submitted. If You institute patent litigation against +any entity (including a cross-claim or counterclaim in a lawsuit) alleging +that the Work or a Contribution incorporated within the Work constitutes direct +or contributory patent infringement, then any patent licenses granted to You +under this License for that Work shall terminate as of the date such litigation +is filed. + +4. Redistribution. You may reproduce and distribute copies of the Work or +Derivative Works thereof in any medium, with or without modifications, and +in Source or Object form, provided that You meet the following conditions: + +(a) You must give any other recipients of the Work or Derivative Works a copy +of this License; and + +(b) You must cause any modified files to carry prominent notices stating that +You changed the files; and + +(c) You must retain, in the Source form of any Derivative Works that You distribute, +all copyright, patent, trademark, and attribution notices from the Source +form of the Work, excluding those notices that do not pertain to any part +of the Derivative Works; and + +(d) If the Work includes a "NOTICE" text file as part of its distribution, +then any Derivative Works that You distribute must include a readable copy +of the attribution notices contained within such NOTICE file, excluding those +notices that do not pertain to any part of the Derivative Works, in at least +one of the following places: within a NOTICE text file distributed as part +of the Derivative Works; within the Source form or documentation, if provided +along with the Derivative Works; or, within a display generated by the Derivative +Works, if and wherever such third-party notices normally appear. The contents +of the NOTICE file are for informational purposes only and do not modify the +License. You may add Your own attribution notices within Derivative Works +that You distribute, alongside or as an addendum to the NOTICE text from the +Work, provided that such additional attribution notices cannot be construed +as modifying the License. + +You may add Your own copyright statement to Your modifications and may provide +additional or different license terms and conditions for use, reproduction, +or distribution of Your modifications, or for any such Derivative Works as +a whole, provided Your use, reproduction, and distribution of the Work otherwise +complies with the conditions stated in this License. + +5. Submission of Contributions. Unless You explicitly state otherwise, any +Contribution intentionally submitted for inclusion in the Work by You to the +Licensor shall be under the terms and conditions of this License, without +any additional terms or conditions. Notwithstanding the above, nothing herein +shall supersede or modify the terms of any separate license agreement you +may have executed with Licensor regarding such Contributions. + +6. Trademarks. This License does not grant permission to use the trade names, +trademarks, service marks, or product names of the Licensor, except as required +for reasonable and customary use in describing the origin of the Work and +reproducing the content of the NOTICE file. + +7. Disclaimer of Warranty. Unless required by applicable law or agreed to +in writing, Licensor provides the Work (and each Contributor provides its +Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +KIND, either express or implied, including, without limitation, any warranties +or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR +A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness +of using or redistributing the Work and assume any risks associated with Your +exercise of permissions under this License. + +8. Limitation of Liability. In no event and under no legal theory, whether +in tort (including negligence), contract, or otherwise, unless required by +applicable law (such as deliberate and grossly negligent acts) or agreed to +in writing, shall any Contributor be liable to You for damages, including +any direct, indirect, special, incidental, or consequential damages of any +character arising as a result of this License or out of the use or inability +to use the Work (including but not limited to damages for loss of goodwill, +work stoppage, computer failure or malfunction, or any and all other commercial +damages or losses), even if such Contributor has been advised of the possibility +of such damages. + +9. Accepting Warranty or Additional Liability. While redistributing the Work +or Derivative Works thereof, You may choose to offer, and charge a fee for, +acceptance of support, warranty, indemnity, or other liability obligations +and/or rights consistent with this License. However, in accepting such obligations, +You may act only on Your own behalf and on Your sole responsibility, not on +behalf of any other Contributor, and only if You agree to indemnify, defend, +and hold each Contributor harmless for any liability incurred by, or claims +asserted against, such Contributor by reason of your accepting any such warranty +or additional liability. END OF TERMS AND CONDITIONS + +APPENDIX: How to apply the Apache License to your work. + +To apply the Apache License to your work, attach the following boilerplate +notice, with the fields enclosed by brackets "[]" replaced with your own identifying +information. (Don't include the brackets!) The text should be enclosed in +the appropriate comment syntax for the file format. We also recommend that +a file or class name and description of purpose be included on the same "printed +page" as the copyright notice for easier identification within third-party +archives. + +Copyright [yyyy] [name of copyright owner] + +Licensed under the Apache License, Version 2.0 (the "License"); + +you may not use this file except in compliance with the License. + +You may obtain a copy of the License at + +http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software + +distributed under the License is distributed on an "AS IS" BASIS, + +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + +See the License for the specific language governing permissions and + +limitations under the License. diff --git a/LICENSES/CC-BY-SA-4.0.txt b/LICENSES/CC-BY-SA-4.0.txt new file mode 100644 index 000000000..f50cdd32a --- /dev/null +++ b/LICENSES/CC-BY-SA-4.0.txt @@ -0,0 +1,350 @@ +Creative Commons Attribution-ShareAlike 4.0 International Creative Commons +Corporation ("Creative Commons") is not a law firm and does not provide legal +services or legal advice. Distribution of Creative Commons public licenses +does not create a lawyer-client or other relationship. Creative Commons makes +its licenses and related information available on an "as-is" basis. Creative +Commons gives no warranties regarding its licenses, any material licensed +under their terms and conditions, or any related information. Creative Commons +disclaims all liability for damages resulting from their use to the fullest +extent possible. + +Using Creative Commons Public Licenses + +Creative Commons public licenses provide a standard set of terms and conditions +that creators and other rights holders may use to share original works of +authorship and other material subject to copyright and certain other rights +specified in the public license below. The following considerations are for +informational purposes only, are not exhaustive, and do not form part of our +licenses. + +Considerations for licensors: Our public licenses are intended for use by +those authorized to give the public permission to use material in ways otherwise +restricted by copyright and certain other rights. Our licenses are irrevocable. +Licensors should read and understand the terms and conditions of the license +they choose before applying it. Licensors should also secure all rights necessary +before applying our licenses so that the public can reuse the material as +expected. Licensors should clearly mark any material not subject to the license. +This includes other CC-licensed material, or material used under an exception +or limitation to copyright. More considerations for licensors : wiki.creativecommons.org/Considerations_for_licensors + +Considerations for the public: By using one of our public licenses, a licensor +grants the public permission to use the licensed material under specified +terms and conditions. If the licensor's permission is not necessary for any +reason–for example, because of any applicable exception or limitation to copyright–then +that use is not regulated by the license. Our licenses grant only permissions +under copyright and certain other rights that a licensor has authority to +grant. Use of the licensed material may still be restricted for other reasons, +including because others have copyright or other rights in the material. A +licensor may make special requests, such as asking that all changes be marked +or described. + +Although not required by our licenses, you are encouraged to respect those +requests where reasonable. More considerations for the public : wiki.creativecommons.org/Considerations_for_licensees + +Creative Commons Attribution-ShareAlike 4.0 International Public License + +By exercising the Licensed Rights (defined below), You accept and agree to +be bound by the terms and conditions of this Creative Commons Attribution-ShareAlike +4.0 International Public License ("Public License"). To the extent this Public +License may be interpreted as a contract, You are granted the Licensed Rights +in consideration of Your acceptance of these terms and conditions, and the +Licensor grants You such rights in consideration of benefits the Licensor +receives from making the Licensed Material available under these terms and +conditions. + +Section 1 – Definitions. + +a. Adapted Material means material subject to Copyright and Similar Rights +that is derived from or based upon the Licensed Material and in which the +Licensed Material is translated, altered, arranged, transformed, or otherwise +modified in a manner requiring permission under the Copyright and Similar +Rights held by the Licensor. For purposes of this Public License, where the +Licensed Material is a musical work, performance, or sound recording, Adapted +Material is always produced where the Licensed Material is synched in timed +relation with a moving image. + +b. Adapter's License means the license You apply to Your Copyright and Similar +Rights in Your contributions to Adapted Material in accordance with the terms +and conditions of this Public License. + +c. BY-SA Compatible License means a license listed at creativecommons.org/compatiblelicenses, +approved by Creative Commons as essentially the equivalent of this Public +License. + +d. Copyright and Similar Rights means copyright and/or similar rights closely +related to copyright including, without limitation, performance, broadcast, +sound recording, and Sui Generis Database Rights, without regard to how the +rights are labeled or categorized. For purposes of this Public License, the +rights specified in Section 2(b)(1)-(2) are not Copyright and Similar Rights. + +e. Effective Technological Measures means those measures that, in the absence +of proper authority, may not be circumvented under laws fulfilling obligations +under Article 11 of the WIPO Copyright Treaty adopted on December 20, 1996, +and/or similar international agreements. + +f. Exceptions and Limitations means fair use, fair dealing, and/or any other +exception or limitation to Copyright and Similar Rights that applies to Your +use of the Licensed Material. + +g. License Elements means the license attributes listed in the name of a Creative +Commons Public License. The License Elements of this Public License are Attribution +and ShareAlike. + +h. Licensed Material means the artistic or literary work, database, or other +material to which the Licensor applied this Public License. + +i. Licensed Rights means the rights granted to You subject to the terms and +conditions of this Public License, which are limited to all Copyright and +Similar Rights that apply to Your use of the Licensed Material and that the +Licensor has authority to license. + +j. Licensor means the individual(s) or entity(ies) granting rights under this +Public License. + +k. Share means to provide material to the public by any means or process that +requires permission under the Licensed Rights, such as reproduction, public +display, public performance, distribution, dissemination, communication, or +importation, and to make material available to the public including in ways +that members of the public may access the material from a place and at a time +individually chosen by them. + +l. Sui Generis Database Rights means rights other than copyright resulting +from Directive 96/9/EC of the European Parliament and of the Council of 11 +March 1996 on the legal protection of databases, as amended and/or succeeded, +as well as other essentially equivalent rights anywhere in the world. + +m. You means the individual or entity exercising the Licensed Rights under +this Public License. Your has a corresponding meaning. + +Section 2 – Scope. + + a. License grant. + +1. Subject to the terms and conditions of this Public License, the Licensor +hereby grants You a worldwide, royalty-free, non-sublicensable, non-exclusive, +irrevocable license to exercise the Licensed Rights in the Licensed Material +to: + + A. reproduce and Share the Licensed Material, in whole or in part; and + + B. produce, reproduce, and Share Adapted Material. + +2. Exceptions and Limitations. For the avoidance of doubt, where Exceptions +and Limitations apply to Your use, this Public License does not apply, and +You do not need to comply with its terms and conditions. + + 3. Term. The term of this Public License is specified in Section 6(a). + +4. Media and formats; technical modifications allowed. The Licensor authorizes +You to exercise the Licensed Rights in all media and formats whether now known +or hereafter created, and to make technical modifications necessary to do +so. The Licensor waives and/or agrees not to assert any right or authority +to forbid You from making technical modifications necessary to exercise the +Licensed Rights, including technical modifications necessary to circumvent +Effective Technological Measures. For purposes of this Public License, simply +making modifications authorized by this Section 2(a)(4) never produces Adapted +Material. + + 5. Downstream recipients. + +A. Offer from the Licensor – Licensed Material. Every recipient of the Licensed +Material automatically receives an offer from the Licensor to exercise the +Licensed Rights under the terms and conditions of this Public License. + +B. Additional offer from the Licensor – Adapted Material. Every recipient +of Adapted Material from You automatically receives an offer from the Licensor +to exercise the Licensed Rights in the Adapted Material under the conditions +of the Adapter's License You apply. + +C. No downstream restrictions. You may not offer or impose any additional +or different terms or conditions on, or apply any Effective Technological +Measures to, the Licensed Material if doing so restricts exercise of the Licensed +Rights by any recipient of the Licensed Material. + +6. No endorsement. Nothing in this Public License constitutes or may be construed +as permission to assert or imply that You are, or that Your use of the Licensed +Material is, connected with, or sponsored, endorsed, or granted official status +by, the Licensor or others designated to receive attribution as provided in +Section 3(a)(1)(A)(i). + + b. Other rights. + +1. Moral rights, such as the right of integrity, are not licensed under this +Public License, nor are publicity, privacy, and/or other similar personality +rights; however, to the extent possible, the Licensor waives and/or agrees +not to assert any such rights held by the Licensor to the limited extent necessary +to allow You to exercise the Licensed Rights, but not otherwise. + +2. Patent and trademark rights are not licensed under this Public License. + +3. To the extent possible, the Licensor waives any right to collect royalties +from You for the exercise of the Licensed Rights, whether directly or through +a collecting society under any voluntary or waivable statutory or compulsory +licensing scheme. In all other cases the Licensor expressly reserves any right +to collect such royalties. + +Section 3 – License Conditions. + +Your exercise of the Licensed Rights is expressly made subject to the following +conditions. + + a. Attribution. + +1. If You Share the Licensed Material (including in modified form), You must: + +A. retain the following if it is supplied by the Licensor with the Licensed +Material: + +i. identification of the creator(s) of the Licensed Material and any others +designated to receive attribution, in any reasonable manner requested by the +Licensor (including by pseudonym if designated); + + ii. a copyright notice; + + iii. a notice that refers to this Public License; + + iv. a notice that refers to the disclaimer of warranties; + +v. a URI or hyperlink to the Licensed Material to the extent reasonably practicable; + +B. indicate if You modified the Licensed Material and retain an indication +of any previous modifications; and + +C. indicate the Licensed Material is licensed under this Public License, and +include the text of, or the URI or hyperlink to, this Public License. + +2. You may satisfy the conditions in Section 3(a)(1) in any reasonable manner +based on the medium, means, and context in which You Share the Licensed Material. +For example, it may be reasonable to satisfy the conditions by providing a +URI or hyperlink to a resource that includes the required information. + +3. If requested by the Licensor, You must remove any of the information required +by Section 3(a)(1)(A) to the extent reasonably practicable. + +b. ShareAlike.In addition to the conditions in Section 3(a), if You Share +Adapted Material You produce, the following conditions also apply. + +1. The Adapter's License You apply must be a Creative Commons license with +the same License Elements, this version or later, or a BY-SA Compatible License. + +2. You must include the text of, or the URI or hyperlink to, the Adapter's +License You apply. You may satisfy this condition in any reasonable manner +based on the medium, means, and context in which You Share Adapted Material. + +3. You may not offer or impose any additional or different terms or conditions +on, or apply any Effective Technological Measures to, Adapted Material that +restrict exercise of the rights granted under the Adapter's License You apply. + +Section 4 – Sui Generis Database Rights. + +Where the Licensed Rights include Sui Generis Database Rights that apply to +Your use of the Licensed Material: + +a. for the avoidance of doubt, Section 2(a)(1) grants You the right to extract, +reuse, reproduce, and Share all or a substantial portion of the contents of +the database; + +b. if You include all or a substantial portion of the database contents in +a database in which You have Sui Generis Database Rights, then the database +in which You have Sui Generis Database Rights (but not its individual contents) +is Adapted Material, including for purposes of Section 3(b); and + +c. You must comply with the conditions in Section 3(a) if You Share all or +a substantial portion of the contents of the database. + +For the avoidance of doubt, this Section 4 supplements and does not replace +Your obligations under this Public License where the Licensed Rights include +other Copyright and Similar Rights. + +Section 5 – Disclaimer of Warranties and Limitation of Liability. + +a. Unless otherwise separately undertaken by the Licensor, to the extent possible, +the Licensor offers the Licensed Material as-is and as-available, and makes +no representations or warranties of any kind concerning the Licensed Material, +whether express, implied, statutory, or other. This includes, without limitation, +warranties of title, merchantability, fitness for a particular purpose, non-infringement, +absence of latent or other defects, accuracy, or the presence or absence of +errors, whether or not known or discoverable. Where disclaimers of warranties +are not allowed in full or in part, this disclaimer may not apply to You. + +b. To the extent possible, in no event will the Licensor be liable to You +on any legal theory (including, without limitation, negligence) or otherwise +for any direct, special, indirect, incidental, consequential, punitive, exemplary, +or other losses, costs, expenses, or damages arising out of this Public License +or use of the Licensed Material, even if the Licensor has been advised of +the possibility of such losses, costs, expenses, or damages. Where a limitation +of liability is not allowed in full or in part, this limitation may not apply +to You. + +c. The disclaimer of warranties and limitation of liability provided above +shall be interpreted in a manner that, to the extent possible, most closely +approximates an absolute disclaimer and waiver of all liability. + +Section 6 – Term and Termination. + +a. This Public License applies for the term of the Copyright and Similar Rights +licensed here. However, if You fail to comply with this Public License, then +Your rights under this Public License terminate automatically. + +b. Where Your right to use the Licensed Material has terminated under Section +6(a), it reinstates: + +1. automatically as of the date the violation is cured, provided it is cured +within 30 days of Your discovery of the violation; or + + 2. upon express reinstatement by the Licensor. + +c. For the avoidance of doubt, this Section 6(b) does not affect any right +the Licensor may have to seek remedies for Your violations of this Public +License. + +d. For the avoidance of doubt, the Licensor may also offer the Licensed Material +under separate terms or conditions or stop distributing the Licensed Material +at any time; however, doing so will not terminate this Public License. + + e. Sections 1, 5, 6, 7, and 8 survive termination of this Public License. + +Section 7 – Other Terms and Conditions. + +a. The Licensor shall not be bound by any additional or different terms or +conditions communicated by You unless expressly agreed. + +b. Any arrangements, understandings, or agreements regarding the Licensed +Material not stated herein are separate from and independent of the terms +and conditions of this Public License. + +Section 8 – Interpretation. + +a. For the avoidance of doubt, this Public License does not, and shall not +be interpreted to, reduce, limit, restrict, or impose conditions on any use +of the Licensed Material that could lawfully be made without permission under +this Public License. + +b. To the extent possible, if any provision of this Public License is deemed +unenforceable, it shall be automatically reformed to the minimum extent necessary +to make it enforceable. If the provision cannot be reformed, it shall be severed +from this Public License without affecting the enforceability of the remaining +terms and conditions. + +c. No term or condition of this Public License will be waived and no failure +to comply consented to unless expressly agreed to by the Licensor. + +d. Nothing in this Public License constitutes or may be interpreted as a limitation +upon, or waiver of, any privileges and immunities that apply to the Licensor +or You, including from the legal processes of any jurisdiction or authority. + +Creative Commons is not a party to its public licenses. Notwithstanding, Creative +Commons may elect to apply one of its public licenses to material it publishes +and in those instances will be considered the "Licensor." The text of the +Creative Commons public licenses is dedicated to the public domain under the +CC0 Public Domain Dedication. Except for the limited purpose of indicating +that material is shared under a Creative Commons public license or as otherwise +permitted by the Creative Commons policies published at creativecommons.org/policies, +Creative Commons does not authorize the use of the trademark "Creative Commons" +or any other trademark or logo of Creative Commons without its prior written +consent including, without limitation, in connection with any unauthorized +modifications to any of its public licenses or any other arrangements, understandings, +or agreements concerning use of licensed material. For the avoidance of doubt, +this paragraph does not form part of the public licenses. + +Creative Commons may be contacted at creativecommons.org. diff --git a/LICENSES/CC0-1.0.txt b/LICENSES/CC0-1.0.txt new file mode 100644 index 000000000..a343ccd43 --- /dev/null +++ b/LICENSES/CC0-1.0.txt @@ -0,0 +1,119 @@ +Creative Commons Legal Code + +CC0 1.0 Universal CREATIVE COMMONS CORPORATION IS NOT A LAW FIRM AND DOES +NOT PROVIDE LEGAL SERVICES. DISTRIBUTION OF THIS DOCUMENT DOES NOT CREATE +AN ATTORNEY-CLIENT RELATIONSHIP. CREATIVE COMMONS PROVIDES THIS INFORMATION +ON AN "AS-IS" BASIS. CREATIVE COMMONS MAKES NO WARRANTIES REGARDING THE USE +OF THIS DOCUMENT OR THE INFORMATION OR WORKS PROVIDED HEREUNDER, AND DISCLAIMS +LIABILITY FOR DAMAGES RESULTING FROM THE USE OF THIS DOCUMENT OR THE INFORMATION +OR WORKS PROVIDED HEREUNDER. + +Statement of Purpose + +The laws of most jurisdictions throughout the world automatically confer exclusive +Copyright and Related Rights (defined below) upon the creator and subsequent +owner(s) (each and all, an "owner") of an original work of authorship and/or +a database (each, a "Work"). + +Certain owners wish to permanently relinquish those rights to a Work for the +purpose of contributing to a commons of creative, cultural and scientific +works ("Commons") that the public can reliably and without fear of later claims +of infringement build upon, modify, incorporate in other works, reuse and +redistribute as freely as possible in any form whatsoever and for any purposes, +including without limitation commercial purposes. These owners may contribute +to the Commons to promote the ideal of a free culture and the further production +of creative, cultural and scientific works, or to gain reputation or greater +distribution for their Work in part through the use and efforts of others. + +For these and/or other purposes and motivations, and without any expectation +of additional consideration or compensation, the person associating CC0 with +a Work (the "Affirmer"), to the extent that he or she is an owner of Copyright +and Related Rights in the Work, voluntarily elects to apply CC0 to the Work +and publicly distribute the Work under its terms, with knowledge of his or +her Copyright and Related Rights in the Work and the meaning and intended +legal effect of CC0 on those rights. + +1. Copyright and Related Rights. A Work made available under CC0 may be protected +by copyright and related or neighboring rights ("Copyright and Related Rights"). +Copyright and Related Rights include, but are not limited to, the following: + +i. the right to reproduce, adapt, distribute, perform, display, communicate, +and translate a Work; + + ii. moral rights retained by the original author(s) and/or performer(s); + +iii. publicity and privacy rights pertaining to a person's image or likeness +depicted in a Work; + +iv. rights protecting against unfair competition in regards to a Work, subject +to the limitations in paragraph 4(a), below; + +v. rights protecting the extraction, dissemination, use and reuse of data +in a Work; + +vi. database rights (such as those arising under Directive 96/9/EC of the +European Parliament and of the Council of 11 March 1996 on the legal protection +of databases, and under any national implementation thereof, including any +amended or successor version of such directive); and + +vii. other similar, equivalent or corresponding rights throughout the world +based on applicable law or treaty, and any national implementations thereof. + +2. Waiver. To the greatest extent permitted by, but not in contravention of, +applicable law, Affirmer hereby overtly, fully, permanently, irrevocably and +unconditionally waives, abandons, and surrenders all of Affirmer's Copyright +and Related Rights and associated claims and causes of action, whether now +known or unknown (including existing as well as future claims and causes of +action), in the Work (i) in all territories worldwide, (ii) for the maximum +duration provided by applicable law or treaty (including future time extensions), +(iii) in any current or future medium and for any number of copies, and (iv) +for any purpose whatsoever, including without limitation commercial, advertising +or promotional purposes (the "Waiver"). Affirmer makes the Waiver for the +benefit of each member of the public at large and to the detriment of Affirmer's +heirs and successors, fully intending that such Waiver shall not be subject +to revocation, rescission, cancellation, termination, or any other legal or +equitable action to disrupt the quiet enjoyment of the Work by the public +as contemplated by Affirmer's express Statement of Purpose. + +3. Public License Fallback. Should any part of the Waiver for any reason be +judged legally invalid or ineffective under applicable law, then the Waiver +shall be preserved to the maximum extent permitted taking into account Affirmer's +express Statement of Purpose. In addition, to the extent the Waiver is so +judged Affirmer hereby grants to each affected person a royalty-free, non +transferable, non sublicensable, non exclusive, irrevocable and unconditional +license to exercise Affirmer's Copyright and Related Rights in the Work (i) +in all territories worldwide, (ii) for the maximum duration provided by applicable +law or treaty (including future time extensions), (iii) in any current or +future medium and for any number of copies, and (iv) for any purpose whatsoever, +including without limitation commercial, advertising or promotional purposes +(the "License"). The License shall be deemed effective as of the date CC0 +was applied by Affirmer to the Work. Should any part of the License for any +reason be judged legally invalid or ineffective under applicable law, such +partial invalidity or ineffectiveness shall not invalidate the remainder of +the License, and in such case Affirmer hereby affirms that he or she will +not (i) exercise any of his or her remaining Copyright and Related Rights +in the Work or (ii) assert any associated claims and causes of action with +respect to the Work, in either case contrary to Affirmer's express Statement +of Purpose. + + 4. Limitations and Disclaimers. + +a. No trademark or patent rights held by Affirmer are waived, abandoned, surrendered, +licensed or otherwise affected by this document. + +b. Affirmer offers the Work as-is and makes no representations or warranties +of any kind concerning the Work, express, implied, statutory or otherwise, +including without limitation warranties of title, merchantability, fitness +for a particular purpose, non infringement, or the absence of latent or other +defects, accuracy, or the present or absence of errors, whether or not discoverable, +all to the greatest extent permissible under applicable law. + +c. Affirmer disclaims responsibility for clearing rights of other persons +that may apply to the Work or any use thereof, including without limitation +any person's Copyright and Related Rights in the Work. Further, Affirmer disclaims +responsibility for obtaining any necessary consents, permissions or other +rights required for any use of the Work. + +d. Affirmer understands and acknowledges that Creative Commons is not a party +to this document and has no duty or obligation with respect to this CC0 or +use of the Work. diff --git a/LICENSES/GPL-3.0-or-later.txt b/LICENSES/GPL-3.0-or-later.txt new file mode 100644 index 000000000..e142a525b --- /dev/null +++ b/LICENSES/GPL-3.0-or-later.txt @@ -0,0 +1,625 @@ +GNU GENERAL PUBLIC LICENSE + +Version 3, 29 June 2007 + +Copyright © 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/LICENSES/LGPL-3.0-or-later.txt b/LICENSES/LGPL-3.0-or-later.txt new file mode 100644 index 000000000..bd405afbe --- /dev/null +++ b/LICENSES/LGPL-3.0-or-later.txt @@ -0,0 +1,163 @@ +GNU LESSER 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. + +This version of the GNU Lesser General Public License incorporates the terms +and conditions of version 3 of the GNU General Public License, supplemented +by the additional permissions listed below. + + 0. Additional Definitions. + + + +As used herein, "this License" refers to version 3 of the GNU Lesser General +Public License, and the "GNU GPL" refers to version 3 of the GNU General Public +License. + + + +"The Library" refers to a covered work governed by this License, other than +an Application or a Combined Work as defined below. + + + +An "Application" is any work that makes use of an interface provided by the +Library, but which is not otherwise based on the Library. Defining a subclass +of a class defined by the Library is deemed a mode of using an interface provided +by the Library. + + + +A "Combined Work" is a work produced by combining or linking an Application +with the Library. The particular version of the Library with which the Combined +Work was made is also called the "Linked Version". + + + +The "Minimal Corresponding Source" for a Combined Work means the Corresponding +Source for the Combined Work, excluding any source code for portions of the +Combined Work that, considered in isolation, are based on the Application, +and not on the Linked Version. + + + +The "Corresponding Application Code" for a Combined Work means the object +code and/or source code for the Application, including any data and utility +programs needed for reproducing the Combined Work from the Application, but +excluding the System Libraries of the Combined Work. + + 1. Exception to Section 3 of the GNU GPL. + +You may convey a covered work under sections 3 and 4 of this License without +being bound by section 3 of the GNU GPL. + + 2. Conveying Modified Versions. + +If you modify a copy of the Library, and, in your modifications, a facility +refers to a function or data to be supplied by an Application that uses the +facility (other than as an argument passed when the facility is invoked), +then you may convey a copy of the modified version: + +a) under this License, provided that you make a good faith effort to ensure +that, in the event an Application does not supply the function or data, the +facility still operates, and performs whatever part of its purpose remains +meaningful, or + +b) under the GNU GPL, with none of the additional permissions of this License +applicable to that copy. + + 3. Object Code Incorporating Material from Library Header Files. + +The object code form of an Application may incorporate material from a header +file that is part of the Library. You may convey such object code under terms +of your choice, provided that, if the incorporated material is not limited +to numerical parameters, data structure layouts and accessors, or small macros, +inline functions and templates (ten or fewer lines in length), you do both +of the following: + +a) Give prominent notice with each copy of the object code that the Library +is used in it and that the Library and its use are covered by this License. + +b) Accompany the object code with a copy of the GNU GPL and this license document. + + 4. Combined Works. + +You may convey a Combined Work under terms of your choice that, taken together, +effectively do not restrict modification of the portions of the Library contained +in the Combined Work and reverse engineering for debugging such modifications, +if you also do each of the following: + +a) Give prominent notice with each copy of the Combined Work that the Library +is used in it and that the Library and its use are covered by this License. + +b) Accompany the Combined Work with a copy of the GNU GPL and this license +document. + +c) For a Combined Work that displays copyright notices during execution, include +the copyright notice for the Library among these notices, as well as a reference +directing the user to the copies of the GNU GPL and this license document. + + d) Do one of the following: + +0) Convey the Minimal Corresponding Source under the terms of this License, +and the Corresponding Application Code in a form suitable for, and under terms +that permit, the user to recombine or relink the Application with a modified +version of the Linked Version to produce a modified Combined Work, in the +manner specified by section 6 of the GNU GPL for conveying Corresponding Source. + +1) Use a suitable shared library mechanism for linking with the Library. A +suitable mechanism is one that (a) uses at run time a copy of the Library +already present on the user's computer system, and (b) will operate properly +with a modified version of the Library that is interface-compatible with the +Linked Version. + +e) Provide Installation Information, but only if you would otherwise be required +to provide such information under section 6 of the GNU GPL, and only to the +extent that such information is necessary to install and execute a modified +version of the Combined Work produced by recombining or relinking the Application +with a modified version of the Linked Version. (If you use option 4d0, the +Installation Information must accompany the Minimal Corresponding Source and +Corresponding Application Code. If you use option 4d1, you must provide the +Installation Information in the manner specified by section 6 of the GNU GPL +for conveying Corresponding Source.) + + 5. Combined Libraries. + +You may place library facilities that are a work based on the Library side +by side in a single library together with other library facilities that are +not Applications and are not covered by this License, and convey such a combined +library under terms of your choice, if you do both of the following: + +a) Accompany the combined library with a copy of the same work based on the +Library, uncombined with any other library facilities, conveyed under the +terms of this License. + +b) Give prominent notice with the combined library that part of it is a work +based on the Library, and explaining where to find the accompanying uncombined +form of the same work. + + 6. Revised Versions of the GNU Lesser General Public License. + +The Free Software Foundation may publish revised and/or new versions of the +GNU Lesser 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 Library as you +received it specifies that a certain numbered version of the GNU Lesser General +Public License "or any later version" applies to it, you have the option of +following the terms and conditions either of that published version or of +any later version published by the Free Software Foundation. If the Library +as you received it does not specify a version number of the GNU Lesser General +Public License, you may choose any version of the GNU Lesser General Public +License ever published by the Free Software Foundation. + +If the Library as you received it specifies that a proxy can decide whether +future versions of the GNU Lesser General Public License shall apply, that +proxy's public statement of acceptance of any version is permanent authorization +for you to choose that version for the Library. diff --git a/LICENSES/MIT.txt b/LICENSES/MIT.txt new file mode 100644 index 000000000..204b93da4 --- /dev/null +++ b/LICENSES/MIT.txt @@ -0,0 +1,19 @@ +MIT License Copyright (c) + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is furnished +to do so, subject to the following conditions: + +The above copyright notice and this permission notice (including the next +paragraph) shall be included in all copies or substantial portions of the +Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS +FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS +OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, +WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF +OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/README.asciidoc b/README.asciidoc new file mode 100644 index 000000000..1243f0c28 --- /dev/null +++ b/README.asciidoc @@ -0,0 +1,55 @@ +// SPDX-FileCopyrightText: Retroshare Team +// SPDX-License-Identifier: CC-BY-SA-4.0 + += RetroShare + +RetroShare is a decentralized, private, secure, cross-platform, communication +toolkit. +RetroShare provides filesharing, chat, messages, forums, channels and more. + +.Build Status +|=============================================================================== +|GNU/Linux, MacOS, (via travis-ci) | image:https://travis-ci.org/RetroShare/RetroShare.svg?branch=master[link="https://travis-ci.org/RetroShare/RetroShare"] +|Windows (via appveyor) | image:https://ci.appveyor.com/api/projects/status/github/RetroShare/RetroShare?svg=true[link="https://ci.appveyor.com/project/RetroShare58622/retroshare"] +|=============================================================================== + + +== Compilation + +It is very difficult to keep a comprehensive (we support many platforms) and +updated documentation on how to build RetroShare, instead we provide scripts and +recipes that are used to create the packages for the supported platforms and +more in the `build_scripts` directory of this repository. + +Those packaging receipts together with the continuous integration files +`.travis.yml` and `appveyor.yml` are a good source of knowledge on how to +compile RetroShare on different platforms. + + +== Using RetroShare on a headless computer with WebUI + +WARNING: This section is outdated need to be adapted to new WebUI + +The webUI needs to be enabled as a parameter option in retroshare-service: + +[source,bash] +-------- +./retroshare-nogui --webinterface 9090 --docroot /usr/share/retroshare/webui/ +-------- + +The webUI is only accessible on localhost:9090. It is advised to keep it that way so that your RS +cannot be controlled using an untrusted connection. + +To access your web UI from a distance, just open a SSH tunnel on it: + +[source,bash] +-------- +distant_machine:~/ > ssh rs_host -L 9090:localhost:9090 -N +-------- + +"rs_host" is the machine running retroshare-nogui. Then on the distant machine, access your webUI on + + + http://localhost:9090 + +That also works with a retroshare GUI of course. diff --git a/README.md b/README.md deleted file mode 100644 index 2619312a8..000000000 --- a/README.md +++ /dev/null @@ -1,151 +0,0 @@ -RetroShare -============================== -RetroShare is a decentralized, private and secure commmunication and sharing platform. RetroShare provides filesharing, chat, messages, forums and channels. - -Build Status ------------- - -| Platform | Build Status | -| :------------- | :------------- | -| GNU/Linux, MacOS, (via travis-ci) | [![Build Status](https://travis-ci.org/RetroShare/RetroShare.svg?branch=master)](https://travis-ci.org/RetroShare/RetroShare) | -| Windows, `MSys2` (via appveyor) | [![Build status](https://ci.appveyor.com/api/projects/status/github/RetroShare/RetroShare?svg=true)](https://ci.appveyor.com/project/RetroShare58622/retroshare) | - -Compilation on Windows ----------------------------- -Follow this file : [WindowsMSys2_InstallGuide.md](https://github.com/RetroShare/RetroShare/blob/master/WindowsMSys2_InstallGuide.md) - -Compilation on MacOSX ----------------------------- -Follow this file : [MacOS_X_InstallGuide](https://github.com/RetroShare/RetroShare/blob/master/MacOS_X_InstallGuide.md) - -Compilation for Android ---------------------------- -Follow this file : [README-Android](https://github.com/RetroShare/RetroShare/blob/master/README-Android.asciidoc) - -Compilation on Linux ----------------------------- - -1. Install package dependencies: - * Debian/Ubuntu - ```bash - sudo apt-get install libglib2.0-dev libupnp-dev qt4-dev-tools \ - libqt4-dev libssl-dev libxss-dev libgnome-keyring-dev libbz2-dev \ - libqt4-opengl-dev libqtmultimediakit1 qtmobility-dev libsqlcipher-dev \ - libspeex-dev libspeexdsp-dev libxslt1-dev libcurl4-openssl-dev \ - libopencv-dev tcl8.5 libmicrohttpd-dev rapidjson-dev - ``` - * openSUSE - ```bash - sudo zypper install gcc-c++ libqt4-devel libgnome-keyring-devel \ - glib2-devel speex-devel libssh-devel protobuf-devel libcurl-devel \ - libxml2-devel libxslt-devel sqlcipher-devel libmicrohttpd-devel \ - opencv-devel speexdsp-devel libupnp-devel libavcodec-devel rapidjson - ``` - * Arch Linux - ```bash - pacman -S base-devel libgnome-keyring libmicrohttpd libupnp libxslt \ - libxss opencv qt4 speex speexdsp sqlcipher rapidjson - ``` - -2. Checkout the source code - ```bash - mkdir ~/retroshare - cd ~/retroshare - git clone https://github.com/RetroShare/RetroShare.git trunk - ``` - -3. Compile - ```bash - cd trunk - qmake CONFIG+=debug - make - ``` - -4. Install - ```bash - sudo make install - ``` - - The executables produced will be: - - /usr/bin/retroshare - /usr/bin/retroshare-nogui - -5. Uninstall: - ```bash - sudo make uninstall - ``` - -Compile only retroshare-nogui ------------------------------ -If you want to run RetroShare on a server and don’t need the gui and plugins, -you can run the following commands to only compile/install the nogui version: - -```bash -qmake -make retroshare-nogui -sudo make retroshare-nogui-install_subtargets -``` - -For packagers -------------- -Packagers can use PREFIX and LIB\_DIR to customize the installation paths: -```bash -qmake PREFIX=/usr LIB_DIR=/usr/lib64 "CONFIG-=debug" "CONFIG+=release" -make -make INSTALL_ROOT=${PKGDIR} install -``` - -If libsqlcipher is not available as a package ---------------------------------------------- - -You need to place sqlcipher so that the hierarchy is: - - retroshare - | - +--- trunk - | - +--- lib - | - +---- sqlcipher -```bash -mkdir lib -cd lib -git clone git://github.com/sqlcipher/sqlcipher.git -cd sqlcipher -./configure --enable-tempstore=yes CFLAGS="-DSQLITE_HAS_CODEC" LDFLAGS="-lcrypto" -make -cd .. -``` - -Using retroshare-nogui & webUI ------------------------------- - -The webUI needs to be enabled as a parameter option in retroshare-nogui: - -```bash -./retroshare-nogui --webinterface 9090 --docroot /usr/share/retroshare/webui/ -``` - -The webUI is only accessible on localhost:9090. It is advised to keep it that way so that your RS -cannot be controlled using an untrusted connection. - -To access your web UI from a distance, just open a SSH tunnel on it: - -```bash -distant_machine:~/ > ssh rs_host -L 9090:localhost:9090 -N -``` - -"rs_host" is the machine running retroshare-nogui. Then on the distant machine, access your webUI on - - - http://localhost:9090 - -That also works with a retroshare GUI of course. - -Compile and run tests ---------------------- - - qmake CONFIG+=tests - make - tests/unittests/unittests diff --git a/RetroShare.pro b/RetroShare.pro index c04c62ed2..e835e4ca2 100644 --- a/RetroShare.pro +++ b/RetroShare.pro @@ -1,20 +1,25 @@ -################################################################################ -# Retroshare.pro # -# Copyright (C) 2018, Retroshare team # -# # -# This program is free software: you can redistribute it and/or modify # -# it under the terms of the GNU Affero General Public License as # -# published by the Free Software Foundation, either version 3 of the # -# License, or (at your option) any later version. # -# # -# This program is distributed in the hope that it will be useful, # -# but WITHOUT ANY WARRANTY; without even the implied warranty of # -# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # -# GNU Affero General Public License for more details. # -# # -# You should have received a copy of the GNU Affero General Public License # -# along with this program. If not, see . # -################################################################################ +# RetroShare main qmake build script +# +# Copyright (C) 2004-2019, Retroshare Team +# Copyright (C) 2016-2019, Gioacchino Mazzurco +# +# This program is free software: you can redistribute it and/or modify it under +# the terms of the GNU Lesser 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 Lesser General Public License for more details. +# +# You should have received a copy of the GNU Lesser General Public License along +# with this program. If not, see . +# +# SPDX-FileCopyrightText: Retroshare Team +# SPDX-License-Identifier: LGPL-3.0-or-later + +CONFIG += c++11 !include("retroshare.pri"): error("Could not include file retroshare.pri") @@ -36,59 +41,11 @@ libretroshare.depends += openpgpsdk libbitdht SUBDIRS += libretroshare libretroshare.file = libretroshare/src/libretroshare.pro -libresapi { - SUBDIRS += libresapi - libresapi.file = libresapi/src/libresapi.pro - libresapi.depends += libretroshare -} - retroshare_gui { SUBDIRS += retroshare_gui retroshare_gui.file = retroshare-gui/src/retroshare-gui.pro retroshare_gui.target = retroshare_gui - - libresapi { - retroshare_gui.depends = libresapi - } else { - retroshare_gui.depends = libretroshare - } -} - -retroshare_nogui { - SUBDIRS += retroshare_nogui - retroshare_nogui.file = retroshare-nogui/src/retroshare-nogui.pro - retroshare_nogui.target = retroshare_nogui - - libresapi { - retroshare_nogui.depends = libresapi - } else { - retroshare_nogui.depends = libretroshare - } -} - -retroshare_android_service { - SUBDIRS += retroshare_android_service - retroshare_android_service.file = retroshare-android-service/src/retroshare-android-service.pro - retroshare_android_service.depends = libresapi - retroshare_android_service.target = retroshare_android_service -} - -retroshare_android_notify_service { - SUBDIRS += retroshare_android_notify_service - retroshare_android_notify_service.file = retroshare-android-notify-service/src/retroshare-android-notify-service.pro - retroshare_android_notify_service.depends = retroshare_android_service - retroshare_android_notify_service.target = retroshare_android_notify_service -} - -retroshare_qml_app { - SUBDIRS += retroshare_qml_app - retroshare_qml_app.file = retroshare-qml-app/src/retroshare-qml-app.pro - retroshare_qml_app.depends = retroshare_android_service - retroshare_qml_app.target = retroshare_qml_app - - android-g++ { - retroshare_qml_app.depends += retroshare_android_notify_service - } + retroshare_gui.depends = libretroshare } retroshare_service { diff --git a/TODO.circles.txt b/TODO.circles.txt deleted file mode 100644 index 4e70dccc9..000000000 --- a/TODO.circles.txt +++ /dev/null @@ -1,47 +0,0 @@ -Legend: - [X]: done, [ ]: pending, [-]: Cancelled, [/]: ongoing - -GUI - [X] disable edit circles or make it work - [X] make GUI update when creating a circle - [ ] handle the display of encrypted forums/channels/etc when we do not have the keys - [ ] disable posting to circles for which we do not have the rights - [ ] warn about creating a circle without one of your ids in it - [X] group "show details" should be made up to date for restrinction options - [ ] allow to share circles publish rights - [X] allow non admin to see circles details but not edit - - [ ] update TS of groups linked to a modified circle, so as to cause updates when a new member is addded to the group - [X] forums GUI should show correct restriction options for restricted forums - [X] changing a circle's name should update the GUI - [ ] make sure we cannot post in forums using IDs that are not in the circle - [ ] make sure unauthorised ids are rejected when validating posts from a circle restricted group - [ ] add GUI for local circles in circle GUI - [ ] share publish rights between circles - [ ] clean GUI (hide IDs) - - -Tests - [X] create a safe testing environment: 2 peers with no other contacts, 2 IDs each, and some forums - [X] test #001: transactions should encrypt and decrypt ok on both sides - [X] test #002: peers inside a circles should see the data - [X] test #003: peers outside of a circles shouldn't see the data - [-] test #004: peers subscribed to encrypted circles shouldn't keep asking for the data if they cannot decrypt - [X] test #005: peers can be added/removed from circles, and the circles update between friends - [ ] test #006: peers subscribed to encrypted circles who recently got added to the circle should get the data - [ ] test #007: peers outside a circle shouldn't be able to post (or posts shouldn't propagate) - -Backend - [X] add debug output later RS_NXS_DEBUG_7 in rsgxsnetservice.cc for the crypto layer - -Bugs - [X] Peers cannot be removed from a circle - [X] Context menu should not allow to edit non admin circles - [X] Editing circles make them subscribed, even non admin ones. - [X] Disable autosync for circles (in rsinit.cc) - [-] Add explicit circle sync request for all grps restricted to a circle (same as IDs) - [X] when a peer receives a circle, there is no way to view its details, only the id is available - [X] if a peer has circles available in "Circles (others)"... if you click on - "Create Circle" on the gui, then all circles are automatically subscribed - - diff --git a/TODO.txt b/TODO.txt deleted file mode 100644 index b130f80d8..000000000 --- a/TODO.txt +++ /dev/null @@ -1,135 +0,0 @@ -Legend: - E: easy. Just GUI stuff, no algorithmics involved. That does not mean it's easy to come up with. - M: medium, either because it's a big task, or because it needs to understand a lot of code. - H: hard. Needs digging deep into libretroshare, possibly involving some crypto. - - [ ] pending - [/] half-done, someone's on it - [-] cancelled - [?] needs discussion. Not sure we need this. - [X] done - -PS: no tabs in this file,thx ;-) - ----------------------------------------- TODO for RC --------------------------------------------- - - E [ ] Implement creation of a default (signed) gxs id in startup wizard. Needs to show to the user a proper separation between nodes (network layer) and GXS ids (service layer). - E [ ] add tooltips in in permission matrix when hovering over the top most button/service name explain what the service does and the dependencies - E [ ] finish pass of GXS network service - ------------------------------------------ TODO list ---------------------------------------------- - -GUI - E [X] add a "Contact" list to help selecting peers in People/FriendChooser/messages/etc. - E [ ] fix posted GUI. Needs to be more handy and more appealing. - E [ ] add RS links for GXS identities, so that they can be transferred easily between nodes in forums, etc - E [ ] enable people dialog - M [ ] Personal Page (Profile Page for GXS ID Users,view latest Posts, public forum/channels,posted posts, comments in all areas, Reputation Infos, Popularity and more) - E [ ] fix RSButtonOnText::eventFilter, and fix all places where RSButtonOnText gets deleted - E [ ] find all places where the deprecated(in Qt5) Q_WS_WIN and other Q_WS* macros are used, and replace with something else - E [ ] Make RS fully compatible with High DPI screens. - M [ ] improve comments in channels. Comments should be more available, more visible, and easier to handle. - E [ ] make GRouter statistics less CPU greedy - M [ ] Merge the various help systems. there's 3 of them now. Lots of duplicate code, etc. - M [ ] New and consistent icon set (Purplehaze420 said he would provide a consistent set of icons. Is that still alive?) - M [ ] add in options->Network a way to select which network interface is used to talk (choice between "auto" or selected from a list) - M [?] add a RS link for encrypted messages (encrypt for multiple GXS ids at once). Messages will appear as a link when encrypted and - be automatically decrypted when a suitable GXS id is available for it. Could be a way to securely post something in a public place. - -File transfer (all 3 tasks are related) - E [ ] Add a limit of the total number of files simultaneously asked to the same peer using direct transfer. - H [ ] implement a new file list management, with new info such as access time,total upload, popularity, etc - H [ ] implement a new file list sharing service based on auto-sync system - M [ ] get rid of the old cache system (remove CacheStrapper, CacheSource,etc) - M [ ] implement end-to-end encryption using chacha20 and H(F), requesting file on H(H(F)). Make this optional and backward compatible. - -DHT - H [-] improve DHT lookups to find masquerading peers using fake peers. First experiments (by cyril) do not prove very efficient. - -GXS - M [X] create a tunnel service from distant chat code to make it (1) more generic (2) resistant to packet loss. - M [X] optimise GXS sync BW. For the moment too much is sent between nodes. - H [/] add the ability to use anonymous identities into circles. Needs new distribution model using items encrypted for multiple GXS keys. - H [ ] use different and incompatible classes for public and private keys in GxsSecurity - -VOIP - H [ ] use proper video encoding. What we have now is decent for video, but sound should be prioritized. Experiments - with QtAV seem to work nicely. Finish and integrate! - M [ ] Deactivate Voip Buttons, when Friend has no Voip plugin enabled. - M [ ] Implement Voice for Video Chat - M [ ] Improve Voice and Video Quality - M [ ] Video Quality/Resolution Settings (High, Medium, Low) HD, HQ, SD ) - M [ ] Video Device: WebCam(s) or Desktop Selection - M [ ] Audio Input Device Selection (Microphone) - M [ ] Audio Output Device Selection (Speaker) - M [ ] Video Snapshots https://support.skype.com/en/faq/FA1222/what-is-video-snapshot - M [ ] Voice Messaging (record and send a voice message) - M [ ] Video Messages (send a video greeting to multiple friends/coworkers/developers at once.) - M [ ] Add Call status (when im on the phone changes my status with phone icon) - H [ ] Audio Conference - H [ ] Video Conference - -Messages - H [X] make the mail system re-send failed emails notified by the global router. This is hard because it needs a proper management of duplicate messages - E [X] add flags to allow distant messaging from contact list only / everyone / noone / only signed ids. - M [ ] add Signature feature to messages - M [ ] add vacation responser for messages (automatic replies) - -Chat - E [X] add flags to allow distant chat from contact list only / everyone / noone / only signed ids. - -Libretroshare - E [X] groups small packets in pqistreamer::handleoutgoing_locked(), and see if that removes some padding overhead - E [ ] make sure at least one location is kept when removing old locations as it avoids lots of connection problems. - M [ ] improve serialisation system. Lots of serialisation tasks (header, verifications, serialiser=>template, can be factored) - M [ ] separate chat stuff from rsmsgs.h into rschat.h - M [ ] crash at shutdown due to memory management already cleared while new objects keep being requested. - - #0 0x0000000000da52eb in RsMemoryManagement:¿mallObject:¿mallObject() () - #1 0x0000000000da3694 in RsItem::RsItem(unsigned int) () - #2 0x0000000000dcb365 in RsRawItem::RsRawItem (this=0x0, t=33559555, size=38) at ./serialiser/rsserial.h - #3 0x0000000000fc1643 in RsServiceSerialiser::deserialise(void*, unsigned int*) () - #4 0x0000000000da4451 in RsSerialiser::deserialise(void*, unsigned int*) () - #5 0x0000000000fb5b4b in pqistreamer::handleincoming_locked() () - #6 0x0000000000fb4b3e in pqistreamer::tick_recv(unsigned int) () - #7 0x0000000000fb744a in pqithreadstreamer::data_tick() () - #8 0x0000000000e19b27 in RsTickingThread::runloop (this=0x7fffb004e7e8) at util/rsthreads.cc:196 - #9 0x0000000000e19748 in RsThread::rsthread_init (p=0x7fffb004e7e8) at util/rsthreads.cc:63 - #10 0x00007ffff4006f6b in start_thread () from /lib64/libpthread.so.0 - #11 0x00007ffff351c7ed in clone () from /lib64/libc.so.6 - -Channels - E [ ] allow to set a download directory per channel - M [ ] Thumbnail View for Channels - M [ ] Count commments on Comments Button - M [ ] Notify Channel comments/replies - -Posted - E [ ] Show an info page for unsubscribed posted threads (same as forums) - E [ ] Make the GUI of Posted more sexy: more compact items, remove unecessary text, use consistent icons,... - -Forums - E [ ] do we keep "Getting Started" ? the look needs to be improved. Any help doing this is welcome! - E [ ] some widgets in the GUI do not follow the system style => GUI looks bad on these systems - -Bugs - E [ ] find the bug that shows some peers online in Network although they are not. - M [X] Selecting different options in messages composer -> contact list then come back, - shows disappearing / re-appearing people. What causes this??? - -Sounds - E [ ] add default sounds for Friend go online, New Chat Message, Message arrived, Download complete - M [ ] make sure sound is working for users on linux. We also need a "test sound" button in config->sound. - -Packaging - E [ ] Sound files should be part of the install package at least on ubuntu (put them in /usr/share) - -List of pending non backward compatible changes -=============================================== - - * RsGxsGrpMetaData::deserialis should use a proper TLV_STR_TYPE_NAME instead of 0 for - mGroupName and mMsgName, in rsgxsdata.cc - * p3IdService::service_CreateGroup() should convert the mPgpSign member to radix64!! For now - it is hard-coded in binary in a string. - - diff --git a/android-prepare-toolchain.sh b/android-prepare-toolchain.sh deleted file mode 100755 index 100b426ff..000000000 --- a/android-prepare-toolchain.sh +++ /dev/null @@ -1,333 +0,0 @@ -#!/bin/bash - -## Define default value for variable, take two arguments, $1 variable name, -## $2 default variable value, if the variable is not already define define it -## with default value. -function define_default_value() -{ - VAR_NAME="${1}" - DEFAULT_VALUE="${2}" - - [ -z "${!VAR_NAME}" ] && export ${VAR_NAME}="${DEFAULT_VALUE}" -} - -## You are supposed to provide the following variables according to your system setup -define_default_value ANDROID_NDK_PATH "/opt/android-ndk/" -define_default_value ANDROID_NDK_ARCH "arm" -define_default_value ANDROID_NDK_ABI_VER "4.9" -define_default_value ANDROID_PLATFORM_VER "18" -define_default_value NATIVE_LIBS_TOOLCHAIN_PATH "${HOME}/Builds/android-toolchains/retroshare-android-${ANDROID_PLATFORM_VER}-${ANDROID_NDK_ARCH}-abi${ANDROID_NDK_ABI_VER}/" -define_default_value HOST_NUM_CPU $(nproc) - -define_default_value BZIP2_SOURCE_VERSION "1.0.6" -define_default_value BZIP2_SOURCE_SHA256 a2848f34fcd5d6cf47def00461fcb528a0484d8edef8208d6d2e2909dc61d9cd - -define_default_value OPENSSL_SOURCE_VERSION "1.0.2n" -define_default_value OPENSSL_SOURCE_SHA256 370babb75f278c39e0c50e8c4e7493bc0f18db6867478341a832a982fd15a8fe - -define_default_value SQLITE_SOURCE_YEAR "2018" -define_default_value SQLITE_SOURCE_VERSION "3220000" -define_default_value SQLITE_SOURCE_SHA256 2824ab1238b706bc66127320afbdffb096361130e23291f26928a027b885c612 - -define_default_value SQLCIPHER_SOURCE_VERSION "3.4.2" -define_default_value SQLCIPHER_SOURCE_SHA256 69897a5167f34e8a84c7069f1b283aba88cdfa8ec183165c4a5da2c816cfaadb - -define_default_value LIBUPNP_SOURCE_VERSION "1.6.24" -define_default_value LIBUPNP_SOURCE_SHA256 7d83d79af3bb4062e5c3a58bf2e90d2da5b8b99e2b2d57c23b5b6f766288cf96 - -define_default_value INSTALL_QT_ANDROID "false" -define_default_value QT_VERSION "5.9.4" -define_default_value QT_ANDROID_INSTALLER_SHA256 a214084e2295c9a9f8727e8a0131c37255bf724bfc69e80f7012ba3abeb1f763 - - -## $1 filename, $2 sha256 hash -function check_sha256() -{ - echo ${2} "${1}" | sha256sum -c &> /dev/null -} - -## $1 filename, $2 sha256 hash, $3 url -function verified_download() -{ - FILENAME="$1" - SHA256="$2" - URL="$3" - - check_sha256 "${FILENAME}" "${SHA256}" || - { - rm -rf "${FILENAME}" - - wget -O "${FILENAME}" "$URL" || - { - echo "Failed downloading ${FILENAME} from $URL" - exit 1 - } - - check_sha256 "${FILENAME}" "${SHA256}" || - { - echo "SHA256 mismatch for ${FILENAME} from ${URL} expected sha256 ${SHA256} got $(sha256sum ${FILENAME} | awk '{print $1}')" - exit 1 - } - } -} - - - -if [ "${ANDROID_NDK_ARCH}" == "x86" ]; then - cArch="i686" - eABI="" -else - cArch="${ANDROID_NDK_ARCH}" - eABI="eabi" -fi -export SYSROOT="${NATIVE_LIBS_TOOLCHAIN_PATH}/sysroot" -export PREFIX="${SYSROOT}" -export CC="${NATIVE_LIBS_TOOLCHAIN_PATH}/bin/${cArch}-linux-android${eABI}-gcc" -export CXX="${NATIVE_LIBS_TOOLCHAIN_PATH}/bin/${cArch}-linux-android${eABI}-g++" -export AR="${NATIVE_LIBS_TOOLCHAIN_PATH}/bin/${cArch}-linux-android${eABI}-ar" -export RANLIB="${NATIVE_LIBS_TOOLCHAIN_PATH}/bin/${cArch}-linux-android${eABI}-ranlib" -export ANDROID_DEV="${ANDROID_NDK_PATH}/platforms/android-${ANDROID_PLATFORM_VER}/arch-${ANDROID_NDK_ARCH}/usr" - - -## More information available at https://android.googlesource.com/platform/ndk/+/ics-mr0/docs/STANDALONE-TOOLCHAIN.html -build_toolchain() -{ - rm -rf ${NATIVE_LIBS_TOOLCHAIN_PATH} - [ "${ANDROID_NDK_ARCH}" == "x86" ] && toolchainName="${ANDROID_NDK_ARCH}-${ANDROID_NDK_ABI_VER}" || toolchainName="${ANDROID_NDK_ARCH}-linux-androideabi-${ANDROID_NDK_ABI_VER}" - ${ANDROID_NDK_PATH}/build/tools/make-standalone-toolchain.sh --ndk-dir=${ANDROID_NDK_PATH} --arch=${ANDROID_NDK_ARCH} --install-dir=${NATIVE_LIBS_TOOLCHAIN_PATH} --platform=android-${ANDROID_PLATFORM_VER} --toolchain=${toolchainName} --verbose -} - -## More information available at https://gitlab.com/relan/provisioners/merge_requests/1 and http://stackoverflow.com/a/34032216 -install_qt_android() -{ - QT_VERSION_CODE=$(echo $QT_VERSION | tr -d .) - QT_INSTALL_PATH=${NATIVE_LIBS_TOOLCHAIN_PATH}/Qt - QT_INSTALLER="qt-unified-linux-x64-3.0.2-online.run" - - verified_download $QT_INSTALLER $QT_ANDROID_INSTALLER_SHA256 \ - http://master.qt.io/archive/online_installers/3.0/${QT_INSTALLER} - - chmod a+x ${QT_INSTALLER} - - QT_INSTALLER_SCRIPT="qt_installer_script.js" - cat << EOF > "${QT_INSTALLER_SCRIPT}" -function Controller() { - installer.autoRejectMessageBoxes(); - installer.installationFinished.connect(function() { - gui.clickButton(buttons.NextButton); - }); - - var welcomePage = gui.pageWidgetByObjectName("WelcomePage"); - welcomePage.completeChanged.connect(function() { - if (gui.currentPageWidget().objectName == welcomePage.objectName) - gui.clickButton(buttons.NextButton); - }); -} - -Controller.prototype.WelcomePageCallback = function() { - gui.clickButton(buttons.NextButton); -} - -Controller.prototype.CredentialsPageCallback = function() { - gui.clickButton(buttons.NextButton); -} - -Controller.prototype.IntroductionPageCallback = function() { - gui.clickButton(buttons.NextButton); -} - -Controller.prototype.TargetDirectoryPageCallback = function() { - gui.currentPageWidget().TargetDirectoryLineEdit.setText("$QT_INSTALL_PATH"); - gui.clickButton(buttons.NextButton); -} - -Controller.prototype.ComponentSelectionPageCallback = function() { - var widget = gui.currentPageWidget(); - - // You can get these component names by running the installer with the - // --verbose flag. It will then print out a resource tree. - - widget.deselectComponent("qt.tools.qtcreator"); - widget.deselectComponent("qt.tools.doc"); - widget.deselectComponent("qt.tools.examples"); - - widget.selectComponent("qt.$QT_VERSION_CODE.android_armv7"); - - gui.clickButton(buttons.NextButton); -} - -Controller.prototype.LicenseAgreementPageCallback = function() { - gui.currentPageWidget().AcceptLicenseRadioButton.setChecked(true); - gui.clickButton(buttons.NextButton); -} - -Controller.prototype.StartMenuDirectoryPageCallback = function() { - gui.clickButton(buttons.NextButton); -} - -Controller.prototype.ReadyForInstallationPageCallback = function() { - gui.clickButton(buttons.NextButton); -} - -Controller.prototype.FinishedPageCallback = function() { - var checkBoxForm = gui.currentPageWidget().LaunchQtCreatorCheckBoxForm; - if (checkBoxForm && checkBoxForm.launchQtCreatorCheckBox) - checkBoxForm.launchQtCreatorCheckBox.checked = false; - gui.clickButton(buttons.FinishButton); -} -EOF - -QT_QPA_PLATFORM=minimal ./${QT_INSTALLER} --script ${QT_INSTALLER_SCRIPT} -} - -## More information available at retroshare://file?name=Android%20Native%20Development%20Kit%20Cookbook.pdf&size=29214468&hash=0123361c1b14366ce36118e82b90faf7c7b1b136 -build_bzlib() -{ - B_dir="bzip2-${BZIP2_SOURCE_VERSION}" - rm -rf $B_dir - - verified_download $B_dir.tar.gz $BZIP2_SOURCE_SHA256 \ - http://www.bzip.org/${BZIP2_SOURCE_VERSION}/bzip2-${BZIP2_SOURCE_VERSION}.tar.gz - - tar -xf $B_dir.tar.gz - cd $B_dir - sed -i "/^CC=.*/d" Makefile - sed -i "/^AR=.*/d" Makefile - sed -i "/^RANLIB=.*/d" Makefile - sed -i "/^LDFLAGS=.*/d" Makefile - sed -i "s/^all: libbz2.a bzip2 bzip2recover test/all: libbz2.a bzip2 bzip2recover/" Makefile - make -j${HOST_NUM_CPU} - make install PREFIX=${SYSROOT}/usr -# sed -i "/^CC=.*/d" Makefile-libbz2_so -# make -f Makefile-libbz2_so -j${HOST_NUM_CPU} -# cp libbz2.so.1.0.6 ${SYSROOT}/usr/lib/libbz2.so - cd .. -} - -## More information available at http://doc.qt.io/qt-5/opensslsupport.html -build_openssl() -{ - B_dir="openssl-${OPENSSL_SOURCE_VERSION}" - rm -rf $B_dir - - verified_download $B_dir.tar.gz $OPENSSL_SOURCE_SHA256 \ - https://www.openssl.org/source/$B_dir.tar.gz - - tar -xf $B_dir.tar.gz - cd $B_dir - if [ "${ANDROID_NDK_ARCH}" == "arm" ]; then - oArch="armv7" - else - oArch="${ANDROID_NDK_ARCH}" - fi -# ANDROID_NDK_ROOT="${ANDROID_NDK_PATH}" ./Configure android-${oArch} shared --prefix="${SYSROOT}/usr" --openssldir="${SYSROOT}/etc/ssl" -## We link openssl statically to avoid android silently sneaking in his own -## version of libssl.so (we noticed this because it had some missing symbol -## that made RS crash), the crash in some android version is only one of the -## possible problems the fact that android insert his own binary libssl.so pose -## non neglegible security concerns. - ANDROID_NDK_ROOT="${ANDROID_NDK_PATH}" ./Configure android-${oArch} --prefix="${SYSROOT}/usr" --openssldir="${SYSROOT}/etc/ssl" - sed -i 's/LIBNAME=$$i LIBVERSION=$(SHLIB_MAJOR).$(SHLIB_MINOR) \\/LIBNAME=$$i \\/g' Makefile - sed -i '/LIBCOMPATVERSIONS=";$(SHLIB_VERSION_HISTORY)" \\/d' Makefile - make -j${HOST_NUM_CPU} - make install -# cp *.so "${SYSROOT}/usr/lib" - cd .. -} - -build_sqlite() -{ - B_dir="sqlite-autoconf-${SQLITE_SOURCE_VERSION}" - - verified_download $B_dir.tar.gz $SQLITE_SOURCE_SHA256 \ - https://www.sqlite.org/${SQLITE_SOURCE_YEAR}/$B_dir.tar.gz - - tar -xf $B_dir.tar.gz - cd $B_dir - ./configure --prefix="${SYSROOT}/usr" --host=${ANDROID_NDK_ARCH}-linux - make -j${HOST_NUM_CPU} - make install - rm -f ${SYSROOT}/usr/lib/libsqlite3.so* -# ${CC} -shared -o libsqlite3.so -fPIC sqlite3.o -ldl -# cp libsqlite3.so "${SYSROOT}/usr/lib" - cd .. -} - -build_sqlcipher() -{ - B_dir="sqlcipher-${SQLCIPHER_SOURCE_VERSION}" - rm -rf $B_dir - - T_file="${B_dir}.tar.gz" - - verified_download $T_file $SQLCIPHER_SOURCE_SHA256 \ - https://github.com/sqlcipher/sqlcipher/archive/v${SQLCIPHER_SOURCE_VERSION}.tar.gz - - tar -xf $T_file - cd $B_dir - ./configure --build=$(sh ./config.guess) \ - --host=${ANDROID_NDK_ARCH}-linux \ - --prefix="${SYSROOT}/usr" --with-sysroot="${SYSROOT}" \ - --enable-tempstore=yes \ - --disable-tcl --disable-shared \ - CFLAGS="-DSQLITE_HAS_CODEC" LDFLAGS="${SYSROOT}/usr/lib/libcrypto.a" - make -j${HOST_NUM_CPU} - make install - cd .. -} - -build_libupnp() -{ - B_dir="libupnp-${LIBUPNP_SOURCE_VERSION}" - rm -rf $B_dir - - verified_download $B_dir.tar.bz2 $LIBUPNP_SOURCE_SHA256 \ - https://sourceforge.net/projects/pupnp/files/pupnp/libUPnP%20${LIBUPNP_SOURCE_VERSION}/$B_dir.tar.bz2 - - tar -xf $B_dir.tar.bz2 - cd $B_dir -## liupnp must be configured as static library because if not the linker will -## look for libthreadutils.so.6 at runtime that cannot be packaged on android -## as it supports only libname.so format for libraries, thus resulting in a -## crash at startup. - ./configure --enable-static --disable-shared --disable-samples --prefix="${SYSROOT}/usr" --host=${ANDROID_NDK_ARCH}-linux - make -j${HOST_NUM_CPU} - make install - cd .. -} - -build_libmicrohttpd() -{ - echo "libmicrohttpd not supported yet on android" - return 0 - - B_dir="libmicrohttpd-0.9.50" - rm -rf $B_dir - [ -f $B_dir.tar.gz ] || wget ftp://ftp.gnu.org/gnu/libmicrohttpd/$B_dir.tar.gz - tar -xf $B_dir.tar.gz - cd $B_dir - ./configure --prefix="${SYSROOT}/usr" --host=${ANDROID_NDK_ARCH}-linux - #make -e ? - make -j${HOST_NUM_CPU} - make install - cd .. -} - -build_rapidjson() -{ - B_dir="rapidjson-1.1.0" - [ -f $B_dir.tar.gz ] || wget -O $B_dir.tar.gz https://github.com/Tencent/rapidjson/archive/v1.1.0.tar.gz - tar -xf $B_dir.tar.gz - cp -r rapidjson-1.1.0/include/rapidjson/ "${SYSROOT}/usr/include/rapidjson" -} - -build_toolchain -[ "${INSTALL_QT_ANDROID}X" == "trueX" ] && install_qt_android -build_bzlib -build_openssl -build_sqlite -build_sqlcipher -build_libupnp -build_rapidjson - -echo NATIVE_LIBS_TOOLCHAIN_PATH=${NATIVE_LIBS_TOOLCHAIN_PATH} diff --git a/appveyor.yml b/appveyor.yml index 98686b717..b22beb2de 100644 --- a/appveyor.yml +++ b/appveyor.yml @@ -1,3 +1,6 @@ +# SPDX-FileCopyrightText: (C) 2004-2019 Retroshare Team +# SPDX-License-Identifier: CC0-1.0 + # Notes: # - Minimal appveyor.yml file is an empty file. All sections are optional. # - Indent each level of configuration with 2 spaces. Do not use tabs! @@ -90,8 +93,10 @@ install: # Configuring MSys2 - set PATH=C:\msys64\usr\bin;%PATH% - set PATH=C:\msys64\mingw32\bin;%PATH% - - pacman --noconfirm -S mingw-w64-i686-qt5 mingw-w64-i686-miniupnpc mingw-w64-i686-sqlcipher mingw-w64-i686-libmicrohttpd mingw-w64-i686-xapian-core mingw-w64-i686-cmark - #- pacman --noconfirm -S mingw-w64-i686-qt5-static mingw-w64-i686-miniupnpc mingw-w64-i686-sqlcipher mingw-w64-i686-libmicrohttpd + - > + pacman --noconfirm -S + mingw-w64-i686-qt5 mingw-w64-i686-miniupnpc mingw-w64-i686-rapidjson + mingw-w64-i686-sqlcipher mingw-w64-i686-xapian-core mingw-w64-i686-cmark #- set PATH=C:\msys64\mingw32\qt5-static\bin\;%PATH% # Configuring Qt @@ -138,6 +143,10 @@ configuration: Release # scripts to run before build before_build: - cd C:\projects\RetroShare + - git submodule update --init + - cd C:\projects\ + - mkdir RetroShare-build + - cd RetroShare-build # - find C:\ > filelist.txt # scripts to run *after* solution is built and *before* automatic packaging occurs (web apps, NuGet packages, Azure Cloud Services) @@ -146,15 +155,18 @@ before_package: # to run your custom scripts instead of automatic MSBuild build_script: - env - - git submodule update --init - - qmake -Wall -spec win32-g++ "CONFIG=debug" + - qmake ../RetroShare -spec win32-g++ "CONFIG+=debug" - mingw32-make -j3 # scripts to run after build after_build: + - find . + - mkdir %RS_DEPLOY% - - copy retroshare-service\src\retroshare-service.exe %RS_DEPLOY%\ - - copy retroshare-gui\src\retroshare.exe %RS_DEPLOY%\ + - copy retroshare-gui\src\debug\retroshare.exe %RS_DEPLOY%\ + - copy retroshare-service\src\debug\retroshare-service.exe %RS_DEPLOY%\ +# - copy retroshare-service\src\retroshare-service.exe %RS_DEPLOY%\ +# - copy retroshare-gui\src\retroshare.exe %RS_DEPLOY%\ ## In Debug build winedeplyqt forget the non debug Qt libs - copy C:\msys64\mingw32\bin\Qt5Svg.dll %RS_DEPLOY%\ @@ -234,24 +246,10 @@ after_build: - copy C:\msys64\mingw32\bin\libwebpdemux*.dll %RS_DEPLOY%\ - copy C:\msys64\mingw32\bin\liblzma*.dll %RS_DEPLOY%\ -## Needed for libresapi http - - copy C:\msys64\mingw32\bin\libmicrohttpd*.dll %RS_DEPLOY%\ - - copy C:\msys64\mingw32\bin\libgnutls*.dll %RS_DEPLOY%\ - - copy C:\msys64\mingw32\bin\libgmp*.dll %RS_DEPLOY%\ - - copy C:\msys64\mingw32\bin\libhogweed*.dll %RS_DEPLOY%\ - - copy C:\msys64\mingw32\bin\libidn2*.dll %RS_DEPLOY%\ - - copy C:\msys64\mingw32\bin\libnettle*.dll %RS_DEPLOY%\ - - copy C:\msys64\mingw32\bin\libp11-kit*.dll %RS_DEPLOY%\ - - copy C:\msys64\mingw32\bin\libtasn1*.dll %RS_DEPLOY%\ - - copy C:\msys64\mingw32\bin\libunistring*.dll %RS_DEPLOY%\ - - copy C:\msys64\mingw32\bin\libffi*.dll %RS_DEPLOY%\ - ## Needed for cmark - copy C:\msys64\mingw32\bin\libcmark*.dll %RS_DEPLOY%\ - copy C:\msys64\mingw32\bin\libdouble-conversion*.dll %RS_DEPLOY%\ - - find C:\projects\RetroShare >> filelist.txt - # to disable automatic builds #build: off diff --git a/README-Android.asciidoc b/build_scripts/Android/README.asciidoc similarity index 91% rename from README-Android.asciidoc rename to build_scripts/Android/README.asciidoc index f64336c1c..d045281b9 100644 --- a/README-Android.asciidoc +++ b/build_scripts/Android/README.asciidoc @@ -1,3 +1,6 @@ +// SPDX-FileCopyrightText: RetroShare Team +// SPDX-License-Identifier: CC-BY-SA-4.0 + Compile Retroshare for Android ============================== @@ -37,7 +40,7 @@ export NATIVE_LIBS_TOOLCHAIN_PATH="${HOME}/Builds/android-toolchains/retroshare- export ANDROID_NDK_ARCH="arm" ## The Android API level the Android device you want to target -export ANDROID_PLATFORM_VER="19" +export ANDROID_PLATFORM_VER="16" ## The number of core that yout host CPU have (just to speed up compilation) set ## it to 1 if unsure @@ -60,30 +63,28 @@ project and in the Projects left menu add the newly created kit if not already present, so you can select it on the build type selection button down on the left. -As we use a custom toolchain one more step is needed + +Now you need to set properly a few options like `JSONAPI_GENERATOR_EXE` and +disable some of RetroShare modules like `retroshare-gui` that are not available +on Android so you will have to go to _Qt Creator left pane -> Projects -> Build and Run -> Android SOMESTUFF kit -> -Build Environement -> Add +Build Steps -> qmake -> Additional arguments_ + -Variable: +NATIVE_LIBS_TOOLCHAIN_PATH+ -Value: +Same value as NATIVE_LIBS_TOOLCHAIN_PATH in Preparing The Environement step+ - -Some of RetroShare modules like +retroshare-gui+ and +WebUI+ are not available -on Android so to be able to compile RetroShare without errors you will have to -go to + - -_Qt Creator left pane -> Projects -> Build and Run -> Android SOMESTUFF kit -> -Build Steps -> qmake -> Additional arguments_ - -and add the following configurations +and add the following configurations (change `Your_Path` according to your +deployment) [source,makefile] ------------------------------------------------------------------------------- -CONFIG+=no_retroshare_gui CONFIG+=no_retroshare_nogui CONFIG+=no_retroshare_plugins CONFIG+=retroshare_android_service CONFIG+=libresapilocalserver CONFIG+=no_libresapihttpserver CONFIG+=retroshare_qml_app +CONFIG+=retroshare_service CONFIG+=rs_jsonapi CONFIG+=rs_deep_search +RS_UPNP_LIB=miniupnpc +JSONAPI_GENERATOR_EXE=Your_Path/jsonapi-generator/src/jsonapi-generator +NATIVE_LIBS_TOOLCHAIN_PATH=Your_Path/retroshare-android-16-arm/ +CONFIG+=no_retroshare_gui CONFIG+=no_rs_service_webui_terminal_password +CONFIG+=no_rs_service_terminal_login ------------------------------------------------------------------------------- TIP: Some versions of QtCreator try to find the Android SDK in -+/opt/android/sdk+. A workaround to this is to make a symbolic link there +`/opt/android/sdk`. A workaround to this is to make a symbolic link there pointing to your SDK installation path, like +mkdir -p /opt/android/sdk && ln -s /home/user/android-sdk-linux /opt/android/sdk+ @@ -117,7 +118,7 @@ only solution is to uninstall the app and then install the new APK but if you do it also the application data and your precious cryptographic keys, friend list etc. will be lost forever. To avoid that you can attempt to manually backup and then restore from the -command-line (+adb backup+ seems not working either) to change the app source +command-line (`adb backup` seems not working either) to change the app source without erasing the appliation data. CAUTION: Following steps require root access on your Android device diff --git a/build_scripts/Android/prepare-toolchain-clang.sh b/build_scripts/Android/prepare-toolchain-clang.sh index b943ee5e3..295f4604f 100755 --- a/build_scripts/Android/prepare-toolchain-clang.sh +++ b/build_scripts/Android/prepare-toolchain-clang.sh @@ -1,5 +1,25 @@ #!/bin/bash +# Script to prepare RetroShare Android package building toolchain +# +# Copyright (C) 2016-2019 Gioacchino Mazzurco +# +# This program is free software: you can redistribute it and/or modify it under +# the terms of the GNU Affero General Public License as published by the +# Free Software Foundation, version 3. +# +# This program is distributed in the hope that it will be useful, but +# WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or +# FITNESS FOR A PARTICULAR PURPOSE. +# See the GNU Affero General Public License for more details. +# +# You should have received a copy of the GNU Affero General Public License along +# with this program. If not, see +# +# SPDX-FileCopyrightText: Retroshare Team +# SPDX-License-Identifier: AGPL-3.0-only + + ## Define default value for variable, take two arguments, $1 variable name, ## $2 default variable value, if the variable is not already define define it ## with default value. @@ -424,7 +444,7 @@ build_restbed() rm -rf restbed-build; mkdir restbed-build ; cd restbed-build cmake \ - -DCMAKE_POSITION_INDEPENDENT_CODE=ON \ + -DCMAKE_POSITION_INDEPENDENT_CODE=ON BUILD_TESTS=OFF \ -DBUILD_SSL=OFF -DCMAKE_INSTALL_PREFIX="${PREFIX}" -B. -H../restbed make -j${HOST_NUM_CPU} make install diff --git a/build_scripts/Debian+Ubuntu/debian/copyright b/build_scripts/Debian+Ubuntu/debian/copyright deleted file mode 100644 index 84b7e4a7f..000000000 --- a/build_scripts/Debian+Ubuntu/debian/copyright +++ /dev/null @@ -1,44 +0,0 @@ -This package was debianized by: - - Cyril Soler on Sat, 06 Feb 2010 07:15:46 +0100 - -It was downloaded from: - - - -Upstream Author(s): - - - - -Copyright: - - - - -License: - - 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 package 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 . - -On Debian systems, the complete text of the GNU General -Public License version 3 can be found in `/usr/share/common-licenses/GPL-3'. - -The Debian packaging is: - - Copyright (C) 2010 Cyril Soler - -and is licensed under the GPL version 3, see above. - -# Please also look if there are files or directories which have a -# different copyright/license attached and list them here. diff --git a/build_scripts/Debian+Ubuntu/debian/copyright b/build_scripts/Debian+Ubuntu/debian/copyright new file mode 120000 index 000000000..f5498e1c0 --- /dev/null +++ b/build_scripts/Debian+Ubuntu/debian/copyright @@ -0,0 +1 @@ +../../../.reuse/dep5 \ No newline at end of file diff --git a/build_scripts/Debian/debian/copyright b/build_scripts/Debian/debian/copyright deleted file mode 100644 index c94948a36..000000000 --- a/build_scripts/Debian/debian/copyright +++ /dev/null @@ -1,151 +0,0 @@ -Format: https://www.debian.org/doc/packaging-manuals/copyright-format/1.0/ -Upstream-Name: retroshare -Upstream-Contact: retroshare.team@gmail.com -Source: https://github.com/retroshare/retroshare - -Files: openpgpsdk/* -Copyright: 2005-2008 Ben Laurie, Rachel Willmer, Retroshare Team -License: Apache-2.0 - -Files: jsonapi-generator/* libretroshare/src/jsonapi/* -Copyright: 2018-2019 Gioacchino Mazzurco -License: AGPL-3+ - -Files: libretroshare/* -Copyright: 2007-2018, Retroshare Team -License: LGPL-3+ - -Files: src/retroshare-gui/src/TorControl/ -Copyright: 2014, John Brooks -License: BSD-New - -Files: src/libresapi/src/api/json.h \ - libresapi/src/webui-src/app/mithril.min.js \ - src/rapidjson-1.1.0/* \ - retroshare-gui/src/gui/common/PictureFlow.* \ - src/retroshare-gui/src/qss/qdarkstyle.qss -Copyright: 2013 Jeff Weinstein -License: MIT - -Files: * -Copyright: 2007-2018, Retroshare Team -License: AGPL-3+ - -####### -# TODO -####### -# src/libretroshare/src/tcponudp/bss_tou.c -# src/retroshare-gui/src/help/content/* -####### - - -License: Apache-2.0 - Contributors: . The Contributors have asserted - their moral rights under the UK Copyright Design and Patents Act 1988 to - be recorded as the authors of this copyright work. - . - Licensed under the Apache License, Version 2.0 (the "License"); you may not - use this file except in compliance with the License. - . - You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 - . - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - . - See the License for the specific language governing permissions and - limitations under the License. - -License: LGPL-3+ - This program is free software: you can redistribute it and/or modify - it under the terms of the GNU Lesser 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 Lesser General Public License for more details. - . - You should have received a copy of the GNU Lesser General Public License - along with this program. If not, see . - . - In addition, as a special exception, the copyright holders give permission to - link this program with the OpenSSL library (or with modified versions of - OpenSSL that use the same license as OpenSSL), and distribute linked - combinations including the two. - -License: AGPL-3+ - This program is free software: you can redistribute it and/or modify - it under the terms of the GNU Affero General Public License as - published by the Free Software Foundation, either version 3 of the - License, or (at your option) any later version. - . - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU Lesser General Public License for more details. - . - You should have received a copy of the GNU Lesser General Public License - along with this program. If not, see . - . - As a special exception, the copyright holders give permission to link the - code of portions of this program with the OpenSSL library under certain - conditions as described in each individual source file and distribute - linked combinations including the program with the OpenSSL library. You - must comply with the GNU Affero General Public License in all respects for - all of the code used other than as permitted herein. If you modify file(s) - with this exception, you may extend this exception to your version of the - file(s), but you are not obligated to do so. If you do not wish to do so, - delete this exception statement from your version. If you delete this - exception statement from all source files in the program, then also delete - it in the license file. - -License: MIT - Permission is hereby granted, free of charge, to any person obtaining a copy - of this software and associated documentation files (the "Software"), to deal - in the Software without restriction, including without limitation the rights - to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - copies of the Software, and to permit persons to whom the Software is - furnished to do so, subject to the following conditions: - . - The above copyright notice and this permission notice shall be included in - all copies or substantial portions of the Software. - . - THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - THE SOFTWARE. - -License: BSD-New - You may use this file under the terms of the BSD license as follows: - . - "Redistribution and use in source and binary forms, with or without - modification, are permitted provided that the following conditions are - met: - * Redistributions of source code must retain the above copyright - notice, this list of conditions and the following disclaimer. - * Redistributions in binary form must reproduce the above copyright - notice, this list of conditions and the following disclaimer in - the documentation and/or other materials provided with the - distribution. - * Neither the name of Digia Plc and its Subsidiary(-ies) nor the names - of its contributors may be used to endorse or promote products derived - from this software without specific prior written permission. - . - . - THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS - "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT - LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR - A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT - OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, - SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, - DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY - THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT - (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE - OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE." - diff --git a/build_scripts/Debian/debian/copyright b/build_scripts/Debian/debian/copyright new file mode 120000 index 000000000..f5498e1c0 --- /dev/null +++ b/build_scripts/Debian/debian/copyright @@ -0,0 +1 @@ +../../../.reuse/dep5 \ No newline at end of file diff --git a/build_scripts/OBS b/build_scripts/OBS index a8c1d3bca..c064abd74 160000 --- a/build_scripts/OBS +++ b/build_scripts/OBS @@ -1 +1 @@ -Subproject commit a8c1d3bca9de4c93d0212ed9dcda22fe06c833ec +Subproject commit c064abd74b27e1cc440917e9dbac800316bb8470 diff --git a/MacOS_X_InstallGuide.md b/build_scripts/OSX/MacOS_X_InstallGuide.md similarity index 100% rename from MacOS_X_InstallGuide.md rename to build_scripts/OSX/MacOS_X_InstallGuide.md diff --git a/travis_makeOSXPackage.sh b/build_scripts/OSX/travis_makeOSXPackage.sh old mode 100644 new mode 100755 similarity index 100% rename from travis_makeOSXPackage.sh rename to build_scripts/OSX/travis_makeOSXPackage.sh diff --git a/WindowsMSys2_InstallGuide.md b/build_scripts/Windows-msys2/WindowsMSys2_InstallGuide.md similarity index 98% rename from WindowsMSys2_InstallGuide.md rename to build_scripts/Windows-msys2/WindowsMSys2_InstallGuide.md index c9ce0edd7..5d939d2de 100644 --- a/WindowsMSys2_InstallGuide.md +++ b/build_scripts/Windows-msys2/WindowsMSys2_InstallGuide.md @@ -47,6 +47,7 @@ Install all needed dependencies: pacman -S mingw-w64-i686-sqlcipher pacman -S mingw-w64-i686-qt5 pacman -S mingw32/mingw-w64-i686-cmake + pacman -S mingw-w64-i686-rapidjson We're done installing MSYS2, close the shell terminal. diff --git a/build_scripts/Windows-msys2/build/build.bat b/build_scripts/Windows-msys2/build/build.bat index 97d6e5853..d15e5babc 100644 --- a/build_scripts/Windows-msys2/build/build.bat +++ b/build_scripts/Windows-msys2/build/build.bat @@ -18,7 +18,7 @@ if errorlevel 2 exit /B 2 if errorlevel 1 goto error_env :: Install needed things -%EnvMSYS2Cmd% "pacman --noconfirm --needed -S make git mingw-w64-%RsMSYS2Architecture%-toolchain mingw-w64-%RsMSYS2Architecture%-qt5 mingw-w64-%RsMSYS2Architecture%-miniupnpc mingw-w64-%RsMSYS2Architecture%-sqlcipher mingw-w64-%RsMSYS2Architecture%-libmicrohttpd mingw-w64-%RsMSYS2Architecture%-xapian-core" +%EnvMSYS2Cmd% "pacman --noconfirm --needed -S make git mingw-w64-%RsMSYS2Architecture%-toolchain mingw-w64-%RsMSYS2Architecture%-qt5 mingw-w64-%RsMSYS2Architecture%-miniupnpc mingw-w64-%RsMSYS2Architecture%-sqlcipher mingw-w64-%RsMSYS2Architecture%-libmicrohttpd mingw-w64-%RsMSYS2Architecture%-xapian-core mingw-w64-%RsMSYS2Architecture%-cmake mingw-w64-%RsMSYS2Architecture%-rapidjson" :: Plugins if "%ParamPlugins%"=="1" %EnvMSYS2Cmd% "pacman --noconfirm --needed -S mingw-w64-%RsMSYS2Architecture%-speex mingw-w64-%RsMSYS2Architecture%-speexdsp mingw-w64-%RsMSYS2Architecture%-curl mingw-w64-%RsMSYS2Architecture%-libxslt mingw-w64-%RsMSYS2Architecture%-opencv mingw-w64-%RsMSYS2Architecture%-ffmpeg" diff --git a/build_scripts/Windows-msys2/build/pack.bat b/build_scripts/Windows-msys2/build/pack.bat index 5be0ac56e..e8c9761bc 100644 --- a/build_scripts/Windows-msys2/build/pack.bat +++ b/build_scripts/Windows-msys2/build/pack.bat @@ -99,6 +99,7 @@ copy nul "%RsDeployPath%\portable" %Quite% echo copy binaries copy "%RsBuildPath%\retroshare-gui\src\%RsBuildConfig%\RetroShare*.exe" "%RsDeployPath%" %Quite% copy "%RsBuildPath%\retroshare-nogui\src\%RsBuildConfig%\retroshare*-nogui.exe" "%RsDeployPath%" %Quite% +copy "%RsBuildPath%\retroshare-service\src\%RsBuildConfig%\retroshare*-service.exe" "%RsDeployPath%" %Quite% echo copy extensions for /D %%D in ("%RsBuildPath%\plugins\*") do ( @@ -127,6 +128,9 @@ if exist "%QtSharePath%\plugins\styles\qwindowsvistastyle.dll" ( copy "%QtSharePath%\plugins\imageformats\*.dll" "%RsDeployPath%\imageformats" %Quite% del /Q "%RsDeployPath%\imageformats\*d?.dll" %Quite% +for %%D in ("%RsDeployPath%\imageformats\*.dll") do ( + call :copy_dependencies "%%D" "%RsDeployPath%" +) echo copy qss xcopy /S "%SourcePath%\retroshare-gui\src\qss" "%RsDeployPath%\qss" %Quite% diff --git a/jsonapi-generator/README.adoc b/jsonapi-generator/README.adoc index 7d7d5be04..95c58ec0c 100644 --- a/jsonapi-generator/README.adoc +++ b/jsonapi-generator/README.adoc @@ -1,3 +1,6 @@ +// SPDX-FileCopyrightText: (C) 2004-2019 Retroshare Team +// SPDX-License-Identifier: CC0-1.0 + RetroShare JSON API =================== diff --git a/jsonapi-generator/src/async-method-wrapper-template.cpp.tmpl b/jsonapi-generator/src/async-method-wrapper-template.cpp.tmpl index 81b97265b..16bfe3304 100644 --- a/jsonapi-generator/src/async-method-wrapper-template.cpp.tmpl +++ b/jsonapi-generator/src/async-method-wrapper-template.cpp.tmpl @@ -4,9 +4,8 @@ * Copyright (C) 2018-2019 Gioacchino Mazzurco * * * * This program is free software: you can redistribute it and/or modify * - * it under the terms of the GNU Affero General Public License as * - * published by the Free Software Foundation, either version 3 of the * - * License, or (at your option) any later version. * + * it under the terms of the GNU Affero General Public License version 3 as * + * published by the Free Software Foundation. * * * * This program is distributed in the hope that it will be useful, * * but WITHOUT ANY WARRANTY; without even the implied warranty of * @@ -43,19 +42,23 @@ $%paramsDeclaration%$ $%inputParamsDeserialization%$ + const std::weak_ptr weakService(mService); const std::weak_ptr weakSession(session); - $%callbackName%$ = [this, weakSession]($%callbackParams%$) + $%callbackName%$ = [this, weakService, weakSession]($%callbackParams%$) { auto session = weakSession.lock(); if(!session || session->is_closed()) return; + auto lService = weakService.lock(); + if(!lService || lService->is_down()) return; + $%callbackParamsSerialization%$ std::stringstream sStream; sStream << "data: " << compactJSON << ctx.mJson << "\n\n"; const std::string message = sStream.str(); - mService.schedule( [weakSession, message]() + lService->schedule( [weakSession, message]() { auto session = weakSession.lock(); if(!session || session->is_closed()) return; diff --git a/jsonapi-generator/src/jsonapi-generator.cpp b/jsonapi-generator/src/jsonapi-generator.cpp index 0a6bf3231..e56082ce6 100644 --- a/jsonapi-generator/src/jsonapi-generator.cpp +++ b/jsonapi-generator/src/jsonapi-generator.cpp @@ -326,7 +326,20 @@ int main(int argc, char *argv[]) QString sessionDelayedClose; if(hasMultiCallback) - sessionDelayedClose = "RsThread::async( [=](){ std::this_thread::sleep_for(std::chrono::seconds(maxWait+120)); mService.schedule( [=](){ auto session = weakSession.lock(); if(session && session->is_open()) session->close(); } ); } );"; + sessionDelayedClose = + "RsThread::async( [=]()" + "{" + "std::this_thread::sleep_for(" + "std::chrono::seconds(maxWait+120) );" + "auto lService = weakService.lock();" + "if(!lService || lService->is_down()) return;" + "lService->schedule( [=]()" + "{" + "auto session = weakSession.lock();" + "if(session && session->is_open())" + "session->close();" + "} );" + "} );"; QString callbackParamsSerialization; diff --git a/jsonapi-generator/src/jsonapi-generator.pro b/jsonapi-generator/src/jsonapi-generator.pro index 2f36f03dc..1d6c45d91 100644 --- a/jsonapi-generator/src/jsonapi-generator.pro +++ b/jsonapi-generator/src/jsonapi-generator.pro @@ -1,3 +1,6 @@ +# SPDX-FileCopyrightText: (C) 2004-2019 Retroshare Team +# SPDX-License-Identifier: CC0-1.0 + TARGET = jsonapi-generator CONFIG += qt diff --git a/libbitdht/src/LICENSE.md b/libbitdht/src/LICENSE.md deleted file mode 100644 index 02a410748..000000000 --- a/libbitdht/src/LICENSE.md +++ /dev/null @@ -1,136 +0,0 @@ -# GNU LIBRARY GENERAL PUBLIC LICENSE - -Version 2, June 1991 - -Copyright (C) 1991 Free Software Foundation, Inc. -51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA -Everyone is permitted to copy and distribute verbatim copies -of this license document, but changing it is not allowed. - -[This is the first released version of the library GPL. It is - numbered 2 because it goes with version 2 of the ordinary GPL.] -Preamble - -The licenses for most software are designed to take away your freedom to share and change it. By contrast, the GNU General Public Licenses are intended to guarantee your freedom to share and change free software--to make sure the software is free for all its users. - -This license, the Library General Public License, applies to some specially designated Free Software Foundation software, and to any other libraries whose authors decide to use it. You can use it for your libraries, 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 this service 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 make restrictions that forbid anyone to deny you these rights or to ask you to surrender the rights. These restrictions translate to certain responsibilities for you if you distribute copies of the library, or if you modify it. - -For example, if you distribute copies of the library, whether gratis or for a fee, you must give the recipients all the rights that we gave you. You must make sure that they, too, receive or can get the source code. If you link a program with the library, you must provide complete object files to the recipients so that they can relink them with the library, after making changes to the library and recompiling it. And you must show them these terms so they know their rights. - -Our method of protecting your rights has two steps: (1) copyright the library, and (2) offer you this license which gives you legal permission to copy, distribute and/or modify the library. - -Also, for each distributor's protection, we want to make certain that everyone understands that there is no warranty for this free library. If the library is modified by someone else and passed on, we want its recipients to know that what they have is not the original version, so that any problems introduced by others will not reflect on the original authors' reputations. - -Finally, any free program is threatened constantly by software patents. We wish to avoid the danger that companies distributing free software will individually obtain patent licenses, thus in effect transforming the program into proprietary software. To prevent this, we have made it clear that any patent must be licensed for everyone's free use or not licensed at all. - -Most GNU software, including some libraries, is covered by the ordinary GNU General Public License, which was designed for utility programs. This license, the GNU Library General Public License, applies to certain designated libraries. This license is quite different from the ordinary one; be sure to read it in full, and don't assume that anything in it is the same as in the ordinary license. - -The reason we have a separate public license for some libraries is that they blur the distinction we usually make between modifying or adding to a program and simply using it. Linking a program with a library, without changing the library, is in some sense simply using the library, and is analogous to running a utility program or application program. However, in a textual and legal sense, the linked executable is a combined work, a derivative of the original library, and the ordinary General Public License treats it as such. - -Because of this blurred distinction, using the ordinary General Public License for libraries did not effectively promote software sharing, because most developers did not use the libraries. We concluded that weaker conditions might promote sharing better. - -However, unrestricted linking of non-free programs would deprive the users of those programs of all benefit from the free status of the libraries themselves. This Library General Public License is intended to permit developers of non-free programs to use free libraries, while preserving your freedom as a user of such programs to change the free libraries that are incorporated in them. (We have not seen how to achieve this as regards changes in header files, but we have achieved it as regards changes in the actual functions of the Library.) The hope is that this will lead to faster development of free libraries. - -The precise terms and conditions for copying, distribution and modification follow. Pay close attention to the difference between a "work based on the library" and a "work that uses the library". The former contains code derived from the library, while the latter only works together with the library. - -Note that it is possible for a library to be covered by the ordinary General Public License rather than by this special one. - -## TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION - -0. This License Agreement applies to any software library which contains a notice placed by the copyright holder or other authorized party saying it may be distributed under the terms of this Library General Public License (also called "this License"). Each licensee is addressed as "you". - -A "library" means a collection of software functions and/or data prepared so as to be conveniently linked with application programs (which use some of those functions and data) to form executables. - -The "Library", below, refers to any such software library or work which has been distributed under these terms. A "work based on the Library" means either the Library or any derivative work under copyright law: that is to say, a work containing the Library or a portion of it, either verbatim or with modifications and/or translated straightforwardly into another language. (Hereinafter, translation is included without limitation in the term "modification".) - -"Source code" for a work means the preferred form of the work for making modifications to it. For a library, complete source code means all the source code for all modules it contains, plus any associated interface definition files, plus the scripts used to control compilation and installation of the library. - -Activities other than copying, distribution and modification are not covered by this License; they are outside its scope. The act of running a program using the Library is not restricted, and output from such a program is covered only if its contents constitute a work based on the Library (independent of the use of the Library in a tool for writing it). Whether that is true depends on what the Library does and what the program that uses the Library does. - -1. You may copy and distribute verbatim copies of the Library's complete source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice and disclaimer of warranty; keep intact all the notices that refer to this License and to the absence of any warranty; and distribute a copy of this License along with the Library. - -You may charge a fee for the physical act of transferring a copy, and you may at your option offer warranty protection in exchange for a fee. - -2. You may modify your copy or copies of the Library or any portion of it, thus forming a work based on the Library, and copy and distribute such modifications or work under the terms of Section 1 above, provided that you also meet all of these conditions: - -a) The modified work must itself be a software library. -b) You must cause the files modified to carry prominent notices stating that you changed the files and the date of any change. -c) You must cause the whole of the work to be licensed at no charge to all third parties under the terms of this License. -d) If a facility in the modified Library refers to a function or a table of data to be supplied by an application program that uses the facility, other than as an argument passed when the facility is invoked, then you must make a good faith effort to ensure that, in the event an application does not supply such function or table, the facility still operates, and performs whatever part of its purpose remains meaningful. -(For example, a function in a library to compute square roots has a purpose that is entirely well-defined independent of the application. Therefore, Subsection 2d requires that any application-supplied function or table used by this function must be optional: if the application does not supply it, the square root function must still compute square roots.) - -These requirements apply to the modified work as a whole. If identifiable sections of that work are not derived from the Library, and can be reasonably considered independent and separate works in themselves, then this License, and its terms, do not apply to those sections when you distribute them as separate works. But when you distribute the same sections as part of a whole which is a work based on the Library, the distribution of the whole must be on the terms of this License, whose permissions for other licensees extend to the entire whole, and thus to each and every part regardless of who wrote it. - -Thus, it is not the intent of this section to claim rights or contest your rights to work written entirely by you; rather, the intent is to exercise the right to control the distribution of derivative or collective works based on the Library. - -In addition, mere aggregation of another work not based on the Library with the Library (or with a work based on the Library) on a volume of a storage or distribution medium does not bring the other work under the scope of this License. - -3. You may opt to apply the terms of the ordinary GNU General Public License instead of this License to a given copy of the Library. To do this, you must alter all the notices that refer to this License, so that they refer to the ordinary GNU General Public License, version 2, instead of to this License. (If a newer version than version 2 of the ordinary GNU General Public License has appeared, then you can specify that version instead if you wish.) Do not make any other change in these notices. - -Once this change is made in a given copy, it is irreversible for that copy, so the ordinary GNU General Public License applies to all subsequent copies and derivative works made from that copy. - -This option is useful when you wish to copy part of the code of the Library into a program that is not a library. - -4. You may copy and distribute the Library (or a portion or derivative of it, under Section 2) in object code or executable form under the terms of Sections 1 and 2 above provided that you accompany it with the complete corresponding machine-readable source code, which must be distributed under the terms of Sections 1 and 2 above on a medium customarily used for software interchange. - -If distribution of object code is made by offering access to copy from a designated place, then offering equivalent access to copy the source code from the same place satisfies the requirement to distribute the source code, even though third parties are not compelled to copy the source along with the object code. - -5. A program that contains no derivative of any portion of the Library, but is designed to work with the Library by being compiled or linked with it, is called a "work that uses the Library". Such a work, in isolation, is not a derivative work of the Library, and therefore falls outside the scope of this License. - -However, linking a "work that uses the Library" with the Library creates an executable that is a derivative of the Library (because it contains portions of the Library), rather than a "work that uses the library". The executable is therefore covered by this License. Section 6 states terms for distribution of such executables. - -When a "work that uses the Library" uses material from a header file that is part of the Library, the object code for the work may be a derivative work of the Library even though the source code is not. Whether this is true is especially significant if the work can be linked without the Library, or if the work is itself a library. The threshold for this to be true is not precisely defined by law. - -If such an object file uses only numerical parameters, data structure layouts and accessors, and small macros and small inline functions (ten lines or less in length), then the use of the object file is unrestricted, regardless of whether it is legally a derivative work. (Executables containing this object code plus portions of the Library will still fall under Section 6.) - -Otherwise, if the work is a derivative of the Library, you may distribute the object code for the work under the terms of Section 6. Any executables containing that work also fall under Section 6, whether or not they are linked directly with the Library itself. - -6. As an exception to the Sections above, you may also compile or link a "work that uses the Library" with the Library to produce a work containing portions of the Library, and distribute that work under terms of your choice, provided that the terms permit modification of the work for the customer's own use and reverse engineering for debugging such modifications. - -You must give prominent notice with each copy of the work that the Library is used in it and that the Library and its use are covered by this License. You must supply a copy of this License. If the work during execution displays copyright notices, you must include the copyright notice for the Library among them, as well as a reference directing the user to the copy of this License. Also, you must do one of these things: - -a) Accompany the work with the complete corresponding machine-readable source code for the Library including whatever changes were used in the work (which must be distributed under Sections 1 and 2 above); and, if the work is an executable linked with the Library, with the complete machine-readable "work that uses the Library", as object code and/or source code, so that the user can modify the Library and then relink to produce a modified executable containing the modified Library. (It is understood that the user who changes the contents of definitions files in the Library will not necessarily be able to recompile the application to use the modified definitions.) -b) Accompany the work with a written offer, valid for at least three years, to give the same user the materials specified in Subsection 6a, above, for a charge no more than the cost of performing this distribution. -c) If distribution of the work is made by offering access to copy from a designated place, offer equivalent access to copy the above specified materials from the same place. -d) Verify that the user has already received a copy of these materials or that you have already sent this user a copy. -For an executable, the required form of the "work that uses the Library" must include any data and utility programs needed for reproducing the executable from it. However, as a special exception, the source code distributed need not include anything that is normally distributed (in either source or binary form) with the major components (compiler, kernel, and so on) of the operating system on which the executable runs, unless that component itself accompanies the executable. - -It may happen that this requirement contradicts the license restrictions of other proprietary libraries that do not normally accompany the operating system. Such a contradiction means you cannot use both them and the Library together in an executable that you distribute. - -7. You may place library facilities that are a work based on the Library side-by-side in a single library together with other library facilities not covered by this License, and distribute such a combined library, provided that the separate distribution of the work based on the Library and of the other library facilities is otherwise permitted, and provided that you do these two things: - -a) Accompany the combined library with a copy of the same work based on the Library, uncombined with any other library facilities. This must be distributed under the terms of the Sections above. -b) Give prominent notice with the combined library of the fact that part of it is a work based on the Library, and explaining where to find the accompanying uncombined form of the same work. -8. You may not copy, modify, sublicense, link with, or distribute the Library except as expressly provided under this License. Any attempt otherwise to copy, modify, sublicense, link with, or distribute the Library is void, and will automatically terminate your rights under this License. However, parties who have received copies, or rights, from you under this License will not have their licenses terminated so long as such parties remain in full compliance. - -9. You are not required to accept this License, since you have not signed it. However, nothing else grants you permission to modify or distribute the Library or its derivative works. These actions are prohibited by law if you do not accept this License. Therefore, by modifying or distributing the Library (or any work based on the Library), you indicate your acceptance of this License to do so, and all its terms and conditions for copying, distributing or modifying the Library or works based on it. - -10. Each time you redistribute the Library (or any work based on the Library), the recipient automatically receives a license from the original licensor to copy, distribute, link with or modify the Library subject to these terms and conditions. You may not impose any further restrictions on the recipients' exercise of the rights granted herein. You are not responsible for enforcing compliance by third parties to this License. - -11. If, as a consequence of a court judgment or allegation of patent infringement or for any other reason (not limited to patent issues), 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 distribute so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not distribute the Library at all. For example, if a patent license would not permit royalty-free redistribution of the Library by all those who receive copies directly or indirectly through you, then the only way you could satisfy both it and this License would be to refrain entirely from distribution of the Library. - -If any portion of this section is held invalid or unenforceable under any particular circumstance, the balance of the section is intended to apply, and the section as a whole is intended to apply in other circumstances. - -It is not the purpose of this section to induce you to infringe any patents or other property right claims or to contest validity of any such claims; this section has the sole purpose of protecting the integrity of the free software distribution system which is implemented by public license practices. Many people have made generous contributions to the wide range of software distributed through that system in reliance on consistent application of that system; it is up to the author/donor to decide if he or she is willing to distribute software through any other system and a licensee cannot impose that choice. - -This section is intended to make thoroughly clear what is believed to be a consequence of the rest of this License. - -12. If the distribution and/or use of the Library is restricted in certain countries either by patents or by copyrighted interfaces, the original copyright holder who places the Library under this License may add an explicit geographical distribution limitation excluding those countries, so that distribution is permitted only in or among countries not thus excluded. In such case, this License incorporates the limitation as if written in the body of this License. - -13. The Free Software Foundation may publish revised and/or new versions of the Library 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 Library specifies a version number of this License which applies to it and "any later version", you have the option of following the terms and conditions either of that version or of any later version published by the Free Software Foundation. If the Library does not specify a license version number, you may choose any version ever published by the Free Software Foundation. - -14. If you wish to incorporate parts of the Library into other free programs whose distribution conditions are incompatible with these, write to the author to ask for permission. For software which is copyrighted by the Free Software Foundation, write to the Free Software Foundation; we sometimes make exceptions for this. Our decision will be guided by the two goals of preserving the free status of all derivatives of our free software and of promoting the sharing and reuse of software generally. - -### NO WARRANTY - -15. BECAUSE THE LIBRARY IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY FOR THE LIBRARY, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE LIBRARY "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 LIBRARY IS WITH YOU. SHOULD THE LIBRARY PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. - -16. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR REDISTRIBUTE THE LIBRARY 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 LIBRARY (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 LIBRARY TO OPERATE WITH ANY OTHER SOFTWARE), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. - -# END OF TERMS AND CONDITIONS diff --git a/libbitdht/src/README.txt b/libbitdht/src/README.txt index 8f4daabf2..a1dff67e4 100644 --- a/libbitdht/src/README.txt +++ b/libbitdht/src/README.txt @@ -1,3 +1,5 @@ +# SPDX-FileCopyrightText: (C) 2004-2019 Retroshare Team +# SPDX-License-Identifier: CC0-1.0 What's in the Package --------------------------------------------------------------- diff --git a/libbitdht/src/libbitdht.pro b/libbitdht/src/libbitdht.pro index c607fc58c..ab53768a5 100644 --- a/libbitdht/src/libbitdht.pro +++ b/libbitdht/src/libbitdht.pro @@ -1,20 +1,22 @@ -################################################################################ -# libbitdht.pro # -# Copyright (C) 2018, Retroshare team # -# # -# This program is free software: you can redistribute it and/or modify # -# it under the terms of the GNU Affero General Public License as # -# published by the Free Software Foundation, either version 3 of the # -# License, or (at your option) any later version. # -# # -# This program is distributed in the hope that it will be useful, # -# but WITHOUT ANY WARRANTY; without even the implied warranty of # -# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # -# GNU Affero General Public License for more details. # -# # -# You should have received a copy of the GNU Affero General Public License # -# along with this program. If not, see . # -################################################################################ +# RetroShare main qmake build script +# +# Copyright (C) 2004-2019, Retroshare Team +# +# This program is free software: you can redistribute it and/or modify it under +# the terms of the GNU Lesser 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 Lesser General Public License for more details. +# +# You should have received a copy of the GNU Lesser General Public License along +# with this program. If not, see . +# +# SPDX-FileCopyrightText: Retroshare Team +# SPDX-License-Identifier: LGPL-3.0-or-later !include("../../retroshare.pri"): error("Could not include file ../../retroshare.pri") diff --git a/libbitdht/src/use_libbitdht.pri b/libbitdht/src/use_libbitdht.pri index a31c0d452..5758393af 100644 --- a/libbitdht/src/use_libbitdht.pri +++ b/libbitdht/src/use_libbitdht.pri @@ -1,20 +1,22 @@ -################################################################################ -# use_libbitdht.pri # -# Copyright (C) 2018, Retroshare team # -# # -# This program is free software: you can redistribute it and/or modify # -# it under the terms of the GNU Lesser 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 Lesser General Public License for more details. # -# # -# You should have received a copy of the GNU Lesser General Public License # -# along with this program. If not, see . # -################################################################################ +# RetroShare main qmake build script +# +# Copyright (C) 2004-2019, Retroshare Team +# +# This program is free software: you can redistribute it and/or modify it under +# the terms of the GNU Lesser 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 Lesser General Public License for more details. +# +# You should have received a copy of the GNU Lesser General Public License along +# with this program. If not, see . +# +# SPDX-FileCopyrightText: Retroshare Team +# SPDX-License-Identifier: LGPL-3.0-or-later DEPENDPATH *= $$system_path($$clean_path($${PWD}/../../libbitdht/src)) INCLUDEPATH *= $$system_path($$clean_path($${PWD}/../../libbitdht/src)) diff --git a/libresapi/src/.gitignore b/libresapi/src/.gitignore deleted file mode 100644 index afe2a0b3d..000000000 --- a/libresapi/src/.gitignore +++ /dev/null @@ -1 +0,0 @@ -webui/* diff --git a/libresapi/src/README.md b/libresapi/src/README.md deleted file mode 100644 index ee8cf5671..000000000 --- a/libresapi/src/README.md +++ /dev/null @@ -1,14 +0,0 @@ -libresapi: resource_api and new webinterface -============================================ - -* ./api contains a C++ backend to control retroshare from webinterfaces or scripting -* ./webui contains compiled files for the webinterface (after build) -* ./webui-src contains HTML/CSS/JavaScript source files for the webinterface (NEW, webinterface made with mithril.js) - -Quickinfo for builders and packagers -==================================== - -* copy the files in ./webui to -* ./webui (Windows) -* /usr/share/retroshare/webui (Linux) -* other OS: see RsAccountsDetail::PathDataDirectory() diff --git a/libresapi/src/api/ApiPluginHandler.cpp b/libresapi/src/api/ApiPluginHandler.cpp deleted file mode 100644 index 29253aa42..000000000 --- a/libresapi/src/api/ApiPluginHandler.cpp +++ /dev/null @@ -1,62 +0,0 @@ -/******************************************************************************* - * libresapi/api/ApiPluginHandler.cpp * - * * - * LibResAPI: API for local socket server * - * * - * Copyright 2018 by Retroshare Team * - * * - * This program is free software: you can redistribute it and/or modify * - * it under the terms of the GNU Affero General Public License as * - * published by the Free Software Foundation, either version 3 of the * - * License, or (at your option) any later version. * - * * - * This program is distributed in the hope that it will be useful, * - * but WITHOUT ANY WARRANTY; without even the implied warranty of * - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * - * GNU Affero General Public License for more details. * - * * - * You should have received a copy of the GNU Affero General Public License * - * along with this program. If not, see . * - * * - *******************************************************************************/ -#include "ApiPluginHandler.h" - -namespace resource_api -{ - -ApiPluginHandler::ApiPluginHandler(StateTokenServer* statetokenserver, const RsPlugInInterfaces& ifaces) -{ - for(int i = 0; i < ifaces.mPluginHandler->nbPlugins(); i++) - { - RsPlugin* plugin = ifaces.mPluginHandler->plugin(i); - // if plugin is not loaded, pointer is null - if(plugin == 0) - continue; - std::string entrypoint; - ResourceRouter* child = plugin->new_resource_api_handler(ifaces, statetokenserver, entrypoint); - if(child != 0) - { - mChildren.push_back(child); - if(isNameUsed(entrypoint)) - { - std::cerr << "Cannot add plugin api entry point with name=" << entrypoint << ", becaus ethis name is already in use!" << std::endl; - } - else - { - std::cerr << "Added libresapi plugin with entrypoint " << entrypoint << std::endl; - addResourceHandler(entrypoint, child, &ResourceRouter::handleRequest); - } - } - } -} - -ApiPluginHandler::~ApiPluginHandler() -{ - for(std::vector::iterator vit = mChildren.begin(); vit != mChildren.end(); ++vit) - { - delete *vit; - } - mChildren.clear(); -} - -} // namespace resource_api diff --git a/libresapi/src/api/ApiPluginHandler.h b/libresapi/src/api/ApiPluginHandler.h deleted file mode 100644 index 600e8b505..000000000 --- a/libresapi/src/api/ApiPluginHandler.h +++ /dev/null @@ -1,41 +0,0 @@ -/******************************************************************************* - * libresapi/api/ApiPluginHandler.h * - * * - * LibResAPI: API for local socket server * - * * - * Copyright 2018 by Retroshare Team * - * * - * This program is free software: you can redistribute it and/or modify * - * it under the terms of the GNU Affero General Public License as * - * published by the Free Software Foundation, either version 3 of the * - * License, or (at your option) any later version. * - * * - * This program is distributed in the hope that it will be useful, * - * but WITHOUT ANY WARRANTY; without even the implied warranty of * - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * - * GNU Affero General Public License for more details. * - * * - * You should have received a copy of the GNU Affero General Public License * - * along with this program. If not, see . * - * * - *******************************************************************************/ -#pragma once - -#include "ResourceRouter.h" -#include - -namespace resource_api -{ - -// forwards all incoming requests to retroshare plugins -class ApiPluginHandler: public ResourceRouter -{ -public: - ApiPluginHandler(StateTokenServer* statetokenserver, const RsPlugInInterfaces& ifaces); - virtual ~ApiPluginHandler(); - -private: - std::vector mChildren; -}; - -} // namespace resource_api diff --git a/libresapi/src/api/ApiServer.cpp b/libresapi/src/api/ApiServer.cpp deleted file mode 100644 index 8217dc7f6..000000000 --- a/libresapi/src/api/ApiServer.cpp +++ /dev/null @@ -1,464 +0,0 @@ -/******************************************************************************* - * libresapi/api/ApiServer.cpp * - * * - * LibResAPI: API for local socket server * - * * - * Copyright 2018 by Retroshare Team * - * * - * This program is free software: you can redistribute it and/or modify * - * it under the terms of the GNU Affero General Public License as * - * published by the Free Software Foundation, either version 3 of the * - * License, or (at your option) any later version. * - * * - * This program is distributed in the hope that it will be useful, * - * but WITHOUT ANY WARRANTY; without even the implied warranty of * - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * - * GNU Affero General Public License for more details. * - * * - * You should have received a copy of the GNU Affero General Public License * - * along with this program. If not, see . * - * * - *******************************************************************************/ -#include "ApiServer.h" - -#include -#include - -#include -#include -#include -#include -#include "json.h" - -#include -#include "JsonStream.h" -#include "StateTokenServer.h" // for the state token serialisers - -#include "ApiPluginHandler.h" -#include "ChannelsHandler.h" -#include "StatsHandler.h" - -#ifdef LIBRESAPI_SETTINGS - #include "SettingsHandler.h" -#endif - -/* -data types in json http://json.org/ -string (utf-8 unicode) -number (int and float) -object (key value pairs, key must be a string) -true -false -null - -data types in lua http://www.lua.org/pil/2.html -nil -boolean -number (double) -string (8-bit) -table (key value pairs, keys can be anything except nil) - -data types in QML http://qt-project.org/doc/qt-5/qtqml-typesystem-basictypes.html -bool -string -real/double -int -list -object types? - -QML has many more types with special meaning like date - - -C++ delivers -std::string -bool -int -(double? i don't know) -enum -bitflags -raw binary data - -objects -std::vector -std::list - -different types of ids/hashes --> convert to/from string with a generic operator --> the operator signals ok/fail to the stream - - -*/ - -/* - -data types to handle: -- bool -- string -- bitflags -- enums - -containers: -- arrays: collection of objects or values without name, usually of the same type -- objects: objects and values with names - -careful: the json lib has many asserts, so retroshare will stop if the smalles thing goes wrong --> check type of json before usage - -there are two possible implementations: -- with a virtual base class for the serialisation targets - - better documentation of the interface -- with templates - -*/ - -/* - -the general idea is: -want output in many different formats, while the retrival of the source data is always the same - -get, put - -ressource adress like -.org.retroshare.api.peers - -generic router from adress to the ressource handler object - -data formats for input and output: -- json -- lua -- QObject -- maybe just a typed c++ object - -rest inspired / resource based interface -- have resources with adresses -- requests: - - put - - get -- request has parameters -- response: - - returncode: - - ok - - not modified - - error - - data = object or list of objects - -want to have a typesafe interface at the top? -probably not, a system with generic return values is enough -this interface is for scripting languages which don't have types - -the interface at the top should look like this: -template -processRequest(const RequestMeta& req, const RequestDataFormatT& reqData, - ResponseMeta& respMeta, ResponseDataFormatT& respData); - -idea: pass all the interfaces to the retroshare core to this function, -or have this function as part of an object - -the processor then applies all members of the request and response data to the data format like this: -reqData << "member1" << member1 - << "member2" << member2 ... ; - -these operators have to be implemented for common things like boolean, int, std::string, std::vector, std::list ... -request data gets only deserialised -response data gets only serialised - -response and request meta contains things like resource address, method and additional parameters - -want generic resource caching mechanism -- on first request a request handler is created -- request handler is stored with its input data -- if a request handler for a given resource adress and parameters exists - then the request handler is asked if the result is still valid - if yes the result from the existing handler is used -- request handler gets deleted after timeout -- can have two types of resource handlers: static handlers and dynamic handlers - - static handlers don't get deleted, because they don't contain result data - - dynamic handlers contain result data, and thus get deleted after a while - -it is even possible to implement a resource-changed check at the highest level -this allows to compute everything on the server side and only send changes to the client -the different resource providers don't have to implement a resource changed check then -a top level change detector will poll them -of course this does not work with a deep resource tree with millions of nodes - -for this we have the dynamic handlers, -they are created on demand and know how to listen for changes which affect them - -*/ - -namespace resource_api{ - -// old code, only to copy and paste from -// to be removed -/* -class ChatlobbiesHandler -{ -public: - ChatlobbiesHandler(RsMsgs* msgs): mMsgs(msgs) {} - - template - void handleRequest(Request& req, InputT& reqData, Response& resp, OutputT& respData) - { - if(req.mMethod == "GET") - { - typename OutputT::Array result; - // subscribed lobbies - std::list slobbies; - mMsgs->getChatLobbyList(slobbies); - for(std::list::iterator lit = slobbies.begin(); lit != slobbies.end(); lit++) - { - typename OutputT::Object lobby; - ChatLobbyInfo& lobbyRecord = *lit; - lobby["name"] = lobbyRecord.lobby_name; - RsPeerId pid; - mMsgs->getVirtualPeerId(lobbyRecord.lobby_id, pid); - lobby["id"] = pid.toStdString(); - lobby["subscribed"] = true; - result.push_back(lobby); - } - // unsubscirbed lobbies - std::vector ulobbies; - mMsgs->getListOfNearbyChatLobbies(ulobbies); - for(std::vector::iterator vit = ulobbies.begin(); vit != ulobbies.end(); vit++) - { - typename OutputT::Object lobby; - VisibleChatLobbyRecord& lobbyRecord = *vit; - lobby["name"] = lobbyRecord.lobby_name; - RsPeerId pid; - mMsgs->getVirtualPeerId(lobbyRecord.lobby_id, pid); - lobby["id"] = pid.toStdString(); - lobby["subscribed"] = false; - result.push_back(lobby); - } - respData = result; - } - else if(req.mMethod == "PUT") - { - RsPeerId id = RsPeerId(req.mAdress.substr(1)); - - if(!id.isNull() && reqData.HasKey("msg")) - { - // for now can send only id as message - mMsgs->sendPrivateChat(id, reqData["msg"]); - } - } - } - - RsMsgs* mMsgs; -}; -*/ - -class ApiServerMainModules -{ -public: - ApiServerMainModules(ResourceRouter& router, StateTokenServer* sts, const RsPlugInInterfaces &ifaces): - mPeersHandler(sts, ifaces.mNotify, ifaces.mPeers, ifaces.mMsgs), - mIdentityHandler(sts, ifaces.mNotify, ifaces.mIdentity), - mForumHandler(ifaces.mGxsForums), - mServiceControlHandler(ifaces.mServiceControl), - mFileSearchHandler(sts, ifaces.mNotify, ifaces.mTurtle, ifaces.mFiles), - mFileSharingHandler(sts, ifaces.mFiles, *ifaces.mNotify), - mTransfersHandler(sts, ifaces.mFiles, ifaces.mPeers, *ifaces.mNotify), - mChatHandler(sts, ifaces.mNotify, ifaces.mMsgs, ifaces.mPeers, ifaces.mIdentity, &mPeersHandler), - mApiPluginHandler(sts, ifaces), - mChannelsHandler(*ifaces.mGxsChannels), - mStatsHandler() -#ifdef LIBRESAPI_SETTINGS - ,mSettingsHandler(sts) -#endif - { - // the dynamic cast is to not confuse the addResourceHandler template like this: - // addResourceHandler(derived class, parent class) - // the template would then be instantiated using derived class as parameter - // and then parent class would not match the type - router.addResourceHandler("peers",dynamic_cast(&mPeersHandler), - &PeersHandler::handleRequest); - router.addResourceHandler("identity", dynamic_cast(&mIdentityHandler), - &IdentityHandler::handleRequest); - router.addResourceHandler("forums", dynamic_cast(&mForumHandler), - &ForumHandler::handleRequest); - router.addResourceHandler("servicecontrol", dynamic_cast(&mServiceControlHandler), - &ServiceControlHandler::handleRequest); - router.addResourceHandler("filesearch", dynamic_cast(&mFileSearchHandler), - &FileSearchHandler::handleRequest); - router.addResourceHandler("filesharing", dynamic_cast(&mFileSharingHandler), - &FileSharingHandler::handleRequest); - router.addResourceHandler("transfers", dynamic_cast(&mTransfersHandler), - &TransfersHandler::handleRequest); - router.addResourceHandler("chat", dynamic_cast(&mChatHandler), - &ChatHandler::handleRequest); - router.addResourceHandler("apiplugin", dynamic_cast(&mApiPluginHandler), - &ChatHandler::handleRequest); - router.addResourceHandler("channels", dynamic_cast(&mChannelsHandler), - &ChannelsHandler::handleRequest); - router.addResourceHandler("stats", dynamic_cast(&mStatsHandler), - &StatsHandler::handleRequest); -#ifdef LIBRESAPI_SETTINGS - router.addResourceHandler("settings", dynamic_cast(&mSettingsHandler), - &SettingsHandler::handleRequest); -#endif - } - - PeersHandler mPeersHandler; - IdentityHandler mIdentityHandler; - ForumHandler mForumHandler; - ServiceControlHandler mServiceControlHandler; - FileSearchHandler mFileSearchHandler; - FileSharingHandler mFileSharingHandler; - TransfersHandler mTransfersHandler; - ChatHandler mChatHandler; - ApiPluginHandler mApiPluginHandler; - ChannelsHandler mChannelsHandler; - StatsHandler mStatsHandler; - -#ifdef LIBRESAPI_SETTINGS - SettingsHandler mSettingsHandler; -#endif -}; - -ApiServer::ApiServer(): - mMtx("ApiServer mMtx"), - mStateTokenServer(), - mLivereloadhandler(&mStateTokenServer), - mTmpBlobStore(&mStateTokenServer), - mMainModules(0) -{ - mRouter.addResourceHandler("statetokenservice", dynamic_cast(&mStateTokenServer), - &StateTokenServer::handleRequest); - mRouter.addResourceHandler("livereload", dynamic_cast(&mLivereloadhandler), - &LivereloadHandler::handleRequest); -} - -ApiServer::~ApiServer() -{ - RS_STACK_MUTEX(mMtx); // ********** LOCKED ********** - for(std::vector::iterator vit = mRequests.begin(); vit != mRequests.end(); ++vit) - delete vit->task; - mRequests.clear(); - - if(mMainModules) - delete mMainModules; -} - -void ApiServer::loadMainModules(const RsPlugInInterfaces &ifaces) -{ - RS_STACK_MUTEX(mMtx); // ********** LOCKED ********** - if(mMainModules == 0) - mMainModules = new ApiServerMainModules(mRouter, &mStateTokenServer, ifaces); -} - -std::string ApiServer::handleRequest(Request &request) -{ - resource_api::JsonStream outstream; - std::stringstream debugString; - - StreamBase& data = outstream.getStreamToMember("data"); - resource_api::Response resp(data, debugString); - - ResponseTask* task = 0; - { - RS_STACK_MUTEX(mMtx); // ********** LOCKED ********** - task = mRouter.handleRequest(request, resp); - } - - //time_t start = time(NULL); - bool morework = true; - while(task && morework) - { - { - RS_STACK_MUTEX(mMtx); // ********** LOCKED ********** - morework = task->doWork(request, resp); - } - if(morework) - usleep(10*1000); - /*if(time(NULL) > (start+5)) - { - std::cerr << "ApiServer::handleRequest() Error: task timed out" << std::endl; - resp.mDebug << "Error: task timed out." << std::endl; - resp.mReturnCode = resource_api::Response::FAIL; - break; - }*/ - } - if(task) - delete task; - - std::string returncode; - switch(resp.mReturnCode){ - case resource_api::Response::NOT_SET: - returncode = "not_set"; - break; - case resource_api::Response::OK: - returncode = "ok"; - break; - case resource_api::Response::WARNING: - returncode = "warning"; - break; - case resource_api::Response::FAIL: - returncode = "fail"; - break; - } - - // evil HACK, remove this - if(data.isRawData()) - return data.getRawData(); - - if(!resp.mCallbackName.empty()) - outstream << resource_api::makeKeyValueReference("callback_name", resp.mCallbackName); - - outstream << resource_api::makeKeyValue("debug_msg", debugString.str()); - outstream << resource_api::makeKeyValueReference("returncode", returncode); - if(!resp.mStateToken.isNull()) - outstream << resource_api::makeKeyValueReference("statetoken", resp.mStateToken); - return outstream.getJsonString(); -} - -ApiServer::RequestId ApiServer::handleRequest(Request &request, Response &response) -{ - RequestId id; - ResponseTask* task = 0; - { - RS_STACK_MUTEX(mMtx); // ********** LOCKED ********** - task = mRouter.handleRequest(request, response); - } - if(task == 0) - { - id.done = true; - return id; - } - id.done = false, - id.task = task; - id.request = &request; - id.response = &response; - { - RS_STACK_MUTEX(mMtx); // ********** LOCKED ********** - mRequests.push_back(id); - } - return id; -} - -bool ApiServer::isRequestDone(RequestId id) -{ - if(id.done) - return true; - - RS_STACK_MUTEX(mMtx); // ********** LOCKED ********** - std::vector::iterator vit = std::find(mRequests.begin(), mRequests.end(), id); - // Request id not found, maybe the id is old and was removed from the list - if(vit == mRequests.end()) - return true; - - if(id.task->doWork(*id.request, *id.response)) - return false; - - // if we reach this point, the request is in the list and done - // remove the id from the list of valid ids - // delete the ResponseTask object - - *vit = mRequests.back(); - mRequests.pop_back(); - - delete id.task; - return true; -} - -} // namespace resource_api diff --git a/libresapi/src/api/ApiServer.h b/libresapi/src/api/ApiServer.h deleted file mode 100644 index 42331c33e..000000000 --- a/libresapi/src/api/ApiServer.h +++ /dev/null @@ -1,132 +0,0 @@ -/******************************************************************************* - * libresapi/api/ApiServer.h * - * * - * LibResAPI: API for local socket server * - * * - * Copyright 2018 by Retroshare Team * - * * - * This program is free software: you can redistribute it and/or modify * - * it under the terms of the GNU Affero General Public License as * - * published by the Free Software Foundation, either version 3 of the * - * License, or (at your option) any later version. * - * * - * This program is distributed in the hope that it will be useful, * - * but WITHOUT ANY WARRANTY; without even the implied warranty of * - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * - * GNU Affero General Public License for more details. * - * * - * You should have received a copy of the GNU Affero General Public License * - * along with this program. If not, see . * - * * - *******************************************************************************/ -#pragma once - -#include - -#include "ApiTypes.h" -#include "PeersHandler.h" -#include "IdentityHandler.h" -#include "ForumHandler.h" -#include "ServiceControlHandler.h" -#include "StateTokenServer.h" -#include "FileSearchHandler.h" -#include "FileSharingHandler.h" -#include "TransfersHandler.h" -#include "LivereloadHandler.h" -#include "TmpBlobStore.h" -#include "ChatHandler.h" - -namespace resource_api{ - -class ApiServerMainModules; - -// main entry point for all resource_api calls -// general part of the api server -// should work with any http library or a different transport protocol (e.g. SSH) - -// call chain is like this: -// HTTP server -> ApiServer -> different handlers -// or -// GUI -> ApiServer -> different handlers -// multiple clients can use the same ApiServer instance at the same time - -// ALL public methods in this class are thread safe -// this allows differen threads to send requests -class ApiServer -{ -public: - ApiServer(); - ~ApiServer(); - - class RequestId{ - public: - RequestId(): done(false), task(0), request(0), response(0){} - bool operator ==(const RequestId& r){ - const RequestId& l = *this; - return (l.done==r.done)&&(l.task==r.task)&&(l.request==r.request)&&(l.response&&r.response); - } - private: - friend class ApiServer; - bool done; // this flag will be set to true, to signal the task id is valid and the task is done - // (in case there was no ResponseTask and task was zero) - ResponseTask* task; // null when the task id is invalid or when there was no task - Request* request; - Response* response; - }; - - // process the requestgiven by request and return the response as json string - // blocks until the request was processed - std::string handleRequest(Request& request); - - // request and response must stay valid until isRequestDone returns true - // this method may do some work but it does not block - RequestId handleRequest(Request& request, Response& response); - - // ticks the request - // returns true if the request is done or the id is invalid - // this method may do some work but it does not block - bool isRequestDone(RequestId id); - - // load the main api modules - void loadMainModules(const RsPlugInInterfaces& ifaces); - - // allows to add more handlers - // make sure the livetime of the handlers is longer than the api server - template - void addResourceHandler(std::string name, T* instance, ResponseTask* (T::*callback)(Request& req, Response& resp)); - template - void addResourceHandler(std::string name, T* instance, void (T::*callback)(Request& req, Response& resp)); - - StateTokenServer* getStateTokenServer(){ return &mStateTokenServer; } - TmpBlobStore* getTmpBlobStore(){ return &mTmpBlobStore; } - -private: - RsMutex mMtx; - StateTokenServer mStateTokenServer; // goes first, as others may depend on it - // is always loaded, because it has no dependencies - LivereloadHandler mLivereloadhandler; - TmpBlobStore mTmpBlobStore; - - // only pointers here, to load/unload modules at runtime - ApiServerMainModules* mMainModules; // loaded when RS is started - - ResourceRouter mRouter; - - std::vector mRequests; -}; - -// implementations -template -void ApiServer::addResourceHandler(std::string name, T* instance, ResponseTask* (T::*callback)(Request& req, Response& resp)) -{ - RS_STACK_MUTEX(mMtx); // ********** LOCKED ********** - mRouter.addResourceHandler(name, instance, callback); -} -template -void ApiServer::addResourceHandler(std::string name, T* instance, void (T::*callback)(Request& req, Response& resp)) -{ - RS_STACK_MUTEX(mMtx); // ********** LOCKED ********** - mRouter.addResourceHandler(name, instance, callback); -} - -} diff --git a/libresapi/src/api/ApiServerLocal.cpp b/libresapi/src/api/ApiServerLocal.cpp deleted file mode 100644 index e856f2db2..000000000 --- a/libresapi/src/api/ApiServerLocal.cpp +++ /dev/null @@ -1,180 +0,0 @@ -/******************************************************************************* - * libresapi/api/ApiServer.cpp * - * * - * LibResAPI: API for local socket server * - * * - * Copyright 2016 by Gioacchino Mazzurco * - * * - * This program is free software: you can redistribute it and/or modify * - * it under the terms of the GNU Affero General Public License as * - * published by the Free Software Foundation, either version 3 of the * - * License, or (at your option) any later version. * - * * - * This program is distributed in the hope that it will be useful, * - * but WITHOUT ANY WARRANTY; without even the implied warranty of * - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * - * GNU Affero General Public License for more details. * - * * - * You should have received a copy of the GNU Affero General Public License * - * along with this program. If not, see . * - * * - *******************************************************************************/ - -#include -#include -#include - -#include "ApiServerLocal.h" -#include "JsonStream.h" - - -namespace resource_api{ - -ApiServerLocal::ApiServerLocal(ApiServer* server, - const QString &listenPath, QObject *parent) : - QObject(parent), serverThread(this), - // Must have no parent to be movable to other thread - localListener(server, listenPath) -{ - qRegisterMetaType(); - localListener.moveToThread(&serverThread); - serverThread.start(); -} - -ApiServerLocal::~ApiServerLocal() -{ - serverThread.quit(); - serverThread.wait(); -} - -ApiLocalListener::ApiLocalListener(ApiServer *server, - const QString &listenPath, - QObject *parent) : - QObject(parent), mApiServer(server), mLocalServer(this) -{ - QFileInfo fileInfo(listenPath); - if(fileInfo.exists()) - { - std::cerr << __PRETTY_FUNCTION__ << listenPath.toLatin1().data() - << " already exists. " - << "Removing it assuming it's a past crash leftover! " - << "Are you sure another instance is not listening there?" - << std::endl; - mLocalServer.removeServer(listenPath); - } -#if QT_VERSION >= 0x050000 - mLocalServer.setSocketOptions(QLocalServer::UserAccessOption); -#endif - connect( &mLocalServer, &QLocalServer::newConnection, - this, &ApiLocalListener::handleConnection ); - - QDir&& lDir(fileInfo.absoluteDir()); - if(!lDir.exists()) - { - std::cerr << __PRETTY_FUNCTION__ << " Directory for listening socket " - << listenPath.toLatin1().data() << " doesn't exists. " - << " Creating it!" << std::endl; - lDir.mkpath(lDir.absolutePath()); - } - - if(!mLocalServer.listen(listenPath)) - { - std::cerr << __PRETTY_FUNCTION__ << " mLocalServer.listen(" - << listenPath.toLatin1().data() << ") failed with: " - << mLocalServer.errorString().toLatin1().data() << std::endl; - } -} - -void ApiLocalListener::handleConnection() -{ - new ApiLocalConnectionHandler(mApiServer, - mLocalServer.nextPendingConnection(), this); -} - -ApiLocalConnectionHandler::ApiLocalConnectionHandler( - ApiServer* apiServer, QLocalSocket* sock, QObject *parent) : - QObject(parent), mApiServer(apiServer), mLocalSocket(sock), - mState(WAITING_PATH) -{ - connect(mLocalSocket, SIGNAL(disconnected()), this, SLOT(deleteLater())); - connect(sock, SIGNAL(readyRead()), this, SLOT(handlePendingRequests())); -} - -ApiLocalConnectionHandler::~ApiLocalConnectionHandler() -{ - /* Any attempt of closing the socket here also deferred method call, causes - * crash when the core is asked to stop, at least from the JSON API call. - * QMetaObject::invokeMethod(&app, "close", Qt::QueuedConnection) - * mLocalSocket->disconnectFromServer() - * mLocalSocket->close() */ - mLocalSocket->deleteLater(); -} - -void ApiLocalConnectionHandler::handlePendingRequests() -{ - switch(mState) - { - case WAITING_PATH: - { - if(mLocalSocket->canReadLine()) - { -readPath: - QString rString(mLocalSocket->readLine()); - rString = rString.simplified(); - if (!rString.isEmpty()) - { - if(rString.startsWith("PUT", Qt::CaseInsensitive)) reqMeth = resource_api::Request::PUT; - else if (rString.startsWith("DELETE", Qt::CaseInsensitive)) reqMeth = resource_api::Request::DELETE_AA; - else reqMeth = resource_api::Request::GET; - if(rString.contains(' ')) rString = rString.split(' ')[1]; - - reqPath = rString.toStdString(); - mState = WAITING_DATA; - - /* Because QLocalSocket is SOCK_STREAM some clients implementations - * like the one based on QLocalSocket feel free to send the whole - * request (PATH + DATA) in a single write(), causing readyRead() - * signal being emitted only once, in that case we should continue - * processing without waiting for readyRead() being fired again, so - * we don't break here as there may be more lines to read */ - } - else break; - } - } - case WAITING_DATA: - { - if(mLocalSocket->canReadLine()) - { - resource_api::JsonStream reqJson; - reqJson.setJsonString(std::string(mLocalSocket->readLine().constData())); - resource_api::Request req(reqJson); - req.mMethod = reqMeth; - req.setPath(reqPath); - - // Need this idiom because binary result may contains \0 - std::string&& resultString = mApiServer->handleRequest(req); - QByteArray rB(resultString.data(), resultString.length()); - - // Dirty trick to support avatars answers - if(rB.contains("\n") || !rB.startsWith("{") || !rB.endsWith("}")) - mLocalSocket->write(rB.toBase64()); - else mLocalSocket->write(rB); - mLocalSocket->write("\n\0"); - - mState = WAITING_PATH; - - /* Because QLocalSocket is SOCK_STREAM some clients implementations - * like the one based on QLocalSocket feel free to coalesce multiple - * upper level write() into a single socket write(), causing - * readyRead() signal being emitted only once, in that case we should - * keep processing without waiting for readyRead() being fired again */ - if(mLocalSocket->canReadLine()) goto readPath; - - // Now there are no more requests to process we can break - break; - } - } - } -} - -} // namespace resource_api diff --git a/libresapi/src/api/ApiServerLocal.h b/libresapi/src/api/ApiServerLocal.h deleted file mode 100644 index c9ef246b8..000000000 --- a/libresapi/src/api/ApiServerLocal.h +++ /dev/null @@ -1,100 +0,0 @@ -/******************************************************************************* - * libresapi/api/ApiServer.h * - * * - * LibResAPI: API for local socket server * - * * - * Copyright 2016 by Gioacchino Mazzurco * - * * - * This program is free software: you can redistribute it and/or modify * - * it under the terms of the GNU Affero General Public License as * - * published by the Free Software Foundation, either version 3 of the * - * License, or (at your option) any later version. * - * * - * This program is distributed in the hope that it will be useful, * - * but WITHOUT ANY WARRANTY; without even the implied warranty of * - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * - * GNU Affero General Public License for more details. * - * * - * You should have received a copy of the GNU Affero General Public License * - * along with this program. If not, see . * - * * - *******************************************************************************/ -#pragma once - -#include -#include -#include -#include -#include -#include - -#include "ApiTypes.h" -#include "ApiServer.h" - -namespace resource_api -{ - -class ApiLocalListener : public QObject -{ - Q_OBJECT - -public: - ApiLocalListener(ApiServer* server, const QString &listenPath, QObject *parent=0); - ~ApiLocalListener() { mLocalServer.close(); } - -public slots: - void handleConnection(); - -private: - ApiServer* mApiServer; - QLocalServer mLocalServer; -}; - -class ApiServerLocal : public QObject -{ - Q_OBJECT - -public: - ApiServerLocal(ApiServer* server, const QString& listenPath, QObject *parent=0); - ~ApiServerLocal(); - - const static QString& loginServerPath() - { - const static QString sockPath(RsAccounts::ConfigDirectory() - .append("/libresapi.sock").c_str()); - return sockPath; - } - - const static QString& serverPath() - { - const static QString sockPath(RsAccounts::AccountDirectory() - .append("/libresapi.sock").c_str()); - return sockPath; - } - -private: - QThread serverThread; - ApiLocalListener localListener; -}; - -class ApiLocalConnectionHandler : public QObject -{ - Q_OBJECT - -public: - ApiLocalConnectionHandler(ApiServer* apiServer, QLocalSocket* sock, QObject *parent = 0); - ~ApiLocalConnectionHandler(); - enum State {WAITING_PATH, WAITING_DATA}; - -public slots: - void handlePendingRequests(); - -private: - ApiServer* mApiServer; - QLocalSocket* mLocalSocket; - State mState; - std::string reqPath; - resource_api::Request::Method reqMeth; -}; - -} // namespace resource_api diff --git a/libresapi/src/api/ApiServerMHD.cpp b/libresapi/src/api/ApiServerMHD.cpp deleted file mode 100644 index 81da6893d..000000000 --- a/libresapi/src/api/ApiServerMHD.cpp +++ /dev/null @@ -1,693 +0,0 @@ -/******************************************************************************* - * libresapi/api/ApiServerMHD.cpp * - * * - * LibResAPI: API for local socket server * - * * - * Copyright 2018 by Retroshare Team * - * * - * This program is free software: you can redistribute it and/or modify * - * it under the terms of the GNU Affero General Public License as * - * published by the Free Software Foundation, either version 3 of the * - * License, or (at your option) any later version. * - * * - * This program is distributed in the hope that it will be useful, * - * but WITHOUT ANY WARRANTY; without even the implied warranty of * - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * - * GNU Affero General Public License for more details. * - * * - * You should have received a copy of the GNU Affero General Public License * - * along with this program. If not, see . * - * * - *******************************************************************************/ -#include "ApiServerMHD.h" - -#include -#include -#include -#include -#include - -#include -#include "util/ContentTypes.h" - -// for filestreamer -#include - -// to determine default docroot -#include - -#include "JsonStream.h" -#include "ApiServer.h" - -#if MHD_VERSION < 0x00090000 - // very old version, probably v0.4.x on old debian/ubuntu - #define OLD_04_MHD_FIX -#endif - -// filestreamer only works if a content reader callback is allowed to return 0 -// this is allowed since libmicrohttpd revision 30402 -#if MHD_VERSION >= 0x00093101 // 0.9.31-1 - #define ENABLE_FILESTREAMER -#else - #warning libmicrohttpd is too old to support file streaming. upgrade to a newer version. -#endif - -#ifdef OLD_04_MHD_FIX -#define MHD_CONTENT_READER_END_OF_STREAM ((size_t) -1LL) -/** - * Create a response object. The response object can be extended with - * header information and then be used any number of times. - * - * @param size size of the data portion of the response - * @param fd file descriptor referring to a file on disk with the - * data; will be closed when response is destroyed; - * fd should be in 'blocking' mode - * @return NULL on error (i.e. invalid arguments, out of memory) - * @ingroup response - */ -struct MHD_Response * MHD_create_response_from_fd(size_t size, int fd) -{ - unsigned char *buf = (unsigned char *)malloc(size) ; - - if(buf == 0) - { - std::cerr << "replacement MHD_create_response_from_fd: malloc failed, size was " << size << std::endl; - close(fd); - return NULL ; - } - if(read(fd,buf,size) != size) - { - std::cerr << "replacement MHD_create_response_from_fd: READ error in file descriptor " << fd << " requested read size was " << size << std::endl; - close(fd); - free(buf) ; - return NULL ; - } - else - { - close(fd); - return MHD_create_response_from_data(size, buf,1,0) ; - } -} -#endif - -namespace resource_api{ - -std::string getDefaultDocroot() -{ - return RsAccounts::systemDataDirectory(false) + "/webui"; -} - -const char* API_ENTRY_PATH = "/api/v2"; -const char* FILESTREAMER_ENTRY_PATH = "/fstream/"; -const char* STATIC_FILES_ENTRY_PATH = "/static/"; -const char* UPLOAD_ENTRY_PATH = "/upload/"; - -static void secure_queue_response(MHD_Connection *connection, unsigned int status_code, struct MHD_Response* response); -static void sendMessage(MHD_Connection *connection, unsigned int status, std::string message); - -// interface for request handler classes -class MHDHandlerBase -{ -public: - virtual ~MHDHandlerBase(){} - // return MHD_NO to terminate connection - // return MHD_YES otherwise - // this function will get called by MHD until a response was queued - virtual int handleRequest( struct MHD_Connection *connection, - const char *url, const char *method, const char *version, - const char *upload_data, size_t *upload_data_size) = 0; -}; - -// handles calls to the resource_api -class MHDUploadHandler: public MHDHandlerBase -{ -public: - MHDUploadHandler(ApiServer* s): mState(BEGIN), mApiServer(s){} - virtual ~MHDUploadHandler(){} - // return MHD_NO or MHD_YES - virtual int handleRequest( struct MHD_Connection *connection, - const char */*url*/, const char *method, const char */*version*/, - const char *upload_data, size_t *upload_data_size) - { - // new request - if(mState == BEGIN) - { - if(strcmp(method, "POST") == 0) - { - mState = WAITING_DATA; - // first time there is no data, do nothing and return - return MHD_YES; - } - } - if(mState == WAITING_DATA) - { - if(upload_data && *upload_data_size) - { - mRequesString += std::string(upload_data, *upload_data_size); - *upload_data_size = 0; - return MHD_YES; - } - } - - std::vector bytes(mRequesString.begin(), mRequesString.end()); - - int id = mApiServer->getTmpBlobStore()->storeBlob(bytes); - - resource_api::JsonStream responseStream; - if(id) - responseStream << makeKeyValue("ok", true); - else - responseStream << makeKeyValue("ok", false); - - responseStream << makeKeyValueReference("id", id); - - std::string result = responseStream.getJsonString(); - - struct MHD_Response* resp = MHD_create_response_from_data(result.size(), (void*)result.data(), 0, 1); - - MHD_add_response_header(resp, "Content-Type", "application/json"); - - secure_queue_response(connection, MHD_HTTP_OK, resp); - MHD_destroy_response(resp); - return MHD_YES; - } - enum State {BEGIN, WAITING_DATA}; - State mState; - std::string mRequesString; - ApiServer* mApiServer; -}; - -// handles calls to the resource_api -class MHDApiHandler: public MHDHandlerBase -{ -public: - MHDApiHandler(ApiServer* s): mState(BEGIN), mApiServer(s){} - virtual ~MHDApiHandler(){} - // return MHD_NO or MHD_YES - virtual int handleRequest( struct MHD_Connection *connection, - const char *url, const char *method, const char */*version*/, - const char *upload_data, size_t *upload_data_size) - { - // new request - if(mState == BEGIN) - { - if(strcmp(method, "POST") == 0) - { - mState = WAITING_DATA; - // first time there is no data, do nothing and return - return MHD_YES; - } - } - if(mState == WAITING_DATA) - { - if(upload_data && *upload_data_size) - { - mRequesString += std::string(upload_data, *upload_data_size); - *upload_data_size = 0; - return MHD_YES; - } - } - - if(strstr(url, API_ENTRY_PATH) != url) - { - std::cerr << "FATAL ERROR in MHDApiHandler::handleRequest(): url does not start with api entry path, which is \"" << API_ENTRY_PATH << "\"" << std::endl; - return MHD_NO; - } - std::string path2 = (url + strlen(API_ENTRY_PATH)); - - resource_api::JsonStream instream; - instream.setJsonString(mRequesString); - resource_api::Request req(instream); - - if(strcmp(method, "GET") == 0) - { - req.mMethod = resource_api::Request::GET; - } - else if(strcmp(method, "POST") == 0) - { - req.mMethod = resource_api::Request::PUT; - } - else if(strcmp(method, "DELETE") == 0) - { - req.mMethod = resource_api::Request::DELETE_AA; - } - - req.setPath(path2); - - std::string result = mApiServer->handleRequest(req); - - struct MHD_Response* resp = MHD_create_response_from_data(result.size(), (void*)result.data(), 0, 1); - - // EVIL HACK remove - if(result[0] != '{') - MHD_add_response_header(resp, "Content-Type", "image/png"); - else - MHD_add_response_header(resp, "Content-Type", "application/json"); - - secure_queue_response(connection, MHD_HTTP_OK, resp); - MHD_destroy_response(resp); - return MHD_YES; - } - enum State {BEGIN, WAITING_DATA}; - State mState; - std::string mRequesString; - ApiServer* mApiServer; -}; - -#ifdef ENABLE_FILESTREAMER -class MHDFilestreamerHandler: public MHDHandlerBase -{ -public: - MHDFilestreamerHandler(): mSize(0){} - virtual ~MHDFilestreamerHandler(){} - - RsFileHash mHash; - uint64_t mSize; - - // return MHD_NO or MHD_YES - virtual int handleRequest( struct MHD_Connection *connection, - const char *url, const char */*method*/, const char */*version*/, - const char */*upload_data*/, size_t */*upload_data_size*/) - { - if(rsFiles == 0) - { - sendMessage(connection, MHD_HTTP_INTERNAL_SERVER_ERROR, "Error: rsFiles is null. Retroshare is probably not yet started."); - return MHD_YES; - } - std::string urls(url); - urls = urls.substr(strlen(FILESTREAMER_ENTRY_PATH)); - size_t perpos = urls.find('/'); - if(perpos == std::string::npos){ - mHash = RsFileHash(urls); - }else{ - mHash = RsFileHash(urls.substr(0, perpos)); - } - if(urls.empty() || mHash.isNull()) - { - sendMessage(connection, MHD_HTTP_NOT_FOUND, "Error: URL is not a valid file hash"); - return MHD_YES; - } - - FileInfo info; - std::list dls; - rsFiles->FileDownloads(dls); - if(!(rsFiles->alreadyHaveFile(mHash, info) || std::find(dls.begin(), dls.end(), mHash) != dls.end())) - { - sendMessage(connection, MHD_HTTP_NOT_FOUND, "Error: file not existing on local peer and not downloading. Start the download before streaming it."); - return MHD_YES; - } - mSize = info.size; - - struct MHD_Response* resp = MHD_create_response_from_callback( - mSize, 1024*1024, &contentReadercallback, this, NULL); - - // get content-type from extension - std::string ext = ""; - std::string::size_type i = info.fname.rfind('.'); - if(i != std::string::npos) - ext = info.fname.substr(i+1); - MHD_add_response_header(resp, "Content-Type", ContentTypes::cTypeFromExt(ext).c_str()); - - secure_queue_response(connection, MHD_HTTP_OK, resp); - MHD_destroy_response(resp); - return MHD_YES; - } - - static ssize_t contentReadercallback(void *cls, uint64_t pos, char *buf, size_t max) - { - MHDFilestreamerHandler* handler = (MHDFilestreamerHandler*)cls; - if(pos >= handler->mSize) - return MHD_CONTENT_READER_END_OF_STREAM; - uint32_t size_to_send = max; - if(!rsFiles->getFileData(handler->mHash, pos, size_to_send, (uint8_t*)buf)) - return 0; - return size_to_send; - } -}; -#endif // ENABLE_FILESTREAMER - -// MHD will call this for each element of the http header -static int _extract_host_header_it_cb(void *cls, - enum MHD_ValueKind kind, - const char *key, - const char *value) -{ - if(kind == MHD_HEADER_KIND) - { - // check if key is host - const char* h = "host"; - while(*key && *h) - { - if(tolower(*key) != *h) - return MHD_YES; - key++; - h++; - } - // strings have same length and content - if(*key == 0 && *h == 0) - { - *((std::string*)cls) = value; - } - } - return MHD_YES; -} - -// add security related headers and send the response on the given connection -// the reference counter is not touched -// this function is a wrapper around MHD_queue_response -// MHD_queue_response should be replaced with this function -static void secure_queue_response(MHD_Connection *connection, unsigned int status_code, struct MHD_Response* response) -{ - // TODO: protect againts handling untrusted content to the browser - // see: - // http://www.dotnetnoob.com/2012/09/security-through-http-response-headers.html - // http://www.w3.org/TR/CSP2/ - // https://code.google.com/p/doctype-mirror/wiki/ArticleContentSniffing - - // check content type - // don't server when no type or no whitelisted type is given - // TODO sending invalid mime types is as bad as not sending them TODO - /* - std::vector allowed_types; - allowed_types.push_back("text/html"); - allowed_types.push_back("application/json"); - allowed_types.push_back("image/png"); - */ - const char* type = MHD_get_response_header(response, "Content-Type"); - if(type == 0 /*|| std::find(allowed_types.begin(), allowed_types.end(), std::string(type)) == allowed_types.end()*/) - { - std::string page; - if(type == 0) - page = "

Fatal Error: no content type was set on this response. This is a bug.

"; - else - page = "

Fatal Error: this content type is not allowed. This is a bug.
Content-Type: "+std::string(type)+"

"; - struct MHD_Response* resp = MHD_create_response_from_data(page.size(), (void*)page.data(), 0, 1); - MHD_add_response_header(resp, "Content-Type", "text/html"); - MHD_queue_response(connection, MHD_HTTP_INTERNAL_SERVER_ERROR, resp); - MHD_destroy_response(resp); - } - - // tell Internet Explorer to not do content sniffing - MHD_add_response_header(response, "X-Content-Type-Options", "nosniff"); - - // Prevent clickjacking attacks (also prevented by CSP, but not in all browsers, including FireFox) - MHD_add_response_header(response, "X-Frame-Options", "SAMEORIGIN"); - - // Content security policy header, its a new technology and not implemented everywhere - - // get own host name as the browser sees it - std::string host; - MHD_get_connection_values(connection, MHD_HEADER_KIND, _extract_host_header_it_cb, (void*)&host); - - std::string csp; - csp += "default-src 'none';"; - csp += "script-src '"+host+STATIC_FILES_ENTRY_PATH+"';"; - csp += "font-src '"+host+STATIC_FILES_ENTRY_PATH+"';"; - csp += "img-src 'self';"; // allow images from all paths on this server - csp += "media-src 'self';"; // allow media files from all paths on this server - - MHD_add_response_header(response, "X-Content-Security-Policy", csp.c_str()); - - MHD_queue_response(connection, status_code, response); -} - -// wraps the given string in a html page and sends it as response with the given status code -static void sendMessage(MHD_Connection *connection, unsigned int status, std::string message) -{ - std::string page = "

"+message+"

"; - struct MHD_Response* resp = MHD_create_response_from_data(page.size(), (void*)page.data(), 0, 1); - MHD_add_response_header(resp, "Content-Type", "text/html"); - secure_queue_response(connection, status, resp); - MHD_destroy_response(resp); -} - -// convert all character to hex html entities -static std::string escape_html(std::string in) -{ - std::string out; - for(uint32_t i = 0; i < in.size(); i++) - { - char a = (in[i]&0xF0)>>4; - a = a < 10? a+'0': a-10+'A'; - char b = (in[i]&0x0F); - b = b < 10? b+'0': b-10+'A'; - out += std::string("&#x")+a+b+";"; - } - return out; -} - -ApiServerMHD::ApiServerMHD(ApiServer *server): - mConfigOk(false), mDaemon(0), mApiServer(server) -{ - memset(&mListenAddr, 0, sizeof(mListenAddr)); -} - -ApiServerMHD::~ApiServerMHD() -{ - stop(); -} - -bool ApiServerMHD::configure(std::string docroot, uint16_t port, std::string /*bind_address*/, bool allow_from_all) -{ - mRootDir = docroot; - // make sure the docroot dir ends with a slash - if(mRootDir.empty()) - mRootDir = "./"; - else if (mRootDir[mRootDir.size()-1] != '/' && mRootDir[mRootDir.size()-1] != '\\') - mRootDir += "/"; - - mListenAddr.sin_family = AF_INET; - mListenAddr.sin_port = htons(port); - - // untested - /* - if(!bind_address.empty()) - { - if(!inet_pton(AF_INET6, bind_address.c_str(), &mListenAddr.sin6_addr)) - { - std::cerr << "ApiServerMHD::configure() invalid bind address: \"" << bind_address << "\"" << std::endl; - return false; - } - } - else*/ if(allow_from_all) - { - mListenAddr.sin_addr.s_addr = htonl(INADDR_ANY); - std::cerr << "ApiServerMHD::configure(): will serve the webinterface to ALL IP adresses." << std::endl; - } - else - { - mListenAddr.sin_addr.s_addr = htonl(INADDR_LOOPBACK); - std::cerr << "ApiServerMHD::configure(): will serve the webinterface to LOCALHOST only." << std::endl; - } - - mConfigOk = true; - return true; -} - -bool ApiServerMHD::start() -{ - if(!mConfigOk) - { - std::cerr << "ApiServerMHD::start() ERROR: server not configured. You have to call configure() first." << std::endl; - return false; - } - if(mDaemon) - { - std::cerr << "ApiServerMHD::start() ERROR: server already started. You have to call stop() first." << std::endl; - return false; - } - mDaemon = MHD_start_daemon(MHD_USE_SELECT_INTERNALLY, 9999, // port will be overwritten by MHD_OPTION_SOCK_ADDR - &static_acceptPolicyCallback, this, - &static_accessHandlerCallback, this, - MHD_OPTION_NOTIFY_COMPLETED, &static_requestCompletedCallback, this, - MHD_OPTION_SOCK_ADDR, &mListenAddr, - MHD_OPTION_END); - if(mDaemon) - { - std::cerr << "ApiServerMHD::start() SUCCESS. Started server on port " << ntohs(mListenAddr.sin_port) << ". Serving files from \"" << mRootDir << "\" at " << STATIC_FILES_ENTRY_PATH << std::endl; - return true; - } - else - { - std::cerr << "ApiServerMHD::start() ERROR: starting the server failed. Maybe port " << ntohs(mListenAddr.sin_port) << " is already in use?" << std::endl; - return false; - } -} - -void ApiServerMHD::stop() -{ - if(mDaemon == 0) - return; - MHD_stop_daemon(mDaemon); - mDaemon = 0; -} - -int ApiServerMHD::static_acceptPolicyCallback(void *cls, const sockaddr *addr, socklen_t addrlen) -{ - return ((ApiServerMHD*)cls)->acceptPolicyCallback(addr, addrlen); -} - -int ApiServerMHD::static_accessHandlerCallback(void* cls, struct MHD_Connection * connection, - const char *url, const char *method, const char *version, - const char *upload_data, size_t *upload_data_size, - void **con_cls) -{ - return ((ApiServerMHD*)cls)->accessHandlerCallback(connection, url, method, version, - upload_data, upload_data_size, con_cls); -} - -void ApiServerMHD::static_requestCompletedCallback(void *cls, MHD_Connection* connection, - void **con_cls, MHD_RequestTerminationCode toe) -{ - ((ApiServerMHD*)cls)->requestCompletedCallback(connection, con_cls, toe); -} - - -int ApiServerMHD::acceptPolicyCallback(const sockaddr* /*addr*/, socklen_t /*addrlen*/) -{ - // accept all connetions - return MHD_YES; -} - -int ApiServerMHD::accessHandlerCallback(MHD_Connection *connection, - const char *url, const char *method, const char *version, - const char *upload_data, size_t *upload_data_size, - void **con_cls) -{ - // is this call a continuation for an existing request? - if(*con_cls) - { - return ((MHDHandlerBase*)(*con_cls))->handleRequest(connection, url, method, version, upload_data, upload_data_size); - } - - // these characters are not allowed in the url, raise an error if they occur - // reason: don't want to serve files outside the current document root - const char *double_dots = ".."; - if(strstr(url, double_dots)) - { - const char *error = "

Fatal error: found double dots (\"..\") in the url. This is not allowed

"; - struct MHD_Response* resp = MHD_create_response_from_data(strlen(error), (void*)error, 0, 1); - MHD_add_response_header(resp, "Content-Type", "text/html"); - secure_queue_response(connection, MHD_HTTP_INTERNAL_SERVER_ERROR, resp); - MHD_destroy_response(resp); - return MHD_YES; - } - - // if no path is given, redirect to index.html in static files directory - if(strlen(url) == 1 && url[0] == '/') - { - std::string location = std::string(STATIC_FILES_ENTRY_PATH) + "index.html"; - std::string errstr = "

Webinterface is at "+location+"

"; - const char *error = errstr.c_str(); - struct MHD_Response* resp = MHD_create_response_from_data(strlen(error), (void*)error, 0, 1); - MHD_add_response_header(resp, "Content-Type", "text/html"); - MHD_add_response_header(resp, "Location", location.c_str()); - secure_queue_response(connection, MHD_HTTP_FOUND, resp); - MHD_destroy_response(resp); - return MHD_YES; - } - // is it a call to the resource api? - if(strstr(url, API_ENTRY_PATH) == url) - { - // create a new handler and store it in con_cls - MHDHandlerBase* handler = new MHDApiHandler(mApiServer); - *con_cls = (void*) handler; - return handler->handleRequest(connection, url, method, version, upload_data, upload_data_size); - } - // is it a call to the filestreamer? - if(strstr(url, FILESTREAMER_ENTRY_PATH) == url) - { -#ifdef ENABLE_FILESTREAMER - // create a new handler and store it in con_cls - MHDHandlerBase* handler = new MHDFilestreamerHandler(); - *con_cls = (void*) handler; - return handler->handleRequest(connection, url, method, version, upload_data, upload_data_size); -#else - sendMessage(connection, MHD_HTTP_NOT_FOUND, "The filestreamer is not available, because this executable was compiled with a too old version of libmicrohttpd."); - return MHD_YES; -#endif - } - // is it a path to the static files? - if(strstr(url, STATIC_FILES_ENTRY_PATH) == url) - { - url = url + strlen(STATIC_FILES_ENTRY_PATH); - // else server static files - std::string filename = mRootDir + url; - // important: binary open mode (windows) - // else libmicrohttpd will replace crlf with lf and add garbage at the end of the file -#ifdef O_BINARY - int fd = open(filename.c_str(), O_RDONLY | O_BINARY); -#else - int fd = open(filename.c_str(), O_RDONLY); -#endif - if(fd == -1) - { - std::string direxists; - if(RsDirUtil::checkDirectory(mRootDir)) - direxists = "directory ""+mRootDir+"" exists"; - else - direxists = "directory ""+mRootDir+"" does not exist!"; - std::string msg = "

Error: can't open the requested file. path=""+escape_html(filename)+""

"+direxists+"

"; - sendMessage(connection, MHD_HTTP_NOT_FOUND, msg); - return MHD_YES; - } - - struct stat s; - if(fstat(fd, &s) == -1) - { - close(fd); - const char *error = "

Error: file was opened but stat failed.

"; - struct MHD_Response* resp = MHD_create_response_from_data(strlen(error), (void*)error, 0, 1); - MHD_add_response_header(resp, "Content-Type", "text/html"); - secure_queue_response(connection, MHD_HTTP_NOT_FOUND, resp); - MHD_destroy_response(resp); - return MHD_YES; - } - - // find the file extension and the content type - std::string extension; - int i = filename.size()-1; - while(i >= 0 && filename[i] != '.') - { - extension = filename[i] + extension; - i--; - }; - - struct MHD_Response* resp = MHD_create_response_from_fd(s.st_size, fd); - MHD_add_response_header(resp, "Content-Type", ContentTypes::cTypeFromExt(extension).c_str()); - secure_queue_response(connection, MHD_HTTP_OK, resp); - MHD_destroy_response(resp); - return MHD_YES; - } - - if(strstr(url, UPLOAD_ENTRY_PATH) == url) - { - // create a new handler and store it in con_cls - MHDHandlerBase* handler = new MHDUploadHandler(mApiServer); - *con_cls = (void*) handler; - return handler->handleRequest(connection, url, method, version, upload_data, upload_data_size); - } - - // if url is not a valid path, then serve a help page - sendMessage(connection, MHD_HTTP_NOT_FOUND, - "This address is invalid. Try one of the adresses below:
" - "
    " - "
  • /
    Retroshare webinterface
  • " - "
  • "+std::string(API_ENTRY_PATH)+"
    JSON over http api
  • " - "
  • "+std::string(FILESTREAMER_ENTRY_PATH)+"
    file streamer
  • " - "
  • "+std::string(STATIC_FILES_ENTRY_PATH)+"
    static files
  • " - "
" - ); - return MHD_YES; -} - -void ApiServerMHD::requestCompletedCallback(struct MHD_Connection */*connection*/, - void **con_cls, MHD_RequestTerminationCode /*toe*/) -{ - if(*con_cls) - { - delete (MHDHandlerBase*)(*con_cls); - } -} - -} // namespace resource_api diff --git a/libresapi/src/api/ApiServerMHD.h b/libresapi/src/api/ApiServerMHD.h deleted file mode 100644 index 8258e90ad..000000000 --- a/libresapi/src/api/ApiServerMHD.h +++ /dev/null @@ -1,74 +0,0 @@ -/******************************************************************************* - * libresapi/api/ApiServerMHD.h * - * * - * LibResAPI: API for local socket server * - * * - * Copyright 2018 by Retroshare Team * - * * - * This program is free software: you can redistribute it and/or modify * - * it under the terms of the GNU Affero General Public License as * - * published by the Free Software Foundation, either version 3 of the * - * License, or (at your option) any later version. * - * * - * This program is distributed in the hope that it will be useful, * - * but WITHOUT ANY WARRANTY; without even the implied warranty of * - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * - * GNU Affero General Public License for more details. * - * * - * You should have received a copy of the GNU Affero General Public License * - * along with this program. If not, see . * - * * - *******************************************************************************/ -#pragma once - -#include -#include -#include -#include -#include -#include - -#ifndef WINDOWS_SYS -#include -#endif - -namespace resource_api{ -class ApiServer; - -// returns the default docroot path -// (it is differen on different operating systems) -std::string getDefaultDocroot(); - -class ApiServerMHD -{ -public: - ApiServerMHD(ApiServer* server); - ~ApiServerMHD(); - /** - * @brief configure the http server - * @param docroot sets the directory from which static files should be served. default = ./ - * @param port the port to listen on. The server will listen on ipv4 and ipv6. - * @param bind_address NOT IMPLEMENTED optional, specifies an ipv6 adress to listen on. - * @param allow_from_all when true, listen on all ips. (only when bind_adress is empty) - * @return true on success - */ - bool configure(std::string docroot, uint16_t port, std::string bind_address, bool allow_from_all); - bool start(); - void stop(); - -private: - // static callbacks for libmicrohttpd, they call the members below - static int static_acceptPolicyCallback(void* cls, const struct sockaddr * addr, socklen_t addrlen); - static int static_accessHandlerCallback(void* cls, struct MHD_Connection * connection, const char *url, const char *method, const char *version, const char *upload_data, size_t *upload_data_size, void **con_cls); - static void static_requestCompletedCallback(void *cls, struct MHD_Connection* connection, void **con_cls, enum MHD_RequestTerminationCode toe); - int acceptPolicyCallback(const struct sockaddr * addr, socklen_t addrlen); - int accessHandlerCallback(struct MHD_Connection * connection, const char *url, const char *method, const char *version, const char *upload_data, size_t *upload_data_size, void **con_cls); - void requestCompletedCallback(struct MHD_Connection *connection, void **con_cls, MHD_RequestTerminationCode toe); - bool mConfigOk; - std::string mRootDir; - struct sockaddr_in mListenAddr; - MHD_Daemon* mDaemon; - ApiServer* mApiServer; -}; - -} // namespace resource_api diff --git a/libresapi/src/api/ApiTypes.h b/libresapi/src/api/ApiTypes.h deleted file mode 100644 index ba171f9be..000000000 --- a/libresapi/src/api/ApiTypes.h +++ /dev/null @@ -1,335 +0,0 @@ -/******************************************************************************* - * libresapi/api/ApiTypes.h * - * * - * LibResAPI: API for local socket server * - * * - * Copyright 2018 by Retroshare Team * - * * - * This program is free software: you can redistribute it and/or modify * - * it under the terms of the GNU Affero General Public License as * - * published by the Free Software Foundation, either version 3 of the * - * License, or (at your option) any later version. * - * * - * This program is distributed in the hope that it will be useful, * - * but WITHOUT ANY WARRANTY; without even the implied warranty of * - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * - * GNU Affero General Public License for more details. * - * * - * You should have received a copy of the GNU Affero General Public License * - * along with this program. If not, see . * - * * - *******************************************************************************/ -#pragma once - -#include -#include -#include -#include -#include - -#include "util/rsdeprecate.h" - -namespace resource_api -{ -// things to clean up: -// - temporary variables when serialising rs-ids -// - always ensure proper return values -// - add help functions -// - remove unused functions or implement them -// - add operators or functions for std::set, std::list, std::vector, std::map - - -// idea: -// make a second parameter like -// ValueReference(this->member, OPTIONAL); // optional signals that it is not an error if this member is missing -// make a third parameter with a type hint: time, length, kilobytes - -// to make arrays -template -class ValueReference -{ -public: - ValueReference(T& value): value(value){} - T& value; -}; - -template -ValueReference makeValueReference(T& value); - -template -class Value -{ -public: - Value(T value): value(value){} - operator ValueReference(){ return ValueReference(value);} - T value; -}; - -template -Value makeValue(T value); - -// to make objects -template -class KeyValueReference -{ -public: - KeyValueReference(std::string key, T& value): key(key), value(value){} - //KeyValueReference(const char* key, T& value): key(key), value(value){} - std::string key; - T& value; -}; - -template -KeyValueReference makeKeyValueReference(std::string key, T& value); - -// for serialisation -// copies the supplied value -// automatically converts itself to a KeyValueReference -template -class KeyValue -{ -public: - KeyValue(std::string key, T value): key(key), value(value){} - - operator KeyValueReference(){ return KeyValueReference(key, value);} - - std::string key; - T value; -}; - -template -KeyValue makeKeyValue(std::string key, T value); - -// interface for streams -class StreamBase -{ -public: - // the stream provides operators for basic data types - // everything else should be broken down by others - // the same stream can either become an object or an array stream, or a binary data object - // a binary data object is just raw binary data without any decoration - // binary data is good to pass things like images and small files - // this depends on how this stream is used - // but once the stream is used as array, then only array operations are allowed - // same with an stream used as object - - // idea: can have filter streams which forward the calls to another stream - // to make debug protocols of other steam implementations - // idea: make a stream shich creates a hash from the input to detect changes in the data - - // make an array - virtual StreamBase& operator<<(ValueReference value) = 0; - virtual StreamBase& operator<<(ValueReference value) = 0; - virtual StreamBase& operator<<(ValueReference value) = 0; - virtual StreamBase& operator<<(ValueReference value) = 0; - // usefull if the new array member should be an array or object - // the reference should be at least valid until another method of this class gets called - virtual StreamBase& getStreamToMember() = 0; - - // make an object - virtual StreamBase& operator<<(KeyValueReference keyValue) = 0; - virtual StreamBase& operator<<(KeyValueReference keyValue) = 0; - virtual StreamBase& operator<<(KeyValueReference keyValue) = 0; - virtual StreamBase& operator<<(KeyValueReference keyValue) = 0; - // usefull if the new object member should be an array or object - // the reference should be at least valid until another method of this class gets called - virtual StreamBase& getStreamToMember(std::string name) = 0; - - // make a binay data object (not a real object, just binary data) - // idea: can use vector.swap() to allow passing larger data items without copying - virtual StreamBase& operator<<(std::vector& data) = 0; - - // return true if there are more members in this object/array - // useful for array reading - virtual bool hasMore() = 0; - - virtual bool serialise() = 0; // let external operators find out they should serialise or deserialise - // return true if no serialisation/deserialisation error occoured - virtual bool isOK() = 0; - virtual void setError() = 0; // let external operators set the failed bit - //virtual void addLogMsg(std::string msg) = 0; - virtual void addErrorMsg(std::string msg) = 0; - virtual std::string getLog() = 0; - virtual std::string getErrorLog() = 0; - - virtual bool isRawData() = 0; - virtual std::string getRawData() = 0;// HACK, remove this -}; - -// todo: -// define clear rules how a response to a request should look like -// the clients should be able to know when something failed -// then it is desired to have a minimum of debug output to track the errors down -// currently no check for successful serialisation/deserialisation is performed -// -// response metadata: -// - etag, when will this result expire -// - maybe a hint how often this etag should be checked for updates -// -// outcome of a request: -// - full ok -// - partial ok -// - resource not found, invalid address or resource not available -// - not ok, internal error -// - wrong usage, parameters or POST data is wrong, like deserialisation error -// is is hard to find the cause of the error -// maybe include a comment with additional info -// -// want to include a mime type of the resulting data? -// because some data is json, othe plain text, other unknown binary stuff - -// live-stream resources -// some resources like typing notifications are only valid for a short time - -// resource types: -// - list, either with objects or adresses of objects. -// lists need a navigation mechanism like get objects before and get objects after -// - object -// - stream -// - binary data, for example files - -// TODO: record a timestamp for each token, to allow garbage collection of very old tokens -class StateToken{ -public: - StateToken(): value(0){} - StateToken(uint32_t value): value(value){} - std::string toString(); - - uint32_t getValue() const {return value;} - bool isNull() const {return value == 0;} -private: - uint32_t value; // 0 is reserved for invalid token -}; - -class Request -{ -public: - Request(StreamBase& stream) : mStream(stream), mMethod(GET){} - - RS_DEPRECATED bool isGet(){ return mMethod == GET;} - RS_DEPRECATED bool isPut(){ return mMethod == PUT;} - RS_DEPRECATED bool isDelete(){ return mMethod == DELETE_AA;} - RS_DEPRECATED bool isExec(){ return mMethod == EXEC;} - - /** - * Path is the adress to the resource if the path has multiple parts which - * get handled by different handlers, then each handler should pop the top - * element - */ - std::stack mPath; - std::string mFullPath; - bool setPath(const std::string &reqPath) - { - std::string str; - std::string::const_reverse_iterator sit; - for( sit = reqPath.rbegin(); sit != reqPath.rend(); ++sit ) - { - // add to front because we are traveling in reverse order - if((*sit) != '/') str = *sit + str; - else if(!str.empty()) - { - mPath.push(str); - str.clear(); - } - } - if(!str.empty()) mPath.push(str); - mFullPath = reqPath; - - return true; - } - - /// Contains data for new resources - StreamBase& mStream; - - /** - * @deprecated - * Method and derivated stuff usage is deprecated as it make implementation - * more complex and less readable without advantage - */ - enum Method { GET, PUT, DELETE_AA, EXEC}; - RS_DEPRECATED Method mMethod; -}; - -// new notes on responses -// later we want to send multiple requests over the same link -// and we want to be able to send the responses in a different order than the requests -// for this we need a unique token in every request which gets returned in the response - -// response: -// message token -// status (ok, warning, fail) -// data (different for different resources) -// debugstring (a human readable error message in case something went wrong) - -class Response -{ -public: - Response(StreamBase& stream, std::ostream& debug): mReturnCode(NOT_SET), mDataStream(stream), mDebug(debug){} - - // WARNING means: a valid result is available, but an error occoured - // FAIL means: the result is not valid - enum ReturnCode{ NOT_SET, OK, WARNING, FAIL}; - ReturnCode mReturnCode; - - StateToken mStateToken; - - //Just for GUI benefit - std::string mCallbackName; - - // the result - StreamBase& mDataStream; - - // humand readable string for debug messages/logging - std::ostream& mDebug; - - inline void setOk(){mReturnCode = OK;} - inline void setWarning(std::string msg = ""){ - mReturnCode = WARNING; - if(msg != "") - mDebug << msg << std::endl;} - inline void setFail(std::string msg = ""){ - mReturnCode = FAIL; - if(msg != "") - mDebug << msg << std::endl; - } -}; - -// if a response can not be handled immediately, -// then the handler should return a ResponseTask object -// the api server will then call the doWork() method periodically -class ResponseTask -{ -public: - virtual ~ResponseTask(){} - // return true if function should get called again - // return false when finished - virtual bool doWork(Request& req, Response& resp) = 0; -}; - -// implementations - -template -ValueReference makeValueReference(T& value) -{ - return ValueReference(value); -} - -template -Value makeValue(T value) -{ - return Value(value); -} - -template -KeyValueReference makeKeyValueReference(std::string key, T& value) -{ - return KeyValueReference(key, value); -} - -template -KeyValue makeKeyValue(std::string key, T value) -{ - return KeyValue(key, value); -} - -} // namespace resource_api diff --git a/libresapi/src/api/ChannelsHandler.cpp b/libresapi/src/api/ChannelsHandler.cpp deleted file mode 100644 index 01000f7d0..000000000 --- a/libresapi/src/api/ChannelsHandler.cpp +++ /dev/null @@ -1,540 +0,0 @@ -/******************************************************************************* - * libresapi/api/ChannelsHandler.cpp * - * * - * LibResAPI: API for local socket server * - * * - * Copyright 2018 by Gioacchino Mazzurco * - * * - * This program is free software: you can redistribute it and/or modify * - * it under the terms of the GNU Affero General Public License as * - * published by the Free Software Foundation, either version 3 of the * - * License, or (at your option) any later version. * - * * - * This program is distributed in the hope that it will be useful, * - * but WITHOUT ANY WARRANTY; without even the implied warranty of * - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * - * GNU Affero General Public License for more details. * - * * - * You should have received a copy of the GNU Affero General Public License * - * along with this program. If not, see . * - * * - *******************************************************************************/ - -#include "ChannelsHandler.h" - -#include -#include -#include -#include -#include - -#include "Operators.h" - -namespace resource_api -{ - -StreamBase& operator << (StreamBase& left, RsGxsFile& file) -{ - left << makeKeyValueReference("name", file.mName) - << makeKeyValueReference("hash", file.mHash); - if(left.serialise()) - { - double size = file.mSize; - left << makeKeyValueReference("size", size); - } - else - { - double size = 0; - left << makeKeyValueReference("size", size); - file.mSize = size; - } - return left; -} - -ChannelsHandler::ChannelsHandler(RsGxsChannels& channels): mChannels(channels) -{ - addResourceHandler("list_channels", this, - &ChannelsHandler::handleListChannels); - addResourceHandler("get_channel_info", this, &ChannelsHandler::handleGetChannelInfo); - addResourceHandler("get_channel_content", this, &ChannelsHandler::handleGetChannelContent); - addResourceHandler("toggle_subscribe", this, &ChannelsHandler::handleToggleSubscription); - addResourceHandler("toggle_auto_download", this, &ChannelsHandler::handleToggleAutoDownload); - addResourceHandler("toggle_read", this, &ChannelsHandler::handleTogglePostRead); - addResourceHandler("create_channel", this, &ChannelsHandler::handleCreateChannel); - addResourceHandler("create_post", this, &ChannelsHandler::handleCreatePost); -} - -void ChannelsHandler::handleListChannels(Request& /*req*/, Response& resp) -{ - RsTokReqOptions opts; - opts.mReqType = GXS_REQUEST_TYPE_GROUP_META; - uint32_t token; - - RsTokenService& tChannels = *mChannels.getTokenService(); - - tChannels.requestGroupInfo(token, RS_DEPRECATED_TOKREQ_ANSTYPE, opts); - - time_t start = time(NULL); - while((tChannels.requestStatus(token) != RsTokenService::COMPLETE) - &&(tChannels.requestStatus(token) != RsTokenService::FAILED) - &&((time(NULL) < (start+10)))) rstime::rs_usleep(500*1000); - - std::list grps; - if( tChannels.requestStatus(token) == RsTokenService::COMPLETE - && mChannels.getGroupSummary(token, grps) ) - { - for( RsGroupMetaData& grp : grps ) - { - KeyValueReference id("channel_id", grp.mGroupId); - KeyValueReference vis_msg("visible_msg_count", grp.mVisibleMsgCount); - bool own = (grp.mSubscribeFlags & GXS_SERV::GROUP_SUBSCRIBE_ADMIN); - bool subscribed = IS_GROUP_SUBSCRIBED(grp.mSubscribeFlags); - std::string lastPostTsStr = std::to_string(grp.mLastPost); - std::string publishTsStr = std::to_string(grp.mPublishTs); - resp.mDataStream.getStreamToMember() - << id - << makeKeyValueReference("name", grp.mGroupName) - << makeKeyValueReference("last_post_ts", lastPostTsStr) - << makeKeyValueReference("popularity", grp.mPop) - << makeKeyValueReference("publish_ts", publishTsStr) - << vis_msg - << makeKeyValueReference("group_status", grp.mGroupStatus) - << makeKeyValueReference("author_id", grp.mAuthorId) - << makeKeyValueReference("parent_grp_id", grp.mParentGrpId) - << makeKeyValueReference("own", own) - << makeKeyValueReference("subscribed", subscribed); - } - - resp.setOk(); - } - else resp.setFail("Cant get data from GXS!"); -} - -void ChannelsHandler::handleGetChannelInfo(Request& req, Response& resp) -{ - std::string chanIdStr; - req.mStream << makeKeyValueReference("channel_id", chanIdStr); - if(chanIdStr.empty()) - { - resp.setFail("channel_id required!"); - return; - } - - RsGxsGroupId chanId(chanIdStr); - if(chanId.isNull()) - { - resp.setFail("Invalid channel_id:" + chanIdStr); - return; - } - - bool wantThumbnail = true; - req.mStream << makeKeyValueReference("want_thumbnail", wantThumbnail); - - std::list groupIds; groupIds.push_back(chanId); - RsTokReqOptions opts; - opts.mReqType = GXS_REQUEST_TYPE_GROUP_DATA; - uint32_t token; - - RsTokenService& tChannels = *mChannels.getTokenService(); - tChannels.requestGroupInfo( token, RS_DEPRECATED_TOKREQ_ANSTYPE, - opts, groupIds ); - - time_t start = time(NULL); - while((tChannels.requestStatus(token) != RsTokenService::COMPLETE) - &&(tChannels.requestStatus(token) != RsTokenService::FAILED) - &&((time(NULL) < (start+10)))) rstime::rs_usleep(500*1000); - - std::vector grps; - if( tChannels.requestStatus(token) == RsTokenService::COMPLETE - && mChannels.getGroupData(token, grps) ) - { - for( RsGxsChannelGroup& grp : grps ) - { - KeyValueReference id("channel_id", grp.mMeta.mGroupId); - KeyValueReference vis_msg("visible_msg_count", grp.mMeta.mVisibleMsgCount); - bool own = (grp.mMeta.mSubscribeFlags & GXS_SERV::GROUP_SUBSCRIBE_ADMIN); - bool subscribed = IS_GROUP_SUBSCRIBED(grp.mMeta.mSubscribeFlags); - std::string lastPostTsStr = std::to_string(grp.mMeta.mLastPost); - std::string publishTsStr = std::to_string(grp.mMeta.mPublishTs); - StreamBase& rgrp(resp.mDataStream.getStreamToMember()); - rgrp << id - << makeKeyValueReference("name", grp.mMeta.mGroupName) - << makeKeyValueReference("last_post_ts", lastPostTsStr) - << makeKeyValueReference("popularity", grp.mMeta.mPop) - << makeKeyValueReference("publish_ts", publishTsStr) - << vis_msg - << makeKeyValueReference("group_status", grp.mMeta.mGroupStatus) - << makeKeyValueReference("author_id", grp.mMeta.mAuthorId) - << makeKeyValueReference("parent_grp_id", grp.mMeta.mParentGrpId) - << makeKeyValueReference("description", grp.mDescription) - << makeKeyValueReference("own", own) - << makeKeyValueReference("subscribed", subscribed) - << makeKeyValueReference("auto_download", grp.mAutoDownload); - - if(wantThumbnail) - { - std::string thumbnail_base64; - Radix64::encode(grp.mImage.mData, grp.mImage.mSize, thumbnail_base64); - rgrp << makeKeyValueReference("thumbnail_base64_png", thumbnail_base64); - } - } - - resp.setOk(); - } - else resp.setFail("Cant get data from GXS!"); -} - -void ChannelsHandler::handleGetChannelContent(Request& req, Response& resp) -{ - std::string chanIdStr; - req.mStream << makeKeyValueReference("channel_id", chanIdStr); - if(chanIdStr.empty()) - { - resp.setFail("channel_id required!"); - return; - } - - RsGxsGroupId chanId(chanIdStr); - if(chanId.isNull()) - { - resp.setFail("Invalid channel_id:" + chanIdStr); - return; - } - - std::list groupIds; groupIds.push_back(chanId); - uint32_t token; - RsTokReqOptions opts; - opts.mReqType = GXS_REQUEST_TYPE_MSG_DATA; - - if(! mChannels.getTokenService()-> - requestMsgInfo(token, RS_TOKREQ_ANSTYPE_DATA, opts, groupIds) ) - { - resp.setFail("Unknown GXS error!"); - return; - } - - time_t start = time(NULL); - while((mChannels.getTokenService()->requestStatus(token) != RsTokenService::COMPLETE) - &&(mChannels.getTokenService()->requestStatus(token) != RsTokenService::FAILED) - &&((time(NULL) < (start+10)))) rstime::rs_usleep(500*1000); - - std::vector posts; - std::vector comments; - if( mChannels.getTokenService()->requestStatus(token) == - RsTokenService::COMPLETE && - mChannels.getPostData(token, posts, comments) ) - { - for( std::vector::iterator vit = posts.begin(); - vit != posts.end(); ++vit ) - { - RsGxsChannelPost& post = *vit; - RsMsgMetaData& pMeta = post.mMeta; - resp.mDataStream.getStreamToMember() - << makeKeyValueReference("channel_id", pMeta.mGroupId) - << makeKeyValueReference("name", pMeta.mMsgName) - << makeKeyValueReference("post_id", pMeta.mMsgId) - << makeKeyValueReference("parent_id", pMeta.mParentId) - << makeKeyValueReference("author_id", pMeta.mAuthorId) - << makeKeyValueReference("orig_msg_id", pMeta.mOrigMsgId) - << makeKeyValueReference("thread_id", pMeta.mThreadId) - << makeKeyValueReference("message", post.mMsg); - } - - for( std::vector::iterator vit = comments.begin(); - vit != comments.end(); ++vit ) - { - RsGxsComment& comment = *vit; - RsMsgMetaData& cMeta = comment.mMeta; - std::string scoreStr = std::to_string(comment.mScore); - resp.mDataStream.getStreamToMember() - << makeKeyValueReference("channel_id", cMeta.mGroupId) - << makeKeyValueReference("name", cMeta.mMsgName) - << makeKeyValueReference("comment_id", cMeta.mMsgId) - << makeKeyValueReference("parent_id", cMeta.mParentId) - << makeKeyValueReference("author_id", cMeta.mAuthorId) - << makeKeyValueReference("orig_msg_id", cMeta.mOrigMsgId) - << makeKeyValueReference("thread_id", cMeta.mThreadId) - << makeKeyValueReference("score", scoreStr) - << makeKeyValueReference("message", comment.mComment); - } - - resp.setOk(); - } - else resp.setFail("Cant get data from GXS!"); -} - -void ChannelsHandler::handleToggleSubscription(Request& req, Response& resp) -{ - std::string chanIdStr; - bool subscribe = true; - - req.mStream << makeKeyValueReference("channel_id", chanIdStr) - << makeKeyValueReference("subscribe", subscribe); - - if(chanIdStr.empty()) - { - resp.setFail("channel_id required!"); - return; - } - - RsGxsGroupId chanId(chanIdStr); - if(chanId.isNull()) - { - resp.setFail("Invalid channel_id:" + chanIdStr); - return; - } - - uint32_t token; - if(mChannels.subscribeToGroup(token, chanId, subscribe)) - { - RsTokenService& tChannels = *mChannels.getTokenService(); - - time_t start = time(NULL); - while((tChannels.requestStatus(token) != RsTokenService::COMPLETE) - &&(tChannels.requestStatus(token) != RsTokenService::FAILED) - &&((time(NULL) < (start+10)))) rstime::rs_usleep(500*1000); - - if(tChannels.requestStatus(token) == RsTokenService::COMPLETE) - resp.setOk(); - else resp.setFail("Unknown GXS error!"); - } - else resp.setFail("Unknown GXS error!"); -} - -void ChannelsHandler::handleCreateChannel(Request& req, Response& resp) -{ - RsGxsChannelGroup chan; - RsGroupMetaData& cMeta = chan.mMeta; - std::string authorIdStr; - std::string thumbnail_base64; - - req.mStream << makeKeyValueReference("author_id", authorIdStr) - << makeKeyValueReference("name", cMeta.mGroupName) - << makeKeyValueReference("description", chan.mDescription) - << makeKeyValueReference("thumbnail_base64_png", thumbnail_base64); - - if(cMeta.mGroupName.empty()) - { - resp.setFail("Channel name required!"); - return; - } - - if(thumbnail_base64.empty()) chan.mImage.clear(); - else - { - std::vector png_data = Radix64::decode(thumbnail_base64); - if(!png_data.empty()) - { - if(png_data.size() < 8) - { - resp.setFail("Decoded thumbnail_base64_png is smaller than 8 byte. This can't be a valid png file!"); - return; - } - uint8_t png_magic_number[] = {0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a}; - if(!std::equal(&png_magic_number[0],&png_magic_number[8],png_data.begin())) - { - resp.setFail("Decoded thumbnail_base64_png does not seem to be a png file. (Header is missing magic number)"); - return; - } - chan.mImage.copy(png_data.data(), png_data.size()); - } - } - - if(!authorIdStr.empty()) cMeta.mAuthorId = RsGxsId(authorIdStr); - - // ATM supports creating only public channels - cMeta.mGroupFlags = GXS_SERV::FLAG_PRIVACY_PUBLIC; - - // I am not sure about those flags I have reversed them with the debugger - // that gives 520 as value of this member when a channel with default - // options is created from Qt Gui - cMeta.mSignFlags = GXS_SERV::MSG_AUTHEN_CHILD_AUTHOR_SIGN | - GXS_SERV::FLAG_AUTHOR_AUTHENTICATION_REQUIRED; - - uint32_t token; - if(mChannels.createGroup(token, chan)) - { - RsTokenService& tChannels = *mChannels.getTokenService(); - - time_t start = time(NULL); - while((tChannels.requestStatus(token) != RsTokenService::COMPLETE) - &&(tChannels.requestStatus(token) != RsTokenService::FAILED) - &&((time(NULL) < (start+10)))) rstime::rs_usleep(500*1000); - - if(tChannels.requestStatus(token) == RsTokenService::COMPLETE) - resp.setOk(); - else resp.setFail("Unknown GXS error!"); - } - else resp.setFail("Unkown GXS error!"); -} - -void ChannelsHandler::handleToggleAutoDownload(Request& req, Response& resp) -{ - - std::string chanIdStr; - bool autoDownload = true; - - req.mStream << makeKeyValueReference("channel_id", chanIdStr) - << makeKeyValueReference("auto_download", autoDownload); - - if(chanIdStr.empty()) - { - resp.setFail("channel_id required!"); - return; - } - - RsGxsGroupId chanId(chanIdStr); - if(chanId.isNull()) - { - resp.setFail("Invalid channel_id:" + chanIdStr); - return; - } - - if(mChannels.setChannelAutoDownload(chanId, autoDownload)) - resp.setOk(); - else resp.setFail(); -} - -void ChannelsHandler::handleTogglePostRead(Request& req, Response& resp) -{ - std::string chanIdStr; - std::string postIdStr; - bool read = true; - - req.mStream << makeKeyValueReference("channel_id", chanIdStr) - << makeKeyValueReference("post_id", postIdStr) - << makeKeyValueReference("read", read); - - if(chanIdStr.empty()) - { - resp.setFail("channel_id required!"); - return; - } - - RsGxsGroupId chanId(chanIdStr); - if(chanId.isNull()) - { - resp.setFail("Invalid channel_id:" + chanIdStr); - return; - } - - if(postIdStr.empty()) - { - resp.setFail("post_id required!"); - return; - } - - RsGxsMessageId postId(postIdStr); - if(postId.isNull()) - { - resp.setFail("Invalid post_id:" + postIdStr); - return; - } - - std::cerr << __PRETTY_FUNCTION__ << " " << chanIdStr << " " << postIdStr - << " " << read << std::endl; - - uint32_t token; - mChannels.setMessageReadStatus(token, std::make_pair(chanId,postId), read); - - RsTokenService& tChannels = *mChannels.getTokenService(); - - time_t start = time(NULL); - while((tChannels.requestStatus(token) != RsTokenService::COMPLETE) - &&(tChannels.requestStatus(token) != RsTokenService::FAILED) - &&((time(NULL) < (start+10)))) rstime::rs_usleep(500*1000); - - if(tChannels.requestStatus(token) == RsTokenService::COMPLETE) - resp.setOk(); - else resp.setFail("Unknown GXS error!"); -} - -void ChannelsHandler::handleCreatePost(Request &req, Response &resp) -{ - RsGxsChannelPost post; - - req.mStream << makeKeyValueReference("channel_id", post.mMeta.mGroupId); - req.mStream << makeKeyValueReference("subject", post.mMeta.mMsgName); - req.mStream << makeKeyValueReference("message", post.mMsg); - - StreamBase& file_array = req.mStream.getStreamToMember("files"); - while(file_array.hasMore()) - { - RsGxsFile file; - file_array.getStreamToMember() << file; - post.mFiles.push_back(file); - } - - std::string thumbnail_base64; - req.mStream << makeKeyValueReference("thumbnail_base64_png", thumbnail_base64); - - if(post.mMeta.mGroupId.isNull()) - { - resp.setFail("groupd_id is null"); - return; - } - if(post.mMeta.mMsgName.empty()) - { - resp.setFail("subject is empty"); - return; - } - if(post.mMsg.empty()) - { - resp.setFail("msg text is empty"); - return; - } - // empty file list is ok, but files have to be valid - for(std::list::iterator lit = post.mFiles.begin(); lit != post.mFiles.end(); ++lit) - { - if(lit->mHash.isNull()) - { - resp.setFail("at least one file hash is empty"); - return; - } - if(lit->mName.empty()) - { - resp.setFail("at leats one file name is empty"); - return; - } - if(lit->mSize == 0) - { - resp.setFail("at least one file size is empty"); - return; - } - } - - std::vector png_data = Radix64::decode(thumbnail_base64); - if(!png_data.empty()) - { - if(png_data.size() < 8) - { - resp.setFail("Decoded thumbnail_base64_png is smaller than 8 byte. This can't be a valid png file!"); - return; - } - uint8_t png_magic_number[] = {0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a}; - if(!std::equal(&png_magic_number[0],&png_magic_number[8],png_data.begin())) - { - resp.setFail("Decoded thumbnail_base64_png does not seem to be a png file. (Header is missing magic number)"); - return; - } - post.mThumbnail.copy(png_data.data(), png_data.size()); - } - - uint32_t token; - if(mChannels.createPost(token, post)) - { - RsTokenService& tChannels = *mChannels.getTokenService(); - - time_t start = time(NULL); - while((tChannels.requestStatus(token) != RsTokenService::COMPLETE) - &&(tChannels.requestStatus(token) != RsTokenService::FAILED) - &&((time(NULL) < (start+10)))) rstime::rs_usleep(500*1000); - - if(tChannels.requestStatus(token) == RsTokenService::COMPLETE) - resp.setOk(); - else resp.setFail("Unknown GXS error!"); - } - else resp.setFail("Unknown GXS error!"); -} - -} // namespace resource_api diff --git a/libresapi/src/api/ChannelsHandler.h b/libresapi/src/api/ChannelsHandler.h deleted file mode 100644 index 3a731e321..000000000 --- a/libresapi/src/api/ChannelsHandler.h +++ /dev/null @@ -1,48 +0,0 @@ -/******************************************************************************* - * libresapi/api/ChannelsHandler.h * - * * - * LibResAPI: API for local socket server * - * * - * Copyright 2018 by Gioacchino Mazzurco * - * * - * This program is free software: you can redistribute it and/or modify * - * it under the terms of the GNU Affero General Public License as * - * published by the Free Software Foundation, either version 3 of the * - * License, or (at your option) any later version. * - * * - * This program is distributed in the hope that it will be useful, * - * but WITHOUT ANY WARRANTY; without even the implied warranty of * - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * - * GNU Affero General Public License for more details. * - * * - * You should have received a copy of the GNU Affero General Public License * - * along with this program. If not, see . * - * * - *******************************************************************************/ -#pragma once - -#include "ResourceRouter.h" - -class RsGxsChannels; - -namespace resource_api -{ - -struct ChannelsHandler : ResourceRouter -{ - ChannelsHandler(RsGxsChannels& channels); - -private: - void handleListChannels(Request& req, Response& resp); - void handleGetChannelInfo(Request& req, Response& resp); - void handleGetChannelContent(Request& req, Response& resp); - void handleToggleSubscription(Request& req, Response& resp); - void handleCreateChannel(Request& req, Response& resp); - void handleToggleAutoDownload(Request& req, Response& resp); - void handleTogglePostRead(Request& req, Response& resp); - void handleCreatePost(Request& req, Response& resp); - - RsGxsChannels& mChannels; -}; - -} // namespace resource_api diff --git a/libresapi/src/api/ChatHandler.cpp b/libresapi/src/api/ChatHandler.cpp deleted file mode 100644 index a266a8540..000000000 --- a/libresapi/src/api/ChatHandler.cpp +++ /dev/null @@ -1,1491 +0,0 @@ -/******************************************************************************* - * libresapi/api/ChatHandler.cpp * - * * - * LibResAPI: API for local socket server * - * * - * Copyright 2015 by electron128 * - * Copyright 2017 by Gioacchino Mazzurco * - * * - * This program is free software: you can redistribute it and/or modify * - * it under the terms of the GNU Affero General Public License as * - * published by the Free Software Foundation, either version 3 of the * - * License, or (at your option) any later version. * - * * - * This program is distributed in the hope that it will be useful, * - * but WITHOUT ANY WARRANTY; without even the implied warranty of * - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * - * GNU Affero General Public License for more details. * - * * - * You should have received a copy of the GNU Affero General Public License * - * along with this program. If not, see . * - * * - *******************************************************************************/ - -#include "ChatHandler.h" -#include "Pagination.h" -#include "Operators.h" -#include "GxsResponseTask.h" - -#include -#include -#include - -#include -#include -#include -#include - -namespace resource_api -{ - -std::string id(const ChatHandler::Msg& m) -{ - std::stringstream ss; - ss << m.id; - return ss.str(); -} - -StreamBase& operator << (StreamBase& left, ChatHandler::Msg& m) -{ - left << makeKeyValueReference("incoming", m.incoming) - << makeKeyValueReference("was_send", m.was_send) - << makeKeyValueReference("read", m.read) - << makeKeyValueReference("author_id", m.author_id) - << makeKeyValueReference("author_name", m.author_name) - << makeKeyValueReference("msg", m.msg) - << makeKeyValueReference("recv_time", m.recv_time) - << makeKeyValueReference("send_time", m.send_time) - << makeKeyValueReference("id", m.id); - StreamBase& ls = left.getStreamToMember("links"); - ls.getStreamToMember(); - for(std::vector::iterator vit = m.links.begin(); vit != m.links.end(); ++vit) - { - ls.getStreamToMember() << makeKeyValueReference("first", vit->first) - << makeKeyValueReference("second", vit->second) - << makeKeyValueReference("third", vit->third); - } - return left; -} - -bool compare_lobby_id(const ChatHandler::Lobby& l1, const ChatHandler::Lobby& l2) -{ - if(l1.auto_subscribe && !l2.auto_subscribe) return true; - if(!l1.auto_subscribe && l2.auto_subscribe) return false; - if(l1.is_private && !l2.is_private) return true; - if(!l1.is_private && l2.is_private) return false; - if(l1.subscribed && !l2.subscribed) return true; - if(!l1.subscribed && l2.subscribed) return false; - return l1.id < l2.id; -} - -StreamBase& operator <<(StreamBase& left, KeyValueReference kv) -{ - if(left.serialise()) - { - std::stringstream ss; - ss << kv.value; - left << makeKeyValue(kv.key, ss.str()); - } - else - { - std::string val; - left << makeKeyValueReference(kv.key, val); - std::stringstream ss(val); - ss >> kv.value; - } - return left; -} - -StreamBase& operator << (StreamBase& left, ChatHandler::Lobby& l) -{ - ChatId chatId(l.id); - if (l.is_broadcast) - chatId = ChatId::makeBroadcastId(); - left << makeKeyValueReference("id", l.id) - << makeKeyValue("chat_id", chatId.toStdString()) - << makeKeyValueReference("name",l.name) - << makeKeyValueReference("topic", l.topic) - << makeKeyValueReference("subscribed", l.subscribed) - << makeKeyValueReference("auto_subscribe", l.auto_subscribe) - << makeKeyValueReference("is_private", l.is_private) - << makeKeyValueReference("is_broadcast", l.is_broadcast) - << makeKeyValueReference("gxs_id", l.gxs_id); - return left; -} - -StreamBase& operator << (StreamBase& left, ChatHandler::ChatInfo& info) -{ - left << makeKeyValueReference("remote_author_id", info.remote_author_id) - << makeKeyValueReference("remote_author_name", info.remote_author_name) - << makeKeyValueReference("own_author_id", info.own_author_id) - << makeKeyValueReference("own_author_name", info.own_author_name) - << makeKeyValueReference("is_broadcast", info.is_broadcast) - << makeKeyValueReference("is_distant_chat_id", info.is_distant_chat_id) - << makeKeyValueReference("is_lobby", info.is_lobby) - << makeKeyValueReference("is_peer", info.is_peer); - return left; -} - -class SendLobbyParticipantsTask: public GxsResponseTask -{ -public: - SendLobbyParticipantsTask(RsIdentity* idservice, ChatHandler::LobbyParticipantsInfo pi): - GxsResponseTask(idservice, 0), mParticipantsInfo(pi) - { - const auto& map = mParticipantsInfo.participants; - for(auto mit = map.begin(); mit != map.end(); ++mit) - { - requestGxsId(mit->first); - } - } -private: - ChatHandler::LobbyParticipantsInfo mParticipantsInfo; -protected: - virtual void gxsDoWork(Request &/*req*/, Response &resp) - { - resp.mDataStream.getStreamToMember(); - const auto& map = mParticipantsInfo.participants; - for(auto mit = map.begin(); mit != map.end(); ++mit) - { - StreamBase& stream = resp.mDataStream.getStreamToMember(); - double last_active = mit->second; - stream << makeKeyValueReference("last_active", last_active); - streamGxsId(mit->first, stream.getStreamToMember("identity")); - } - resp.mStateToken = mParticipantsInfo.state_token; - resp.setOk(); - done(); - } - -}; - -ChatHandler::ChatHandler(StateTokenServer *sts, RsNotify *notify, RsMsgs *msgs, RsPeers* peers, RsIdentity* identity, UnreadMsgNotify* unread): - mStateTokenServer(sts), mNotify(notify), mRsMsgs(msgs), mRsPeers(peers), mRsIdentity(identity), mUnreadMsgNotify(unread), mMtx("ChatHandler::mMtx") -{ - mNotify->registerNotifyClient(this); - mStateTokenServer->registerTickClient(this); - - mMsgStateToken = mStateTokenServer->getNewToken(); - mLobbiesStateToken = mStateTokenServer->getNewToken(); - mUnreadMsgsStateToken = mStateTokenServer->getNewToken(); - mInvitationsStateToken = mStateTokenServer->getNewToken(); - - addResourceHandler("*", this, &ChatHandler::handleWildcard); - addResourceHandler("lobbies", this, &ChatHandler::handleLobbies); - addResourceHandler("create_lobby", this, &ChatHandler::handleCreateLobby); - addResourceHandler("subscribe_lobby", this, &ChatHandler::handleSubscribeLobby); - addResourceHandler("unsubscribe_lobby", this, &ChatHandler::handleUnsubscribeLobby); - addResourceHandler("autosubscribe_lobby", this, &ChatHandler::handleAutoSubsribeLobby); - addResourceHandler("clear_lobby", this, &ChatHandler::handleClearLobby); - addResourceHandler("invite_to_lobby", this, &ChatHandler::handleInviteToLobby); - addResourceHandler("get_invitations_to_lobby", this, &ChatHandler::handleGetInvitationsToLobby); - addResourceHandler("answer_to_invitation", this, &ChatHandler::handleAnswerToInvitation); - addResourceHandler("lobby_participants", this, &ChatHandler::handleLobbyParticipants); - addResourceHandler("get_default_identity_for_chat_lobby", this, &ChatHandler::handleGetDefaultIdentityForChatLobby); - addResourceHandler("set_default_identity_for_chat_lobby", this, &ChatHandler::handleSetDefaultIdentityForChatLobby); - addResourceHandler("get_identity_for_chat_lobby", this, &ChatHandler::handleGetIdentityForChatLobby); - addResourceHandler("set_identity_for_chat_lobby", this, &ChatHandler::handleSetIdentityForChatLobby); - addResourceHandler("messages", this, &ChatHandler::handleMessages); - addResourceHandler("send_message", this, &ChatHandler::handleSendMessage); - addResourceHandler("mark_message_as_read", this, &ChatHandler::handleMarkMessageAsRead); - addResourceHandler("mark_chat_as_read", this, &ChatHandler::handleMarkChatAsRead); - addResourceHandler("info", this, &ChatHandler::handleInfo); - addResourceHandler("receive_status", this, &ChatHandler::handleReceiveStatus); - addResourceHandler("send_status", this, &ChatHandler::handleSendStatus); - addResourceHandler("unread_msgs", this, &ChatHandler::handleUnreadMsgs); - addResourceHandler("initiate_distant_chat", this, &ChatHandler::handleInitiateDistantChatConnexion); - addResourceHandler("distant_chat_status", this, &ChatHandler::handleDistantChatStatus); - addResourceHandler("close_distant_chat", this, &ChatHandler::handleCloseDistantChatConnexion); -} - -ChatHandler::~ChatHandler() -{ - mNotify->unregisterNotifyClient(this); - mStateTokenServer->unregisterTickClient(this); -} - -void ChatHandler::notifyChatMessage(const ChatMessage &msg) -{ - RS_STACK_MUTEX(mMtx); // ********** LOCKED ********** - mRawMsgs.push_back(msg); -} - -void ChatHandler::notifyChatCleared(const ChatId &chat_id) -{ - RS_STACK_MUTEX(mMtx); // ********** LOCKED ********** - //Remove processed messages - std::list& msgs = mMsgs[chat_id]; - msgs.clear(); - //Remove unprocessed messages - for(std::list::iterator lit = mRawMsgs.begin(); lit != mRawMsgs.end();) - { - ChatMessage& msg = *lit; - if (msg.chat_id == chat_id) - { - lit = mRawMsgs.erase(lit); - } else { - ++lit; - } - } -} - -void ChatHandler::notifyChatStatus(const ChatId &chat_id, const std::string &status) -{ - RS_STACK_MUTEX(mMtx); // ********** LOCKED ********** - locked_storeTypingInfo(chat_id, status); -} - -void ChatHandler::notifyChatLobbyEvent(uint64_t lobby_id, uint32_t event_type, - const RsGxsId &nickname, const std::string& any_string) -{ - RS_STACK_MUTEX(mMtx); // ********** LOCKED ********** - if(event_type == RS_CHAT_LOBBY_EVENT_PEER_STATUS) - { - locked_storeTypingInfo(ChatId(lobby_id), any_string, nickname); - } -} - -void ChatHandler::notifyListChange(int list, int /*type*/) -{ - if(list == NOTIFY_LIST_CHAT_LOBBY_INVITATION) - { - RS_STACK_MUTEX(mMtx); // ********** LOCKED ********** - mStateTokenServer->replaceToken(mInvitationsStateToken); - } -} - -void ChatHandler::tick() -{ - RS_STACK_MUTEX(mMtx); // ********** LOCKED ********** - - // first fetch lobbies - std::vector lobbies; - std::list subscribed_ids; - mRsMsgs->getChatLobbyList(subscribed_ids); - for(std::list::iterator lit = subscribed_ids.begin(); lit != subscribed_ids.end(); ++lit) - { - ChatLobbyInfo info; - if(mRsMsgs->getChatLobbyInfo(*lit,info)) - { - Lobby l; - l.id = *lit; - l.name = info.lobby_name; - l.topic = info.lobby_topic; - l.subscribed = true; - l.auto_subscribe = info.lobby_flags & RS_CHAT_LOBBY_FLAGS_AUTO_SUBSCRIBE; - l.is_private = !(info.lobby_flags & RS_CHAT_LOBBY_FLAGS_PUBLIC); - l.is_broadcast = false; - l.gxs_id = info.gxs_id; - lobbies.push_back(l); - - // update the lobby participants list - // maybe it causes to much traffic to do this in every tick, - // because the client would get the whole list every time a message was received - // we could reduce the checking frequency - std::map::iterator mit = mLobbyParticipantsInfos.find(*lit); - if(mit == mLobbyParticipantsInfos.end()) - { - mLobbyParticipantsInfos[*lit].participants = info.gxs_ids; - mLobbyParticipantsInfos[*lit].state_token = mStateTokenServer->getNewToken(); - } - else - { - LobbyParticipantsInfo& pi = mit->second; - if(!std::equal(pi.participants.begin(), pi.participants.end(), info.gxs_ids.begin()) - || pi.participants.size() != info.gxs_ids.size()) - { - pi.participants = info.gxs_ids; - mStateTokenServer->replaceToken(pi.state_token); - } - } - } - } - - // remove participants info of old lobbies - std::vector participants_info_to_delete; - for(std::map::iterator mit = mLobbyParticipantsInfos.begin(); - mit != mLobbyParticipantsInfos.end(); ++mit) - { - if(std::find(subscribed_ids.begin(), subscribed_ids.end(), mit->first) == subscribed_ids.end()) - { - participants_info_to_delete.push_back(mit->first); - } - } - for(std::vector::iterator vit = participants_info_to_delete.begin(); vit != participants_info_to_delete.end(); ++vit) - { - LobbyParticipantsInfo& pi = mLobbyParticipantsInfos[*vit]; - mStateTokenServer->discardToken(pi.state_token); - mLobbyParticipantsInfos.erase(*vit); - } - - { - Lobby l; - l.name = "BroadCast"; - l.topic = "Retroshare broadcast chat: messages are sent to all connected friends."; - l.subscribed = true; - l.auto_subscribe = false; - l.is_private = false; - l.is_broadcast = true; - lobbies.push_back(l); - } - - std::vector unsubscribed_lobbies; - mRsMsgs->getListOfNearbyChatLobbies(unsubscribed_lobbies); - for(std::vector::iterator vit = unsubscribed_lobbies.begin(); vit != unsubscribed_lobbies.end(); ++vit) - { - const VisibleChatLobbyRecord& info = *vit; - if(std::find(subscribed_ids.begin(), subscribed_ids.end(), info.lobby_id) == subscribed_ids.end()) - { - Lobby l; - l.id = info.lobby_id; - l.name = info.lobby_name; - l.topic = info.lobby_topic; - l.subscribed = false; - l.auto_subscribe = info.lobby_flags & RS_CHAT_LOBBY_FLAGS_AUTO_SUBSCRIBE; - l.is_private = !(info.lobby_flags & RS_CHAT_LOBBY_FLAGS_PUBLIC); - l.is_broadcast = false; - l.gxs_id = RsGxsId(); - lobbies.push_back(l); - } - } - - // process new messages - bool changed = false; - bool lobby_unread_count_changed = false; - std::vector::iterator> done; - std::vector peers_changed; - - bool gxs_id_failed = false; // to prevent asking for multiple failing gxs ids in one tick, to not flush the cache - - for(std::list::iterator lit = mRawMsgs.begin(); lit != mRawMsgs.end(); ++lit) - { - ChatMessage& msg = *lit; - std::string author_id; - std::string author_name; - if(msg.chat_id.isBroadcast()) - { - author_id = msg.broadcast_peer_id.toStdString(); - author_name = mRsPeers->getPeerName(msg.broadcast_peer_id); - } - else if(msg.chat_id.isDistantChatId()) - { - DistantChatPeerInfo dcpinfo ; - - if(!rsMsgs->getDistantChatStatus(msg.chat_id.toDistantChatId(),dcpinfo)) - { - std::cerr << "(EE) cannot get info for distant chat peer " << msg.chat_id.toDistantChatId() << std::endl; - continue ; - } - - RsIdentityDetails details; - if(!gxs_id_failed && mRsIdentity->getIdDetails(msg.incoming? dcpinfo.to_id: dcpinfo.own_id, details)) - { - author_id = details.mId.toStdString(); - author_name = details.mNickname; - } - else - { - gxs_id_failed = true; - continue; - } - } - else if(msg.chat_id.isLobbyId()) - { - author_id = msg.lobby_peer_gxs_id.toStdString(); - RsIdentityDetails details; - if(!gxs_id_failed && mRsIdentity->getIdDetails(msg.lobby_peer_gxs_id, details)) - { - author_name = details.mNickname; - lobby_unread_count_changed = true; - } - else - { - gxs_id_failed = true; - continue; - } - } - else if(msg.chat_id.isPeerId()) - { - RsPeerId id; - if(msg.incoming) - id = msg.chat_id.toPeerId(); - else - id = mRsPeers->getOwnId(); - author_id = id.toStdString(); - author_name = mRsPeers->getPeerName(id); - if(std::find(peers_changed.begin(), peers_changed.end(), msg.chat_id.toPeerId()) == peers_changed.end()) - peers_changed.push_back(msg.chat_id.toPeerId()); - } - else - { - std::cerr << "Error in ChatHandler::tick(): unhandled chat_id=" << msg.chat_id.toStdString() << std::endl; - // remove from queue, so msgs with wrong ids to not pile up - done.push_back(lit); - continue; - } - - if(mChatInfo.find(msg.chat_id) == mChatInfo.end()) - { - ChatInfo info; - info.is_broadcast = msg.chat_id.isBroadcast(); - info.is_distant_chat_id = msg.chat_id.isDistantChatId(); - info.is_lobby = msg.chat_id.isLobbyId(); - info.is_peer = msg.chat_id.isPeerId(); - if(msg.chat_id.isLobbyId()) - { - for(std::vector::iterator vit = mLobbies.begin(); vit != mLobbies.end(); ++vit) - { - if(vit->id == msg.chat_id.toLobbyId()) - info.remote_author_name = vit->name; - } - } - else if(msg.chat_id.isDistantChatId()) - { - RsIdentityDetails detailsRemoteIdentity; - RsIdentityDetails detailsOwnIdentity; - DistantChatPeerInfo dcpinfo; - - if( !gxs_id_failed && - rsMsgs->getDistantChatStatus( - msg.chat_id.toDistantChatId(), dcpinfo ) - && mRsIdentity->getIdDetails(dcpinfo.to_id, detailsRemoteIdentity) - && mRsIdentity->getIdDetails(dcpinfo.own_id, detailsOwnIdentity)) - { - info.remote_author_id = detailsRemoteIdentity.mId.toStdString(); - info.remote_author_name = detailsRemoteIdentity.mNickname; - - info.own_author_id = detailsOwnIdentity.mId.toStdString(); - info.own_author_name = detailsOwnIdentity.mNickname; - } - else - { - gxs_id_failed = true; - continue; - } - } - else if(msg.chat_id.isPeerId()) - { - info.remote_author_id = msg.chat_id.toPeerId().toStdString(); - info.remote_author_name = mRsPeers->getPeerName(msg.chat_id.toPeerId()); - } - mChatInfo[msg.chat_id] = info; - } - - Msg m; - m.read = !msg.incoming; - m.incoming = msg.incoming; - m.was_send = msg.online; - m.author_id = author_id; - m.author_name = author_name; - - // remove html tags from chat message - // extract links form href - getPlainText(msg.msg, m.msg, m.links); - m.recv_time = msg.recvTime; - m.send_time = msg.sendTime; - - m.id = RSRandom::random_u32(); - - mMsgs[msg.chat_id].push_back(m); - done.push_back(lit); - - changed = true; - } - for(std::vector::iterator>::iterator vit = done.begin(); vit != done.end(); ++vit) - mRawMsgs.erase(*vit); - - // send changes - - if(changed) - { - mStateTokenServer->replaceToken(mMsgStateToken); - mStateTokenServer->replaceToken(mUnreadMsgsStateToken); - } - - for(std::vector::iterator vit = peers_changed.begin(); vit != peers_changed.end(); ++vit) - { - const std::list& msgs = mMsgs[ChatId(*vit)]; - uint32_t count = 0; - for(std::list::const_iterator lit = msgs.begin(); lit != msgs.end(); ++lit) - if(!lit->read) - count++; - if(mUnreadMsgNotify) - mUnreadMsgNotify->notifyUnreadMsgCountChanged(*vit, count); - } - - std::sort(lobbies.begin(), lobbies.end(), &compare_lobby_id); - if(lobby_unread_count_changed || mLobbies != lobbies) - { - mStateTokenServer->replaceToken(mLobbiesStateToken); - mLobbies = lobbies; - } -} - -static void writeUTF8 ( std::ostream & Out, unsigned int Ch ) -/* writes Ch in UTF-8 encoding to Out. Note this version only deals - with characters up to 16 bits. - From: http://www.codecodex.com/wiki/Unescape_HTML_special_characters_from_a_String*/ -{ - if (Ch >= 0x800) - { - Out.put(0xE0 | ((Ch >> 12) & 0x0F)); - Out.put(0x80 | ((Ch >> 6) & 0x3F)); - Out.put(0x80 | ((Ch ) & 0x3F)); - } - else if (Ch >= 0x80) - { - Out.put(0xC0 | ((Ch >> 6) & 0x1F)); - Out.put(0x80 | ((Ch ) & 0x3F)); - } - else - { - Out.put(Ch); - } -} - -static unsigned int stringToDecUInt ( std::string str) -{ - unsigned int out = 0; - unsigned int max = std::numeric_limits::max() / 10; - int lenght = str.length(); - for (int curs = 0; curs < lenght; ++curs) { - char c = str[curs]; - if ( (c >= '0') - && (c <= '9') - && (out < max) - ) { - out *= 10; - out += (int)( c - '0'); - } else return 0; - } - return out; -} - -void ChatHandler::getPlainText(const std::string& in, std::string &out, std::vector &links) -{ - if (in.size() == 0) - return; - - if (in[0] != '<' || in[in.size() - 1] != '>') - { - // It's a plain text message without HTML - out = in; - return; - } - bool ignore = false; - - bool keep_link = false; - std::string last_six_chars; - unsigned int tag_start_index = 0; - Triple current_link; - bool onEscapeChar = false; - unsigned int escapeCharIndexStart = -1; - - for(unsigned int i = 0; i < in.size(); ++i) - { - if(keep_link && in[i] == '"') - { - keep_link = false; - current_link.second = out.size(); - } - if(last_six_chars == "href=\"") - { - keep_link = true; - current_link.first = out.size(); - } - - // "rising edge" sets mode to ignore - if(in[i] == '<') - { - tag_start_index = i; - ignore = true; - } - if(!ignore || keep_link) - out += in[i]; - // "falling edge" resets mode to keep - if(in[i] == '>' && ignore) { - // leave ignore mode on, if it's a style tag - if (tag_start_index == 0 || tag_start_index + 6 > i || in.substr(tag_start_index, 6) != " 6) - last_six_chars = last_six_chars.substr(1); - std::string a = ""; - if( current_link.first != -1 - && last_six_chars.size() >= a.size() - && last_six_chars.substr(last_six_chars.size()-a.size()) == a) - { - // only allow these protocols - // we don't want for example javascript:alert(0) - std::string http = "http://"; - std::string https = "https://"; - std::string retroshare = "retroshare://"; - if( out.substr(current_link.first, http.size()) == http - || out.substr(current_link.first, https.size()) == https - || out.substr(current_link.first, retroshare.size()) == retroshare) - { - current_link.third = out.size(); - links.push_back(current_link); - } - current_link = Triple(); - } - std::string br = "
"; - if(last_six_chars.size() >= br.size() - && last_six_chars.substr(last_six_chars.size()-br.size()) == br) - { - out += "\n"; - } - if (in[i] == '&') { - onEscapeChar = true; - escapeCharIndexStart = out.length(); - } - if (ignore || keep_link) { - onEscapeChar = false; - escapeCharIndexStart = -1; - } - if ((in[i] == ';') && onEscapeChar) { - onEscapeChar = false; - bool escapeFound = true; - std::string escapeReplace = ""; - //Keep only escape value to replace it - std::string escapeCharValue = out.substr(escapeCharIndexStart, - out.length() - escapeCharIndexStart - 1); - if (escapeCharValue[0] == '#') { - int escapedCharUTF8 = stringToDecUInt(escapeCharValue.substr(1)); - std::ostringstream escapedSStream; - writeUTF8( escapedSStream, escapedCharUTF8); - escapeReplace = escapedSStream.str(); - } else if (escapeCharValue == "euro") { - escapeReplace = "€"; - } else if (escapeCharValue == "nbsp") { - escapeReplace = " "; - } else if (escapeCharValue == "quot") { - escapeReplace = "\""; - } else if (escapeCharValue == "amp") { - escapeReplace = "&"; - } else if (escapeCharValue == "lt") { - escapeReplace = "<"; - } else if (escapeCharValue == "gt") { - escapeReplace = ">"; - } else if (escapeCharValue == "iexcl") { - escapeReplace = "¡"; - } else if (escapeCharValue == "cent") { - escapeReplace = "¢"; - } else if (escapeCharValue == "pound") { - escapeReplace = "£"; - } else if (escapeCharValue == "curren") { - escapeReplace = "¤"; - } else if (escapeCharValue == "yen") { - escapeReplace = "¥"; - } else if (escapeCharValue == "brvbar") { - escapeReplace = "¦"; - } else if (escapeCharValue == "sect") { - escapeReplace = "§"; - } else if (escapeCharValue == "uml") { - escapeReplace = "¨"; - } else if (escapeCharValue == "copy") { - escapeReplace = "©"; - } else if (escapeCharValue == "ordf") { - escapeReplace = "ª"; - } else if (escapeCharValue == "not") { - escapeReplace = "¬"; - } else if (escapeCharValue == "shy") { - escapeReplace = " ";//? - } else if (escapeCharValue == "reg") { - escapeReplace = "®"; - } else if (escapeCharValue == "macr") { - escapeReplace = "¯"; - } else if (escapeCharValue == "deg") { - escapeReplace = "°"; - } else if (escapeCharValue == "plusmn") { - escapeReplace = "±"; - } else if (escapeCharValue == "sup2") { - escapeReplace = "²"; - } else if (escapeCharValue == "sup3") { - escapeReplace = "³"; - } else if (escapeCharValue == "acute") { - escapeReplace = "´"; - } else if (escapeCharValue == "micro") { - escapeReplace = "µ"; - } else if (escapeCharValue == "para") { - escapeReplace = "¶"; - } else if (escapeCharValue == "middot") { - escapeReplace = "·"; - } else if (escapeCharValue == "cedil") { - escapeReplace = "¸"; - } else if (escapeCharValue == "sup1") { - escapeReplace = "¹"; - } else if (escapeCharValue == "ordm") { - escapeReplace = "º"; - } else if (escapeCharValue == "raquo") { - escapeReplace = "»"; - } else if (escapeCharValue == "frac14") { - escapeReplace = "¼"; - } else if (escapeCharValue == "frac12") { - escapeReplace = "½"; - } else if (escapeCharValue == "frac34") { - escapeReplace = "¾"; - } else if (escapeCharValue == "iquest") { - escapeReplace = "¿"; - } else if (escapeCharValue == "Agrave") { - escapeReplace = "À"; - } else if (escapeCharValue == "Aacute") { - escapeReplace = "Á"; - } else if (escapeCharValue == "Acirc") { - escapeReplace = "Â"; - } else if (escapeCharValue == "Atilde") { - escapeReplace = "Ã"; - } else if (escapeCharValue == "Auml") { - escapeReplace = "Ä"; - } else if (escapeCharValue == "Aring") { - escapeReplace = "Å"; - } else if (escapeCharValue == "AElig") { - escapeReplace = "Æ"; - } else if (escapeCharValue == "Ccedil") { - escapeReplace = "Ç"; - } else if (escapeCharValue == "Egrave") { - escapeReplace = "È"; - } else if (escapeCharValue == "Eacute") { - escapeReplace = "É"; - } else if (escapeCharValue == "Ecirc") { - escapeReplace = "Ê"; - } else if (escapeCharValue == "Euml") { - escapeReplace = "Ë"; - } else if (escapeCharValue == "Igrave") { - escapeReplace = "Ì"; - } else if (escapeCharValue == "Iacute") { - escapeReplace = "Í"; - } else if (escapeCharValue == "Icirc") { - escapeReplace = "Î"; - } else if (escapeCharValue == "Iuml") { - escapeReplace = "Ï"; - } else if (escapeCharValue == "ETH") { - escapeReplace = "Ð"; - } else if (escapeCharValue == "Ntilde") { - escapeReplace = "Ñ"; - } else if (escapeCharValue == "Ograve") { - escapeReplace = "Ò"; - } else if (escapeCharValue == "Oacute") { - escapeReplace = "Ó"; - } else if (escapeCharValue == "Ocirc") { - escapeReplace = "Ô"; - } else if (escapeCharValue == "Otilde") { - escapeReplace = "Õ"; - } else if (escapeCharValue == "Ouml") { - escapeReplace = "Ö"; - } else if (escapeCharValue == "times") { - escapeReplace = "×"; - } else if (escapeCharValue == "Oslash") { - escapeReplace = "Ø"; - } else if (escapeCharValue == "Ugrave") { - escapeReplace = "Ù"; - } else if (escapeCharValue == "Uacute") { - escapeReplace = "Ú"; - } else if (escapeCharValue == "Ucirc") { - escapeReplace = "Û"; - } else if (escapeCharValue == "Uuml") { - escapeReplace = "Ü"; - } else if (escapeCharValue == "Yacute") { - escapeReplace = "Ý"; - } else if (escapeCharValue == "THORN") { - escapeReplace = "Þ"; - } else if (escapeCharValue == "szlig") { - escapeReplace = "ß"; - } else if (escapeCharValue == "agrave") { - escapeReplace = "à"; - } else if (escapeCharValue == "aacute") { - escapeReplace = "á"; - } else if (escapeCharValue == "acirc") { - escapeReplace = "â"; - } else if (escapeCharValue == "atilde") { - escapeReplace = "ã"; - } else if (escapeCharValue == "auml") { - escapeReplace = "ä"; - } else if (escapeCharValue == "aring") { - escapeReplace = "å"; - } else if (escapeCharValue == "aelig") { - escapeReplace = "æ"; - } else if (escapeCharValue == "ccedil") { - escapeReplace = "ç"; - } else if (escapeCharValue == "egrave") { - escapeReplace = "è"; - } else if (escapeCharValue == "eacute") { - escapeReplace = "é"; - } else if (escapeCharValue == "ecirc") { - escapeReplace = "ê"; - } else if (escapeCharValue == "euml") { - escapeReplace = "ë"; - } else if (escapeCharValue == "igrave") { - escapeReplace = "ì"; - } else if (escapeCharValue == "iacute") { - escapeReplace = "í"; - } else if (escapeCharValue == "icirc") { - escapeReplace = "î"; - } else if (escapeCharValue == "iuml") { - escapeReplace = "ï"; - } else if (escapeCharValue == "eth") { - escapeReplace = "ð"; - } else if (escapeCharValue == "ntilde") { - escapeReplace = "ñ"; - } else if (escapeCharValue == "ograve") { - escapeReplace = "ò"; - } else if (escapeCharValue == "oacute") { - escapeReplace = "ó"; - } else if (escapeCharValue == "ocirc") { - escapeReplace = "ô"; - } else if (escapeCharValue == "otilde") { - escapeReplace = "õ"; - } else if (escapeCharValue == "ouml") { - escapeReplace = "ö"; - } else if (escapeCharValue == "divide") { - escapeReplace = "÷"; - } else if (escapeCharValue == "oslash") { - escapeReplace = "ø"; - } else if (escapeCharValue == "ugrave") { - escapeReplace = "ù"; - } else if (escapeCharValue == "uacute") { - escapeReplace = "ú"; - } else if (escapeCharValue == "ucirc") { - escapeReplace = "û"; - } else if (escapeCharValue == "uuml") { - escapeReplace = "ü"; - } else if (escapeCharValue == "yacute") { - escapeReplace = "ý"; - } else if (escapeCharValue == "thorn") { - escapeReplace = "þ"; - } else { - escapeFound = false; - } - if (escapeFound) { - out = out.substr(0, escapeCharIndexStart-1); - out += escapeReplace; - } - } - } -} - -void ChatHandler::locked_storeTypingInfo(const ChatId &chat_id, std::string status, RsGxsId lobby_gxs_id) -{ - TypingLabelInfo& info = mTypingLabelInfo[chat_id]; - info.timestamp = time(0); - info.status = status; - mStateTokenServer->replaceToken(info.state_token); - info.author_id = lobby_gxs_id; -} - -void ChatHandler::handleWildcard(Request &/*req*/, Response &resp) -{ - RS_STACK_MUTEX(mMtx); // ********** LOCKED ********** - resp.mDataStream.getStreamToMember(); - for(std::map >::iterator mit = mMsgs.begin(); mit != mMsgs.end(); ++mit) - { - resp.mDataStream.getStreamToMember() << makeValue(mit->first.toStdString()); - } - resp.setOk(); -} - -void ChatHandler::handleLobbies(Request &/*req*/, Response &resp) -{ - tick(); - - { - RS_STACK_MUTEX(mMtx); // ********** LOCKED ********** - resp.mDataStream.getStreamToMember(); - for(std::vector::iterator vit = mLobbies.begin(); vit != mLobbies.end(); ++vit) - { - uint32_t unread_msgs = 0; - ChatId chat_id(vit->id); - std::map >::iterator mit = mMsgs.find(chat_id); - if(mit != mMsgs.end()) - { - std::list& msgs = mit->second; - for(std::list::iterator lit = msgs.begin(); lit != msgs.end(); ++lit) - if(!lit->read) - unread_msgs++; - } - resp.mDataStream.getStreamToMember() << *vit << makeKeyValueReference("unread_msg_count", unread_msgs); - } - resp.mStateToken = mLobbiesStateToken; - } - resp.setOk(); -} - -void ChatHandler::handleSubscribeLobby(Request &req, Response &resp) -{ - ChatLobbyId id = 0; - RsGxsId gxs_id; - req.mStream << makeKeyValueReference("id", id) << makeKeyValueReference("gxs_id", gxs_id); - - if(id == 0) - { - resp.setFail("Error: id must not be null"); - return; - } - if(gxs_id.isNull()) - { - resp.setFail("Error: gxs_id must not be null"); - return; - } - if(mRsMsgs->joinVisibleChatLobby(id, gxs_id)) - resp.setOk(); - else - resp.setFail("lobby join failed. (See console for more info)"); -} - -void ChatHandler::handleUnsubscribeLobby(Request &req, Response &resp) -{ - ChatLobbyId id = 0; - req.mStream << makeKeyValueReference("id", id); - mRsMsgs->unsubscribeChatLobby(id); - resp.setOk(); -} - -void ChatHandler::handleAutoSubsribeLobby(Request& req, Response& resp) -{ - ChatLobbyId chatId = 0; - bool autosubsribe; - req.mStream << makeKeyValueReference("chatid", chatId) << makeKeyValueReference("autosubsribe", autosubsribe); - mRsMsgs->setLobbyAutoSubscribe(chatId, autosubsribe); - resp.setOk(); -} - -void ChatHandler::handleClearLobby(Request &req, Response &resp) -{ - ChatLobbyId id = 0; - req.mStream << makeKeyValueReference("id", id); - if (id !=0) { - notifyChatCleared(ChatId(id)); - } else { - //Is BroadCast - notifyChatCleared(ChatId("B")); - } - resp.setOk(); -} - -void ChatHandler::handleInviteToLobby(Request& req, Response& resp) -{ - std::string chat_id; - std::string pgp_id; - req.mStream << makeKeyValueReference("chat_id", chat_id); - req.mStream << makeKeyValueReference("pgp_id", pgp_id); - - ChatId chatId(chat_id); - RsPgpId pgpId(pgp_id); - - std::list peerIds; - mRsPeers->getAssociatedSSLIds(pgpId, peerIds); - - for(std::list::iterator it = peerIds.begin(); it != peerIds.end(); it++) - mRsMsgs->invitePeerToLobby(chatId.toLobbyId(), (*it)); - - resp.setOk(); -} - -void ChatHandler::handleGetInvitationsToLobby(Request& /*req*/, Response& resp) -{ - std::list invites; - mRsMsgs->getPendingChatLobbyInvites(invites); - - resp.mDataStream.getStreamToMember(); - for(std::list::const_iterator it = invites.begin(); it != invites.end(); ++it) - { - resp.mDataStream.getStreamToMember() - << makeKeyValue("peer_id", (*it).peer_id.toStdString()) - << makeKeyValue("lobby_id", (*it).lobby_id) - << makeKeyValue("lobby_name", (*it).lobby_name) - << makeKeyValue("lobby_topic", (*it).lobby_topic); - } - - resp.mStateToken = mInvitationsStateToken; - resp.setOk(); -} - -void ChatHandler::handleAnswerToInvitation(Request& req, Response& resp) -{ - ChatLobbyId lobbyId = 0; - req.mStream << makeKeyValueReference("lobby_id", lobbyId); - - bool join; - req.mStream << makeKeyValueReference("join", join); - - std::string gxs_id; - req.mStream << makeKeyValueReference("gxs_id", gxs_id); - RsGxsId gxsId(gxs_id); - - if(join) - { - if(rsMsgs->acceptLobbyInvite(lobbyId, gxsId)) - resp.setOk(); - else - resp.setFail(); - } - else - { - rsMsgs->denyLobbyInvite(lobbyId); - resp.setOk(); - } -} - -ResponseTask* ChatHandler::handleLobbyParticipants(Request &req, Response &resp) -{ - RS_STACK_MUTEX(mMtx); // ********** LOCKED ********** - - ChatId id(req.mPath.top()); - if(!id.isLobbyId()) - { - resp.setFail("Path element \""+req.mPath.top()+"\" is not a ChatLobbyId."); - return 0; - } - std::map::const_iterator mit = mLobbyParticipantsInfos.find(id.toLobbyId()); - if(mit == mLobbyParticipantsInfos.end()) - { - resp.setFail("lobby not found"); - return 0; - } - return new SendLobbyParticipantsTask(mRsIdentity, mit->second); -} - -void ChatHandler::handleGetDefaultIdentityForChatLobby(Request& /*req*/, - Response& resp) -{ - RsGxsId gxsId; - mRsMsgs->getDefaultIdentityForChatLobby(gxsId); - resp.mDataStream << makeKeyValue("gxs_id", gxsId.toStdString()); - resp.setOk(); -} - -void ChatHandler::handleSetDefaultIdentityForChatLobby(Request& req, Response& resp) -{ - std::string gxs_id; - req.mStream << makeKeyValueReference("gxs_id", gxs_id); - RsGxsId gxsId(gxs_id); - - if(gxsId.isNull()) - { - resp.setFail("Error: gxs_id must not be null"); - return; - } - - if(mRsMsgs->setDefaultIdentityForChatLobby(gxsId)) - resp.setOk(); - else - resp.setFail("Failure to change default identity for chat lobby"); -} - -void ChatHandler::handleGetIdentityForChatLobby(Request& req, Response& resp) -{ - RsGxsId gxsId; - std::string chat_id; - req.mStream << makeKeyValueReference("chat_id", chat_id); - ChatId chatId(chat_id); - - if(chatId.isNotSet()) - { - resp.setFail("Error: chat_id must not be null"); - return; - } - - if(mRsMsgs->getIdentityForChatLobby(chatId.toLobbyId(), gxsId)) - { - resp.mDataStream << makeKeyValue("gxs_id", gxsId.toStdString()); - resp.setOk(); - } - else - resp.setFail(); -} - -void ChatHandler::handleSetIdentityForChatLobby(Request& req, Response& resp) -{ - std::string chat_id; - req.mStream << makeKeyValueReference("chat_id", chat_id); - ChatId chatId(chat_id); - - if(chatId.isNotSet()) - { - resp.setFail("Error: chat_id must not be null"); - return; - } - - std::string gxs_id; - req.mStream << makeKeyValueReference("gxs_id", gxs_id); - RsGxsId gxsId(gxs_id); - - if(gxsId.isNull()) - { - resp.setFail("Error: gxs_id must not be null"); - return; - } - - if(mRsMsgs->setIdentityForChatLobby(chatId.toLobbyId(), gxsId)) - resp.setOk(); - else - resp.setFail(); -} - -void ChatHandler::handleMessages(Request &req, Response &resp) -{ - /* G10h4ck: Whithout this the request processing won't happen, copied from - * ChatHandler::handleLobbies, is this a work around or is the right way of - * doing it? */ - tick(); - - { - RS_STACK_MUTEX(mMtx); // ********** LOCKED ********** - ChatId id(req.mPath.top()); - - // make response a list - resp.mDataStream.getStreamToMember(); - if(id.isNotSet()) - { - resp.setFail("\""+req.mPath.top()+"\" is not a valid chat id"); - return; - } - std::map >::iterator mit = mMsgs.find(id); - if(mit == mMsgs.end()) - { - /* set state token, even if not found yet, maybe later messages arrive - * and then the chat id will be found */ - resp.mStateToken = mMsgStateToken; - resp.setFail("chat with id=\""+req.mPath.top()+"\" not found"); - return; - } - resp.mStateToken = mMsgStateToken; - handlePaginationRequest(req, resp, mit->second); - } -} - -void ChatHandler::handleSendMessage(Request &req, Response &resp) -{ - std::string chat_id; - std::string msg; - req.mStream << makeKeyValueReference("chat_id", chat_id) - << makeKeyValueReference("msg", msg); - ChatId id(chat_id); - if(id.isNotSet()) - { - resp.setFail("chat_id is invalid"); - return; - } - if(mRsMsgs->sendChat(id, msg)) - resp.setOk(); - else - resp.setFail("failed to send message"); -} - -void ChatHandler::handleMarkMessageAsRead(Request &req, Response &resp) -{ - std::string chat_id_string; - std::string msg_id; - req.mStream << makeKeyValueReference("chat_id", chat_id_string) - << makeKeyValueReference("msg_id", msg_id); - - ChatId chatId(chat_id_string); - if(chatId.isNotSet()) - { - resp.setFail(chat_id_string + " is not a valid chat id"); - return; - } - - std::map >::iterator mit = mMsgs.find(chatId); - if(mit == mMsgs.end()) - { - resp.setFail("chat not found. Maybe this chat does not have messages yet?"); - return; - } - - std::list& msgs = mit->second; - for(std::list::iterator lit = msgs.begin(); lit != msgs.end(); ++lit) - { - if(id((*lit)) == msg_id) - (*lit).read = true; - } - - // lobby list contains unread msgs, so update it - if(chatId.isLobbyId()) - mStateTokenServer->replaceToken(mLobbiesStateToken); - if(chatId.isPeerId() && mUnreadMsgNotify) - mUnreadMsgNotify->notifyUnreadMsgCountChanged(chatId.toPeerId(), 0); - - mStateTokenServer->replaceToken(mMsgStateToken); - mStateTokenServer->replaceToken(mUnreadMsgsStateToken); -} - -void ChatHandler::handleMarkChatAsRead(Request &req, Response &resp) -{ - RS_STACK_MUTEX(mMtx); // ********** LOCKED ********** - ChatId id(req.mPath.top()); - - if(id.isNotSet()) - { - resp.setFail("\""+req.mPath.top()+"\" is not a valid chat id"); - return; - } - std::map >::iterator mit = mMsgs.find(id); - if(mit == mMsgs.end()) - { - resp.setFail("chat not found. Maybe this chat does not have messages yet?"); - return; - } - std::list& msgs = mit->second; - for(std::list::iterator lit = msgs.begin(); lit != msgs.end(); ++lit) - { - lit->read = true; - } - // lobby list contains unread msgs, so update it - if(id.isLobbyId()) - mStateTokenServer->replaceToken(mLobbiesStateToken); - if(id.isPeerId() && mUnreadMsgNotify) - mUnreadMsgNotify->notifyUnreadMsgCountChanged(id.toPeerId(), 0); - - mStateTokenServer->replaceToken(mMsgStateToken); - mStateTokenServer->replaceToken(mUnreadMsgsStateToken); -} - -void ChatHandler::handleInfo(Request &req, Response &resp) -{ - RS_STACK_MUTEX(mMtx); // ********** LOCKED ********** - ChatId id(req.mPath.top()); - if(id.isNotSet()) - { - resp.setFail("\""+req.mPath.top()+"\" is not a valid chat id"); - return; - } - std::map::iterator mit = mChatInfo.find(id); - if(mit == mChatInfo.end()) - { - resp.setFail("chat not found."); - return; - } - resp.mDataStream << mit->second; - resp.setOk(); -} - -class SendTypingLabelInfo: public GxsResponseTask -{ -public: - SendTypingLabelInfo(RsIdentity* identity, RsPeers* peers, ChatId id, const ChatHandler::TypingLabelInfo& info): - GxsResponseTask(identity), mState(BEGIN), mPeers(peers),mId(id), mInfo(info) {} -private: - enum State {BEGIN, WAITING_ID}; - State mState; - RsPeers* mPeers; - ChatId mId; - ChatHandler::TypingLabelInfo mInfo; -protected: - void gxsDoWork(Request& /*req*/, Response& resp) - { - if(mState == BEGIN) - { - // lobby and distant require to fetch a gxs_id - if(mId.isLobbyId()) - { - if(!mInfo.author_id.isNull()) - requestGxsId(mInfo.author_id); - } - else if(mId.isDistantChatId()) - { - DistantChatPeerInfo dcpinfo ; - rsMsgs->getDistantChatStatus(mId.toDistantChatId(), dcpinfo); - requestGxsId(dcpinfo.to_id); - } - mState = WAITING_ID; - } - else - { - std::string name = "BUG: case not handled in SendTypingLabelInfo"; - RsGxsId author_id = mInfo.author_id; - if(mId.isPeerId()) - { - name = mPeers->getPeerName(mId.toPeerId()); - } - else if(mId.isDistantChatId()) - { - DistantChatPeerInfo dcpinfo ; - rsMsgs->getDistantChatStatus(mId.toDistantChatId(), dcpinfo); - name = getName(dcpinfo.to_id); - author_id = dcpinfo.to_id; - } - else if(mId.isLobbyId()) - { - name = getName(mInfo.author_id); - } - else if(mId.isBroadcast()) - { - name = mPeers->getPeerName(mId.broadcast_status_peer_id); - } - uint32_t ts = mInfo.timestamp; - resp.mDataStream << makeKeyValueReference("author_name", name) - << makeKeyValue("author_id", author_id.toStdString()) - << makeKeyValueReference("timestamp", ts) - << makeKeyValueReference("status_string", mInfo.status); - resp.mStateToken = mInfo.state_token; - resp.setOk(); - done(); - } - } -}; - -ResponseTask* ChatHandler::handleReceiveStatus(Request &req, Response &resp) -{ - RS_STACK_MUTEX(mMtx); // ********** LOCKED ********** - ChatId id(req.mPath.top()); - if(id.isNotSet()) - { - resp.setFail("\""+req.mPath.top()+"\" is not a valid chat id"); - return 0; - } - std::map::iterator mit = mTypingLabelInfo.find(id); - if(mit == mTypingLabelInfo.end()) - { - locked_storeTypingInfo(id, ""); - mit = mTypingLabelInfo.find(id); - } - - return new SendTypingLabelInfo(mRsIdentity, mRsPeers, id, mit->second); -} - -void ChatHandler::handleSendStatus(Request &req, Response &resp) -{ - std::string chat_id; - std::string status; - req.mStream << makeKeyValueReference("chat_id", chat_id) - << makeKeyValueReference("status", status); - ChatId id(chat_id); - if(id.isNotSet()) - { - resp.setFail("chat_id is invalid"); - return; - } - mRsMsgs->sendStatusString(id, status); - resp.setOk(); -} - -void ChatHandler::handleUnreadMsgs(Request &/*req*/, Response &resp) -{ - RS_STACK_MUTEX(mMtx); // ********** LOCKED ********** - - resp.mDataStream.getStreamToMember(); - for( std::map >::const_iterator mit = mMsgs.begin(); - mit != mMsgs.end(); ++mit ) - { - uint32_t count = 0; - for( std::list::const_iterator lit = mit->second.begin(); - lit != mit->second.end(); ++lit ) if(!lit->read) ++count; - std::map::iterator mit2 = mChatInfo.find(mit->first); - if(mit2 == mChatInfo.end()) - std::cerr << "Error in ChatHandler::handleUnreadMsgs(): ChatInfo not found. It is weird if this happens. Normally it should not happen." << std::endl; - if(count && (mit2 != mChatInfo.end())) - { - resp.mDataStream.getStreamToMember() -#warning Gioacchino Mazzurco 2017-03-24: @deprecated using "id" as key can cause problems in some JS based \ - languages like Qml @see chat_id instead - << makeKeyValue("id", mit->first.toStdString()) - << makeKeyValue("chat_id", mit->first.toStdString()) - << makeKeyValueReference("unread_count", count) - << mit2->second; - } - } - resp.mStateToken = mUnreadMsgsStateToken; - resp.setOk(); -} - -void ChatHandler::handleInitiateDistantChatConnexion(Request& req, Response& resp) -{ - std::string own_gxs_hex, remote_gxs_hex; - - req.mStream << makeKeyValueReference("own_gxs_hex", own_gxs_hex) - << makeKeyValueReference("remote_gxs_hex", remote_gxs_hex); - - RsGxsId sender_id(own_gxs_hex); - if(sender_id.isNull()) - { - resp.setFail("own_gxs_hex is invalid"); - return; - } - - RsGxsId receiver_id(remote_gxs_hex); - if(receiver_id.isNull()) - { - resp.setFail("remote_gxs_hex is invalid"); - return; - } - - DistantChatPeerId distant_chat_id; - uint32_t error_code; - - if(mRsMsgs->initiateDistantChatConnexion( receiver_id, sender_id, - distant_chat_id, error_code, - false )) resp.setOk(); - else resp.setFail("Failed to initiate distant chat"); - - ChatId chat_id(distant_chat_id); - resp.mDataStream << makeKeyValue("chat_id", chat_id.toStdString()) - << makeKeyValueReference("error_code", error_code); -} - -void ChatHandler::handleDistantChatStatus(Request& req, Response& resp) -{ - std::string distant_chat_hex; - req.mStream << makeKeyValueReference("chat_id", distant_chat_hex); - - ChatId id(distant_chat_hex); - DistantChatPeerInfo info; - if(mRsMsgs->getDistantChatStatus(id.toDistantChatId(), info)) resp.setOk(); - else resp.setFail("Failed to get status for distant chat"); - - resp.mDataStream << makeKeyValue("own_gxs_hex", info.own_id.toStdString()) - << makeKeyValue("remote_gxs_hex", info.to_id.toStdString()) - << makeKeyValue("chat_id", info.peer_id.toStdString()) - << makeKeyValue("status", info.status); -} - -void ChatHandler::handleCloseDistantChatConnexion(Request& req, Response& resp) -{ - std::string distant_chat_hex; - req.mStream << makeKeyValueReference("distant_chat_hex", distant_chat_hex); - ChatId chatId(distant_chat_hex); - - if (mRsMsgs->closeDistantChatConnexion(chatId.toDistantChatId())) - resp.setOk(); - else - resp.setFail("Failed to close distant chat"); -} - -void ChatHandler::handleCreateLobby(Request& req, Response& resp) -{ - std::set invited_identites; - std::string lobby_name; - std::string lobby_topic; - std::string gxs_id; - - req.mStream << makeKeyValueReference("lobby_name", lobby_name); - req.mStream << makeKeyValueReference("lobby_topic", lobby_topic); - req.mStream << makeKeyValueReference("gxs_id", gxs_id); - - RsGxsId gxsId(gxs_id); - - bool lobby_public; - bool pgp_signed; - - req.mStream << makeKeyValueReference("lobby_public", lobby_public); - req.mStream << makeKeyValueReference("pgp_signed", pgp_signed); - - ChatLobbyFlags lobby_flags; - - if(lobby_public) - lobby_flags |= RS_CHAT_LOBBY_FLAGS_PUBLIC; - - if(pgp_signed) - lobby_flags |= RS_CHAT_LOBBY_FLAGS_PGP_SIGNED; - - mRsMsgs->createChatLobby(lobby_name, gxsId, lobby_topic, invited_identites, lobby_flags); - - tick(); - resp.setOk(); -} - -} // namespace resource_api diff --git a/libresapi/src/api/ChatHandler.h b/libresapi/src/api/ChatHandler.h deleted file mode 100644 index 8294c8e22..000000000 --- a/libresapi/src/api/ChatHandler.h +++ /dev/null @@ -1,203 +0,0 @@ -/******************************************************************************* - * libresapi/api/ChatHandler.h * - * * - * LibResAPI: API for local socket server * - * * - * Copyright 2015 by electron128 * - * Copyright 2017 by Gioacchino Mazzurco * - * * - * This program is free software: you can redistribute it and/or modify * - * it under the terms of the GNU Affero General Public License as * - * published by the Free Software Foundation, either version 3 of the * - * License, or (at your option) any later version. * - * * - * This program is distributed in the hope that it will be useful, * - * but WITHOUT ANY WARRANTY; without even the implied warranty of * - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * - * GNU Affero General Public License for more details. * - * * - * You should have received a copy of the GNU Affero General Public License * - * along with this program. If not, see . * - * * - *******************************************************************************/ -#pragma once - -#include "ResourceRouter.h" -#include "StateTokenServer.h" -#include -#include -#include "util/rstime.h" - -class RsPeers; -struct RsIdentity; - -namespace resource_api -{ - -class UnreadMsgNotify -{ -public: - virtual void notifyUnreadMsgCountChanged(const RsPeerId& peer, uint32_t count) = 0; -}; - -class ChatHandler: public ResourceRouter, NotifyClient, Tickable -{ -public: - ChatHandler(StateTokenServer* sts, RsNotify* notify, RsMsgs* msgs, RsPeers* peers, RsIdentity *identity, UnreadMsgNotify* unread); - virtual ~ChatHandler(); - - // from NotifyClient - // note: this may get called from the own and from foreign threads - virtual void notifyChatMessage(const ChatMessage& msg); - virtual void notifyChatCleared(const ChatId& chat_id); - - // typing label for peer, broadcast and distant chat - virtual void notifyChatStatus (const ChatId& /* chat_id */, const std::string& /* status_string */); - - //typing label for lobby chat, peer join and leave messages - virtual void notifyChatLobbyEvent (uint64_t /* lobby id */, uint32_t /* event type */ , - const RsGxsId& /* nickname */,const std::string& /* any string */); - - virtual void notifyListChange(int list, int type); - - // from tickable - virtual void tick(); - -public: - class Triple - { - public: - Triple(): first(-1), second(-1), third(-1){} - double first; - double second; - double third; - }; - - class Msg{ - public: - bool read; - bool incoming; - bool was_send; - //std::string chat_type; - std::string author_id; // peer or gxs id or "system" for system messages - std::string author_name; - std::string msg; // plain text only! - std::vector links; - uint32_t recv_time; - uint32_t send_time; - - uint32_t id; - }; - - class Lobby{ - public: - Lobby(): id(0), subscribed(false), auto_subscribe(false), is_private(false), is_broadcast(false){} - ChatLobbyId id; - std::string name; - std::string topic; - bool subscribed; - bool auto_subscribe; - bool is_private; - bool is_broadcast; - - RsGxsId gxs_id;// for subscribed lobbies: the id we use to write messages - - bool operator==(const Lobby& l) const - { - return id == l.id - && name == l.name - && topic == l.topic - && subscribed == l.subscribed - && auto_subscribe == l.auto_subscribe - && is_private == l.is_private - && is_broadcast == l.is_broadcast - && gxs_id == l.gxs_id; - } - }; - - class LobbyParticipantsInfo{ - public: - StateToken state_token; - std::map participants; - }; - - class ChatInfo{ - public: - bool is_broadcast; - bool is_distant_chat_id; - bool is_lobby; - bool is_peer; - std::string own_author_id; - std::string own_author_name; - std::string remote_author_id; - std::string remote_author_name; - }; - - class TypingLabelInfo{ - public: - time_t timestamp; - std::string status; - StateToken state_token; - // only for lobbies - RsGxsId author_id; - }; - -private: - void handleWildcard(Request& req, Response& resp); - void handleLobbies(Request& req, Response& resp); - void handleCreateLobby(Request& req, Response& resp); - void handleSubscribeLobby(Request& req, Response& resp); - void handleUnsubscribeLobby(Request& req, Response& resp); - void handleAutoSubsribeLobby(Request& req, Response& resp); - void handleInviteToLobby(Request& req, Response& resp); - void handleGetInvitationsToLobby(Request& req, Response& resp); - void handleAnswerToInvitation(Request& req, Response& resp); - void handleClearLobby(Request& req, Response& resp); - ResponseTask* handleLobbyParticipants(Request& req, Response& resp); - void handleGetDefaultIdentityForChatLobby(Request& req, Response& resp); - void handleSetDefaultIdentityForChatLobby(Request& req, Response& resp); - void handleGetIdentityForChatLobby(Request& req, Response& resp); - void handleSetIdentityForChatLobby(Request& req, Response& resp); - void handleMessages(Request& req, Response& resp); - void handleSendMessage(Request& req, Response& resp); - void handleMarkMessageAsRead(Request& req, Response& resp); - void handleMarkChatAsRead(Request& req, Response& resp); - void handleInfo(Request& req, Response& resp); - ResponseTask *handleReceiveStatus(Request& req, Response& resp); - void handleSendStatus(Request& req, Response& resp); - void handleUnreadMsgs(Request& req, Response& resp); - void handleInitiateDistantChatConnexion(Request& req, Response& resp); - void handleDistantChatStatus(Request& req, Response& resp); - void handleCloseDistantChatConnexion(Request& req, Response& resp); - - void getPlainText(const std::string& in, std::string &out, std::vector &links); - // last parameter is only used for lobbies! - void locked_storeTypingInfo(const ChatId& chat_id, std::string status, RsGxsId lobby_gxs_id = RsGxsId()); - - StateTokenServer* mStateTokenServer; - RsNotify* mNotify; - RsMsgs* mRsMsgs; - RsPeers* mRsPeers; - RsIdentity* mRsIdentity; - UnreadMsgNotify* mUnreadMsgNotify; - - RsMutex mMtx; - - StateToken mMsgStateToken; - std::list mRawMsgs; - std::map > mMsgs; - - std::map mChatInfo; - - std::map mTypingLabelInfo; - - StateToken mLobbiesStateToken; - std::vector mLobbies; - - std::map mLobbyParticipantsInfos; - - StateToken mUnreadMsgsStateToken; - StateToken mInvitationsStateToken; - -}; -} // namespace resource_api diff --git a/libresapi/src/api/FileSearchHandler.cpp b/libresapi/src/api/FileSearchHandler.cpp deleted file mode 100644 index ceb3765c9..000000000 --- a/libresapi/src/api/FileSearchHandler.cpp +++ /dev/null @@ -1,324 +0,0 @@ -/******************************************************************************* - * libresapi/api/FileSearchHandler.cpp * - * * - * LibResAPI: API for local socket server * - * * - * Copyright 2018 by Retroshare Team * - * * - * This program is free software: you can redistribute it and/or modify * - * it under the terms of the GNU Affero General Public License as * - * published by the Free Software Foundation, either version 3 of the * - * License, or (at your option) any later version. * - * * - * This program is distributed in the hope that it will be useful, * - * but WITHOUT ANY WARRANTY; without even the implied warranty of * - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * - * GNU Affero General Public License for more details. * - * * - * You should have received a copy of the GNU Affero General Public License * - * along with this program. If not, see . * - * * - *******************************************************************************/ -#include - -#include "FileSearchHandler.h" - -#include -#include -#include - -#include "Operators.h" - -namespace resource_api -{ - -FileSearchHandler::FileSearchHandler(StateTokenServer *sts, RsNotify *notify, RsTurtle */*turtle*/, RsFiles *files): - mStateTokenServer(sts), mNotify(notify)/*, mTurtle(turtle)*/, mRsFiles(files), - mMtx("FileSearchHandler") -{ - mNotify->registerNotifyClient(this); - addResourceHandler("*", this, &FileSearchHandler::handleWildcard); - addResourceHandler("create_search", this, &FileSearchHandler::handleCreateSearch); - addResourceHandler("get_search_result", this, &FileSearchHandler::handleGetSearchResult); - - mSearchesStateToken = mStateTokenServer->getNewToken(); -} - -FileSearchHandler::~FileSearchHandler() -{ - mNotify->unregisterNotifyClient(this); - mStateTokenServer->discardToken(mSearchesStateToken); -} - -void FileSearchHandler::notifyTurtleSearchResult(const RsPeerId& /*pid*/,uint32_t search_id, const std::list& files) -{ - RS_STACK_MUTEX(mMtx); // ********** LOCKED ********** - std::map::iterator mit = mSearches.find(search_id); - if(mit == mSearches.end()) - return; - - Search& search = mit->second; - // set to a limit of 100 for now, can have more when we have pagination - std::list::const_iterator lit = files.begin(); - bool changed = false; - while(search.mResults.size() < 100 && lit != files.end()) - { - if(search.mHashes.find(lit->hash) == search.mHashes.end()) - { - changed = true; - FileDetail det ; - det.rank = 0 ; - det.age = 0 ; - det.name = (*lit).name; - det.hash = (*lit).hash; - det.size = (*lit).size; - det.id.clear(); - search.mResults.push_back(det); - search.mHashes.insert(lit->hash); - } - lit++; - } - if(changed) - { - mStateTokenServer->discardToken(search.mStateToken); - search.mStateToken = mStateTokenServer->getNewToken(); - } -} - -// TODO: delete searches -void FileSearchHandler::handleWildcard(Request &req, Response &resp) -{ - if(!req.mPath.empty()) - { - std::string str = req.mPath.top(); - req.mPath.pop(); - - if(str.size() != 8) - { - resp.setFail("Error: id has wrong size, should be 8 characters"); - return; - } - uint32_t id = 0; - // TODO fix this - for(uint8_t i = 0; i < 8; i++) - { - id += (uint32_t(str[i]-'A')) << (i*4); - } - - { - RS_STACK_MUTEX(mMtx); // ********** LOCKED ********** - std::map::iterator mit = mSearches.find(id); - if(mit == mSearches.end()) - { - resp.setFail("Error: search id invalid"); - return; - } - - Search& search = mit->second; - resp.mStateToken = search.mStateToken; - resp.mDataStream.getStreamToMember(); - for(std::list::iterator lit = search.mResults.begin(); lit != search.mResults.end(); ++lit) - { - FileDetail& fd = *lit; - double size = fd.size; - resp.mDataStream.getStreamToMember() - << makeKeyValueReference("id", fd.hash) - << makeKeyValueReference("name", fd.name) - << makeKeyValueReference("hash", fd.hash) - << makeKeyValueReference("path", fd.path) - << makeKeyValue("peer_id", fd.id.toStdString()) - << makeKeyValueReference("size", size) - << makeKeyValueReference("rank", fd.rank) - << makeKeyValueReference("age", fd.age); - } - } - } - else - { - // list searches - RS_STACK_MUTEX(mMtx); // ********** LOCKED ********** - resp.mDataStream.getStreamToMember(); - for(std::map::iterator mit = mSearches.begin(); mit != mSearches.end(); ++mit) - { - uint32_t id = mit->first; - std::string idstr; - // how many times do i have to write int to string conversation? - // a library should do this - for(uint8_t i = 0; i < 8; i++) - { - char c = ((id>>(i*4))&0xF)+'A'; - idstr += c; - } - resp.mDataStream.getStreamToMember() - << makeKeyValueReference("id", idstr) - << makeKeyValueReference("search_string", mit->second.mSearchString); - } - resp.mStateToken = mSearchesStateToken; - resp.setOk(); - } -} - -static bool dirDetailToFileDetail(const DirDetails& dir, FileDetail& fd) -{ - if (dir.type == DIR_TYPE_FILE) - { - fd.id = dir.id; - fd.name = dir.name; - fd.hash = dir.hash; - fd.path = dir.path; - fd.size = dir.count; - fd.age = time(NULL) - dir.mtime; - fd.rank = 0; - return true; - } - else - return false; -} - -// see retroshare-gui/src/gui/Searchdialog.cpp -void FileSearchHandler::handleCreateSearch(Request &req, Response &resp) -{ - bool distant = false;// distant involves sending data, so have it off by default for privacy - bool local = true; - bool remote = true; - std::string search_string; - req.mStream << makeKeyValueReference("distant", distant) - << makeKeyValueReference("local", local) - << makeKeyValueReference("remote", remote) - << makeKeyValueReference("search_string", search_string); - - std::istringstream iss(search_string); - std::list words; - std::string s; - while (std::getline(iss, s, ' ')) { - std::cout << s << std::endl; - words.push_back(s); - } - - if(words.empty()) - { - resp.setFail("Error: no search string given"); - return; - } - - RsRegularExpression::NameExpression exprs(RsRegularExpression::ContainsAllStrings,words,true) ; - RsRegularExpression::LinearizedExpression lin_exp ; - exprs.linearize(lin_exp) ; - - uint32_t search_id = RSRandom::random_u32(); - if(distant) - { - // i have no idea what the reasons for two different search modes are - // rs-gui does it, so do we - if(words.size() == 1) - search_id = rsFiles->turtleSearch(words.front()); - else - search_id = rsFiles->turtleSearch(lin_exp); - } - - std::list results; - if(local) - { - std::list local_results; - mRsFiles->SearchBoolExp(&exprs, local_results, RS_FILE_HINTS_LOCAL); - - for(std::list::iterator lit = local_results.begin(); lit != local_results.end(); ++lit) - { - FileDetail fd; - if(dirDetailToFileDetail(*lit, fd)) - results.push_back(fd); - } - } - if(remote) - { - std::list remote_results; - mRsFiles->SearchBoolExp(&exprs, remote_results, RS_FILE_HINTS_REMOTE); - for(std::list::iterator lit = remote_results.begin(); lit != remote_results.end(); ++lit) - { - FileDetail fd; - if(dirDetailToFileDetail(*lit, fd)) - results.push_back(fd); - } - } - - { - RS_STACK_MUTEX(mMtx); // ********** LOCKED ********** - - Search& search = mSearches[search_id]; - search.mStateToken = mStateTokenServer->getNewToken(); - search.mSearchString = search_string; - search.mResults.swap(results); - - mStateTokenServer->discardToken(mSearchesStateToken); - mSearchesStateToken = mStateTokenServer->getNewToken(); - } - - std::string idstr; - // how many times do i have to write int to string conversation? - // a library should do this - for(uint8_t i = 0; i < 8; i++) - { - char c = ((search_id>>(i*4))&0xF)+'A'; - idstr += c; - } - resp.mDataStream << makeKeyValueReference("search_id", idstr); - resp.setOk(); -} - -void FileSearchHandler::handleGetSearchResult(Request& req, Response& resp) -{ - std::string search_id; - req.mStream << makeKeyValueReference("search_id", search_id); - - if(search_id.size() != 8) - { - resp.setFail("Error: id has wrong size, should be 8 characters"); - return; - } - - uint32_t id = 0; - for(uint8_t i = 0; i < 8; i++) - { - id += (uint32_t(search_id[i]-'A')) << (i*4); - } - - { - RS_STACK_MUTEX(mMtx); // ********** LOCKED ********** - std::map::iterator mit = mSearches.find(id); - if(mit == mSearches.end()) - { - resp.setFail("Error: search id invalid"); - return; - } - - Search& search = mit->second; - resp.mStateToken = search.mStateToken; - resp.mDataStream.getStreamToMember(); - - RsPgpId ownId = rsPeers->getGPGOwnId(); - for(std::list::iterator lit = search.mResults.begin(); lit != search.mResults.end(); ++lit) - { - FileDetail& fd = *lit; - bool isFriend = rsPeers->isFriend(fd.id); - bool isOwn = false; - if(ownId == rsPeers->getGPGId(fd.id)) - isOwn = true; - - double size = fd.size; - resp.mDataStream.getStreamToMember() - << makeKeyValueReference("id", fd.hash) - << makeKeyValueReference("name", fd.name) - << makeKeyValueReference("hash", fd.hash) - << makeKeyValueReference("path", fd.path) - << makeKeyValue("peer_id", fd.id.toStdString()) - << makeKeyValueReference("is_friends", isFriend) - << makeKeyValueReference("is_own", isOwn) - << makeKeyValueReference("size", size) - << makeKeyValueReference("rank", fd.rank) - << makeKeyValueReference("age", fd.age); - } - } - resp.setOk(); -} - -} // namespace resource_api diff --git a/libresapi/src/api/FileSearchHandler.h b/libresapi/src/api/FileSearchHandler.h deleted file mode 100644 index ec1585eef..000000000 --- a/libresapi/src/api/FileSearchHandler.h +++ /dev/null @@ -1,65 +0,0 @@ -/******************************************************************************* - * libresapi/api/FileSearchHandler.h * - * * - * LibResAPI: API for local socket server * - * * - * Copyright 2018 by Retroshare Team * - * * - * This program is free software: you can redistribute it and/or modify * - * it under the terms of the GNU Affero General Public License as * - * published by the Free Software Foundation, either version 3 of the * - * License, or (at your option) any later version. * - * * - * This program is distributed in the hope that it will be useful, * - * but WITHOUT ANY WARRANTY; without even the implied warranty of * - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * - * GNU Affero General Public License for more details. * - * * - * You should have received a copy of the GNU Affero General Public License * - * along with this program. If not, see . * - * * - *******************************************************************************/ -#pragma once -#include "ResourceRouter.h" -#include "StateTokenServer.h" - -#include -#include -#include - -namespace resource_api -{ - -class FileSearchHandler: public ResourceRouter, NotifyClient -{ -public: - FileSearchHandler(StateTokenServer* sts, RsNotify* notify, RsTurtle* turtle, RsFiles* files); - virtual ~FileSearchHandler(); - - // from NotifyClient - virtual void notifyTurtleSearchResult(const RsPeerId &pid, uint32_t search_id, const std::list& files); -private: - void handleWildcard(Request& req, Response& resp); - void handleCreateSearch(Request& req, Response& resp); - void handleGetSearchResult(Request& req, Response& resp); - - StateTokenServer* mStateTokenServer; - RsNotify* mNotify; - //RsTurtle* mTurtle; - RsFiles* mRsFiles; - - class Search{ - public: - StateToken mStateToken; - std::string mSearchString; // extra service: store the search string - std::list mResults; - // a set for fast deduplication lookup - std::set mHashes; - }; - - RsMutex mMtx; - StateToken mSearchesStateToken; - std::map mSearches; // mutex protected -}; - -} // namespace resource_api diff --git a/libresapi/src/api/FileSharingHandler.cpp b/libresapi/src/api/FileSharingHandler.cpp deleted file mode 100644 index 5ad9b4601..000000000 --- a/libresapi/src/api/FileSharingHandler.cpp +++ /dev/null @@ -1,573 +0,0 @@ -/******************************************************************************* - * libresapi/api/FileSharingHandler.cpp * - * * - * LibResAPI: API for local socket server * - * * - * Copyright (C) 2017, Konrad Dębiec * - * * - * This program is free software: you can redistribute it and/or modify * - * it under the terms of the GNU Affero General Public License as * - * published by the Free Software Foundation, either version 3 of the * - * License, or (at your option) any later version. * - * * - * This program is distributed in the hope that it will be useful, * - * but WITHOUT ANY WARRANTY; without even the implied warranty of * - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * - * GNU Affero General Public License for more details. * - * * - * You should have received a copy of the GNU Affero General Public License * - * along with this program. If not, see . * - * * - *******************************************************************************/ -#include "FileSharingHandler.h" - -namespace resource_api -{ - -FileSharingHandler::FileSharingHandler(StateTokenServer *sts, RsFiles *files, - RsNotify& notify): - mStateTokenServer(sts), mMtx("FileSharingHandler Mtx"), mRsFiles(files), - mNotify(notify) -{ - addResourceHandler("*", this, &FileSharingHandler::handleWildcard); - addResourceHandler("force_check", this, &FileSharingHandler::handleForceCheck); - - addResourceHandler("get_shared_dirs", this, &FileSharingHandler::handleGetSharedDir); - addResourceHandler("set_shared_dir", this, &FileSharingHandler::handleSetSharedDir); - addResourceHandler("update_shared_dir", this, &FileSharingHandler::handleUpdateSharedDir); - addResourceHandler("remove_shared_dir", this, &FileSharingHandler::handleRemoveSharedDir); - - addResourceHandler("get_dir_parent", this, &FileSharingHandler::handleGetDirectoryParent); - addResourceHandler("get_dir_childs", this, &FileSharingHandler::handleGetDirectoryChilds); - - addResourceHandler( "get_download_directory", this, - &FileSharingHandler::handleGetDownloadDirectory ); - addResourceHandler( "set_download_directory", this, - &FileSharingHandler::handleSetDownloadDirectory ); - - addResourceHandler( "get_partials_directory", this, - &FileSharingHandler::handleGetPartialsDirectory ); - addResourceHandler( "set_partials_directory", this, - &FileSharingHandler::handleSetPartialsDirectory ); - - addResourceHandler("is_dl_dir_shared", this, &FileSharingHandler::handleIsDownloadDirShared); - addResourceHandler("share_dl_dir", this, &FileSharingHandler::handleShareDownloadDirectory); - - addResourceHandler("download", this, &FileSharingHandler::handleDownload); - - mLocalDirStateToken = mStateTokenServer->getNewToken(); - mRemoteDirStateToken = mStateTokenServer->getNewToken(); - mNotify.registerNotifyClient(this); -} - -FileSharingHandler::~FileSharingHandler() -{ - mNotify.unregisterNotifyClient(this); -} - -void FileSharingHandler::notifyListChange(int list, int /* type */) -{ - if(list == NOTIFY_LIST_DIRLIST_LOCAL) - { - RS_STACK_MUTEX(mMtx); - mStateTokenServer->discardToken(mLocalDirStateToken); - mLocalDirStateToken = mStateTokenServer->getNewToken(); - } - else if(list == NOTIFY_LIST_DIRLIST_FRIENDS) - { - RS_STACK_MUTEX(mMtx); - mStateTokenServer->discardToken(mRemoteDirStateToken); - mRemoteDirStateToken = mStateTokenServer->getNewToken(); - } -} - -void FileSharingHandler::handleWildcard(Request & /*req*/, Response & /*resp*/) -{ - -} - -void FileSharingHandler::handleForceCheck(Request&, Response& resp) -{ - mRsFiles->ForceDirectoryCheck(); - resp.setOk(); -} - -void FileSharingHandler::handleGetSharedDir(Request& /*req*/, Response& resp) -{ - DirDetails dirDetails; - mRsFiles->RequestDirDetails(NULL, dirDetails, RS_FILE_HINTS_LOCAL); - - resp.mDataStream << makeKeyValue("parent_reference", *reinterpret_cast(&dirDetails.ref)); - resp.mDataStream << makeKeyValue("path", dirDetails.path); - StreamBase &childsStream = resp.mDataStream.getStreamToMember("childs"); - - for(std::vector::iterator it = dirDetails.children.begin(); it != dirDetails.children.end(); ++it) - { - DirDetails dirDetails; - mRsFiles->RequestDirDetails((*it).ref, dirDetails, RS_FILE_HINTS_LOCAL); - - for(std::vector::iterator vit = dirDetails.children.begin(); vit != dirDetails.children.end(); ++vit) - { - DirDetails dirDetails; - mRsFiles->RequestDirDetails((*vit).ref, dirDetails, RS_FILE_HINTS_LOCAL); - - std::string type; - switch(dirDetails.type) - { - case DIR_TYPE_PERSON: - type = "person"; - break; - case DIR_TYPE_DIR: - type = "folder"; - break; - case DIR_TYPE_FILE: - type = "file"; - break; - } - - bool browsable = false; - bool anon_dl = false; - bool anon_search = false; - - if(dirDetails.flags & DIR_FLAGS_BROWSABLE) - browsable = true; - - if(dirDetails.flags & DIR_FLAGS_ANONYMOUS_DOWNLOAD) - anon_dl = true; - - if(dirDetails.flags & DIR_FLAGS_ANONYMOUS_SEARCH) - anon_search = true; - - StreamBase &streamBase = childsStream.getStreamToMember() - << makeKeyValue("name", dirDetails.name) - << makeKeyValue("path", dirDetails.path) - << makeKeyValue("hash", dirDetails.hash.toStdString()) - << makeKeyValue("peer_id", dirDetails.id.toStdString()) - << makeKeyValue("parent_reference", *reinterpret_cast(&dirDetails.parent)) - << makeKeyValue("reference", *reinterpret_cast(&dirDetails.ref)) - << makeKeyValue("count", static_cast(dirDetails.count)) - << makeKeyValueReference("type", type) - << makeKeyValueReference("browsable", browsable) - << makeKeyValueReference("anon_dl", anon_dl) - << makeKeyValueReference("anon_search", anon_search); - - - int contain_files = 0; - int contain_folders = 0; - - if(dirDetails.count != 0) - { - for(std::vector::iterator vit = dirDetails.children.begin(); vit != dirDetails.children.end(); ++vit) - { - DirDetails dirDetails; - mRsFiles->RequestDirDetails((*vit).ref, dirDetails, RS_FILE_HINTS_LOCAL); - - switch(dirDetails.type) - { - case DIR_TYPE_DIR: - contain_folders++; - break; - case DIR_TYPE_FILE: - contain_files++; - break; - } - } - } - - streamBase - << makeKeyValueReference("contain_files", contain_files) - << makeKeyValueReference("contain_folders", contain_folders); - } - } - - resp.mStateToken = mLocalDirStateToken; -} - -void FileSharingHandler::handleSetSharedDir(Request& req, Response& resp) -{ - std::string dir; - bool browsable = false; - bool anon_dl = false; - bool anon_search = false; - req.mStream << makeKeyValueReference("directory", dir); - req.mStream << makeKeyValueReference("browsable", browsable); - req.mStream << makeKeyValueReference("anon_dl", anon_dl); - req.mStream << makeKeyValueReference("anon_search", anon_search); - - SharedDirInfo sDI; - sDI.filename = dir; - sDI.virtualname.clear(); - sDI.shareflags.clear(); - - if(browsable) - sDI.shareflags |= DIR_FLAGS_BROWSABLE; - - if(anon_dl) - sDI.shareflags |= DIR_FLAGS_ANONYMOUS_DOWNLOAD; - - if(anon_search) - sDI.shareflags |= DIR_FLAGS_ANONYMOUS_SEARCH; - - if(mRsFiles->addSharedDirectory(sDI)) - resp.setOk(); - else - resp.setFail("Couldn't share folder"); -} - -void FileSharingHandler::handleUpdateSharedDir(Request& req, Response& resp) -{ - std::string dir; - std::string virtualname; - bool browsable = false; - bool anon_dl = false; - bool anon_search = false; - req.mStream << makeKeyValueReference("directory", dir); - req.mStream << makeKeyValueReference("virtualname", virtualname); - req.mStream << makeKeyValueReference("browsable", browsable); - req.mStream << makeKeyValueReference("anon_dl", anon_dl); - req.mStream << makeKeyValueReference("anon_search", anon_search); - - SharedDirInfo sDI; - sDI.filename = dir; - sDI.virtualname = virtualname; - sDI.shareflags.clear(); - - if(browsable) - sDI.shareflags |= DIR_FLAGS_BROWSABLE; - - if(anon_dl) - sDI.shareflags |= DIR_FLAGS_ANONYMOUS_DOWNLOAD; - - if(anon_search) - sDI.shareflags |= DIR_FLAGS_ANONYMOUS_SEARCH; - - if(mRsFiles->updateShareFlags(sDI)) - resp.setOk(); - else - resp.setFail("Couldn't update shared folder's flags"); -} - -void FileSharingHandler::handleRemoveSharedDir(Request& req, Response& resp) -{ - std::string dir; - req.mStream << makeKeyValueReference("directory", dir); - - if(mRsFiles->removeSharedDirectory(dir)) - resp.setOk(); - else - resp.setFail("Couldn't remove shared directory."); -} - -void FileSharingHandler::handleGetDirectoryParent(Request& req, Response& resp) -{ - int reference; - bool remote = false; - bool local = true; - - req.mStream << makeKeyValueReference("reference", reference); - req.mStream << makeKeyValueReference("remote", remote); - req.mStream << makeKeyValueReference("local", local); - - void *ref = reinterpret_cast(reference); - - FileSearchFlags flags; - if(remote) - { - flags |= RS_FILE_HINTS_REMOTE; - resp.mStateToken = mRemoteDirStateToken; - } - - if(local) - { - flags |= RS_FILE_HINTS_LOCAL; - resp.mStateToken = mLocalDirStateToken; - } - - DirDetails dirDetails; - mRsFiles->RequestDirDetails(ref, dirDetails, flags); - mRsFiles->RequestDirDetails(dirDetails.parent, dirDetails, flags); - - resp.mDataStream << makeKeyValue("parent_reference", *reinterpret_cast(&dirDetails.ref)); - resp.mDataStream << makeKeyValue("path", dirDetails.path); - StreamBase &childsStream = resp.mDataStream.getStreamToMember("childs"); - - if(dirDetails.count != 0) - { - for(std::vector::iterator vit = dirDetails.children.begin(); vit != dirDetails.children.end(); ++vit) - { - DirDetails dirDetails; - mRsFiles->RequestDirDetails((*vit).ref, dirDetails, flags); - - std::string type; - switch(dirDetails.type) - { - case DIR_TYPE_PERSON: - type = "person"; - break; - case DIR_TYPE_DIR: - type = "folder"; - break; - case DIR_TYPE_FILE: - type = "file"; - break; - } - - bool browsable = false; - bool anon_dl = false; - bool anon_search = false; - - if(dirDetails.flags & DIR_FLAGS_BROWSABLE) - browsable = true; - - if(dirDetails.flags & DIR_FLAGS_ANONYMOUS_DOWNLOAD) - anon_dl = true; - - if(dirDetails.flags & DIR_FLAGS_ANONYMOUS_SEARCH) - anon_search = true; - - StreamBase &streamBase = childsStream.getStreamToMember() - << makeKeyValue("name", dirDetails.name) - << makeKeyValue("path", dirDetails.path) - << makeKeyValue("hash", dirDetails.hash.toStdString()) - << makeKeyValue("peer_id", dirDetails.id.toStdString()) - << makeKeyValue("parent_reference", *reinterpret_cast(&dirDetails.parent)) - << makeKeyValue("reference", *reinterpret_cast(&dirDetails.ref)) - << makeKeyValue("count", static_cast(dirDetails.count)) - << makeKeyValueReference("type", type) - << makeKeyValueReference("browsable", browsable) - << makeKeyValueReference("anon_dl", anon_dl) - << makeKeyValueReference("anon_search", anon_search); - - - int contain_files = 0; - int contain_folders = 0; - - if(dirDetails.count != 0) - { - for(std::vector::iterator vit = dirDetails.children.begin(); vit != dirDetails.children.end(); ++vit) - { - DirDetails dirDetails; - mRsFiles->RequestDirDetails((*vit).ref, dirDetails, flags); - - switch(dirDetails.type) - { - case DIR_TYPE_DIR: - contain_folders++; - break; - case DIR_TYPE_FILE: - contain_files++; - break; - } - } - } - - streamBase - << makeKeyValueReference("contain_files", contain_files) - << makeKeyValueReference("contain_folders", contain_folders); - } - } -} - -void FileSharingHandler::handleGetDirectoryChilds(Request& req, Response& resp) -{ - int reference = 0; - bool remote = false; - bool local = true; - - req.mStream << makeKeyValueReference("reference", reference); - req.mStream << makeKeyValueReference("remote", remote); - req.mStream << makeKeyValueReference("local", local); - - void *ref = reinterpret_cast(reference); - - FileSearchFlags flags; - if(remote) - { - flags |= RS_FILE_HINTS_REMOTE; - resp.mStateToken = mRemoteDirStateToken; - } - - if(local) - { - flags |= RS_FILE_HINTS_LOCAL; - resp.mStateToken = mLocalDirStateToken; - } - - DirDetails dirDetails; - mRsFiles->RequestDirDetails(ref, dirDetails, flags); - - resp.mDataStream << makeKeyValue("parent_reference", *reinterpret_cast(&dirDetails.ref)); - resp.mDataStream << makeKeyValue("path", dirDetails.path); - resp.mDataStream << makeKeyValue("hash", dirDetails.hash.toStdString()); - StreamBase &childsStream = resp.mDataStream.getStreamToMember("childs"); - - if(dirDetails.count != 0) - { - for(std::vector::iterator vit = dirDetails.children.begin(); vit != dirDetails.children.end(); ++vit) - { - DirDetails dirDetails; - mRsFiles->RequestDirDetails((*vit).ref, dirDetails, flags); - - std::string type; - switch(dirDetails.type) - { - case DIR_TYPE_PERSON: - type = "person"; - break; - case DIR_TYPE_DIR: - type = "folder"; - break; - case DIR_TYPE_FILE: - type = "file"; - break; - } - - bool browsable = false; - bool anon_dl = false; - bool anon_search = false; - - if(dirDetails.flags & DIR_FLAGS_BROWSABLE) - browsable = true; - - if(dirDetails.flags & DIR_FLAGS_ANONYMOUS_DOWNLOAD) - anon_dl = true; - - if(dirDetails.flags & DIR_FLAGS_ANONYMOUS_SEARCH) - anon_search = true; - - StreamBase &streamBase = childsStream.getStreamToMember() - << makeKeyValue("name", dirDetails.name) - << makeKeyValue("path", dirDetails.path) - << makeKeyValue("hash", dirDetails.hash.toStdString()) - << makeKeyValue("peer_id", dirDetails.id.toStdString()) - << makeKeyValue("parent_reference", *reinterpret_cast(&dirDetails.parent)) - << makeKeyValue("reference", *reinterpret_cast(&dirDetails.ref)) - << makeKeyValue("count", static_cast(dirDetails.count)) - << makeKeyValueReference("type", type) - << makeKeyValueReference("browsable", browsable) - << makeKeyValueReference("anon_dl", anon_dl) - << makeKeyValueReference("anon_search", anon_search); - - - int contain_files = 0; - int contain_folders = 0; - - if(dirDetails.count != 0) - { - for(std::vector::iterator vit = dirDetails.children.begin(); vit != dirDetails.children.end(); ++vit) - { - DirDetails dirDetails; - mRsFiles->RequestDirDetails((*vit).ref, dirDetails, flags); - - switch(dirDetails.type) - { - case DIR_TYPE_DIR: - contain_folders++; - break; - case DIR_TYPE_FILE: - contain_files++; - break; - } - } - } - - streamBase - << makeKeyValueReference("contain_files", contain_files) - << makeKeyValueReference("contain_folders", contain_folders); - } - } -} - -void FileSharingHandler::handleIsDownloadDirShared(Request&, Response& resp) -{ - bool shared = mRsFiles->getShareDownloadDirectory(); - - resp.mDataStream.getStreamToMember() - << makeKeyValueReference("shared", shared); - - resp.setOk(); -} - -void FileSharingHandler::handleShareDownloadDirectory(Request& req, Response& resp) -{ - bool share; - req.mStream << makeKeyValueReference("share", share); - - if(mRsFiles->shareDownloadDirectory(share)) - resp.setOk(); - else - resp.setFail("Couldn't share/unshare download directory."); -} - -void FileSharingHandler::handleDownload(Request& req, Response& resp) -{ - int size; - std::string hashString; - std::string name; - req.mStream << makeKeyValueReference("hash", hashString); - req.mStream << makeKeyValueReference("name", name); - req.mStream << makeKeyValueReference("size", size); - - std::list srcIds; - RsFileHash hash(hashString); - FileInfo finfo; - mRsFiles->FileDetails(hash, RS_FILE_HINTS_REMOTE, finfo); - - for(std::vector::const_iterator it(finfo.peers.begin());it!=finfo.peers.end();++it) - srcIds.push_back((*it).peerId); - - if(!mRsFiles->FileRequest(name, hash, static_cast(size), "", - RS_FILE_REQ_ANONYMOUS_ROUTING, srcIds)) - { - resp.setOk(); - return; - } - - resp.setFail("Couldn't download file"); -} - -void FileSharingHandler::handleGetDownloadDirectory( Request& /*req*/, - Response& resp ) -{ - std::string dlDir = mRsFiles->getDownloadDirectory(); - resp.mDataStream << makeKeyValueReference("download_directory", dlDir); - resp.setOk(); -} - -void FileSharingHandler::handleSetDownloadDirectory( Request& req, - Response& resp ) -{ - std::string dlDir; - req.mStream << makeKeyValueReference("download_directory", dlDir); - - if(dlDir.empty()) resp.setFail("missing download_directory"); - else - { - mRsFiles->setDownloadDirectory(dlDir); - resp.setOk(); - } -} - -void FileSharingHandler::handleGetPartialsDirectory( Request& /*req*/, - Response& resp ) -{ - std::string partialsDir = mRsFiles->getPartialsDirectory(); - resp.mDataStream << makeKeyValueReference("partials_directory", partialsDir); - resp.setOk(); -} - -void FileSharingHandler::handleSetPartialsDirectory( Request& req, - Response& resp ) -{ - std::string partialsDir; - req.mStream << makeKeyValueReference("partials_directory", partialsDir); - - if(partialsDir.empty()) resp.setFail("missing partials_directory"); - else - { - mRsFiles->setPartialsDirectory(partialsDir); - resp.setOk(); - } -} - -} // namespace resource_api diff --git a/libresapi/src/api/FileSharingHandler.h b/libresapi/src/api/FileSharingHandler.h deleted file mode 100644 index 887d4b9d3..000000000 --- a/libresapi/src/api/FileSharingHandler.h +++ /dev/null @@ -1,87 +0,0 @@ -/******************************************************************************* - * libresapi/api/FileSharingHandler.cpp * - * * - * LibResAPI: API for local socket server * - * * - * Copyright (C) 2017, Konrad Dębiec * - * * - * This program is free software: you can redistribute it and/or modify * - * it under the terms of the GNU Affero General Public License as * - * published by the Free Software Foundation, either version 3 of the * - * License, or (at your option) any later version. * - * * - * This program is distributed in the hope that it will be useful, * - * but WITHOUT ANY WARRANTY; without even the implied warranty of * - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * - * GNU Affero General Public License for more details. * - * * - * You should have received a copy of the GNU Affero General Public License * - * along with this program. If not, see . * - * * - *******************************************************************************/ -#pragma once - -#include "ResourceRouter.h" -#include "StateTokenServer.h" - -#include -#include -#include - -namespace resource_api -{ - -class FileSharingHandler: public ResourceRouter, NotifyClient -{ -public: - FileSharingHandler(StateTokenServer* sts, RsFiles* files, RsNotify& notify); - ~FileSharingHandler(); - - /** - Derived from NotifyClient - This function may be called from foreign thread - */ - virtual void notifyListChange(int list, int type); - -private: - void handleWildcard(Request& req, Response& resp); - void handleForceCheck(Request& req, Response& resp); - - void handleGetSharedDir(Request& req, Response& resp); - void handleSetSharedDir(Request& req, Response& resp); - void handleUpdateSharedDir(Request& req, Response& resp); - void handleRemoveSharedDir(Request& req, Response& resp); - - void handleGetDirectoryParent(Request& req, Response& resp); - void handleGetDirectoryChilds(Request& req, Response& resp); - - void handleIsDownloadDirShared(Request& req, Response& resp); - void handleShareDownloadDirectory(Request& req, Response& resp); - - void handleDownload(Request& req, Response& resp); - - void handleGetDownloadDirectory(Request& req, Response& resp); - void handleSetDownloadDirectory(Request& req, Response& resp); - - void handleGetPartialsDirectory(Request& req, Response& resp); - void handleSetPartialsDirectory(Request& req, Response& resp); - - /// Token indicating change in local shared files - StateToken mLocalDirStateToken; - - /// Token indicating change in remote (friends') shared files - StateToken mRemoteDirStateToken; - - StateTokenServer* mStateTokenServer; - - /** - Protects mLocalDirStateToken and mRemoteDirStateToken that may be changed in foreign thread - @see FileSharingHandler::notifyListChange(...) - */ - RsMutex mMtx; - - RsFiles* mRsFiles; - RsNotify& mNotify; -}; - -} // namespace resource_api diff --git a/libresapi/src/api/ForumHandler.cpp b/libresapi/src/api/ForumHandler.cpp deleted file mode 100644 index c6b6566b9..000000000 --- a/libresapi/src/api/ForumHandler.cpp +++ /dev/null @@ -1,169 +0,0 @@ -/******************************************************************************* - * libresapi/api/ForumHandler.cpp * - * * - * LibResAPI: API for local socket server * - * * - * Copyright 2018 by Retroshare Team * - * * - * This program is free software: you can redistribute it and/or modify * - * it under the terms of the GNU Affero General Public License as * - * published by the Free Software Foundation, either version 3 of the * - * License, or (at your option) any later version. * - * * - * This program is distributed in the hope that it will be useful, * - * but WITHOUT ANY WARRANTY; without even the implied warranty of * - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * - * GNU Affero General Public License for more details. * - * * - * You should have received a copy of the GNU Affero General Public License * - * along with this program. If not, see . * - * * - *******************************************************************************/ -#include "ForumHandler.h" - -#include -#include - -#include "Operators.h" -#include "ApiTypes.h" -#include "GxsResponseTask.h" -#ifndef WINDOWS_SYS -#include "unistd.h" -#endif - -namespace resource_api -{ -ForumHandler::ForumHandler(RsGxsForums* forums): - mRsGxsForums(forums) -{ - addResourceHandler("*", this, &ForumHandler::handleWildcard); -} - -void ForumHandler::handleWildcard(Request &req, Response &resp) -{ - bool ok = true; - if(!req.mPath.empty()) - { - std::string str = req.mPath.top(); - req.mPath.pop(); - if(str != "") - { - //assume we have a groupID - RsGxsGroupId grpId(str); - std::list groupIds; - groupIds.push_back(grpId); - - uint32_t token; - RsTokReqOptions opts; - opts.mReqType = GXS_REQUEST_TYPE_MSG_DATA; - mRsGxsForums->getTokenService()->requestMsgInfo(token, RS_TOKREQ_ANSTYPE_DATA, opts, groupIds); - - time_t start = time(NULL); - while((mRsGxsForums->getTokenService()->requestStatus(token) != RsTokenService::COMPLETE) - &&(mRsGxsForums->getTokenService()->requestStatus(token) != RsTokenService::FAILED) - &&((time(NULL) < (start+10))) - ) - { - #ifdef WINDOWS_SYS - Sleep(500); - #else - usleep(500*1000) ; - #endif - } - - if(mRsGxsForums->getTokenService()->requestStatus(token) == RsTokenService::COMPLETE) - { - std::vector grps; - ok &= mRsGxsForums->getMsgData(token, grps); - for(std::vector::iterator vit = grps.begin(); vit != grps.end(); vit++) - { - RsGxsForumMsg& grp = *vit; - KeyValueReference group_id("group_id", grp.mMeta.mGroupId); - resp.mDataStream.getStreamToMember() - << group_id - << makeKeyValueReference("name", grp.mMeta.mMsgName) - << makeKeyValueReference("id", grp.mMeta.mMsgId) - << makeKeyValueReference("parent_id", grp.mMeta.mParentId) - << makeKeyValueReference("author_id", grp.mMeta.mAuthorId) - << makeKeyValueReference("orig_msg_id", grp.mMeta.mOrigMsgId) - << makeKeyValueReference("thread_id", grp.mMeta.mThreadId) - << makeKeyValueReference("message", grp.mMsg); - } - } - else - { - ok = false; - } - - } - - } - else - { - // no more path element - RsTokReqOptions opts; - opts.mReqType = GXS_REQUEST_TYPE_GROUP_DATA; - uint32_t token; - mRsGxsForums->getTokenService()->requestGroupInfo(token, RS_TOKREQ_ANSTYPE_DATA, opts); - - time_t start = time(NULL); - while((mRsGxsForums->getTokenService()->requestStatus(token) != RsTokenService::COMPLETE) - &&(mRsGxsForums->getTokenService()->requestStatus(token) != RsTokenService::FAILED) - &&((time(NULL) < (start+10))) - ) - { - #ifdef WINDOWS_SYS - Sleep(500); - #else - usleep(500*1000) ; - #endif - } - if(mRsGxsForums->getTokenService()->requestStatus(token) == RsTokenService::COMPLETE) - { - std::vector grps; - ok &= mRsGxsForums->getGroupData(token, grps); - for(std::vector::iterator vit = grps.begin(); vit != grps.end(); vit++) - { - RsGxsForumGroup& grp = *vit; - KeyValueReference id("id", grp.mMeta.mGroupId); - KeyValueReference vis_msg("visible_msg_count", grp.mMeta.mVisibleMsgCount); - //KeyValueReference pgp_id("pgp_id",grp.mPgpId ); - // not very happy about this, i think the flags should stay hidden in rsidentities - bool own = (grp.mMeta.mSubscribeFlags & GXS_SERV::GROUP_SUBSCRIBE_ADMIN); - bool pgp_linked = (grp.mMeta.mGroupFlags & RSGXSID_GROUPFLAG_REALID_kept_for_compatibility); - bool subscribed = IS_GROUP_SUBSCRIBED(grp.mMeta.mSubscribeFlags); - resp.mDataStream.getStreamToMember() - << id - //<< pgp_id - << makeKeyValueReference("name", grp.mMeta.mGroupName) - //<< makeKeyValueReference("last_post", grp.mMeta.mLastPost) - << makeKeyValueReference("pop", grp.mMeta.mPop) - //<< makeKeyValueReference("publish_ts", grp.mMeta.mPublishTs) - << vis_msg - << makeKeyValueReference("group_status", grp.mMeta.mGroupStatus) - << makeKeyValueReference("author_id", grp.mMeta.mAuthorId) - << makeKeyValueReference("parent_grp_id", grp.mMeta.mParentGrpId) - << makeKeyValueReference("description", grp.mDescription) - << makeKeyValueReference("own", own) - << makeKeyValueReference("subscribed", subscribed) - << makeKeyValueReference("pgp_linked", pgp_linked); - } - } - else - { - ok = false; - } - } - - - if(ok) - { - resp.setOk(); - } - else - { - resp.setFail(); - } -} - -} // namespace resource_api diff --git a/libresapi/src/api/ForumHandler.h b/libresapi/src/api/ForumHandler.h deleted file mode 100644 index e5225bb22..000000000 --- a/libresapi/src/api/ForumHandler.h +++ /dev/null @@ -1,41 +0,0 @@ -/******************************************************************************* - * libresapi/api/ForumHandler.h * - * * - * LibResAPI: API for local socket server * - * * - * Copyright 2018 by Retroshare Team * - * * - * This program is free software: you can redistribute it and/or modify * - * it under the terms of the GNU Affero General Public License as * - * published by the Free Software Foundation, either version 3 of the * - * License, or (at your option) any later version. * - * * - * This program is distributed in the hope that it will be useful, * - * but WITHOUT ANY WARRANTY; without even the implied warranty of * - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * - * GNU Affero General Public License for more details. * - * * - * You should have received a copy of the GNU Affero General Public License * - * along with this program. If not, see . * - * * - *******************************************************************************/ -#ifndef FORUMHANDLER_H -#define FORUMHANDLER_H - -#include "ResourceRouter.h" - -class RsGxsForums; - -namespace resource_api -{ - -class ForumHandler : public ResourceRouter -{ -public: - ForumHandler(RsGxsForums* forums); -private: - RsGxsForums* mRsGxsForums; - void handleWildcard(Request& req, Response& resp); -}; -} // namespace resource_api -#endif // FORUMHANDLER_H diff --git a/libresapi/src/api/GetPluginInterfaces.cpp b/libresapi/src/api/GetPluginInterfaces.cpp deleted file mode 100644 index 5375d0eea..000000000 --- a/libresapi/src/api/GetPluginInterfaces.cpp +++ /dev/null @@ -1,72 +0,0 @@ -/******************************************************************************* - * libresapi/api/GetPluginInterfaces.cpp * - * * - * LibResAPI: API for local socket server * - * * - * Copyright 2018 by Retroshare Team * - * * - * This program is free software: you can redistribute it and/or modify * - * it under the terms of the GNU Affero General Public License as * - * published by the Free Software Foundation, either version 3 of the * - * License, or (at your option) any later version. * - * * - * This program is distributed in the hope that it will be useful, * - * but WITHOUT ANY WARRANTY; without even the implied warranty of * - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * - * GNU Affero General Public License for more details. * - * * - * You should have received a copy of the GNU Affero General Public License * - * along with this program. If not, see . * - * * - *******************************************************************************/ -#include "GetPluginInterfaces.h" - -#include - -#include -#include -#include -#include -#include -#include - -#include -#include -#include -#include - -namespace resource_api{ - -bool getPluginInterfaces(RsPlugInInterfaces& interfaces) -{ - // when rsPlugins is null, then rs was not started - if(rsPlugins == 0) - return false; - - interfaces.mFiles = rsFiles; - interfaces.mPeers = rsPeers; - interfaces.mMsgs = rsMsgs; - interfaces.mTurtle = rsTurtle; - interfaces.mDisc = rsDisc; - interfaces.mDht = rsDht; - interfaces.mNotify = rsNotify; - interfaces.mServiceControl = rsServiceControl; - interfaces.mPluginHandler = rsPlugins; - - // gxs - interfaces.mGxsDir = ""; - interfaces.mIdentity = rsIdentity; - // not exposed with global variable, can't get it - interfaces.mRsNxsNetMgr = 0; - // same as identity service, but different interface - interfaces.mGxsIdService = 0; - // - interfaces.mGxsCirlces = 0; - // not exposed with global variable - interfaces.mPgpAuxUtils = 0; - interfaces.mGxsForums = rsGxsForums; - interfaces.mGxsChannels = rsGxsChannels; - return true; -} - -} // namespace resource_api diff --git a/libresapi/src/api/GxsMetaOperators.h b/libresapi/src/api/GxsMetaOperators.h deleted file mode 100644 index ec6a98b9b..000000000 --- a/libresapi/src/api/GxsMetaOperators.h +++ /dev/null @@ -1,6 +0,0 @@ -#pragma once - -#include - -// operators for rsgxsgrpmeta and rsgxsmsgmeta -// diff --git a/libresapi/src/api/GxsResponseTask.cpp b/libresapi/src/api/GxsResponseTask.cpp deleted file mode 100644 index 2a35c979d..000000000 --- a/libresapi/src/api/GxsResponseTask.cpp +++ /dev/null @@ -1,148 +0,0 @@ -/******************************************************************************* - * libresapi/api/GxsResponseTask.cpp * - * * - * LibResAPI: API for local socket server * - * * - * Copyright 2018 by Retroshare Team * - * * - * This program is free software: you can redistribute it and/or modify * - * it under the terms of the GNU Affero General Public License as * - * published by the Free Software Foundation, either version 3 of the * - * License, or (at your option) any later version. * - * * - * This program is distributed in the hope that it will be useful, * - * but WITHOUT ANY WARRANTY; without even the implied warranty of * - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * - * GNU Affero General Public License for more details. * - * * - * You should have received a copy of the GNU Affero General Public License * - * along with this program. If not, see . * - * * - *******************************************************************************/ -#include "GxsResponseTask.h" - -#include "Operators.h" - -namespace resource_api -{ - -GxsResponseTask::GxsResponseTask(RsIdentity *id_service, RsTokenService *token_service): - mIdService(id_service), mTokenService(token_service), - mDone(false) -{ - -} - -bool GxsResponseTask::doWork(Request &req, Response &resp) -{ - bool ready = true; - // check if gxs requests are ready - if(mTokenService && !mWaitingTokens.empty()) - { - for(std::vector::iterator vit = mWaitingTokens.begin(); vit != mWaitingTokens.end(); ++vit) - { - uint8_t status = mTokenService->requestStatus(*vit); - if(status != RsTokenService::COMPLETE) - { - ready = false; - } - if(status == RsTokenService::FAILED) - { - std::cerr << "GxsResponseTask::doWork() Error: token failed. aborting." << std::endl; - resp.setFail("GxsResponseTask::doWork() Error: token failed."); - return false; // don't continue - } - } - } - - if(mIdService == 0) - { - std::cerr << "GxsResponseTask::doWork() ERROR: constucted with idservice = 0. Fix your code or report this bug." << std::endl; - resp.setFail("GxsResponseTask::doWork() ERROR: constucted with idservice = 0. Fix your code or report this bug."); - return false; // don't continue - } - - // check if we have identities to fetch - bool more = true; - while(!mIdentitiesToFetch.empty() && more) - { - // there are two methods to fetch identity data: - // - request gxs group, get token, get group - // - the direct way where we may have to wait, but identities will cache the result - // if we need to get many identuties, then we may flush the cache - // but if we reaquest the groups, no caching is done on the rs side (OS will cache the identities file) - // it has to be measured what is better - RsGxsId id = mIdentitiesToFetch.back(); - RsIdentityDetails details; - if(mIdService->getIdDetails(id, details)) - { - mIdentitiesToFetch.pop_back(); - mIdentityDetails.push_back(details); - } - else - { - more = false; // pause when an id failed, to give the service time tim fetch the data - ready = false; - // TODO: remove identities which failed many times from list, to avoid blocking when ids fail - } - } - if(!ready) - return true; // want to continue later - - mWaitingTokens.clear(); - mIdentitiesToFetch.clear(); - gxsDoWork(req, resp); - - if(mDone) return false; - else return true; -} - -void GxsResponseTask::addWaitingToken(uint32_t token) -{ - if(mTokenService) - mWaitingTokens.push_back(token); - else - std::cerr << "GxsResponseTask::addWaitingToken() ERROR: constructed with tokenservice=0. Unable to handle token processing. Fix your code or report this bug." << std::endl; -} - -void GxsResponseTask::done() -{ - mDone = true; -} - -void GxsResponseTask::requestGxsId(RsGxsId id) -{ - mIdentitiesToFetch.push_back(id); -} - -void GxsResponseTask::streamGxsId(RsGxsId id, StreamBase &stream) -{ - // will see if this works or if we have to use an index - for(std::vector::iterator vit = mIdentityDetails.begin(); - vit != mIdentityDetails.end(); ++vit) - { - if(vit->mId == id) - { - stream << makeKeyValueReference("id", id) - << makeKeyValueReference("gxs_id", id) - << makeKeyValueReference("flags", vit->mFlags) - << makeKeyValueReference("name", vit->mNickname); - return; - } - } -} - -std::string GxsResponseTask::getName(RsGxsId id) -{ - for(std::vector::iterator vit = mIdentityDetails.begin(); - vit != mIdentityDetails.end(); ++vit) - { - if(vit->mId == id) - return vit->mNickname; - } - std::cerr << "Warning: identity not found in GxsResponseTask::getName(). This is probably a bug. You must call GxsResponseTask::requestGxsId() before you can get the name." << std::endl; - return ""; -} - - -} // namespace resource_api diff --git a/libresapi/src/api/GxsResponseTask.h b/libresapi/src/api/GxsResponseTask.h deleted file mode 100644 index 30c30bc40..000000000 --- a/libresapi/src/api/GxsResponseTask.h +++ /dev/null @@ -1,72 +0,0 @@ -/******************************************************************************* - * libresapi/api/GxsResponseTask.h * - * * - * LibResAPI: API for local socket server * - * * - * Copyright 2018 by Retroshare Team * - * * - * This program is free software: you can redistribute it and/or modify * - * it under the terms of the GNU Affero General Public License as * - * published by the Free Software Foundation, either version 3 of the * - * License, or (at your option) any later version. * - * * - * This program is distributed in the hope that it will be useful, * - * but WITHOUT ANY WARRANTY; without even the implied warranty of * - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * - * GNU Affero General Public License for more details. * - * * - * You should have received a copy of the GNU Affero General Public License * - * along with this program. If not, see . * - * * - *******************************************************************************/ -#pragma once - -#include "ApiTypes.h" -#include - -namespace resource_api -{ -// parent class for all responses that use the gxs backend -// this class implements the polling for gxs-tokens -// child classes pass gxs tokens to this class - -// question: should this class be able to handle tokens from different services? -// then we would have to store a pointer to the token service for ever token -class GxsResponseTask: public ResponseTask -{ -public: - // token service is allowed to be null if no token functions are wanted - GxsResponseTask(RsIdentity* id_service, RsTokenService* token_service = 0); - virtual bool doWork(Request &req, Response& resp); - -protected: - // this method gets called when all the pending tokens have either status ok or fail - // (= when the requests for these tokens are processed) - // how will the child class find out if a request failed? - // idea: don't call gxsDoWork() when a request failed, instead set the api response to fail - // con: then the child class has no way to tell the outside world which request failed - // pro: child class gets simpler, because no special error handling is required - // implement this in a child class - virtual void gxsDoWork(Request& req, Response& resp) = 0; - - // call this to wait for tokens before the next call to gxsDoWork() - void addWaitingToken(uint32_t token); - // call this to end the task - void done(); - // request name for gxs id - void requestGxsId(RsGxsId id); - // call stream function in the next cycle, then the names are available - void streamGxsId(RsGxsId id, StreamBase& stream); - std::string getName(RsGxsId id); -private: - RsIdentity* mIdService; - RsTokenService* mTokenService; - - std::vector mWaitingTokens; - bool mDone; - - std::vector mIdentitiesToFetch; - std::vector mIdentityDetails; -}; - -} // namespace resource_api diff --git a/libresapi/src/api/IdentityHandler.cpp b/libresapi/src/api/IdentityHandler.cpp deleted file mode 100644 index e82b857a0..000000000 --- a/libresapi/src/api/IdentityHandler.cpp +++ /dev/null @@ -1,722 +0,0 @@ -/******************************************************************************* - * libresapi/api/IdentityHandler.cpp * - * * - * LibResAPI: API for local socket server * - * * - * Copyright (C) 2015 electron128 * - * Copyright (C) 2017 Gioacchino Mazzurco * - * * - * This program is free software: you can redistribute it and/or modify * - * it under the terms of the GNU Affero General Public License as * - * published by the Free Software Foundation, either version 3 of the * - * License, or (at your option) any later version. * - * * - * This program is distributed in the hope that it will be useful, * - * but WITHOUT ANY WARRANTY; without even the implied warranty of * - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * - * GNU Affero General Public License for more details. * - * * - * You should have received a copy of the GNU Affero General Public License * - * along with this program. If not, see . * - * * - *******************************************************************************/ - -#include "IdentityHandler.h" - -#include -#include -#include -#include - -#include "Operators.h" -#include "ApiTypes.h" -#include "GxsResponseTask.h" -#ifndef WINDOWS_SYS -#include "unistd.h" -#endif - -namespace resource_api -{ - -class SendIdentitiesListTask: public GxsResponseTask -{ -public: - SendIdentitiesListTask(RsIdentity* idservice, std::list ids, StateToken state): - GxsResponseTask(idservice, 0), mStateToken(state) - { - for(std::list::iterator vit = ids.begin(); vit != ids.end(); ++vit) - { - requestGxsId(*vit); - mIds.push_back(*vit);// convert from list to vector - } - } -private: - std::vector mIds; - StateToken mStateToken; -protected: - virtual void gxsDoWork(Request& /*req*/, Response &resp) - { - resp.mDataStream.getStreamToMember(); - for(std::vector::iterator vit = mIds.begin(); vit != mIds.end(); ++vit) - { - streamGxsId(*vit, resp.mDataStream.getStreamToMember()); - } - resp.mStateToken = mStateToken; - resp.setOk(); - done(); - } - -}; - -class CreateIdentityTask: public GxsResponseTask -{ -public: - CreateIdentityTask(RsIdentity* idservice): - GxsResponseTask(idservice, idservice->getTokenService()), mState(BEGIN), mToken(0), mRsIdentity(idservice){} -private: - enum State {BEGIN, WAIT_ACKN, WAIT_ID}; - State mState; - uint32_t mToken; - RsIdentity* mRsIdentity; - RsGxsId mId; -protected: - virtual void gxsDoWork(Request &req, Response &resp) - { - switch(mState) - { - case BEGIN:{ - RsIdentityParameters params; - req.mStream - << makeKeyValueReference("name", params.nickname) - << makeKeyValueReference("pgp_linked", params.isPgpLinked); - - std::string avatar; - req.mStream << makeKeyValueReference("avatar", avatar); - - std::vector avatar_data = Radix64::decode(avatar); - uint8_t *p_avatar_data = &avatar_data[0]; - uint32_t size = avatar_data.size(); - params.mImage.clear(); - params.mImage.copy(p_avatar_data, size); - - if(params.nickname == "") - { - resp.setFail("name can't be empty"); - done(); - return; - } - mRsIdentity->createIdentity(mToken, params); - addWaitingToken(mToken); - mState = WAIT_ACKN; - break; - } - case WAIT_ACKN:{ - RsGxsGroupId grpId; - if(!mRsIdentity->acknowledgeGrp(mToken, grpId)) - { - resp.setFail("acknowledge of group id failed"); - done(); - return; - } - mId = RsGxsId(grpId); - requestGxsId(mId); - mState = WAIT_ID; - break; - } - case WAIT_ID: - streamGxsId(mId, resp.mDataStream); - resp.setOk(); - done(); - } - } -}; - -class DeleteIdentityTask : public GxsResponseTask -{ -public: - DeleteIdentityTask(RsIdentity* idservice) : - GxsResponseTask(idservice, idservice->getTokenService()), - mToken(0), - mRsIdentity(idservice) - {} - -protected: - virtual void gxsDoWork(Request &req, Response & /* resp */) - { - RsGxsIdGroup group; - std::string gxs_id; - - req.mStream << makeKeyValueReference("gxs_id", gxs_id); - group.mMeta.mGroupId = RsGxsGroupId(gxs_id); - - mRsIdentity->deleteIdentity(mToken, group); - addWaitingToken(mToken); - - done(); - return; - } - -private: - uint32_t mToken; - RsIdentity* mRsIdentity; - RsGxsId mId; -}; - -IdentityHandler::IdentityHandler(StateTokenServer *sts, RsNotify *notify, - RsIdentity *identity) : - mStateTokenServer(sts), mNotify(notify), mRsIdentity(identity), - mMtx("IdentityHandler Mtx"), mStateToken(sts->getNewToken()) -{ - mNotify->registerNotifyClient(this); - - addResourceHandler("*", this, &IdentityHandler::handleWildcard); - addResourceHandler("own", this, &IdentityHandler::handleOwn); - - addResourceHandler("own_ids", this, &IdentityHandler::handleOwnIdsRequest); - addResourceHandler("notown_ids", this, - &IdentityHandler::handleNotOwnIdsRequest); - - addResourceHandler("export_key", this, &IdentityHandler::handleExportKey); - addResourceHandler("import_key", this, &IdentityHandler::handleImportKey); - - addResourceHandler("add_contact", this, &IdentityHandler::handleAddContact); - addResourceHandler("remove_contact", this, &IdentityHandler::handleRemoveContact); - - addResourceHandler("create_identity", this, &IdentityHandler::handleCreateIdentity); - addResourceHandler("delete_identity", this, &IdentityHandler::handleDeleteIdentity); - - addResourceHandler("get_identity_details", this, &IdentityHandler::handleGetIdentityDetails); - - addResourceHandler("get_avatar", this, &IdentityHandler::handleGetAvatar); - addResourceHandler("set_avatar", this, &IdentityHandler::handleSetAvatar); - - addResourceHandler("set_ban_node", this, &IdentityHandler::handleSetBanNode); - addResourceHandler("set_opinion", this, &IdentityHandler::handleSetOpinion); -} - -IdentityHandler::~IdentityHandler() -{ - mNotify->unregisterNotifyClient(this); -} - -void IdentityHandler::notifyGxsChange(const RsGxsChanges &changes) -{ - RS_STACK_MUTEX(mMtx); - // if changes come from identity service, invalidate own state token - if(changes.mService == mRsIdentity->getTokenService()) - mStateTokenServer->replaceToken(mStateToken); -} - -void IdentityHandler::handleWildcard(Request & /*req*/, Response &resp) -{ - bool ok = true; - - { - RS_STACK_MUTEX(mMtx); - resp.mStateToken = mStateToken; - } - RsTokReqOptions opts; - opts.mReqType = GXS_REQUEST_TYPE_GROUP_DATA; - uint32_t token; - mRsIdentity->getTokenService()->requestGroupInfo( - token, RS_TOKREQ_ANSTYPE_DATA, opts); - - time_t timeout = time(NULL)+10; - uint8_t rStatus = mRsIdentity->getTokenService()->requestStatus(token); - while( rStatus != RsTokenService::COMPLETE && - rStatus != RsTokenService::FAILED && - time(NULL) < timeout ) - { - usleep(50*1000); - rStatus = mRsIdentity->getTokenService()->requestStatus(token); - } - - if(rStatus == RsTokenService::COMPLETE) - { - std::vector grps; - ok &= mRsIdentity->getGroupData(token, grps); - for( std::vector::iterator vit = grps.begin(); - vit != grps.end(); ++vit ) - { - RsGxsIdGroup& grp = *vit; - /* electron: not very happy about this, i think the flags should - * stay hidden in rsidentities */ - bool own = (grp.mMeta.mSubscribeFlags & - GXS_SERV::GROUP_SUBSCRIBE_ADMIN); - bool pgp_linked = (grp.mMeta.mGroupFlags & - RSGXSID_GROUPFLAG_REALID_kept_for_compatibility); - resp.mDataStream.getStreamToMember() -#warning Gioacchino Mazzurco 2017-03-24: @deprecated using "id" as key can cause problems in some JS based \ - languages like Qml @see gxs_id instead - << makeKeyValueReference("id", grp.mMeta.mGroupId) - << makeKeyValueReference("gxs_id", grp.mMeta.mGroupId) - << makeKeyValueReference("pgp_id",grp.mPgpId ) - << makeKeyValueReference("name", grp.mMeta.mGroupName) - << makeKeyValueReference("contact", grp.mIsAContact) - << makeKeyValueReference("own", own) - << makeKeyValueReference("pgp_linked", pgp_linked) - << makeKeyValueReference("is_contact", grp.mIsAContact); - } - } - else ok = false; - - if(ok) resp.setOk(); - else resp.setFail(); -} - -void IdentityHandler::handleNotOwnIdsRequest(Request & /*req*/, Response &resp) -{ - bool ok = true; - - { - RS_STACK_MUTEX(mMtx); - resp.mStateToken = mStateToken; - } - RsTokReqOptions opts; - opts.mReqType = GXS_REQUEST_TYPE_GROUP_DATA; - uint32_t token; - mRsIdentity->getTokenService()->requestGroupInfo( - token, RS_TOKREQ_ANSTYPE_DATA, opts); - - time_t timeout = time(NULL)+10; - uint8_t rStatus = mRsIdentity->getTokenService()->requestStatus(token); - while( rStatus != RsTokenService::COMPLETE && - rStatus != RsTokenService::FAILED && - time(NULL) < timeout ) - { - usleep(50*1000); - rStatus = mRsIdentity->getTokenService()->requestStatus(token); - } - - if(rStatus == RsTokenService::COMPLETE) - { - std::vector grps; - ok &= mRsIdentity->getGroupData(token, grps); - for(std::vector::iterator vit = grps.begin(); - vit != grps.end(); vit++) - { - RsGxsIdGroup& grp = *vit; - if(!(grp.mMeta.mSubscribeFlags & GXS_SERV::GROUP_SUBSCRIBE_ADMIN)) - { - bool pgp_linked = ( - grp.mMeta.mGroupFlags & - RSGXSID_GROUPFLAG_REALID_kept_for_compatibility ); - resp.mDataStream.getStreamToMember() - << makeKeyValueReference("gxs_id", grp.mMeta.mGroupId) - << makeKeyValueReference("pgp_id",grp.mPgpId ) - << makeKeyValueReference("name", grp.mMeta.mGroupName) - << makeKeyValueReference("pgp_linked", pgp_linked) - << makeKeyValueReference("is_contact", grp.mIsAContact); - } - } - } - else ok = false; - - if(ok) resp.setOk(); - else resp.setFail(); -} - -void IdentityHandler::handleOwnIdsRequest(Request & /*req*/, Response &resp) -{ - bool ok = true; - - { - RS_STACK_MUTEX(mMtx); - resp.mStateToken = mStateToken; - } - RsTokReqOptions opts; - opts.mReqType = GXS_REQUEST_TYPE_GROUP_DATA; - uint32_t token; - mRsIdentity->getTokenService()->requestGroupInfo(token, RS_TOKREQ_ANSTYPE_DATA, opts); - - time_t start = time(NULL); - while((mRsIdentity->getTokenService()->requestStatus(token) != RsTokenService::COMPLETE) - &&(mRsIdentity->getTokenService()->requestStatus(token) != RsTokenService::FAILED) - &&((time(NULL) < (start+10))) - ) - { -#ifdef WINDOWS_SYS - Sleep(500); -#else - usleep(500*1000); -#endif - } - - if(mRsIdentity->getTokenService()->requestStatus(token) == RsTokenService::COMPLETE) - { - std::vector grps; - ok &= mRsIdentity->getGroupData(token, grps); - for(std::vector::iterator vit = grps.begin(); vit != grps.end(); vit++) - { - RsGxsIdGroup& grp = *vit; - //electron: not very happy about this, i think the flags should stay hidden in rsidentities - if(vit->mMeta.mSubscribeFlags & GXS_SERV::GROUP_SUBSCRIBE_ADMIN) - { - bool pgp_linked = (grp.mMeta.mGroupFlags & RSGXSID_GROUPFLAG_REALID_kept_for_compatibility ) ; - resp.mDataStream.getStreamToMember() - << makeKeyValueReference("own_gxs_id", grp.mMeta.mGroupId) - << makeKeyValueReference("pgp_id",grp.mPgpId ) - << makeKeyValueReference("name", grp.mMeta.mGroupName) - << makeKeyValueReference("pgp_linked", pgp_linked); - } - } - - } - else - ok = false; - - if(ok) resp.setOk(); - else resp.setFail(); -} - -void IdentityHandler::handleAddContact(Request& req, Response& resp) -{ - std::string gxs_id; - req.mStream << makeKeyValueReference("gxs_id", gxs_id); - - mRsIdentity->setAsRegularContact(RsGxsId(gxs_id), true); - - { - RS_STACK_MUTEX(mMtx); // ********** LOCKED ********** - mStateTokenServer->replaceToken(mStateToken); - } - - resp.setOk(); -} - -void IdentityHandler::handleRemoveContact(Request& req, Response& resp) -{ - std::string gxs_id; - req.mStream << makeKeyValueReference("gxs_id", gxs_id); - - mRsIdentity->setAsRegularContact(RsGxsId(gxs_id), false); - - { - RS_STACK_MUTEX(mMtx); // ********** LOCKED ********** - mStateTokenServer->replaceToken(mStateToken); - } - - resp.setOk(); -} - -void IdentityHandler::handleGetIdentityDetails(Request& req, Response& resp) -{ - std::string gxs_id; - req.mStream << makeKeyValueReference("gxs_id", gxs_id); - - RsTokReqOptions opts; - opts.mReqType = GXS_REQUEST_TYPE_GROUP_DATA; - uint32_t token; - - std::list groupIds; - groupIds.push_back(RsGxsGroupId(gxs_id)); - mRsIdentity->getTokenService()->requestGroupInfo(token, RS_TOKREQ_ANSTYPE_DATA, opts, groupIds); - - time_t start = time(NULL); - while((mRsIdentity->getTokenService()->requestStatus(token) != RsTokenService::COMPLETE) - &&(mRsIdentity->getTokenService()->requestStatus(token) != RsTokenService::FAILED) - &&((time(NULL) < (start+10))) - ) - { -#ifdef WINDOWS_SYS - Sleep(500); -#else - usleep(500*1000); -#endif - } - - RsGxsIdGroup data; - std::vector datavector; - if (!mRsIdentity->getGroupData(token, datavector)) - { - resp.setFail(); - return; - } - - if(datavector.empty()) - { - resp.setFail(); - return; - } - - data = datavector[0]; - - resp.mDataStream << makeKeyValue("gxs_name", data.mMeta.mGroupName); - resp.mDataStream << makeKeyValue("gxs_id", data.mMeta.mGroupId.toStdString()); - - resp.mDataStream << makeKeyValue("pgp_id_known", data.mPgpKnown); - resp.mDataStream << makeKeyValue("pgp_id", data.mPgpId.toStdString()); - - std::string pgp_name; - if (data.mPgpKnown) - { - RsPeerDetails details; - rsPeers->getGPGDetails(data.mPgpId, details); - pgp_name = details.name; - } - else - { - if (data.mMeta.mGroupFlags & RSGXSID_GROUPFLAG_REALID_kept_for_compatibility) - pgp_name = "[Unknown node]"; - else - pgp_name = "Anonymous Id"; - } - resp.mDataStream << makeKeyValue("pgp_name", pgp_name); - - resp.mDataStream << makeKeyValue("last_usage", (uint32_t)data.mLastUsageTS); - - bool isAnonymous = false; - if(!data.mPgpKnown) - { - if (!(data.mMeta.mGroupFlags & RSGXSID_GROUPFLAG_REALID_kept_for_compatibility)) - isAnonymous = true; - } - resp.mDataStream << makeKeyValue("anonymous", isAnonymous); - - - bool isOwnId = (data.mMeta.mSubscribeFlags & GXS_SERV::GROUP_SUBSCRIBE_ADMIN); - resp.mDataStream << makeKeyValue("own", isOwnId); - - std::string type; - if(isOwnId) - { - if (data.mPgpKnown && !data.mPgpId.isNull()) - type = "Identity owned by you, linked to your Retroshare node"; - else - type = "Anonymous identity, owned by you"; - } - else if (data.mMeta.mGroupFlags & RSGXSID_GROUPFLAG_REALID_kept_for_compatibility) - { - if (data.mPgpKnown) - { - if (rsPeers->isGPGAccepted(data.mPgpId)) - type = "Linked to a friend Retroshare node"; - else - type = "Linked to a known Retroshare node"; - } - else - type = "Linked to unknown Retroshare node"; - } - else - type = "Anonymous identity"; - - resp.mDataStream << makeKeyValue("type", type); - - resp.mDataStream << makeKeyValue("bannned_node", rsReputations->isNodeBanned(data.mPgpId)); - - RsReputationInfo info; - rsReputations->getReputationInfo(RsGxsId(data.mMeta.mGroupId), data.mPgpId, info); - resp.mDataStream << makeKeyValue("friends_positive_votes", info.mFriendsPositiveVotes); - resp.mDataStream << makeKeyValue("friends_negative_votes", info.mFriendsNegativeVotes); - resp.mDataStream << makeKeyValue("overall_reputation_level", (int)info.mOverallReputationLevel); - resp.mDataStream << makeKeyValue("own_opinion", (int)info.mOwnOpinion); - - RsIdentityDetails details; - mRsIdentity->getIdDetails(RsGxsId(data.mMeta.mGroupId), details); - - std::string base64Avatar; - Radix64::encode(details.mAvatar.mData, details.mAvatar.mSize, base64Avatar); - resp.mDataStream << makeKeyValue("avatar", base64Avatar); - - StreamBase& usagesStream = resp.mDataStream.getStreamToMember("usages"); - usagesStream.getStreamToMember(); - - for(auto it(details.mUseCases.begin()); it != details.mUseCases.end(); ++it) - { - usagesStream.getStreamToMember() - << makeKeyValue("usage_time", (uint32_t)data.mLastUsageTS) - << makeKeyValue("usage_service", (int)(it->first.mServiceId)) - << makeKeyValue("usage_case", (int)(it->first.mUsageCode)); - } - - resp.setOk(); -} - -void IdentityHandler::handleSetAvatar(Request& req, Response& resp) -{ - std::string gxs_id; - std::string avatar; - req.mStream << makeKeyValueReference("gxs_id", gxs_id); - req.mStream << makeKeyValueReference("avatar", avatar); - - RsTokReqOptions opts; - opts.mReqType = GXS_REQUEST_TYPE_GROUP_DATA; - uint32_t token; - - std::list groupIds; - groupIds.push_back(RsGxsGroupId(gxs_id)); - mRsIdentity->getTokenService()->requestGroupInfo(token, RS_TOKREQ_ANSTYPE_DATA, opts, groupIds); - - time_t start = time(NULL); - while((mRsIdentity->getTokenService()->requestStatus(token) != RsTokenService::COMPLETE) - &&(mRsIdentity->getTokenService()->requestStatus(token) != RsTokenService::FAILED) - &&((time(NULL) < (start+10))) - ) - { -#ifdef WINDOWS_SYS - Sleep(500); -#else - usleep(500*1000); -#endif - } - - RsGxsIdGroup data; - std::vector datavector; - if (!mRsIdentity->getGroupData(token, datavector)) - { - resp.setFail(); - return; - } - - if(datavector.empty()) - { - resp.setFail(); - return; - } - - data = datavector[0]; - - if(!avatar.empty()) - { - std::vector avatar_data = Radix64::decode(avatar); - uint8_t *p_avatar_data = &avatar_data[0]; - uint32_t size = avatar_data.size(); - data.mImage.clear(); - data.mImage.copy(p_avatar_data, size); - - std::string base64Avatar; - Radix64::encode(data.mImage.mData, data.mImage.mSize, base64Avatar); - resp.mDataStream << makeKeyValue("avatar", base64Avatar); - } - else - data.mImage.clear(); - - uint32_t dummyToken = 0; - mRsIdentity->updateIdentity(dummyToken, data); - - resp.setOk(); -} - -void IdentityHandler::handleGetAvatar(Request& req, Response& resp) -{ - std::string gxs_id; - req.mStream << makeKeyValueReference("gxs_id", gxs_id); - - RsIdentityDetails details; - bool got = mRsIdentity->getIdDetails(RsGxsId(gxs_id), details); - - std::string base64Avatar; - Radix64::encode(details.mAvatar.mData, details.mAvatar.mSize, base64Avatar); - resp.mDataStream << makeKeyValue("avatar", base64Avatar); - - if(got) - resp.setOk(); - else - resp.setFail(); -} - -void IdentityHandler::handleSetBanNode(Request& req, Response& resp) -{ - std::string pgp_id; - req.mStream << makeKeyValueReference("pgp_id", pgp_id); - RsPgpId pgpId(pgp_id); - - bool banned_node; - req.mStream << makeKeyValueReference("banned_node", banned_node); - rsReputations->banNode(pgpId, banned_node); - - resp.setOk(); -} - -void IdentityHandler::handleSetOpinion(Request& req, Response& resp) -{ - std::string gxs_id; - req.mStream << makeKeyValueReference("gxs_id", gxs_id); - RsGxsId gxsId(gxs_id); - - int own_opinion; - req.mStream << makeKeyValueReference("own_opinion", own_opinion); - - RsOpinion opinion; - switch(own_opinion) - { - case 0: opinion = RsOpinion::NEGATIVE; break; - case 1: opinion = RsOpinion::NEUTRAL; break; - case 2: opinion = RsOpinion::POSITIVE; break; - default: - resp.setFail(); - return; - } - rsReputations->setOwnOpinion(gxsId, opinion); - - resp.setOk(); -} - -ResponseTask* IdentityHandler::handleOwn(Request & /* req */, Response &resp) -{ - StateToken state; - { - RS_STACK_MUTEX(mMtx); // ********** LOCKED ********** - state = mStateToken; - } - std::list ids; - if(mRsIdentity->getOwnIds(ids)) - return new SendIdentitiesListTask(mRsIdentity, ids, state); - resp.mDataStream.getStreamToMember(); - resp.setWarning("identities not loaded yet"); - return 0; -} - -ResponseTask* IdentityHandler::handleCreateIdentity(Request & /* req */, Response & /* resp */) -{ - return new CreateIdentityTask(mRsIdentity); -} - -void IdentityHandler::handleExportKey(Request& req, Response& resp) -{ - RsGxsId gxs_id; - req.mStream << makeKeyValueReference("gxs_id", gxs_id); - - std::string radix; - time_t timeout = time(NULL)+2; - bool found = mRsIdentity->serialiseIdentityToMemory(gxs_id, radix); - while(!found && time(nullptr) < timeout) - { - usleep(5000); - found = mRsIdentity->serialiseIdentityToMemory(gxs_id, radix); - } - - if(found) - { - resp.mDataStream << makeKeyValueReference("gxs_id", gxs_id) - << makeKeyValueReference("radix", radix); - - resp.setOk(); - return; - } - - resp.setFail(); -} - -void IdentityHandler::handleImportKey(Request& req, Response& resp) -{ - std::string radix; - req.mStream << makeKeyValueReference("radix", radix); - - RsGxsId gxs_id; - if(mRsIdentity->deserialiseIdentityFromMemory(radix, &gxs_id)) - { - resp.mDataStream << makeKeyValueReference("gxs_id", gxs_id) - << makeKeyValueReference("radix", radix); - resp.setOk(); - return; - } - - resp.setFail(); -} - -ResponseTask* IdentityHandler::handleDeleteIdentity(Request& /*req*/, - Response& /*resp*/) -{ return new DeleteIdentityTask(mRsIdentity); } - -} // namespace resource_api diff --git a/libresapi/src/api/IdentityHandler.h b/libresapi/src/api/IdentityHandler.h deleted file mode 100644 index 84b39878f..000000000 --- a/libresapi/src/api/IdentityHandler.h +++ /dev/null @@ -1,76 +0,0 @@ -/******************************************************************************* - * libresapi/api/IdentityHandler.h * - * * - * LibResAPI: API for local socket server * - * * - * Copyright (C) 2015 electron128 * - * Copyright (C) 2017 Gioacchino Mazzurco * - * * - * This program is free software: you can redistribute it and/or modify * - * it under the terms of the GNU Affero General Public License as * - * published by the Free Software Foundation, either version 3 of the * - * License, or (at your option) any later version. * - * * - * This program is distributed in the hope that it will be useful, * - * but WITHOUT ANY WARRANTY; without even the implied warranty of * - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * - * GNU Affero General Public License for more details. * - * * - * You should have received a copy of the GNU Affero General Public License * - * along with this program. If not, see . * - * * - *******************************************************************************/ -#pragma once - -#include -#include - -#include "ResourceRouter.h" -#include "StateTokenServer.h" - -struct RsIdentity; - -namespace resource_api -{ - -class IdentityHandler: public ResourceRouter, NotifyClient -{ -public: - IdentityHandler(StateTokenServer* sts, RsNotify* notify, RsIdentity* identity); - virtual ~IdentityHandler(); - - // from NotifyClient - // note: this may get called from foreign threads - virtual void notifyGxsChange(const RsGxsChanges &changes); - -private: - void handleWildcard(Request& req, Response& resp); - void handleNotOwnIdsRequest(Request& req, Response& resp); - void handleOwnIdsRequest(Request& req, Response& resp); - - void handleExportKey(Request& req, Response& resp); - void handleImportKey(Request& req, Response& resp); - - void handleAddContact(Request& req, Response& resp); - void handleRemoveContact(Request& req, Response& resp); - - void handleGetIdentityDetails(Request& req, Response& resp); - - void handleGetAvatar(Request& req, Response& resp); - void handleSetAvatar(Request& req, Response& resp); - - void handleSetBanNode(Request& req, Response& resp); - void handleSetOpinion(Request& req, Response& resp); - - ResponseTask *handleOwn(Request& req, Response& resp); - ResponseTask *handleCreateIdentity(Request& req, Response& resp); - ResponseTask *handleDeleteIdentity(Request& req, Response& resp); - - StateTokenServer* mStateTokenServer; - RsNotify* mNotify; - RsIdentity* mRsIdentity; - - RsMutex mMtx; - StateToken mStateToken; // mutex protected -}; -} // namespace resource_api diff --git a/libresapi/src/api/JsonStream.cpp b/libresapi/src/api/JsonStream.cpp deleted file mode 100644 index 4e6cffb6c..000000000 --- a/libresapi/src/api/JsonStream.cpp +++ /dev/null @@ -1,545 +0,0 @@ -/******************************************************************************* - * libresapi/api/jsonStream.cpp * - * * - * LibResAPI: API for local socket server * - * * - * Copyright 2018 by Retroshare Team * - * * - * This program is free software: you can redistribute it and/or modify * - * it under the terms of the GNU Affero General Public License as * - * published by the Free Software Foundation, either version 3 of the * - * License, or (at your option) any later version. * - * * - * This program is distributed in the hope that it will be useful, * - * but WITHOUT ANY WARRANTY; without even the implied warranty of * - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * - * GNU Affero General Public License for more details. * - * * - * You should have received a copy of the GNU Affero General Public License * - * along with this program. If not, see . * - * * - *******************************************************************************/ -#include "JsonStream.h" -#include - -namespace resource_api -{ - -JsonStream::JsonStream(): - mSerialise(true), mDataType(TYPE_UNDEFINED), mArrayNextRead(0), mIsOk(true), mChild(NULL) -{ - -} - -JsonStream::~JsonStream() -{ - deleteCurrentChild(); -} - -void JsonStream::setJsonString(std::string jsonStr) -{ - mRawString = jsonStr; - // have to delay the deserialisation, because this stream can also be a raw data stream without json - // can find this out when others atucally call the operators - mSerialise = false; -} - -std::string JsonStream::getJsonString() -{ - deleteCurrentChild(); - if(mIsOk) - { - switch(mDataType) - { - case TYPE_UNDEFINED: - return ""; - case TYPE_ARRAY: - return json::Serialize(mArray); - case TYPE_OBJECT: - return json::Serialize(mObject); - case TYPE_RAW: - return mRawString; - default: - return ""; - } - } - std::cerr << "JsonStream::getJsonString() Warning: stream not ok, will return empty string." << std::endl; - return ""; -} - -void JsonStream::switchToDeserialisation() -{ - deleteCurrentChild(); - mSerialise = false; -} - - -//----------Stream Interface --------------- - -//----------Array--------------- -StreamBase& JsonStream::operator<<(ValueReference value) -{ - if(serialise()) - { - setType(TYPE_ARRAY); - mArray.push_back(value.value); - } - else - { - if(checkDeserialisation() && arrayBoundsOk()) - { - valueToBool(mArray[mArrayNextRead], value.value); - mArrayNextRead++; - } - } - return *this; -} - -StreamBase& JsonStream::operator<<(ValueReference value) -{ - if(serialise()) - { - setType(TYPE_ARRAY); - mArray.push_back(value.value); - } - else - { - if(checkDeserialisation() && arrayBoundsOk()) - { - valueToInt(mArray[mArrayNextRead], value.value); - mArrayNextRead++; - } - } - return *this; -} - -StreamBase& JsonStream::operator<<(ValueReference value) -{ - if(serialise()) - { - setType(TYPE_ARRAY); - mArray.push_back(value.value); - } - else - { - if(checkDeserialisation() && arrayBoundsOk()) - { - valueToDouble(mArray[mArrayNextRead], value.value); - mArrayNextRead++; - } - } - return *this; -} - -StreamBase& JsonStream::operator<<(ValueReference value) -{ - if(serialise()) - { - setType(TYPE_ARRAY); - mArray.push_back(value.value); - } - else - { - if(checkDeserialisation() && arrayBoundsOk()) - { - valueToString(mArray[mArrayNextRead], value.value); - mArrayNextRead++; - } - } - return *this; -} - -StreamBase& JsonStream::getStreamToMember() -{ - setType(TYPE_ARRAY); - deleteCurrentChild(); - mChild = new JsonStream(); - if(!serialise()) - { - if(checkDeserialisation() && arrayBoundsOk()) - { - mChild->mValue = mArray[mArrayNextRead]; - mChild->mSerialise = false; - mArrayNextRead++; - } - } - return *mChild; -} - -//----------Object--------------- -StreamBase& JsonStream::operator<<(KeyValueReference keyValue) -{ - if(serialise()) - { - setType(TYPE_OBJECT); - mObject[keyValue.key] = keyValue.value; - } - else - { - if(checkDeserialisation() && checkObjectMember(keyValue.key)) - { - valueToBool(mObject[keyValue.key], keyValue.value); - } - } - return *this; -} - -StreamBase& JsonStream::operator<<(KeyValueReference keyValue) -{ - if(serialise()) - { - setType(TYPE_OBJECT); - mObject[keyValue.key] = keyValue.value; - } - else - { - if(checkDeserialisation() && checkObjectMember(keyValue.key)) - { - valueToInt(mObject[keyValue.key], keyValue.value); - } - } - return *this; -} - -StreamBase& JsonStream::operator<<(KeyValueReference keyValue) -{ - if(serialise()) - { - setType(TYPE_OBJECT); - mObject[keyValue.key] = keyValue.value; - } - else - { - if(checkDeserialisation() && checkObjectMember(keyValue.key)) - { - valueToDouble(mObject[keyValue.key], keyValue.value); - } - } - return *this; -} - -StreamBase& JsonStream::operator<<(KeyValueReference keyValue) -{ - if(serialise()) - { - setType(TYPE_OBJECT); - mObject[keyValue.key] = keyValue.value; - } - else - { - if(checkDeserialisation() && checkObjectMember(keyValue.key)) - { - valueToString(mObject[keyValue.key], keyValue.value); - } - } - return *this; -} - -// usefull if the new object member should be an array or object -// the reference should be at least valid until another method of this class gets called -StreamBase& JsonStream::getStreamToMember(std::string name) -{ - setType(TYPE_OBJECT); - deleteCurrentChild(); - mChildKey = name; - mChild = new JsonStream(); - if(!serialise()) - { - mChild->mSerialise = false; - if(checkDeserialisation() && checkObjectMember(name)) - { - mChild->mValue = mObject[name]; - } - } - return *mChild; -} - -// make a binay data object (not a real object, just binary data) -StreamBase& JsonStream::operator<<(std::vector& data) -{ - if(serialise()) - { - if((mDataType == TYPE_UNDEFINED)||(mDataType == TYPE_RAW)) - { - mDataType = TYPE_RAW; - mRawString = std::string(data.begin(), data.end()); - } - else - { - mErrorLog += "Error: trying to set raw data while the type of this object is already another type\n"; - mIsOk = false; - } - } - else - { - if((mDataType == TYPE_UNDEFINED)||(mDataType == TYPE_RAW)) - { - mDataType = TYPE_RAW; - data = std::vector(mRawString.begin(), mRawString.end()); - } - else - { - mErrorLog += "Error: trying to read raw data while the type of this object is already another type\n"; - mIsOk = false; - } - } - return *this; -} - -// return true if there are more members in this object/array -// useful for array reading -bool JsonStream::hasMore() -{ - return arrayBoundsOk(); -} - -bool JsonStream::serialise() -{ - return mSerialise; -} - -bool JsonStream::isOK() -{ - return mIsOk; -} - -void JsonStream::setError() -{ - mIsOk = false; -} - -/* -void JsonStream::addLogMsg(std::string msg) -{} -*/ - -void JsonStream::addErrorMsg(std::string msg) -{ - mErrorLog += msg; -} - -std::string JsonStream::getLog() -{ - return "not implemented yet"; -} - -std::string JsonStream::getErrorLog() -{ - return mErrorLog; -} - -bool JsonStream::isRawData() -{ - return mDataType == TYPE_RAW; -} - -std::string JsonStream::getRawData() -{ - return mRawString; -} - -void JsonStream::setType(DataType type) -{ - if((mDataType == TYPE_UNDEFINED)||(mDataType == type)) - { - mDataType = type; - } - else - { - mIsOk = false; - mErrorLog += "JsonStream::setType() Error: type alread set to another type\n"; - } -} - -bool JsonStream::checkObjectMember(std::string key) -{ - if(mDataType == TYPE_OBJECT) - { - if(mObject.HasKey(key)) - { - return true; - } - else - { - mErrorLog += "JsonStream::checkObjectMember() Warning: missing key \""+key+"\"\n"; - return false; - } - } - else - { - mIsOk = false; - mErrorLog += "JsonStream::checkObjectMember() Error: type is not TYPE_OBJECT\n"; - return false; - } -} - -bool JsonStream::arrayBoundsOk() -{ - if(checkDeserialisation()) - { - if(mDataType == TYPE_ARRAY) - { - if(mArrayNextRead < mArray.size()) - { - return true; - } - else - { - return false; - } - } - else - { - mIsOk = false; - mErrorLog += "JsonStream::arrayBoundsOk() Error: type is not TYPE_ARRAY\n"; - return false; - } - } - return false; -} - -bool JsonStream::checkDeserialisation() -{ - if(mDataType != TYPE_RAW) - { - if(mDataType == TYPE_UNDEFINED) - { - if((mValue.GetType() == json::NULLVal) && mRawString != "") - { - mValue = json::Deserialize(mRawString); - } - if(mValue.GetType() == json::ObjectVal) - { - mDataType = TYPE_OBJECT; - mObject = mValue; - return true; - } - else if(mValue.GetType() == json::ArrayVal) - { - mDataType = TYPE_ARRAY; - mArray = mValue; - return true; - } - else - { - mIsOk = false; - mErrorLog += "JsonStream::checkDeserialisation() Error: deserialisation did not end with an object or array\n"; - return false; - } - } - else - { - // already deserialised - return true; - } - } - else - { - mIsOk = false; - mErrorLog += "JsonStream::checkDeserialisation() Error: type is TYPE_RAW\n"; - return false; - } -} - -void JsonStream::valueToBool(json::Value &value, bool &boolean) -{ - if(value.GetType() == json::BoolVal) - { - boolean = value; - } - else - { - mIsOk = false; - mErrorLog += "JsonStream::valueToBool() Error: wrong type\n"; - } -} - -void JsonStream::valueToInt(json::Value &value, int &integer) -{ - if(value.GetType() == json::IntVal) - { - integer = value; - } - else - { - mIsOk = false; - mErrorLog += "JsonStream::valueToInt() Error: wrong type\n"; - } -} - -void JsonStream::valueToDouble(json::Value &value, double &doubleVal) -{ - if(value.IsNumeric()) - { - doubleVal = value; - } - else - { - mIsOk = false; - mErrorLog += "JsonStream::valueToDouble() Error: wrong type\n"; - } -} - -void JsonStream::valueToString(json::Value &value, std::string& str) -{ - if(value.GetType() == json::StringVal) - { - str = value.ToString(); - } - else - { - mIsOk = false; - mErrorLog += "JsonStream::valueToString() Error: wrong type\n"; - } -} - -void JsonStream::deleteCurrentChild() -{ - if(mChild) - { - if(serialise()) - { - if(mDataType == TYPE_ARRAY) - { - // don't add empty value - if(mChild->getJsonValue().GetType() != json::NULLVal) - mArray.push_back(mChild->getJsonValue()); - } - else if(mDataType == TYPE_OBJECT) - { - mObject[mChildKey] = mChild->getJsonValue(); - } - else - { - mErrorLog += "JsonStream::deleteCurrentChild() Error: cannot add child because own type is wrong\n"; - } - } - else - { - // don't have to do anything for deserialisation - } - delete mChild; - mChild = NULL; - } -} - -json::Value JsonStream::getJsonValue() -{ - // remove the child and add it to own data - deleteCurrentChild(); - switch(mDataType) - { - case TYPE_UNDEFINED: - return json::Value(); - case TYPE_ARRAY: - return mArray; - case TYPE_OBJECT: - return mObject; - case TYPE_RAW: - return mRawString; - default: - return json::Value(); - } -} - -} // namespace resource_api diff --git a/libresapi/src/api/JsonStream.h b/libresapi/src/api/JsonStream.h deleted file mode 100644 index a6e3528ad..000000000 --- a/libresapi/src/api/JsonStream.h +++ /dev/null @@ -1,127 +0,0 @@ -/******************************************************************************* - * libresapi/api/jsonStream.h * - * * - * LibResAPI: API for local socket server * - * * - * Copyright 2018 by Retroshare Team * - * * - * This program is free software: you can redistribute it and/or modify * - * it under the terms of the GNU Affero General Public License as * - * published by the Free Software Foundation, either version 3 of the * - * License, or (at your option) any later version. * - * * - * This program is distributed in the hope that it will be useful, * - * but WITHOUT ANY WARRANTY; without even the implied warranty of * - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * - * GNU Affero General Public License for more details. * - * * - * You should have received a copy of the GNU Affero General Public License * - * along with this program. If not, see . * - * * - *******************************************************************************/ -#pragma once - -#include "ApiTypes.h" -#include "json.h" - -namespace resource_api -{ - -class JsonStream: public StreamBase -{ -public: - JsonStream(); - virtual ~JsonStream(); - - void setJsonString(std::string jsonStr); - std::string getJsonString(); - - // it is possible to use this class as buffer - // first use as serialiser and fill with values - // then call this method to deserialise the values - void switchToDeserialisation(); - - - //----------Stream Interface --------------- - - // make an array - virtual StreamBase& operator<<(ValueReference value); - virtual StreamBase& operator<<(ValueReference value); - virtual StreamBase& operator<<(ValueReference value); - virtual StreamBase& operator<<(ValueReference value); - // usefull if the new array member should be an array or object - // the reference should be at least valid until another method of this class gets called - virtual StreamBase& getStreamToMember(); - - // make an object - virtual StreamBase& operator<<(KeyValueReference keyValue); - virtual StreamBase& operator<<(KeyValueReference keyValue); - virtual StreamBase& operator<<(KeyValueReference keyValue); - virtual StreamBase& operator<<(KeyValueReference keyValue); - // usefull if the new object member should be an array or object - // the reference should be at least valid until another method of this class gets called - virtual StreamBase& getStreamToMember(std::string name); - - // make a binay data object (not a real object, just binary data) - // idea: can use vector.swap() to allow passing larger data items without copying - virtual StreamBase& operator<<(std::vector& data); - - // return true if there are more members in this object/array - // useful for array reading - virtual bool hasMore(); - - virtual bool serialise(); // let external operators find out they should serialise or deserialise - // return true if no serialisation/deserialisation error occoured - virtual bool isOK(); - virtual void setError(); // let external operators set the failed bit - //virtual void addLogMsg(std::string msg); // mayb remove? (put log messages to error log einstead) - virtual void addErrorMsg(std::string msg); - virtual std::string getLog(); - virtual std::string getErrorLog(); - - virtual bool isRawData(); - virtual std::string getRawData(); -private: - bool mSerialise; - enum DataType{ TYPE_UNDEFINED, TYPE_ARRAY, TYPE_OBJECT, TYPE_RAW }; - // check if the current type is undefined - // if not check if the new type matches the old type - // if not set the error bit - void setType(DataType type); - DataType mDataType; - - json::Value mValue; - - json::Object mObject; - // check if we are and object - // check if this key exists - bool checkObjectMember(std::string key); - json::Array mArray; - size_t mArrayNextRead; - // check if we are an array - // check if next read is valid - // if not set error bit - bool arrayBoundsOk(); - std::string mRawString; - - bool mIsOk; - std::string mErrorLog; - - // try serialisation and set error bit on error - bool checkDeserialisation(); - - // check if value has correct type - // if yes return the extracted value - // if not then set the error bit - void valueToBool(json::Value& value, bool& boolean); - void valueToInt(json::Value& value, int& integer); - void valueToDouble(json::Value& value, double& doubleVal); - void valueToString(json::Value& value, std::string& str); - - void deleteCurrentChild(); - json::Value getJsonValue(); - JsonStream* mChild; - std::string mChildKey; -}; - -} // namespace resource_api diff --git a/libresapi/src/api/LivereloadHandler.cpp b/libresapi/src/api/LivereloadHandler.cpp deleted file mode 100644 index c57c86331..000000000 --- a/libresapi/src/api/LivereloadHandler.cpp +++ /dev/null @@ -1,46 +0,0 @@ -/******************************************************************************* - * libresapi/api/LivereloadHarder.cpp * - * * - * LibResAPI: API for local socket server * - * * - * Copyright 2018 by Retroshare Team * - * * - * This program is free software: you can redistribute it and/or modify * - * it under the terms of the GNU Affero General Public License as * - * published by the Free Software Foundation, either version 3 of the * - * License, or (at your option) any later version. * - * * - * This program is distributed in the hope that it will be useful, * - * but WITHOUT ANY WARRANTY; without even the implied warranty of * - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * - * GNU Affero General Public License for more details. * - * * - * You should have received a copy of the GNU Affero General Public License * - * along with this program. If not, see . * - * * - *******************************************************************************/ -#include "LivereloadHandler.h" - -namespace resource_api -{ -LivereloadHandler::LivereloadHandler(StateTokenServer *sts): - mStateTokenServer(sts), mStateToken(sts->getNewToken()) -{ - addResourceHandler("*", this, &LivereloadHandler::handleWildcard); - addResourceHandler("trigger", this, &LivereloadHandler::handleTrigger); -} - -void LivereloadHandler::handleWildcard(Request &/*req*/, Response &resp) -{ - resp.mStateToken = mStateToken; - resp.setOk(); -} - -void LivereloadHandler::handleTrigger(Request &/*req*/, Response &resp) -{ - mStateTokenServer->replaceToken(mStateToken); - resp.mStateToken = mStateToken; - resp.setOk(); -} - -} // namespace resource_api diff --git a/libresapi/src/api/LivereloadHandler.h b/libresapi/src/api/LivereloadHandler.h deleted file mode 100644 index 5f77259c3..000000000 --- a/libresapi/src/api/LivereloadHandler.h +++ /dev/null @@ -1,44 +0,0 @@ -/******************************************************************************* - * libresapi/api/LivereloadHarder.h * - * * - * LibResAPI: API for local socket server * - * * - * Copyright 2018 by Retroshare Team * - * * - * This program is free software: you can redistribute it and/or modify * - * it under the terms of the GNU Affero General Public License as * - * published by the Free Software Foundation, either version 3 of the * - * License, or (at your option) any later version. * - * * - * This program is distributed in the hope that it will be useful, * - * but WITHOUT ANY WARRANTY; without even the implied warranty of * - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * - * GNU Affero General Public License for more details. * - * * - * You should have received a copy of the GNU Affero General Public License * - * along with this program. If not, see . * - * * - *******************************************************************************/ -#pragma once - -#include "ResourceRouter.h" -#include "StateTokenServer.h" - -namespace resource_api -{ - -// very simple livereload system, integrated into the existing state token system -// the response to / is only a statetoken -// if /trigger is called, then the state token is invalidaten and replaced wiht a new one -class LivereloadHandler: public ResourceRouter -{ -public: - LivereloadHandler(StateTokenServer* sts); - -private: - void handleWildcard(Request& req, Response& resp); - void handleTrigger(Request& req, Response& resp); - StateTokenServer* mStateTokenServer; - StateToken mStateToken; -}; -} // namespace resource_api diff --git a/libresapi/src/api/Operators.cpp b/libresapi/src/api/Operators.cpp deleted file mode 100644 index d0a27765e..000000000 --- a/libresapi/src/api/Operators.cpp +++ /dev/null @@ -1,154 +0,0 @@ -/******************************************************************************* - * libresapi/api/Operators.cpp * - * * - * LibResAPI: API for local socket server * - * * - * Copyright 2018 by Retroshare Team * - * * - * This program is free software: you can redistribute it and/or modify * - * it under the terms of the GNU Affero General Public License as * - * published by the Free Software Foundation, either version 3 of the * - * License, or (at your option) any later version. * - * * - * This program is distributed in the hope that it will be useful, * - * but WITHOUT ANY WARRANTY; without even the implied warranty of * - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * - * GNU Affero General Public License for more details. * - * * - * You should have received a copy of the GNU Affero General Public License * - * along with this program. If not, see . * - * * - *******************************************************************************/ -#include "Operators.h" - -namespace resource_api -{ - -StreamBase& operator <<(StreamBase& left, KeyValueReference ref) -{ - if(left.serialise()) - { - uint32_t num = ref.value; - uint8_t digit; - std::string str; - while(num >= 10) - { - digit = num % 10; - num = num / 10; - str = (char)(digit + '0') + str; - } - str = (char)(num + '0') + str; - left << makeKeyValueReference(ref.key, str); - } - else - { - std::string str; - left << makeKeyValueReference(ref.key, str); - uint32_t num = 0; - for(std::string::iterator sit = str.begin(); sit != str.end(); sit++) - { - uint32_t numbefore = num; - num = num * 10; - if(num < numbefore) - { - left.addErrorMsg("operator for uint32_t to std::string: oveflow"); - left.setError(); - } - else if((*sit)<'0' || (*sit)>'9') - { - left.addErrorMsg("operator for uint32_t to std::string: invalid characters"); - left.setError(); - } - else - { - // everything ok, can add value - num += (*sit) - '0'; - } - } - } - return left; -} - - - - -/* -template -StreamBase& operator <<(StreamBase& left, t_RsGenericIdType& id) -{ - if(left.serialise()) - { - left << id.toStdString(); - } - else - { - std::string str; - left << str; - } - return left; -} -*/ - -template -StreamBase& operator <<(StreamBase& left, ValueReference& ref) -{ - if(left.serialise()) - { - left << makeValueReference(ref.value.toStdString()); - } - else - { - std::string str; - left << makeValueReference(str); - T_ID id(str); - if(id.isNull) - { - left.setError(); - left.addErrorMsg("operator for retroshare id value: id is null\n"); - } - ref.value = id; - } - return left; -} - -// idea: have external operators which do the translation form different containers to basic operations -// better idea: take input iterators as arguments, will then work with everything which has an iterator -// but what about deserilisation? -template