Citadel 0.1.0 (#85)

Co-authored-by: nolim1t - f6287b82CC84bcbd <nolim1t@users.noreply.github.com>
Co-authored-by: Aaron Dewes <aaron.dewes@protonmail.com>
Co-authored-by: Philipp Walter <philippwalter@pm.me>
Co-authored-by: Lele <emanuele.lele.calo@gmail.com>
This commit is contained in:
Aaron Dewes 2022-10-26 10:28:31 +02:00 committed by GitHub
parent cdb603c0e1
commit 9054194ab7
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
57 changed files with 758 additions and 2515 deletions

View File

@ -1,6 +1,6 @@
Format: https://www.debian.org/doc/packaging-manuals/copyright-format/1.0/
Upstream-Name: Citadel
Upstream-Contact: Aaron Dewes <aaron.dewes@web.de>
Upstream-Contact: Aaron Dewes <aaron.dewes@proton.me>
Source: runcitadel.space
# Sample paragraph, commented out:

3
.vscode/settings.json.license vendored Normal file
View File

@ -0,0 +1,3 @@
# SPDX-FileCopyrightText: 2022 Citadel and contributors
#
# SPDX-License-Identifier: GPL-3.0-or-later

View File

@ -1,128 +0,0 @@
# Contributor Covenant Code of Conduct
## Our Pledge
We as members, contributors, and leaders pledge to make participation in our
community a harassment-free experience for everyone, regardless of age, body
size, visible or invisible disability, ethnicity, sex characteristics, gender
identity and expression, level of experience, education, socio-economic status,
nationality, personal appearance, race, religion, or sexual identity
and orientation.
We pledge to act and interact in ways that contribute to an open, welcoming,
diverse, inclusive, and healthy community.
## Our Standards
Examples of behavior that contributes to a positive environment for our
community include:
* Demonstrating empathy and kindness toward other people
* Being respectful of differing opinions, viewpoints, and experiences
* Giving and gracefully accepting constructive feedback
* Accepting responsibility and apologizing to those affected by our mistakes,
and learning from the experience
* Focusing on what is best not just for us as individuals, but for the
overall community
Examples of unacceptable behavior include:
* The use of sexualized language or imagery, and sexual attention or
advances of any kind
* Trolling, insulting or derogatory comments, and personal or political attacks
* Public or private harassment
* Publishing others' private information, such as a physical or email
address, without their explicit permission
* Other conduct which could reasonably be considered inappropriate in a
professional setting
## Enforcement Responsibilities
Community leaders are responsible for clarifying and enforcing our standards of
acceptable behavior and will take appropriate and fair corrective action in
response to any behavior that they deem inappropriate, threatening, offensive,
or harmful.
Community leaders have the right and responsibility to remove, edit, or reject
comments, commits, code, wiki edits, issues, and other contributions that are
not aligned to this Code of Conduct, and will communicate reasons for moderation
decisions when appropriate.
## Scope
This Code of Conduct applies within all community spaces, and also applies when
an individual is officially representing the community in public spaces.
Examples of representing our community include using an official e-mail address,
posting via an official social media account, or acting as an appointed
representative at an online or offline event.
## Enforcement
Instances of abusive, harassing, or otherwise unacceptable behavior may be
reported to the community leaders responsible for enforcement at
shared@runcitadel.space.
All complaints will be reviewed and investigated promptly and fairly.
All community leaders are obligated to respect the privacy and security of the
reporter of any incident.
## Enforcement Guidelines
Community leaders will follow these Community Impact Guidelines in determining
the consequences for any action they deem in violation of this Code of Conduct:
### 1. Correction
**Community Impact**: Use of inappropriate language or other behavior deemed
unprofessional or unwelcome in the community.
**Consequence**: A private, written warning from community leaders, providing
clarity around the nature of the violation and an explanation of why the
behavior was inappropriate. A public apology may be requested.
### 2. Warning
**Community Impact**: A violation through a single incident or series
of actions.
**Consequence**: A warning with consequences for continued behavior. No
interaction with the people involved, including unsolicited interaction with
those enforcing the Code of Conduct, for a specified period of time. This
includes avoiding interactions in community spaces as well as external channels
like social media. Violating these terms may lead to a temporary or
permanent ban.
### 3. Temporary Ban
**Community Impact**: A serious violation of community standards, including
sustained inappropriate behavior.
**Consequence**: A temporary ban from any sort of interaction or public
communication with the community for a specified period of time. No public or
private interaction with the people involved, including unsolicited interaction
with those enforcing the Code of Conduct, is allowed during this period.
Violating these terms may lead to a permanent ban.
### 4. Permanent Ban
**Community Impact**: Demonstrating a pattern of violation of community
standards, including sustained inappropriate behavior, harassment of an
individual, or aggression toward or disparagement of classes of individuals.
**Consequence**: A permanent ban from any sort of public interaction within
the community.
## Attribution
This Code of Conduct is adapted from the [Contributor Covenant][homepage],
version 2.0, available at
https://www.contributor-covenant.org/version/2/0/code_of_conduct.html.
Community Impact Guidelines were inspired by [Mozilla's code of conduct
enforcement ladder](https://github.com/mozilla/diversity).
[homepage]: https://www.contributor-covenant.org
For answers to common questions about this code of conduct, see the FAQ at
https://www.contributor-covenant.org/faq. Translations are available at
https://www.contributor-covenant.org/translations.

View File

@ -1,235 +0,0 @@
GNU AFFERO GENERAL PUBLIC LICENSE
Version 3, 19 November 2007
Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/>
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.
<one line to give the program's name and a brief idea of what it does.>
Copyright (C) <year> <name of author>
This program is free software: you can redistribute it and/or modify it under the terms of the GNU 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 <http://www.gnu.org/licenses/>.
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 <http://www.gnu.org/licenses/>.

View File

@ -0,0 +1,232 @@
GNU GENERAL PUBLIC LICENSE
Version 3, 29 June 2007
Copyright © 2007 Free Software Foundation, Inc. <http://fsf.org/>
Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed.
Preamble
The GNU General Public License is a free, copyleft license for software and other kinds of works.
The licenses for most software and other practical works are designed to take away your freedom to share and change the works. By contrast, the GNU General Public License is intended to guarantee your freedom to share and change all versions of a program--to make sure it remains free software for all its users. We, the Free Software Foundation, use the GNU General Public License for most of our software; it applies also to any other work released this way by its authors. You can apply it to your programs, too.
When we speak of free software, we are referring to freedom, not price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for them if you wish), that you receive source code or can get it if you want it, that you can change the software or use pieces of it in new free programs, and that you know you can do these things.
To protect your rights, we need to prevent others from denying you these rights or asking you to surrender the rights. Therefore, you have certain responsibilities if you distribute copies of the software, or if you modify it: responsibilities to respect the freedom of others.
For example, if you distribute copies of such a program, whether gratis or for a fee, you must pass on to the recipients the same freedoms that you received. You must make sure that they, too, receive or can get the source code. And you must show them these terms so they know their rights.
Developers that use the GNU GPL protect your rights with two steps: (1) assert copyright on the software, and (2) offer you this License giving you legal permission to copy, distribute and/or modify it.
For the developers' and authors' protection, the GPL clearly explains that there is no warranty for this free software. For both users' and authors' sake, the GPL requires that modified versions be marked as changed, so that their problems will not be attributed erroneously to authors of previous versions.
Some devices are designed to deny users access to install or run modified versions of the software inside them, although the manufacturer can do so. This is fundamentally incompatible with the aim of protecting users' freedom to change the software. The systematic pattern of such abuse occurs in the area of products for individuals to use, which is precisely where it is most unacceptable. Therefore, we have designed this version of the GPL to prohibit the practice for those products. If such problems arise substantially in other domains, we stand ready to extend this provision to those domains in future versions of the GPL, as needed to protect the freedom of users.
Finally, every program is threatened constantly by software patents. States should not allow patents to restrict development and use of software on general-purpose computers, but in those that do, we wish to avoid the special danger that patents applied to a free program could make it effectively proprietary. To prevent this, the GPL assures that patents cannot be used to render the program non-free.
The precise terms and conditions for copying, distribution and modification follow.
TERMS AND CONDITIONS
0. Definitions.
“This License” refers to version 3 of the GNU General Public License.
“Copyright” also means copyright-like laws that apply to other kinds of works, such as semiconductor masks.
“The Program” refers to any copyrightable work licensed under this License. Each licensee is addressed as “you”. “Licensees” and “recipients” may be individuals or organizations.
To “modify” a work means to copy from or adapt all or part of the work in a fashion requiring copyright permission, other than the making of an exact copy. The resulting work is called a “modified version” of the earlier work or a work “based on” the earlier work.
A “covered work” means either the unmodified Program or a work based on the Program.
To “propagate” a work means to do anything with it that, without permission, would make you directly or secondarily liable for infringement under applicable copyright law, except executing it on a computer or modifying a private copy. Propagation includes copying, distribution (with or without modification), making available to the public, and in some countries other activities as well.
To “convey” a work means any kind of propagation that enables other parties to make or receive copies. Mere interaction with a user through a computer network, with no transfer of a copy, is not conveying.
An interactive user interface displays “Appropriate Legal Notices” to the extent that it includes a convenient and prominently visible feature that (1) displays an appropriate copyright notice, and (2) tells the user that there is no warranty for the work (except to the extent that warranties are provided), that licensees may convey the work under this License, and how to view a copy of this License. If the interface presents a list of user commands or options, such as a menu, a prominent item in the list meets this criterion.
1. Source Code.
The “source code” for a work means the preferred form of the work for making modifications to it. “Object code” means any non-source form of a work.
A “Standard Interface” means an interface that either is an official standard defined by a recognized standards body, or, in the case of interfaces specified for a particular programming language, one that is widely used among developers working in that language.
The “System Libraries” of an executable work include anything, other than the work as a whole, that (a) is included in the normal form of packaging a Major Component, but which is not part of that Major Component, and (b) serves only to enable use of the work with that Major Component, or to implement a Standard Interface for which an implementation is available to the public in source code form. A “Major Component”, in this context, means a major essential component (kernel, window system, and so on) of the specific operating system (if any) on which the executable work runs, or a compiler used to produce the work, or an object code interpreter used to run it.
The “Corresponding Source” for a work in object code form means all the source code needed to generate, install, and (for an executable work) run the object code and to modify the work, including scripts to control those activities. However, it does not include the work's System Libraries, or general-purpose tools or generally available free programs which are used unmodified in performing those activities but which are not part of the work. For example, Corresponding Source includes interface definition files associated with source files for the work, and the source code for shared libraries and dynamically linked subprograms that the work is specifically designed to require, such as by intimate data communication or control flow between those subprograms and other parts of the work.
The Corresponding Source need not include anything that users can regenerate automatically from other parts of the Corresponding Source.
The Corresponding Source for a work in source code form is that same work.
2. Basic Permissions.
All rights granted under this License are granted for the term of copyright on the Program, and are irrevocable provided the stated conditions are met. This License explicitly affirms your unlimited permission to run the unmodified Program. The output from running a covered work is covered by this License only if the output, given its content, constitutes a covered work. This License acknowledges your rights of fair use or other equivalent, as provided by copyright law.
You may make, run and propagate covered works that you do not convey, without conditions so long as your license otherwise remains in force. You may convey covered works to others for the sole purpose of having them make modifications exclusively for you, or provide you with facilities for running those works, provided that you comply with the terms of this License in conveying all material for which you do not control copyright. Those thus making or running the covered works for you must do so exclusively on your behalf, under your direction and control, on terms that prohibit them from making any copies of your copyrighted material outside their relationship with you.
Conveying under any other circumstances is permitted solely under the conditions stated below. Sublicensing is not allowed; section 10 makes it unnecessary.
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
No covered work shall be deemed part of an effective technological measure under any applicable law fulfilling obligations under article 11 of the WIPO copyright treaty adopted on 20 December 1996, or similar laws prohibiting or restricting circumvention of such measures.
When you convey a covered work, you waive any legal power to forbid circumvention of technological measures to the extent such circumvention is effected by exercising rights under this License with respect to the covered work, and you disclaim any intention to limit operation or modification of the work as a means of enforcing, against the work's users, your or third parties' legal rights to forbid circumvention of technological measures.
4. Conveying Verbatim Copies.
You may convey verbatim copies of the Program's source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice; keep intact all notices stating that this License and any non-permissive terms added in accord with section 7 apply to the code; keep intact all notices of the absence of any warranty; and give all recipients a copy of this License along with the Program.
You may charge any price or no price for each copy that you convey, and you may offer support or warranty protection for a fee.
5. Conveying Modified Source Versions.
You may convey a work based on the Program, or the modifications to produce it from the Program, in the form of source code under the terms of section 4, provided that you also meet all of these conditions:
a) The work must carry prominent notices stating that you modified it, and giving a relevant date.
b) The work must carry prominent notices stating that it is released under this License and any conditions added under section 7. This requirement modifies the requirement in section 4 to “keep intact all notices”.
c) You must license the entire work, as a whole, under this License to anyone who comes into possession of a copy. This License will therefore apply, along with any applicable section 7 additional terms, to the whole of the work, and all its parts, regardless of how they are packaged. This License gives no permission to license the work in any other way, but it does not invalidate such permission if you have separately received it.
d) If the work has interactive user interfaces, each must display Appropriate Legal Notices; however, if the Program has interactive interfaces that do not display Appropriate Legal Notices, your work need not make them do so.
A compilation of a covered work with other separate and independent works, which are not by their nature extensions of the covered work, and which are not combined with it such as to form a larger program, in or on a volume of a storage or distribution medium, is called an “aggregate” if the compilation and its resulting copyright are not used to limit the access or legal rights of the compilation's users beyond what the individual works permit. Inclusion of a covered work in an aggregate does not cause this License to apply to the other parts of the aggregate.
6. Conveying Non-Source Forms.
You may convey a covered work in object code form under the terms of sections 4 and 5, provided that you also convey the machine-readable Corresponding Source under the terms of this License, in one of these ways:
a) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by the Corresponding Source fixed on a durable physical medium customarily used for software interchange.
b) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by a written offer, valid for at least three years and valid for as long as you offer spare parts or customer support for that product model, to give anyone who possesses the object code either (1) a copy of the Corresponding Source for all the software in the product that is covered by this License, on a durable physical medium customarily used for software interchange, for a price no more than your reasonable cost of physically performing this conveying of source, or (2) access to copy the Corresponding Source from a network server at no charge.
c) Convey individual copies of the object code with a copy of the written offer to provide the Corresponding Source. This alternative is allowed only occasionally and noncommercially, and only if you received the object code with such an offer, in accord with subsection 6b.
d) Convey the object code by offering access from a designated place (gratis or for a charge), and offer equivalent access to the Corresponding Source in the same way through the same place at no further charge. You need not require recipients to copy the Corresponding Source along with the object code. If the place to copy the object code is a network server, the Corresponding Source may be on a different server (operated by you or a third party) that supports equivalent copying facilities, provided you maintain clear directions next to the object code saying where to find the Corresponding Source. Regardless of what server hosts the Corresponding Source, you remain obligated to ensure that it is available for as long as needed to satisfy these requirements.
e) Convey the object code using peer-to-peer transmission, provided you inform other peers where the object code and Corresponding Source of the work are being offered to the general public at no charge under subsection 6d.
A separable portion of the object code, whose source code is excluded from the Corresponding Source as a System Library, need not be included in conveying the object code work.
A “User Product” is either (1) a “consumer product”, which means any tangible personal property which is normally used for personal, family, or household purposes, or (2) anything designed or sold for incorporation into a dwelling. In determining whether a product is a consumer product, doubtful cases shall be resolved in favor of coverage. For a particular product received by a particular user, “normally used” refers to a typical or common use of that class of product, regardless of the status of the particular user or of the way in which the particular user actually uses, or expects or is expected to use, the product. A product is a consumer product regardless of whether the product has substantial commercial, industrial or non-consumer uses, unless such uses represent the only significant mode of use of the product.
“Installation Information” for a User Product means any methods, procedures, authorization keys, or other information required to install and execute modified versions of a covered work in that User Product from a modified version of its Corresponding Source. The information must suffice to ensure that the continued functioning of the modified object code is in no case prevented or interfered with solely because modification has been made.
If you convey an object code work under this section in, or with, or specifically for use in, a User Product, and the conveying occurs as part of a transaction in which the right of possession and use of the User Product is transferred to the recipient in perpetuity or for a fixed term (regardless of how the transaction is characterized), the Corresponding Source conveyed under this section must be accompanied by the Installation Information. But this requirement does not apply if neither you nor any third party retains the ability to install modified object code on the User Product (for example, the work has been installed in ROM).
The requirement to provide Installation Information does not include a requirement to continue to provide support service, warranty, or updates for a work that has been modified or installed by the recipient, or for the User Product in which it has been modified or installed. Access to a network may be denied when the modification itself materially and adversely affects the operation of the network or violates the rules and protocols for communication across the network.
Corresponding Source conveyed, and Installation Information provided, in accord with this section must be in a format that is publicly documented (and with an implementation available to the public in source code form), and must require no special password or key for unpacking, reading or copying.
7. Additional Terms.
“Additional permissions” are terms that supplement the terms of this License by making exceptions from one or more of its conditions. Additional permissions that are applicable to the entire Program shall be treated as though they were included in this License, to the extent that they are valid under applicable law. If additional permissions apply only to part of the Program, that part may be used separately under those permissions, but the entire Program remains governed by this License without regard to the additional permissions.
When you convey a copy of a covered work, you may at your option remove any additional permissions from that copy, or from any part of it. (Additional permissions may be written to require their own removal in certain cases when you modify the work.) You may place additional permissions on material, added by you to a covered work, for which you have or can give appropriate copyright permission.
Notwithstanding any other provision of this License, for material you add to a covered work, you may (if authorized by the copyright holders of that material) supplement the terms of this License with terms:
a) Disclaiming warranty or limiting liability differently from the terms of sections 15 and 16 of this License; or
b) Requiring preservation of specified reasonable legal notices or author attributions in that material or in the Appropriate Legal Notices displayed by works containing it; or
c) Prohibiting misrepresentation of the origin of that material, or requiring that modified versions of such material be marked in reasonable ways as different from the original version; or
d) Limiting the use for publicity purposes of names of licensors or authors of the material; or
e) Declining to grant rights under trademark law for use of some trade names, trademarks, or service marks; or
f) Requiring indemnification of licensors and authors of that material by anyone who conveys the material (or modified versions of it) with contractual assumptions of liability to the recipient, for any liability that these contractual assumptions directly impose on those licensors and authors.
All other non-permissive additional terms are considered “further restrictions” within the meaning of section 10. If the Program as you received it, or any part of it, contains a notice stating that it is governed by this License along with a term that is a further restriction, you may remove that term. If a license document contains a further restriction but permits relicensing or conveying under this License, you may add to a covered work material governed by the terms of that license document, provided that the further restriction does not survive such relicensing or conveying.
If you add terms to a covered work in accord with this section, you must place, in the relevant source files, a statement of the additional terms that apply to those files, or a notice indicating where to find the applicable terms.
Additional terms, permissive or non-permissive, may be stated in the form of a separately written license, or stated as exceptions; the above requirements apply either way.
8. Termination.
You may not propagate or modify a covered work except as expressly provided under this License. Any attempt otherwise to propagate or modify it is void, and will automatically terminate your rights under this License (including any patent licenses granted under the third paragraph of section 11).
However, if you cease all violation of this License, then your license from a particular copyright holder is reinstated (a) provisionally, unless and until the copyright holder explicitly and finally terminates your license, and (b) permanently, if the copyright holder fails to notify you of the violation by some reasonable means prior to 60 days after the cessation.
Moreover, your license from a particular copyright holder is reinstated permanently if the copyright holder notifies you of the violation by some reasonable means, this is the first time you have received notice of violation of this License (for any work) from that copyright holder, and you cure the violation prior to 30 days after your receipt of the notice.
Termination of your rights under this section does not terminate the licenses of parties who have received copies or rights from you under this License. If your rights have been terminated and not permanently reinstated, you do not qualify to receive new licenses for the same material under section 10.
9. Acceptance Not Required for Having Copies.
You are not required to accept this License in order to receive or run a copy of the Program. Ancillary propagation of a covered work occurring solely as a consequence of using peer-to-peer transmission to receive a copy likewise does not require acceptance. However, nothing other than this License grants you permission to propagate or modify any covered work. These actions infringe copyright if you do not accept this License. Therefore, by modifying or propagating a covered work, you indicate your acceptance of this License to do so.
10. Automatic Licensing of Downstream Recipients.
Each time you convey a covered work, the recipient automatically receives a license from the original licensors, to run, modify and propagate that work, subject to this License. You are not responsible for enforcing compliance by third parties with this License.
An “entity transaction” is a transaction transferring control of an organization, or substantially all assets of one, or subdividing an organization, or merging organizations. If propagation of a covered work results from an entity transaction, each party to that transaction who receives a copy of the work also receives whatever licenses to the work the party's predecessor in interest had or could give under the previous paragraph, plus a right to possession of the Corresponding Source of the work from the predecessor in interest, if the predecessor has it or can get it with reasonable efforts.
You may not impose any further restrictions on the exercise of the rights granted or affirmed under this License. For example, you may not impose a license fee, royalty, or other charge for exercise of rights granted under this License, and you may not initiate litigation (including a cross-claim or counterclaim in a lawsuit) alleging that any patent claim is infringed by making, using, selling, offering for sale, or importing the Program or any portion of it.
11. Patents.
A “contributor” is a copyright holder who authorizes use under this License of the Program or a work on which the Program is based. The work thus licensed is called the contributor's “contributor version”.
A contributor's “essential patent claims” are all patent claims owned or controlled by the contributor, whether already acquired or hereafter acquired, that would be infringed by some manner, permitted by this License, of making, using, or selling its contributor version, but do not include claims that would be infringed only as a consequence of further modification of the contributor version. For purposes of this definition, “control” includes the right to grant patent sublicenses in a manner consistent with the requirements of this License.
Each contributor grants you a non-exclusive, worldwide, royalty-free patent license under the contributor's essential patent claims, to make, use, sell, offer for sale, import and otherwise run, modify and propagate the contents of its contributor version.
In the following three paragraphs, a “patent license” is any express agreement or commitment, however denominated, not to enforce a patent (such as an express permission to practice a patent or covenant not to sue for patent infringement). To “grant” such a patent license to a party means to make such an agreement or commitment not to enforce a patent against the party.
If you convey a covered work, knowingly relying on a patent license, and the Corresponding Source of the work is not available for anyone to copy, free of charge and under the terms of this License, through a publicly available network server or other readily accessible means, then you must either (1) cause the Corresponding Source to be so available, or (2) arrange to deprive yourself of the benefit of the patent license for this particular work, or (3) arrange, in a manner consistent with the requirements of this License, to extend the patent license to downstream recipients. “Knowingly relying” means you have actual knowledge that, but for the patent license, your conveying the covered work in a country, or your recipient's use of the covered work in a country, would infringe one or more identifiable patents in that country that you have reason to believe are valid.
If, pursuant to or in connection with a single transaction or arrangement, you convey, or propagate by procuring conveyance of, a covered work, and grant a patent license to some of the parties receiving the covered work authorizing them to use, propagate, modify or convey a specific copy of the covered work, then the patent license you grant is automatically extended to all recipients of the covered work and works based on it.
A patent license is “discriminatory” if it does not include within the scope of its coverage, prohibits the exercise of, or is conditioned on the non-exercise of one or more of the rights that are specifically granted under this License. You may not convey a covered work if you are a party to an arrangement with a third party that is in the business of distributing software, under which you make payment to the third party based on the extent of your activity of conveying the work, and under which the third party grants, to any of the parties who would receive the covered work from you, a discriminatory patent license (a) in connection with copies of the covered work conveyed by you (or copies made from those copies), or (b) primarily for and in connection with specific products or compilations that contain the covered work, unless you entered into that arrangement, or that patent license was granted, prior to 28 March 2007.
Nothing in this License shall be construed as excluding or limiting any implied license or other defenses to infringement that may otherwise be available to you under applicable patent law.
12. No Surrender of Others' Freedom.
If conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not excuse you from the conditions of this License. If you cannot convey a covered work so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not convey it at all. For example, if you agree to terms that obligate you to collect a royalty for further conveying from those to whom you convey the Program, the only way you could satisfy both those terms and this License would be to refrain entirely from conveying the Program.
13. Use with the GNU Affero General Public License.
Notwithstanding any other provision of this License, you have permission to link or combine any covered work with a work licensed under version 3 of the GNU Affero General Public License into a single combined work, and to convey the resulting work. The terms of this License will continue to apply to the part which is the covered work, but the special requirements of the GNU Affero General Public License, section 13, concerning interaction through a network will apply to the combination as such.
14. Revised Versions of this License.
The Free Software Foundation may publish revised and/or new versions of the GNU General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns.
Each version is given a distinguishing version number. If the Program specifies that a certain numbered version of the GNU General Public License “or any later version” applies to it, you have the option of following the terms and conditions either of that numbered version or of any later version published by the Free Software Foundation. If the Program does not specify a version number of the GNU General Public License, you may choose any version ever published by the Free Software Foundation.
If the Program specifies that a proxy can decide which future versions of the GNU General Public License can be used, that proxy's public statement of acceptance of a version permanently authorizes you to choose that version for the Program.
Later license versions may give you additional or different permissions. However, no additional obligations are imposed on any author or copyright holder as a result of your choosing to follow a later version.
15. Disclaimer of Warranty.
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM “AS IS” WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
16. Limitation of Liability.
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
17. Interpretation of Sections 15 and 16.
If the disclaimer of warranty and limitation of liability provided above cannot be given local legal effect according to their terms, reviewing courts shall apply local law that most closely approximates an absolute waiver of all civil liability in connection with the Program, unless a warranty or assumption of liability accompanies a copy of the Program in return for a fee.
END OF TERMS AND CONDITIONS
How to Apply These Terms to Your New Programs
If you develop a new program, and you want it to be of the greatest possible use to the public, the best way to achieve this is to make it free software which everyone can redistribute and change under these terms.
To do so, attach the following notices to the program. It is safest to attach them to the start of each source file to most effectively state the exclusion of warranty; and each file should have at least the “copyright” line and a pointer to where the full notice is found.
<one line to give the program's name and a brief idea of what it does.>
Copyright (C) <year> <name of author>
This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version.
This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.
You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>.
Also add information on how to contact you by electronic and paper mail.
If the program does terminal interaction, make it output a short notice like this when it starts in an interactive mode:
<program> Copyright (C) <year> <name of author>
This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
This is free software, and you are welcome to redistribute it under certain conditions; type `show c' for details.
The hypothetical commands `show w' and `show c' should show the appropriate parts of the General Public License. Of course, your program's commands might be different; for a GUI interface, you would use an “about box”.
You should also get your employer (if you work as a programmer) or school, if any, to sign a “copyright disclaimer” for the program, if necessary. For more information on this, and how to apply and follow the GNU GPL, see <http://www.gnu.org/licenses/>.
The GNU General Public License does not permit incorporating your program into proprietary programs. If your program is a subroutine library, you may consider it more useful to permit linking proprietary applications with the library. If this is what you want to do, use the GNU Lesser General Public License instead of this License. But first, please read <http://www.gnu.org/philosophy/why-not-lgpl.html>.

9
LICENSES/MIT.txt Normal file
View File

@ -0,0 +1,9 @@
MIT License
Copyright (c) <year> <copyright holders>
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.

View File

@ -1,5 +1,5 @@
<!--
SPDX-FileCopyrightText: 2021 Citadel and contributors
SPDX-FileCopyrightText: 2021-2022 Citadel and contributors
SPDX-License-Identifier: GPL-3.0-or-later
-->
@ -10,7 +10,6 @@ SPDX-License-Identifier: GPL-3.0-or-later
</p>
[![Discord Server](https://img.shields.io/badge/Community%20Chat-Discord-%235351FB?style=flat-square)](https://discord.gg/6U3kM2cjdB)
[![Twitter](https://img.shields.io/twitter/follow/runcitadel?style=flat-square)](https://twitter.com/runcitadel)
![License](https://img.shields.io/github/license/runcitadel/core?style=flat-square)

View File

@ -3,7 +3,7 @@
# SPDX-License-Identifier: GPL-3.0-or-later
# A collection of fully FLOSS app definitions and FLOSS apps for Citadel.
https://github.com/runcitadel/apps v4-stable
https://github.com/runcitadel/apps 0.1.0
# Some apps modified version of Umbrel apps, and their app definitions aren't FLOSS yet.
# Include them anyway, but as a separate repo.

View File

@ -4,11 +4,14 @@
#
# SPDX-License-Identifier: GPL-3.0-or-later
import json
from lib.manage import compose, createDataDir, deleteData, getUserData, setInstalled, setRemoved, startInstalled, stopInstalled, update, deriveEntropy, updateRepos, download, getAvailableUpdates
from lib.validate import findAndValidateApps
import os
import argparse
import json
import os
from lib.manage import (compose, createDataDir, deleteData, deriveEntropy,
download, getAvailableUpdates, getUserData,
setInstalled, setRemoved, update, updateRepos)
from lib.validate import findAndValidateApps
# Print an error if user is not root
if os.getuid() != 0:
@ -97,10 +100,49 @@ elif args.action == 'install':
if not args.app:
print("No app provided")
exit(1)
with open(os.path.join(appsDir, "virtual-apps.json"), "r") as f:
virtual_apps = json.load(f)
userData = getUserData()
for virtual_app in virtual_apps.keys():
implementations = virtual_apps[virtual_app]
if args.app in implementations:
for implementation in implementations:
if "installedApps" in userData and implementation in userData["installedApps"]:
print("Another implementation of {} is already installed: {}. Uninstall it first to install this app.".format(virtual_app, implementation))
exit(1)
createDataDir(args.app)
compose(args.app, "pull")
compose(args.app, "up --detach")
setInstalled(args.app)
registryFile = os.path.join(nodeRoot, "apps", "registry.json")
registry: list = []
if os.path.isfile(registryFile):
with open(registryFile, 'r') as f:
registry = json.load(f)
for app in registry:
if not app.compatible:
for dependency in app.missing_dependencies:
# If dependency is a string, check if it's the app we're installing or the app we're installing implements
if isinstance(dependency, str):
if dependency == args.app or args.app in virtual_apps[dependency]:
# Delete the app's result.yml file
os.remove(os.path.join(nodeRoot, "apps", app.name, "result.yml"))
# Else, it should be a list, so check if the app we're installing is in it
elif isinstance(dependency, list):
for dep in dependency:
if dep == args.app or args.app in virtual_apps[dep]:
# Delete the app's result.yml file
os.remove(os.path.join(nodeRoot, "apps", app.name, "result.yml"))
# Reconfigure
os.system(os.path.join(nodeRoot, "scripts", "configure"))
os.chdir(nodeRoot)
os.system("docker compose stop app-tor")
os.system("docker compose start app-tor")
os.system("docker compose stop app-2-tor")
os.system("docker compose start app-2-tor")
os.system("docker compose stop app-3-tor")
os.system("docker compose start app-3-tor")
elif args.action == 'uninstall':
if not args.app:
print("No app provided")
@ -123,10 +165,6 @@ elif args.action == 'stop':
print("No app provided")
exit(1)
userData = getUserData()
if args.app == "installed":
if "installedApps" in userData:
stopInstalled()
exit(0)
print("Stopping app {}...".format(args.app))
compose(args.app, "rm --force --stop")
elif args.action == 'start':
@ -135,11 +173,6 @@ elif args.action == 'start':
exit(1)
userData = getUserData()
if args.app == "installed":
if "installedApps" in userData:
startInstalled()
exit(0)
if not "installedApps" in userData or args.app not in userData["installedApps"]:
print("App {} is not yet installed".format(args.app))
exit(1)
@ -149,10 +182,6 @@ elif args.action == 'restart':
if not args.app:
print("No app provided")
exit(1)
if args.app == "installed":
stopInstalled()
startInstalled()
exit(0)
userData = getUserData()
if not "installedApps" in userData or args.app not in userData["installedApps"]:

View File

@ -1,201 +0,0 @@
# yaml-language-server: $schema=https://json-schema.org/draft/2020-12/schema
$schema: https://json-schema.org/draft/2020-12/schema
title: Citadel app.yml v2
description: The second revision of Citadel's app.yml format
type: object
properties:
version:
type:
- string
- number
description: The version of the app.yml format you're using.
metadata:
type: object
properties:
name:
description: Displayed name of the app
type: string
version:
description: Displayed version for the app
type: string
category:
description: The category you'd put the app in
type: string
tagline:
description: A clever tagline
type: string
description:
description: A longer description of the app
type: string
developer:
description: The awesome people behind the app
type: string
website:
description: Displayed version for the app
type: string
dependencies:
description: The services the app depends on
type: array
items:
type: string
repo:
description: The development repository for your app
type: string
support:
description: A link to the app support wiki/chat/...
type: string
gallery:
type: array
description: >-
URLs or paths in the runcitadel/app-images/[app-name] folder with app
images
items:
type: string
path:
description: The path of the app's visible site the open button should open
type: string
defaultPassword:
description: The app's default password Set this to $APP_SEED if the password is the environment variable $APP_SEED.
type: string
torOnly:
description: Whether the app is only available over tor
type: boolean
updateContainer:
type:
- string
- array
description: The container(s) the developer system should automatically update.
lightningImplementation:
description: The supported lightning implementation for this app. If your app supports multiple, please publish a separate app.yml for each implementation.
type: string
enum:
- lnd
- c-lightning
required:
- name
- version
- category
- tagline
- description
- developer
- website
- repo
- support
- gallery
additionalProperties: false
containers:
type: array
items:
type: object
properties:
name:
type: string
image:
type: string
permissions:
type: array
items:
type: string
enum:
- lnd
- c-lightning
- bitcoind
- electrum
- root
- hw
ports:
type: array
items:
type:
- string
- number
port:
type: number
description: >-
If this is the main container, the port inside the container which
will be exposed to the outside as the port specified in metadata.
If this is not set, the port is passed as an env variable in the format APP_${APP_NAME}_${CONTAINER_NAME}_PORT
environment:
type: object
data:
type: array
description: >-
An array of at directories in the container the app stores its data
in. Can be empty. Please only list top-level directories.
items:
type: string
user:
type: string
description: The user the container should run as
stop_grace_period:
type: string
description: The grace period for stopping the container. Defaults to 1 minute.
depends_on:
type: array
description: The services the container depends on
entrypoint:
type:
- string
- array
description: The entrypoint for the container
bitcoin_mount_dir:
type: string
description: Where to mount the bitcoin dir
lnd_mount_dir:
type: string
description: Where to mount the lnd dir
c_lightning_mount_dir:
type: string
description: Where to mount the c-lightning dir
command:
type:
- string
- array
description: The command for the container
init:
type: boolean
description: Whether the container should be run with init
stop_signal:
type: string
description: The signal to send to the container when stopping
noNetwork:
type: boolean
description: >-
Set this to true if the container shouldn't get an IP & port
exposed. This isn't necessary, but helps the docker-compose.yml generator to generate a cleaner output.
hiddenServicePorts:
type:
- object
- number
- array
items:
type:
- string
- number
- array
description: >-
This can either be a map of hidden service names (human readable names, not the .onion URL, and strings, not numbers)
to a port if your app needs multiple hidden services on different ports,
a map of port inside to port on the hidden service (if your app has multiple ports on one hidden service),
or simply one port number if your apps hidden service should only expose one port to the outside which isn't 80.
restart:
type: string
description: When the container should restart. Can be 'always' or 'on-failure'.
network_mode:
type: string
additionalProperties: false
required:
- name
- image
additionalProperties: false
required:
- metadata
- containers
additionalProperties: false

View File

@ -1,212 +0,0 @@
# yaml-language-server: $schema=https://json-schema.org/draft/2020-12/schema
$schema: https://json-schema.org/draft/2020-12/schema
title: Citadel app.yml v3
description: The third revision of Citadel's app.yml format
type: object
properties:
version:
type:
- string
- number
description: The version of the app.yml format you're using.
metadata:
type: object
properties:
name:
description: Displayed name of the app
type: string
version:
description: Displayed version for the app
type: string
category:
description: The category you'd put the app in
type: string
tagline:
description: A clever tagline
type: string
description:
description: A longer description of the app
type: string
developers:
description: The awesome people behind the app
type: object
patternProperties:
"^.*$":
type: string
dependencies:
description: >-
The services the app depends on.
This can also contain an array like [c-lightning, lnd] if your app requires one of two dependencies to function.
type: array
items:
type: [string, array]
items:
type: string
repo:
description: "The development repository (or repositories) for your app, kif you have multiple, in the format human readable name: repo url"
type: [string, object]
patternProperties:
"^.*$":
type: string
support:
description: A link to the app support wiki/chat/...
type: string
gallery:
type: array
description: >-
URLs or paths in the runcitadel/app-images/[app-name] folder with app
images
items:
type: string
path:
description: The path of the app's visible site the open button should open
type: string
defaultPassword:
description: >-
The app's default password.
Set this to $APP_SEED if the password is the environment variable $APP_SEED.
type: string
torOnly:
description: Whether the app is only available over tor
type: boolean
updateContainer:
type:
- string
- array
description: The container(s) the automatic update system should automatically update.
required:
- name
- version
- category
- tagline
- description
- developers
- repo
- support
- gallery
additionalProperties: false
containers:
type: array
items:
type: object
properties:
name:
type: string
image:
type: string
requiredPorts:
type: array
items:
type: number
requiredUdpPorts:
type: array
items:
type: number
description: Ports this container requires to be exposed to work properly
port:
type: number
description: >-
If this is the main container, the port inside the container which
will be exposed to the outside as the port specified in metadata.
If this is not set, the port is passed as an env variable in the format APP_${APP_NAME}_${CONTAINER_NAME}_PORT
preferredOutsidePort:
type: number
description: The port this container would like to have "port" exposed as.
requiresPort:
type: boolean
description: Set this to true if the app requires the preferredOutsidePort to be the real outside port.
environment:
type: object
data:
type: array
description: >-
An array of at directories in the container the app stores its data
in. Can be empty. Please only list top-level directories.
items:
type: string
user:
type: string
description: The user the container should run as
stop_grace_period:
type: string
description: The grace period for stopping the container. Defaults to 1 minute.
depends_on:
type: array
description: The services the container depends on
entrypoint:
type:
- string
- array
description: The entrypoint for the container
mounts:
type: object
description: Where to mount some services' data directories
properties:
bitcoin:
type: string
description: Where to mount the bitcoin dir
lnd:
type: string
description: Where to mount the lnd dir
c_lightning:
type: string
description: Where to mount the c-lightning dir
additionalProperties: false
command:
type:
- string
- array
description: The command for the container
init:
type: boolean
description: Whether the container should be run with init
stop_signal:
type: string
description: The signal to send to the container when stopping
noNetwork:
type: boolean
description: >-
Set this to true if the container shouldn't get an IP & port
exposed. This isn't necessary, but helps the docker-compose.yml generator to generate a cleaner output.
hiddenServicePorts:
type:
- object
- number
- array
items:
type:
- string
- number
- array
description: >-
This can either be a map of hidden service names (human readable names, not the .onion URL, and strings, not numbers)
to a port if your app needs multiple hidden services on different ports,
a map of port inside to port on the hidden service (if your app has multiple ports on one hidden service),
or simply one port number if your apps hidden service should only expose one port to the outside which isn't 80.
restart:
type: string
description: When the container should restart. Can be 'always' or 'on-failure'.
requires:
description: Dependencies this container requires, it is ignored without it.
type: array
items:
type: string
network_mode:
type: string
additionalProperties: false
required:
- name
- image
additionalProperties: false
required:
- metadata
- containers
additionalProperties: false

View File

@ -6,26 +6,6 @@ import re
import fcntl
import os
# Helper functions
# Return a list of env vars in a string, supports both $NAME and ${NAME} format for the env var
# This can potentially be used to get around permissions, so this check is critical for security
# Please report any security vulnerabilities you find in this check to aaron.dewes@protonmail.com
def getEnvVars(string: str):
string = str(string)
envVars = re.findall(r'\$\{.*?\}', string)
newEnvVars = re.findall(r"\$(?!{)([A-z1-9]+)", string)
return [envVar[2:-1] for envVar in envVars] + newEnvVars
# Check if an array only contains values which are also in another array
def checkArrayContainsAllElements(array: list, otherArray: list):
for element in array:
if element not in otherArray:
return False
return True
# Parse a dotenv file
# Values can either be KEY=VALUE or KEY="VALUE" or KEY='VALUE'
# Returns all env vars as a dict
@ -46,39 +26,6 @@ def parse_dotenv(file_path):
exit(1)
return envVars
def is_builtin_type(obj):
return isinstance(obj, (int, float, str, bool, list, dict))
# Convert a class to a dict
# Also strip any class member which is null or empty
def classToDict(theClass):
obj: dict = {}
for key, value in theClass.__dict__.items():
if type(value).__name__ == "NoneType" or (isinstance(value, list) and len(value) == 0):
continue
if isinstance(value, list):
newList = []
for element in value:
if is_builtin_type(element):
newList.append(element)
else:
if type(element).__name__ != "NoneType":
newList.append(classToDict(element))
obj[key] = newList
elif isinstance(value, dict):
newDict = {}
for subkey, subvalue in value.items():
if is_builtin_type(subvalue):
newDict[subkey] = subvalue
else:
newDict[subkey] = classToDict(subvalue)
obj[key] = newDict
elif is_builtin_type(value):
obj[key] = value
elif type(value).__name__ != "NoneType":
obj[key] = classToDict(value)
return obj
class FileLock:
"""Implements a file-based lock using flock(2).
The lock file is saved in directory dir with name lock_name.

View File

@ -1,53 +0,0 @@
# SPDX-FileCopyrightText: 2021-2022 Citadel and contributors
#
# SPDX-License-Identifier: GPL-3.0-or-later
def permissions():
return {
"lnd": {
"environment_allow": [
"LND_IP",
"LND_GRPC_PORT",
"LND_REST_PORT",
"BITCOIN_NETWORK"
],
"volumes": [
'${LND_DATA_DIR}:/lnd:ro'
]
},
"bitcoind": {
"environment_allow": [
"BITCOIN_IP",
"BITCOIN_NETWORK",
"BITCOIN_P2P_PORT",
"BITCOIN_RPC_PORT",
"BITCOIN_RPC_USER",
"BITCOIN_RPC_PASS",
"BITCOIN_RPC_AUTH",
"BITCOIN_ZMQ_RAWBLOCK_PORT",
"BITCOIN_ZMQ_RAWTX_PORT",
"BITCOIN_ZMQ_HASHBLOCK_PORT",
"BITCOIN_ZMQ_SEQUENCE_PORT",
],
"volumes": [
"${BITCOIN_DATA_DIR}:/bitcoin"
]
},
"electrum": {
"environment_allow": [
"ELECTRUM_IP",
"ELECTRUM_PORT",
],
"volumes": []
},
"c-lightning": {
"environment_allow": [
"C_LIGHTNING_IP"
],
"volumes": []
},
}
# Vars which are always allowed without permissions
always_allowed_env = ["TOR_PROXY_IP", "TOR_PROXY_PORT",
"APP_DOMAIN", "APP_HIDDEN_SERVICE", "BITCOIN_NETWORK"]

View File

@ -1,53 +0,0 @@
# SPDX-FileCopyrightText: 2021-2022 Citadel and contributors
#
# SPDX-License-Identifier: GPL-3.0-or-later
import re
from typing import Union
from lib.composegenerator.v2.types import App
from lib.composegenerator.shared.const import always_allowed_env
from lib.citadelutils import checkArrayContainsAllElements, getEnvVars
def validateEnvByValue(env: list, allowed: list, app_name: str):
# Combine always_allowed_env with allowed into one list
# Then check if all elements in env are in the resulting list
all_allowed = allowed + always_allowed_env
if not checkArrayContainsAllElements(env, all_allowed):
# This has a weird syntax, and it confuses VSCode, but it works
validation_regex = r"APP_{}(\S+)".format(
app_name.upper().replace("-", "_"))
for key in env:
# If the key is neither in all_allowed nor is a full match against the validation regex, print a warning and return false
if key not in all_allowed and re.fullmatch(validation_regex, key) is None and not key.startswith("APP_HIDDEN_SERVICE")and not key.startswith("APP_SEED"):
print("Invalid environment variable {} in app {}".format(
key, app_name))
return False
return True
def validateEnvStringOrListorDict(env: Union[str, Union[list, dict]], existingEnv: list, app_name: str, container_name: str):
envList = []
if isinstance(env, dict):
envList = env.values()
elif isinstance(env, list):
envList = env
elif isinstance(env, str):
envList = [env]
for envVar in envList:
if not validateEnvByValue(getEnvVars(envVar), existingEnv, app_name):
raise Exception("Env var {} not defined for container {} of app {}".format(envVar, container_name, app_name))
def validateEnv(app: App):
# For every container of the app, check if all env vars in the strings in environment are defined in env
for container in app.containers:
if container is not None:
if container.environment_allow:
existingEnv = container.environment_allow
del container.environment_allow
else:
existingEnv = []
if container.environment:
validateEnvStringOrListorDict(container.command, existingEnv, app.metadata.id, container.name)
validateEnvStringOrListorDict(container.entrypoint, existingEnv, app.metadata.id, container.name)
validateEnvStringOrListorDict(container.environment, existingEnv, app.metadata.id, container.name)
return app

View File

@ -1,29 +0,0 @@
# SPDX-FileCopyrightText: 2021-2022 Citadel and contributors
#
# SPDX-License-Identifier: GPL-3.0-or-later
# Main functions
from lib.composegenerator.v2.types import App, AppStage3
from lib.composegenerator.shared.const import permissions
def convertContainerPermissions(app: App) -> App:
for container in app.containers:
for permission in container.permissions:
if permission in permissions():
container.environment_allow.extend(permissions()[permission]['environment_allow'])
container.volumes.extend(permissions()[permission]['volumes'])
else:
print("Warning: container {} of app {} defines unknown permission {}".format(container.name, app.metadata.name, permission))
return app
def convertContainersToServices(app: AppStage3) -> AppStage3:
services = {}
for container in app.containers:
if container.permissions:
del container.permissions
services[container.name] = container
del services[container.name].name
del app.containers
app.services = services
return app

View File

@ -1,171 +0,0 @@
# SPDX-FileCopyrightText: 2021-2022 Citadel and contributors
#
# SPDX-License-Identifier: GPL-3.0-or-later
import json
from os import path
import random
from lib.composegenerator.shared.utils.networking import getContainerHiddenService
from lib.composegenerator.v2.types import AppStage2, AppStage3, ContainerStage2, NetworkConfig, App, Container
from lib.citadelutils import parse_dotenv
from dacite import from_dict
def getMainContainer(app: App) -> Container:
if len(app.containers) == 1:
return app.containers[0]
else:
for container in app.containers:
# Main is recommended, support web for easier porting from Umbrel
if container.name == 'main' or container.name == 'web':
return container
# Fallback to first container
return app.containers[0]
def assignIpV4(appId: str, containerName: str):
scriptDir = path.dirname(path.realpath(__file__))
nodeRoot = path.join(scriptDir, "..", "..", "..", "..")
networkingFile = path.join(nodeRoot, "apps", "networking.json")
envFile = path.join(nodeRoot, ".env")
cleanContainerName = containerName.strip()
# If the name still contains a newline, throw an error
if cleanContainerName.find("\n") != -1:
raise Exception("Newline in container name")
env_var = "APP_{}_{}_IP".format(
appId.upper().replace("-", "_"),
cleanContainerName.upper().replace("-", "_")
)
# Write a list of used IPs to the usedIpFile as JSON, and read that file to check if an IP
# can be used
usedIps = []
networkingData = {}
if path.isfile(networkingFile):
with open(networkingFile, 'r') as f:
networkingData = json.load(f)
if 'ip_addresses' in networkingData:
usedIps = list(networkingData['ip_addresses'].values())
else:
networkingData['ip_addresses'] = {}
# An IP 10.21.21.xx, with x being a random number above 40 is asigned to the container
# If the IP is already in use, it will be tried again until it's not in use
# If it's not in use, it will be added to the usedIps list and written to the usedIpFile
# If the usedIpsFile contains all IPs between 10.21.21.20 and 10.21.21.255 (inclusive),
# Throw an error, because no more IPs can be used
if len(usedIps) == 235:
raise Exception("No more IPs can be used")
if "{}-{}".format(appId, cleanContainerName) in networkingData['ip_addresses']:
ip = networkingData['ip_addresses']["{}-{}".format(
appId, cleanContainerName)]
else:
while True:
ip = "10.21.21." + str(random.randint(20, 255))
if ip not in usedIps:
networkingData['ip_addresses']["{}-{}".format(
appId, cleanContainerName)] = ip
break
dotEnv = parse_dotenv(envFile)
if env_var in dotEnv and str(dotEnv[env_var]) == str(ip):
return
with open(envFile, 'a') as f:
f.write("{}={}\n".format(env_var, ip))
with open(networkingFile, 'w') as f:
json.dump(networkingData, f)
def assignIp(container: ContainerStage2, appId: str, networkingFile: str, envFile: str) -> ContainerStage2:
# Strip leading/trailing whitespace from container.name
container.name = container.name.strip()
# If the name still contains a newline, throw an error
if container.name.find("\n") != -1:
raise Exception("Newline in container name")
env_var = "APP_{}_{}_IP".format(
appId.upper().replace("-", "_"),
container.name.upper().replace("-", "_")
)
# Write a list of used IPs to the usedIpFile as JSON, and read that file to check if an IP
# can be used
usedIps = []
networkingData = {}
if path.isfile(networkingFile):
with open(networkingFile, 'r') as f:
networkingData = json.load(f)
if 'ip_addresses' in networkingData:
usedIps = list(networkingData['ip_addresses'].values())
else:
networkingData['ip_addresses'] = {}
# An IP 10.21.21.xx, with x being a random number above 40 is asigned to the container
# If the IP is already in use, it will be tried again until it's not in use
# If it's not in use, it will be added to the usedIps list and written to the usedIpFile
# If the usedIpsFile contains all IPs between 10.21.21.20 and 10.21.21.255 (inclusive),
# Throw an error, because no more IPs can be used
if len(usedIps) == 235:
raise Exception("No more IPs can be used")
if "{}-{}".format(appId, container.name) in networkingData['ip_addresses']:
ip = networkingData['ip_addresses']["{}-{}".format(
appId, container.name)]
else:
while True:
ip = "10.21.21." + str(random.randint(20, 255))
if ip not in usedIps:
networkingData['ip_addresses']["{}-{}".format(
appId, container.name)] = ip
break
container.networks = from_dict(data_class=NetworkConfig, data={'default': {
'ipv4_address': "$" + env_var}})
dotEnv = parse_dotenv(envFile)
if env_var in dotEnv and str(dotEnv[env_var]) == str(ip):
return container
# Now append a new line with APP_{app_name}_{container_name}_IP=${IP} to the envFile
with open(envFile, 'a') as f:
f.write("{}={}\n".format(env_var, ip))
with open(networkingFile, 'w') as f:
json.dump(networkingData, f)
return container
def configureIps(app: AppStage2, networkingFile: str, envFile: str):
for container in app.containers:
if container.network_mode and container.network_mode == "host":
continue
if container.noNetwork:
# Check if port is defined for the container
if container.port:
raise Exception("Port defined for container without network")
if getMainContainer(app).name == container.name:
raise Exception("Main container without network")
# Skip this iteration of the loop
continue
container = assignIp(container, app.metadata.id,
networkingFile, envFile)
return app
def configureHiddenServices(app: AppStage3, nodeRoot: str) -> AppStage3:
dotEnv = parse_dotenv(path.join(nodeRoot, ".env"))
hiddenServices = ""
mainContainer = getMainContainer(app)
for container in app.containers:
if container.network_mode and container.network_mode == "host":
continue
env_var = "APP_{}_{}_IP".format(
app.metadata.id.upper().replace("-", "_"),
container.name.upper().replace("-", "_")
)
hiddenServices += getContainerHiddenService(
app.metadata, container, dotEnv[env_var], container.name == mainContainer.name)
if container.hiddenServicePorts:
del container.hiddenServicePorts
torDaemons = ["torrc-apps", "torrc-apps-2", "torrc-apps-3"]
torFileToAppend = torDaemons[random.randint(0, len(torDaemons) - 1)]
with open(path.join(nodeRoot, "tor", torFileToAppend), 'a') as f:
f.write(hiddenServices)
return app

View File

@ -1,99 +0,0 @@
# SPDX-FileCopyrightText: 2021-2022 Citadel and contributors
#
# SPDX-License-Identifier: GPL-3.0-or-later
from lib.composegenerator.v2.types import Metadata, Container
def getHiddenServiceMultiPort(name: str, id: str, internalIp: str, ports: list) -> str:
hiddenServices = """
# {} Hidden Service
HiddenServiceDir /var/lib/tor/app-{}
""".format(
name, id
)
for port in ports:
hiddenServices += "HiddenServicePort {} {}:{}".format(port, internalIp, port)
hiddenServices += "\n"
return hiddenServices
def getHiddenServiceString(
name: str, id: str, internalPort, internalIp: str, publicPort
) -> str:
return """
# {} Hidden Service
HiddenServiceDir /var/lib/tor/app-{}
HiddenServicePort {} {}:{}
""".format(
name, id, publicPort, internalIp, internalPort
)
def getHiddenService(appName: str, appId: str, appIp: str, appPort: str) -> str:
return getHiddenServiceString(appName, appId, appPort, appIp, "80")
def getContainerHiddenService(
metadata: Metadata, container: Container, containerIp: str, isMainContainer: bool
) -> str:
if isMainContainer and not container.hiddenServicePorts:
return getHiddenServiceString(
metadata.name, metadata.id, metadata.internalPort, containerIp, 80
)
if container.hiddenServicePorts:
if isinstance(container.hiddenServicePorts, int):
return getHiddenServiceString(
"{} {}".format(metadata.name, container.name),
metadata.id if isMainContainer else "{}-{}".format(metadata.id, container.name),
container.hiddenServicePorts,
containerIp,
container.hiddenServicePorts,
)
elif isinstance(container.hiddenServicePorts, list):
return getHiddenServiceMultiPort(
"{} {}".format(metadata.name, container.name),
metadata.id if isMainContainer else "{}-{}".format(metadata.id, container.name),
containerIp,
container.hiddenServicePorts,
)
elif isinstance(container.hiddenServicePorts, dict):
additionalHiddenServices = {}
hiddenServices = "# {} {} Hidden Service\nHiddenServiceDir /var/lib/tor/app-{}-{}\n".format(
metadata.name, container.name, metadata.id, container.name
)
initialHiddenServices = "# {} {} Hidden Service\nHiddenServiceDir /var/lib/tor/app-{}-{}\n".format(
metadata.name, container.name, metadata.id, container.name
)
otherHiddenServices = ""
for key, value in container.hiddenServicePorts.items():
if isinstance(key, int):
hiddenServices += "HiddenServicePort {} {}:{}".format(
key, containerIp, value
)
hiddenServices += "\n"
else:
additionalHiddenServices[key] = value
for key, value in additionalHiddenServices.items():
if isinstance(value, int):
otherHiddenServices += "# {} {} {} Hidden Service\nHiddenServiceDir /var/lib/tor/app-{}-{}\n".format(
metadata.name, container.name, key, metadata.id, key
)
otherHiddenServices += "HiddenServicePort {} {}:{}".format(
value, containerIp, value
)
otherHiddenServices += "\n"
elif isinstance(value, list):
otherHiddenServices += getHiddenServiceMultiPort(
"{} {}".format(metadata.name, key), "{}-{}".format(metadata.id, key), containerIp, value
)
if hiddenServices == initialHiddenServices:
return otherHiddenServices
else :
return hiddenServices + "\n" + otherHiddenServices
del container.hiddenServicePorts
return ""

View File

@ -1,73 +0,0 @@
# SPDX-FileCopyrightText: 2021-2022 Citadel and contributors
#
# SPDX-License-Identifier: GPL-3.0-or-later
from lib.composegenerator.v2.types import App, AppStage2, AppStage4, generateApp
from lib.composegenerator.v2.networking import configureMainPort
from lib.composegenerator.shared.networking import configureHiddenServices, configureIps
from lib.composegenerator.shared.main import convertContainerPermissions, convertContainersToServices
from lib.composegenerator.shared.env import validateEnv
from lib.citadelutils import classToDict
import os
def convertDataDirToVolumeGen2(app: App) -> AppStage2:
for container in app.containers:
# Loop through data dirs in container.data, if they don't contain a .., add them to container.volumes
# Also, a datadir shouldn't start with a /
for dataDir in container.data:
if dataDir.find("..") == -1 and dataDir[0] != "/":
container.volumes.append(
'${APP_DATA_DIR}/' + dataDir)
else:
print("Data dir " + dataDir +
" contains invalid characters")
del container.data
if container.bitcoin_mount_dir != None:
if not 'bitcoind' in container.permissions:
print("Warning: container {} of app {} defines bitcoin_mount_dir but has no permissions for bitcoind".format(container.name, app.metadata.name))
# Skip this container
continue
# Also skip the container if container.bitcoin_mount_dir contains a :
if container.bitcoin_mount_dir.find(":") == -1:
container.volumes.append('${BITCOIN_DATA_DIR}:' + container.bitcoin_mount_dir)
del container.bitcoin_mount_dir
if container.lnd_mount_dir != None:
if not 'lnd' in container.permissions:
print("Warning: container {} of app {} defines lnd_mount_dir but doesn't request lnd permission".format(container.name, app.metadata.name))
# Skip this container
continue
# Also skip the container if container.lnd_mount_dir contains a :
if container.lnd_mount_dir.find(":") == -1:
container.volumes.append('${LND_DATA_DIR}:' + container.lnd_mount_dir)
del container.lnd_mount_dir
if container.c_lightning_mount_dir != None:
if not 'lnd' in container.permissions:
print("Warning: container {} of app {} defines c_lightning_mount_dir but doesn't request c-lightning permission".format(container.name, app.metadata.name))
# Skip this container
continue
# Also skip the container if container.c_lightning.mount_dir contains a :
if container.c_lightning_mount_dir.find(":") == -1:
container.volumes.append('${C_LIGHTNING_DATA_DIR}:' + container.c_lightning_mount_dir)
del container.c_lightning_mount_dir
return app
def createComposeConfigFromV2(app: dict, nodeRoot: str):
envFile = os.path.join(nodeRoot, ".env")
networkingFile = os.path.join(nodeRoot, "apps", "networking.json")
newApp: App = generateApp(app)
newApp = convertContainerPermissions(newApp)
newApp = validateEnv(newApp)
newApp = convertDataDirToVolumeGen2(newApp)
newApp = configureIps(newApp, networkingFile, envFile)
newApp = configureMainPort(newApp, nodeRoot)
newApp = configureHiddenServices(newApp, nodeRoot)
finalConfig: AppStage4 = convertContainersToServices(newApp)
newApp = classToDict(finalConfig)
del newApp['metadata']
if "version" in newApp:
del newApp["version"]
# Set version to 3.8 (current compose file version)
newApp = {'version': '3.8', **newApp}
return newApp

View File

@ -1,158 +0,0 @@
# SPDX-FileCopyrightText: 2021-2022 Citadel and contributors
#
# SPDX-License-Identifier: GPL-3.0-or-later
from lib.citadelutils import parse_dotenv
from lib.composegenerator.v2.types import App, AppStage2, AppStage3, Container
import json
from os import path
import os
import random
from lib.composegenerator.shared.networking import assignIp
from lib.citadelutils import FileLock
def getFreePort(networkingFile: str, appId: str):
# Ports used currently in Citadel
usedPorts = [
# Dashboard
80,
# Sometimes used by nginx with some setups
433,
# Dashboard SSL
443,
# Bitcoin Core P2P
8333,
# LND gRPC
10009,
# LND REST
8080,
# Electrum Server
50001,
# Tor Proxy
9050,
]
networkingData = {}
if path.isfile(networkingFile):
with open(networkingFile, 'r') as f:
networkingData = json.load(f)
if 'ports' in networkingData:
usedPorts += list(networkingData['ports'].values())
else:
networkingData['ports'] = {}
if appId in networkingData['ports']:
return networkingData['ports'][appId]
while True:
port = str(random.randint(1024, 49151))
if port not in usedPorts:
# Check if anyhing is listening on the specific port
if os.system("netstat -ntlp | grep " + port + " > /dev/null") != 0:
networkingData['ports'][appId] = port
break
with open(networkingFile, 'w') as f:
json.dump(networkingData, f)
return port
def getMainContainer(app: App) -> Container:
if len(app.containers) == 1:
return app.containers[0]
else:
for container in app.containers:
# Main is recommended, support web for easier porting from Umbrel
if container.name == 'main' or container.name == 'web':
return container
# Fallback to first container
return app.containers[0]
def assignPort(container: dict, appId: str, networkingFile: str, envFile: str):
# Strip leading/trailing whitespace from container.name
container.name = container.name.strip()
# If the name still contains a newline, throw an error
if container.name.find("\n") != -1 or container.name.find(" ") != -1:
raise Exception("Newline or space in container name")
env_var = "APP_{}_{}_PORT".format(
appId.upper().replace("-", "_"),
container.name.upper().replace("-", "_")
)
port = getFreePort(networkingFile, appId)
dotEnv = parse_dotenv(envFile)
if env_var in dotEnv and str(dotEnv[env_var]) == str(port):
return {"port": port, "env_var": "${{{}}}".format(env_var)}
# Now append a new line with APP_{app_name}_{container_name}_PORT=${PORT} to the envFile
with open(envFile, 'a') as f:
f.write("{}={}\n".format(env_var, port))
# This is confusing, but {{}} is an escaped version of {} so it is ${{ {} }}
# where the outer {{ }} will be replaced by {} in the returned string
return {"port": port, "env_var": "${{{}}}".format(env_var)}
def configureMainPort(app: AppStage2, nodeRoot: str) -> AppStage3:
lock = FileLock("citadel_registry_lock", dir="/tmp")
lock.acquire()
registryFile = path.join(nodeRoot, "apps", "registry.json")
registry: list = []
if path.isfile(registryFile):
with open(registryFile, 'r') as f:
registry = json.load(f)
else:
raise Exception("Registry file not found")
mainContainer = getMainContainer(app)
portDetails = assignPort(mainContainer, app.metadata.id, path.join(
nodeRoot, "apps", "networking.json"), path.join(nodeRoot, ".env"))
containerPort = portDetails['port']
portAsEnvVar = portDetails['env_var']
portToAppend = portAsEnvVar
mainPort = False
if mainContainer.port:
portToAppend = "{}:{}".format(portAsEnvVar, mainContainer.port)
mainPort = mainContainer.port
del mainContainer.port
else:
portToAppend = "{}:{}".format(portAsEnvVar, portAsEnvVar)
if mainContainer.ports:
mainContainer.ports.append(portToAppend)
# Set the main port to the first port in the list, if it contains a :, it's the port after the :
# If it doesn't contain a :, it's the port itself
if mainPort == False:
mainPort = mainContainer.ports[0]
if mainPort.find(":") != -1:
mainPort = mainPort.split(":")[1]
else:
mainContainer.ports = [portToAppend]
if mainPort == False:
mainPort = portDetails['port']
if mainContainer.network_mode != "host":
mainContainer = assignIp(mainContainer, app.metadata.id, path.join(
nodeRoot, "apps", "networking.json"), path.join(nodeRoot, ".env"))
# Also set the port in metadata
app.metadata.port = int(containerPort)
if mainPort:
app.metadata.internalPort = int(mainPort)
else:
app.metadata.internalPort = int(containerPort)
for registryApp in registry:
if registryApp['id'] == app.metadata.id:
registry[registry.index(registryApp)]['port'] = int(containerPort)
registry[registry.index(registryApp)]['internalPort'] = app.metadata.internalPort
break
with open(registryFile, 'w') as f:
json.dump(registry, f, indent=4, sort_keys=True)
lock.release()
return app

View File

@ -1,156 +0,0 @@
from typing import Union, List
from dataclasses import dataclass, field
from dacite import from_dict
@dataclass
class Metadata:
id: str
name: str
version: str
category: str
tagline: str
description: str
developer: str
website: str
repo: str
support: str
gallery: List[str] = field(default_factory=list)
dependencies: List[str] = field(default_factory=list)
updateContainer: Union[str, Union[list, None]] = field(default_factory=list)
path: str = ""
defaultPassword: str = ""
torOnly: bool = False
lightningImplementation: Union[str, None] = None
# Added automatically later
port: int = 0
internalPort: int = 0
@dataclass
class Container:
name: str
image: str
permissions: list = field(default_factory=list)
ports: list = field(default_factory=list)
port: Union[int, None] = None
environment: Union[dict, None] = None
data: list = field(default_factory=list)
user: Union[str, None] = None
stop_grace_period: str = '1m'
depends_on: list = field(default_factory=list)
entrypoint: Union[List[str], str] = field(default_factory=list)
bitcoin_mount_dir: Union[str, None] = None
lnd_mount_dir: Union[str, None] = None
c_lightning_mount_dir: Union[str, None] = None
command: Union[List[str], str] = field(default_factory=list)
init: Union[bool, None] = None
stop_signal: Union[str, None] = None
noNetwork: Union[bool, None] = None
hiddenServicePorts: Union[dict, Union[int, Union[None, list]]] = field(default_factory=list)
environment_allow: list = field(default_factory=list)
network_mode: Union[str, None] = None
# Only added later
volumes: list = field(default_factory=list)
restart: Union[str, None] = None
@dataclass
class App:
version: Union[str, int]
metadata: Metadata
containers: List[Container]
# Generate an app instance from an app dict
def generateApp(appDict):
return from_dict(data_class=App, data=appDict)
@dataclass
class Network:
ipv4_address: Union[str, None] = None
@dataclass
class NetworkConfig:
default: Network
# After converting data dir and defining volumes, stage 2
@dataclass
class ContainerStage2:
id: str
name: str
image: str
permissions: List[str] = field(default_factory=list)
ports: list = field(default_factory=list)
environment: Union[dict, None] = None
user: Union[str, None] = None
stop_grace_period: str = '1m'
depends_on: List[str] = field(default_factory=list)
entrypoint: Union[List[str], str] = field(default_factory=list)
command: Union[List[str], str] = field(default_factory=list)
init: Union[bool, None] = None
stop_signal: Union[str, None] = None
noNetwork: Union[bool, None] = None
hiddenServicePorts: Union[dict, Union[int, Union[None, list]]] = field(default_factory=list)
volumes: List[str] = field(default_factory=list)
networks: NetworkConfig = field(default_factory=NetworkConfig)
restart: Union[str, None] = None
network_mode: Union[str, None] = None
@dataclass
class AppStage2:
version: Union[str, int]
metadata: Metadata
containers: List[ContainerStage2]
@dataclass
class MetadataStage3:
id: str
name: str
version: str
category: str
tagline: str
description: str
developer: str
website: str
dependencies: List[str]
repo: str
support: str
gallery: List[str]
updateContainer: Union[str, Union[list, None]] = field(default_factory=list)
path: str = ""
defaultPassword: str = ""
torOnly: bool = False
lightningImplementation: Union[str, None] = None
# Added automatically later
port: int = 0
internalPort: int = 0
@dataclass
class AppStage3:
version: Union[str, int]
metadata: MetadataStage3
containers: List[ContainerStage2]
@dataclass
class ContainerStage4:
id: str
name: str
image: str
ports: list = field(default_factory=list)
environment: Union[dict, None] = None
user: Union[str, None] = None
stop_grace_period: str = '1m'
depends_on: List[str] = field(default_factory=list)
entrypoint: Union[List[str], str] = field(default_factory=list)
command: Union[List[str], str] = field(default_factory=list)
init: Union[bool, None] = None
stop_signal: Union[str, None] = None
noNetwork: Union[bool, None] = None
hiddenServicePorts: Union[dict, Union[int, Union[None, list]]] = field(default_factory=list)
volumes: List[str] = field(default_factory=list)
networks: NetworkConfig = field(default_factory=NetworkConfig)
restart: Union[str, None] = None
network_mode: Union[str, None] = None
@dataclass
class AppStage4:
version: Union[str, int]
metadata: MetadataStage3
services: List[ContainerStage4]

View File

@ -1,108 +0,0 @@
# SPDX-FileCopyrightText: 2021-2022 Citadel and contributors
#
# SPDX-License-Identifier: GPL-3.0-or-later
import os
from lib.citadelutils import classToDict
from lib.composegenerator.shared.main import convertContainersToServices
from lib.composegenerator.shared.env import validateEnv
from lib.composegenerator.shared.networking import configureIps, configureHiddenServices
from lib.composegenerator.v3.types import App, AppStage2, AppStage4, generateApp
from lib.composegenerator.v3.networking import configureMainPort
from lib.composegenerator.shared.const import permissions
def convertContainerPermissions(app: App) -> App:
for container in app.containers:
if container is not None:
for permission in app.metadata.dependencies:
if isinstance(permission, str):
if permission in permissions():
container.environment_allow.extend(permissions()[permission]['environment_allow'])
container.volumes.extend(permissions()[permission]['volumes'])
else:
print("Warning: app {} defines unknown permission {}".format(app.metadata.name, permission))
else:
for subPermission in permission:
if subPermission in permissions():
container.environment_allow.extend(permissions()[subPermission]['environment_allow'])
container.volumes.extend(permissions()[subPermission]['volumes'])
else:
print("Warning: app {} defines unknown permission {}".format(app.metadata.name, subPermission))
return app
def convertDataDirToVolumeGen3(app: App) -> AppStage2:
for container in app.containers:
# Loop through data dirs in container.data, if they don't contain a .., add them to container.volumes
# Also, a datadir shouldn't start with a /
for dataDir in container.data:
if dataDir.find("..") == -1 and dataDir[0] != "/":
container.volumes.append(
'${APP_DATA_DIR}/' + dataDir)
else:
print("Data dir " + dataDir +
" contains invalid characters")
del container.data
for container in app.containers:
if container.mounts:
if container.mounts.lnd:
if not 'lnd' in app.metadata.dependencies:
print("Warning: container {} of app {} defines lnd mount dir but doesn't request lnd permission".format(container.name, app.metadata.name))
# Skip this container
continue
# Also skip the container if container.mounts.lnd contains a :
if container.mounts.lnd.find(":") == -1:
container.volumes.append('${LND_DATA_DIR}:' + container.mounts.lnd)
if container.mounts.bitcoin:
if not 'bitcoind' in app.metadata.dependencies:
print("Warning: container {} of app {} defines lnd mount dir but doesn't request lnd permission".format(container.name, app.metadata.name))
# Skip this container
continue
# Also skip the container if container.lnd_mount_dir contains a :
if container.mounts.bitcoin.find(":") == -1:
container.volumes.append('${BITCOIN_DATA_DIR}:' + container.mounts.bitcoin)
del container.mounts
return app
def createComposeConfigFromV3(app: dict, nodeRoot: str):
envFile = os.path.join(nodeRoot, ".env")
networkingFile = os.path.join(nodeRoot, "apps", "networking.json")
ignoredContainers = []
newApp: App = generateApp(app)
for container in newApp.containers:
# TODO: Make this dynamic and not hardcoded
if container.requires and "c-lightning" in container.requires:
ignoredContainers.append(container.name)
container.ignored = True
elif container.requires:
del container.requires
newApp = convertContainerPermissions(newApp)
newApp = validateEnv(newApp)
newApp = convertDataDirToVolumeGen3(newApp)
newApp = configureIps(newApp, networkingFile, envFile)
# This is validated earlier
for container in newApp.containers:
for tcpPort in container.requiredPorts:
container.ports.append("{}:{}".format(tcpPort, tcpPort))
del container.requiredPorts
for container in newApp.containers:
for udpPort in container.requiredUdpPorts:
container.ports.append("{}:{}/udp".format(udpPort, udpPort))
del container.requiredUdpPorts
newApp = configureMainPort(newApp, nodeRoot)
newApp = configureHiddenServices(newApp, nodeRoot)
for container in newApp.containers:
del container.ignored
finalConfig: AppStage4 = convertContainersToServices(newApp)
newApp = classToDict(finalConfig)
del newApp['metadata']
for container in ignoredContainers:
del newApp['services'][container]
if "version" in newApp:
del newApp["version"]
# Set version to 3.8 (current compose file version)
newApp = {'version': '3.8', **newApp}
return newApp

View File

@ -1,108 +0,0 @@
# SPDX-FileCopyrightText: 2021-2022 Citadel and contributors
#
# SPDX-License-Identifier: GPL-3.0-or-later
from lib.composegenerator.v3.types import App, AppStage2, AppStage3
import json
from os import path
from lib.composegenerator.shared.networking import assignIp
from lib.citadelutils import FileLock
def getMainContainerIndex(app: App):
if len(app.containers) == 1:
return 0
else:
for index, container in enumerate(app.containers):
# Main is recommended, support web for easier porting from Umbrel
if (container.name == 'main' or container.name == 'web') and not container.ignored:
return index
for index, container in enumerate(app.containers):
# Also allow names to start with main
if container.name.startswith("main") and not container.ignored:
return index
# Fallback to first container
return 0
def configureMainPort(app: AppStage2, nodeRoot: str) -> AppStage3:
lock = FileLock("citadel_registry_lock", dir="/tmp")
lock.acquire()
registryFile = path.join(nodeRoot, "apps", "registry.json")
portsFile = path.join(nodeRoot, "apps", "ports.json")
envFile = path.join(nodeRoot, ".env")
registry: list = []
ports = {}
if path.isfile(registryFile):
with open(registryFile, 'r') as f:
registry = json.load(f)
else:
raise Exception("Registry file not found")
if path.isfile(portsFile):
with open(portsFile, 'r') as f:
ports = json.load(f)
else:
raise Exception("Ports file not found")
mainContainerIndex = getMainContainerIndex(app)
mainContainer = app.containers[mainContainerIndex]
portAsEnvVar = "APP_{}_{}_PORT".format(
app.metadata.id.upper().replace("-", "_"),
mainContainer.name.upper().replace("-", "_")
)
portToAppend = portAsEnvVar
mainPort = False
containerPort = False
if mainContainer.port:
portToAppend = "${{{}}}:{}".format(portAsEnvVar, mainContainer.port)
mainPort = mainContainer.port
for port in ports[app.metadata.id][mainContainer.name]:
if str(port["internalPort"]) == str(mainPort):
containerPort = port["publicPort"]
del mainContainer.port
else:
for port in ports[app.metadata.id][mainContainer.name]:
if port["dynamic"]:
mainPort = port["internalPort"]
containerPort = port["publicPort"]
portToAppend = "${{{}}}:${{{}}}".format(portAsEnvVar, portAsEnvVar)
if mainContainer.ports:
mainContainer.ports.append(portToAppend)
# Set the main port to the first port in the list, if it contains a :, it's the port after the :
# If it doesn't contain a :, it's the port itself
if mainPort == False:
mainPort = mainContainer.ports[0]
if mainPort.find(":") != -1:
mainPort = mainPort.split(":")[1]
else:
mainContainer.ports = [portToAppend]
if mainContainer.network_mode != "host":
mainContainer = assignIp(mainContainer, app.metadata.id, path.join(
nodeRoot, "apps", "networking.json"), path.join(nodeRoot, ".env"))
# Also set the port in metadata
app.metadata.port = int(containerPort)
if mainPort:
app.metadata.internalPort = int(mainPort)
else:
app.metadata.internalPort = int(containerPort)
for registryApp in registry:
if registryApp['id'] == app.metadata.id:
registry[registry.index(registryApp)]['port'] = containerPort
registry[registry.index(registryApp)]['internalPort'] = app.metadata.internalPort
break
with open(registryFile, 'w') as f:
json.dump(registry, f, indent=4, sort_keys=True)
lock.release()
with open(envFile, 'a') as f:
f.write("{}={}\n".format(portAsEnvVar, app.metadata.port))
return app

View File

@ -1,166 +0,0 @@
from typing import Union, List
from dataclasses import dataclass, field
from dacite import from_dict
@dataclass
class Metadata:
id: str
name: str
version: str
category: str
tagline: str
description: str
repo: str
support: str
developers: dict = field(default_factory=dict)
gallery: List[Union[list,str]] = field(default_factory=list)
dependencies: List[Union[List[str], str]] = field(default_factory=list)
updateContainer: Union[str, Union[list, None]] = field(default_factory=list)
path: str = ""
defaultPassword: str = ""
torOnly: bool = False
lightningImplementation: Union[str, None] = None
# Added automatically later
port: int = 0
internalPort: int = 0
@dataclass
class ContainerMounts:
bitcoin: Union[str, None] = None
lnd: Union[str, None] = None
c_lightning: Union[str, None] = None
@dataclass
class Container:
name: str
image: str
permissions: list = field(default_factory=list)
port: Union[int, None] = None
requiredPorts: list = field(default_factory=list)
requiredUdpPorts: list = field(default_factory=list)
#preferredOutsidePort: Union[int, None] = None
requiresPort: Union[bool, None] = None
environment: Union[dict, None] = None
data: list = field(default_factory=list)
user: Union[str, None] = None
stop_grace_period: str = '1m'
depends_on: list = field(default_factory=list)
entrypoint: Union[List[str], str] = field(default_factory=list)
mounts: Union[ContainerMounts, None] = None
command: Union[List[str], str] = field(default_factory=list)
init: Union[bool, None] = None
stop_signal: Union[str, None] = None
noNetwork: Union[bool, None] = None
hiddenServicePorts: Union[dict, Union[int, Union[None, list]]] = field(default_factory=list)
environment_allow: list = field(default_factory=list)
requires: list = field(default_factory=list)
network_mode: Union[str, None] = None
# Only added later
volumes: list = field(default_factory=list)
restart: Union[str, None] = None
ports: list = field(default_factory=list)
ignored: bool = False
@dataclass
class App:
version: Union[str, int]
metadata: Metadata
containers: List[Container]
# Generate an app instance from an app dict
def generateApp(appDict):
return from_dict(data_class=App, data=appDict)
@dataclass
class Network:
ipv4_address: Union[str, None] = None
@dataclass
class NetworkConfig:
default: Network
# After converting data dir and defining volumes, stage 2
@dataclass
class ContainerStage2:
id: str
name: str
image: str
permissions: List[str] = field(default_factory=list)
ports: list = field(default_factory=list)
environment: Union[dict, None] = None
user: Union[str, None] = None
stop_grace_period: str = '1m'
depends_on: List[str] = field(default_factory=list)
entrypoint: Union[List[str], str] = field(default_factory=list)
command: Union[List[str], str] = field(default_factory=list)
init: Union[bool, None] = None
stop_signal: Union[str, None] = None
noNetwork: Union[bool, None] = None
hiddenServicePorts: Union[dict, Union[int, Union[None, list]]] = field(default_factory=list)
volumes: List[str] = field(default_factory=list)
networks: NetworkConfig = field(default_factory=NetworkConfig)
restart: Union[str, None] = None
network_mode: Union[str, None] = None
requires: Union[List[str], None] = field(default_factory=list)
@dataclass
class AppStage2:
version: Union[str, int]
metadata: Metadata
containers: List[ContainerStage2]
@dataclass
class MetadataStage3:
id: str
name: str
version: str
category: str
tagline: str
description: str
developer: str
website: str
dependencies: List[str]
repo: str
support: str
gallery: List[str]
updateContainer: Union[str, Union[list, None]] = field(default_factory=list)
path: str = ""
defaultPassword: str = ""
torOnly: bool = False
lightningImplementation: Union[str, None] = None
# Added automatically later
port: int = 0
internalPort: int = 0
@dataclass
class AppStage3:
version: Union[str, int]
metadata: MetadataStage3
containers: List[ContainerStage2]
@dataclass
class ContainerStage4:
id: str
name: str
image: str
ports: list = field(default_factory=list)
environment: Union[dict, None] = None
user: Union[str, None] = None
stop_grace_period: str = '1m'
depends_on: List[str] = field(default_factory=list)
entrypoint: Union[List[str], str] = field(default_factory=list)
command: Union[List[str], str] = field(default_factory=list)
init: Union[bool, None] = None
stop_signal: Union[str, None] = None
noNetwork: Union[bool, None] = None
hiddenServicePorts: Union[dict, Union[int, Union[None, list]]] = field(default_factory=list)
volumes: List[str] = field(default_factory=list)
networks: NetworkConfig = field(default_factory=NetworkConfig)
restart: Union[str, None] = None
network_mode: Union[str, None] = None
@dataclass
class AppStage4:
version: Union[str, int]
metadata: MetadataStage3
services: List[ContainerStage4]

View File

@ -2,44 +2,34 @@
#
# SPDX-License-Identifier: GPL-3.0-or-later
import json
import os
import random
import re
import shutil
import stat
import subprocess
import sys
import tempfile
import threading
import random
from typing import List
import traceback
from sys import argv
import os
import requests
import shutil
import json
import yaml
import subprocess
import re
try:
import semver
except Exception:
print("Semver for python isn't installed")
print("On Debian/Ubuntu, you can install it using")
print(" sudo apt install -y python3-semver")
print("On other systems, please use")
print(" sudo pip3 install semver")
print("Continuing anyway, but some features won't be available,")
print("for example checking for app updates")
from typing import List
from lib.composegenerator.v2.generate import createComposeConfigFromV2
from lib.composegenerator.v3.generate import createComposeConfigFromV3
from lib.validate import findAndValidateApps
from lib.metadata import getAppRegistry
import requests
import semver
import yaml
from lib.citadelutils import FileLock, parse_dotenv
from lib.entropy import deriveEntropy
from lib.citadelutils import FileLock
from lib.metadata import getAppMetadata
from lib.validate import findAndValidateApps
# For an array of threads, join them and wait for them to finish
def joinThreads(threads: List[threading.Thread]):
for thread in threads:
thread.join()
# The directory with this script
scriptDir = os.path.dirname(os.path.realpath(__file__))
nodeRoot = os.path.join(scriptDir, "..", "..")
@ -53,24 +43,6 @@ legacyScript = os.path.join(nodeRoot, "scripts", "app")
with open(os.path.join(nodeRoot, "db", "dependencies.yml"), "r") as file:
dependencies = yaml.safe_load(file)
def parse_dotenv(file_path):
envVars: dict = {}
with open(file_path, 'r') as file:
for line in file:
line = line.strip()
if line.startswith('#') or len(line) == 0:
continue
if '=' in line:
key, value = line.split('=', 1)
value = value.strip('"').strip("'")
envVars[key] = value
else:
print("Error: Invalid line in {}: {}".format(file_path, line))
print("Line should be in the format KEY=VALUE or KEY=\"VALUE\" or KEY='VALUE'")
exit(1)
return envVars
dotCitadelPath = os.path.join(nodeRoot, "..", ".citadel")
dotenv = {}
# Returns a list of every argument after the second one in sys.argv joined into a string by spaces
@ -80,17 +52,33 @@ def getArguments():
arguments += argv[i] + " "
return arguments
def get_var(var_name):
if os.path.isfile(dotCitadelPath):
dotenv=parse_dotenv(os.path.join(nodeRoot, "..", ".env"))
else:
def get_var_safe(var_name):
dotenv = parse_dotenv(os.path.join(nodeRoot, ".env"))
if var_name in dotenv:
return str(dotenv[var_name])
else:
print("Error: {} is not defined!".format(var_name))
return False
def get_var(var_name):
var_value = get_var_safe(var_name)
if var_value:
return var_value
else:
print("Error: {} is not defined!".format(var_name))
exit(1)
def getInstalledVirtualApps():
installedApps = []
with open(os.path.join(appsDir, "virtual-apps.json"), "r") as f:
virtual_apps = json.load(f)
userData = getUserData()
for virtual_app in virtual_apps.keys():
for implementation in virtual_apps[virtual_app]:
if "installedApps" in userData and implementation in userData["installedApps"]:
installedApps.append(virtual_app)
return installedApps
# Converts a string to uppercase, also replaces all - with _
def convert_to_upper(string):
return string.upper().replace('-', '_')
@ -100,10 +88,18 @@ def convert_to_upper(string):
def replace_vars(file_content: str):
return re.sub(r'<(.*?)>', lambda m: get_var(convert_to_upper(m.group(1))), file_content)
def handleAppV4(app):
def handleAppV3OrV4(app):
# Currently part of Citadel
services = ["lnd", "bitcoind"]
userData = getUserData()
if not "installedApps" in userData:
userData["installedApps"] = []
services.extend(userData["installedApps"])
services.extend(getInstalledVirtualApps())
composeFile = os.path.join(appsDir, app, "docker-compose.yml")
os.chown(os.path.join(appsDir, app), 1000, 1000)
os.system("docker run --rm -v {}:/apps -u 1000:1000 {} /app-cli convert --app-name '{}' --port-map /apps/ports.json /apps/{}/app.yml /apps/{}/result.yml".format(appsDir, dependencies['app-cli'], app, app, app))
if not os.path.isfile(os.path.join(appsDir, app, "result.yml")):
os.system("docker run --rm -v {}:/apps -u 1000:1000 {} /app-cli convert --app-name '{}' --port-map /apps/ports.json --services '{}' /apps/{}/app.yml /apps/{}/result.yml".format(appsDir, dependencies['app-cli'], app, ",".join(services), app, app))
with open(os.path.join(appsDir, app, "result.yml"), "r") as resultFile:
resultYml = yaml.safe_load(resultFile)
with open(composeFile, "w") as dockerComposeFile:
@ -112,7 +108,7 @@ def handleAppV4(app):
torFileToAppend = torDaemons[random.randint(0, len(torDaemons) - 1)]
with open(os.path.join(nodeRoot, "tor", torFileToAppend), 'a') as f:
f.write(replace_vars(resultYml["new_tor_entries"]))
mainPort = resultYml["port"]
registryFile = os.path.join(nodeRoot, "apps", "registry.json")
registry: list = []
lock = FileLock("citadel_registry_lock", dir="/tmp")
@ -120,13 +116,13 @@ def handleAppV4(app):
if os.path.isfile(registryFile):
with open(registryFile, 'r') as f:
registry = json.load(f)
else:
raise Exception("Registry file not found")
for registryApp in registry:
if registryApp['id'] == app:
registry[registry.index(registryApp)]['port'] = mainPort
break
resultYml["metadata"]['port'] = resultYml["port"]
resultYml["metadata"]['defaultPassword'] = resultYml["metadata"].get('defaultPassword', '')
if resultYml["metadata"]['defaultPassword'] == "$APP_SEED":
resultYml["metadata"]['defaultPassword'] = deriveEntropy("app-{}-seed".format(app))
registry.append(resultYml["metadata"])
with open(registryFile, 'w') as f:
json.dump(registry, f, indent=4, sort_keys=True)
@ -157,41 +153,36 @@ def update(verbose: bool = False):
with open(os.path.join(appsDir, "ports.cache.json"), "w") as f:
portCache = json.load(f)
except Exception: pass
# The compose generation process updates the registry, so we need to get it set up with the basics before that
registry = getAppRegistry(apps, appsDir, portCache)
with open(os.path.join(appsDir, "registry.json"), "w") as f:
json.dump(registry["metadata"], f, sort_keys=True)
registry = getAppMetadata(apps, appsDir, portCache)
with open(os.path.join(appsDir, "ports.json"), "w") as f:
json.dump(registry["ports"], f, sort_keys=True)
with open(os.path.join(appsDir, "ports.cache.json"), "w") as f:
json.dump(registry["portCache"], f, sort_keys=True)
with open(os.path.join(appsDir, "virtual-apps.json"), "w") as f:
json.dump(registry["virtual_apps"], f, sort_keys=True)
print("Wrote registry to registry.json")
print("Processed app metadata")
# Delete the registry so it's regenerated
os.remove(os.path.join(nodeRoot, "apps", "registry.json"))
os.system("docker pull {}".format(dependencies['app-cli']))
threads = list()
# Loop through the apps and generate valid compose files from them, then put these into the app dir
for app in apps:
try:
composeFile = os.path.join(appsDir, app, "docker-compose.yml")
appYml = os.path.join(appsDir, app, "app.yml")
with open(appYml, 'r') as f:
appDefinition = yaml.safe_load(f)
if 'citadel_version' in appDefinition:
thread = threading.Thread(target=handleAppV4, args=(app,))
if ('citadel_version' in appDefinition) or ('version' in appDefinition and str(appDefinition['version']) == "3"):
thread = threading.Thread(target=handleAppV3OrV4, args=(app,))
thread.start()
threads.append(thread)
else:
appCompose = getApp(appDefinition, app)
with open(composeFile, "w") as f:
if appCompose:
f.write(yaml.dump(appCompose, sort_keys=False))
if verbose:
print("Wrote " + app + " to " + composeFile)
raise Exception("Error: Unsupported version of app.yml")
except Exception as err:
print("Failed to convert app {}".format(app))
print(err)
print(traceback.format_exc())
joinThreads(threads)
print("Generated configuration successfully")
@ -205,7 +196,6 @@ def download(app: str):
else:
print("Warning: Could not download " + app)
def getUserData():
userData = {}
if os.path.isfile(userFile):
@ -213,65 +203,23 @@ def getUserData():
userData = json.load(f)
return userData
def startInstalled():
# If userfile doesn't exist, just do nothing
userData = {}
if os.path.isfile(userFile):
with open(userFile, "r") as f:
userData = json.load(f)
#threads = []
for app in userData["installedApps"]:
if not os.path.isdir(os.path.join(appsDir, app)):
print("Warning: App {} doesn't exist on Citadel".format(app))
continue
print("Starting app {}...".format(app))
# Run compose(args.app, "up --detach") asynchrounously for all apps, then exit(0) when all are finished
#thread = threading.Thread(target=compose, args=(app, "up --detach"))
#thread.start()
#threads.append(thread)
compose(app, "up --detach")
#joinThreads(threads)
def stopInstalled():
# If userfile doesn't exist, just do nothing
userData = {}
if os.path.isfile(userFile):
with open(userFile, "r") as f:
userData = json.load(f)
threads = []
for app in userData["installedApps"]:
if not os.path.isdir(os.path.join(appsDir, app)):
print("Warning: App {} doesn't exist on Citadel".format(app))
continue
print("Stopping app {}...".format(app))
# Run compose(args.app, "up --detach") asynchrounously for all apps, then exit(0) when all are finished
thread = threading.Thread(
target=compose, args=(app, "rm --force --stop"))
thread.start()
threads.append(thread)
joinThreads(threads)
# Loads an app.yml and converts it to a docker-compose.yml
def getApp(app, appId: str):
if not "metadata" in app:
raise Exception("Error: Could not find metadata in " + appId)
app["metadata"]["id"] = appId
if 'version' in app and str(app['version']) == "2":
print("Warning: App {} uses version 2 of the app.yml format, which is scheduled for removal in Citadel 0.1.5".format(appId))
return createComposeConfigFromV2(app, nodeRoot)
elif 'version' in app and str(app['version']) == "3":
print("Warning: App {} uses version 3 of the app.yml format, which is scheduled for removal in Citadel 0.1.5".format(appId))
return createComposeConfigFromV3(app, nodeRoot)
else:
raise Exception("Error: Unsupported version of app.yml")
def compose(app, arguments):
if not os.path.isdir(os.path.join(appsDir, app)):
print("Warning: App {} doesn't exist on Citadel".format(app))
print("Warning: App {} doesn't exist on this node!".format(app))
return
virtual_apps = {}
with open(os.path.join(appsDir, "virtual-apps.json"), "r") as f:
virtual_apps = json.load(f)
userData = getUserData()
for virtual_app in virtual_apps.keys():
implementations = virtual_apps[virtual_app]
for implementation in implementations:
if "installedApps" in userData and implementation in userData["installedApps"]:
if get_var_safe("APP_{}_SERVICE_IP".format(convert_to_upper(implementation))):
os.environ["APP_{}_IP".format(convert_to_upper(virtual_app))] = get_var_safe("APP_{}_SERVICE_IP".format(convert_to_upper(implementation))) # type: ignore
#if get_var_safe("APP_{}_SERVICE_PORT".format(convert_to_upper(implementation))):
#os.environ["APP_{}_PORT".format(virtual_app)] = get_var_safe("APP_{}_SERVICE_PORT".format(convert_to_upper(implementation))) # type: ignore
break
# Runs a compose command in the app dir
# Before that, check if a docker-compose.yml exists in the app dir
composeFile = os.path.join(appsDir, app, "docker-compose.yml")
@ -422,11 +370,11 @@ def updateRepos():
"githubRepo": gitUrl.removeprefix("https://github.com/").removesuffix(".git").removesuffix("/"),
"branch": branch,
}
if os.path.isdir(os.path.join(tempDir, "apps", app)):
if os.path.isdir(os.path.join(appsDir, app)):
shutil.rmtree(os.path.join(appsDir, app), onerror=remove_readonly)
if os.path.isdir(os.path.join(tempDir, "apps", app)):
shutil.copytree(os.path.join(tempDir, "apps", app), os.path.join(appsDir, app),
symlinks=False, ignore=shutil.ignore_patterns(".gitignore"))
symlinks=False, ignore=shutil.ignore_patterns(".gitignore", "result.yml"))
alreadyInstalled.append(app)
# Remove the temporary dir
shutil.rmtree(tempDir)

View File

@ -2,17 +2,73 @@
#
# SPDX-License-Identifier: GPL-3.0-or-later
import json
import os
import yaml
import random
import traceback
from os import path
from lib.composegenerator.shared.networking import assignIpV4
import yaml
from lib.citadelutils import parse_dotenv
from lib.entropy import deriveEntropy
appPorts = {}
appPortMap = {}
disabledApps = []
def assignIpV4(appId: str, containerName: str):
scriptDir = path.dirname(path.realpath(__file__))
nodeRoot = path.join(scriptDir, "..", "..")
networkingFile = path.join(nodeRoot, "apps", "networking.json")
envFile = path.join(nodeRoot, ".env")
cleanContainerName = containerName.strip()
# If the name still contains a newline, throw an error
if cleanContainerName.find("\n") != -1:
raise Exception("Newline in container name")
env_var = "APP_{}_{}_IP".format(
appId.upper().replace("-", "_"),
cleanContainerName.upper().replace("-", "_")
)
# Write a list of used IPs to the usedIpFile as JSON, and read that file to check if an IP
# can be used
usedIps = []
networkingData = {}
if path.isfile(networkingFile):
with open(networkingFile, 'r') as f:
networkingData = json.load(f)
if 'ip_addresses' in networkingData:
usedIps = list(networkingData['ip_addresses'].values())
else:
networkingData['ip_addresses'] = {}
# An IP 10.21.21.xx, with x being a random number above 40 is asigned to the container
# If the IP is already in use, it will be tried again until it's not in use
# If it's not in use, it will be added to the usedIps list and written to the usedIpFile
# If the usedIpsFile contains all IPs between 10.21.21.20 and 10.21.21.255 (inclusive),
# Throw an error, because no more IPs can be used
if len(usedIps) == 235:
raise Exception("No more IPs can be used")
if "{}-{}".format(appId, cleanContainerName) in networkingData['ip_addresses']:
ip = networkingData['ip_addresses']["{}-{}".format(
appId, cleanContainerName)]
else:
while True:
ip = "10.21.21." + str(random.randint(20, 255))
if ip not in usedIps:
networkingData['ip_addresses']["{}-{}".format(
appId, cleanContainerName)] = ip
break
dotEnv = parse_dotenv(envFile)
if env_var in dotEnv and str(dotEnv[env_var]) == str(ip):
return
with open(envFile, 'a') as f:
f.write("{}={}\n".format(env_var, ip))
with open(networkingFile, 'w') as f:
json.dump(networkingData, f)
def appPortsToMap():
for port in appPorts:
appId = appPorts[port]["app"]
@ -33,8 +89,7 @@ def appPortsToMap():
# Also check the path and defaultPassword and set them to an empty string if they don't exist
# In addition, set id on the metadata to the name of the app
# Return a list of all app's metadata
def getAppRegistry(apps, app_path, portCache):
app_metadata = []
def getAppMetadata(apps, app_path, portCache):
virtual_apps = {}
appPorts = portCache
for app in apps:
@ -49,22 +104,12 @@ def getAppRegistry(apps, app_path, portCache):
elif 'citadel_version' in app_yml:
version = int(app_yml['citadel_version'])
metadata: dict = app_yml['metadata']
metadata['id'] = app
metadata['path'] = metadata.get('path', '')
metadata['defaultPassword'] = metadata.get('defaultPassword', '')
if metadata['defaultPassword'] == "$APP_SEED":
metadata['defaultPassword'] = deriveEntropy("app-{}-seed".format(app))
if "mainContainer" in metadata:
metadata.pop("mainContainer")
if "implements" in metadata:
implements = metadata["implements"]
if implements not in virtual_apps:
virtual_apps[implements] = []
virtual_apps[implements].append(app)
app_metadata.append(metadata)
if version < 3:
getPortsOldApp(app_yml, app)
elif version == 3:
if version == 3:
getPortsV3App(app_yml, app)
elif version == 4:
getPortsV4App(app_yml, app)
@ -74,7 +119,6 @@ def getAppRegistry(apps, app_path, portCache):
appPortsToMap()
return {
"virtual_apps": virtual_apps,
"metadata": app_metadata,
"ports": appPortMap,
"portCache": appPorts,
}
@ -93,7 +137,7 @@ citadelPorts = [
# LND REST
8080,
# Electrum Server
50001,
# 50001,
# Tor Proxy
9050,
]
@ -108,7 +152,7 @@ def getNewPort(usedPorts, appId, containerName, allowExisting):
lastPort2 = lastPort2 + 1
return lastPort2
def validatePort(containerName, appContainer, port, appId, priority: int, isDynamic = False):
def validatePort(containerName, port, appId, priority: int, isDynamic = False, implements = ""):
if port not in appPorts and port not in citadelPorts and port != 0:
appPorts[port] = {
"app": appId,
@ -116,6 +160,7 @@ def validatePort(containerName, appContainer, port, appId, priority: int, isDyna
"container": containerName,
"priority": priority,
"dynamic": isDynamic,
"implements": implements,
}
else:
if port in citadelPorts or appPorts[port]["app"] != appId or appPorts[port]["container"] != containerName:
@ -129,64 +174,68 @@ def validatePort(containerName, appContainer, port, appId, priority: int, isDyna
"container": containerName,
"priority": priority,
"dynamic": isDynamic,
"implements": implements,
}
else:
if "requiresPort" in appContainer and appContainer["requiresPort"]:
# Apps implement the same service and can't be installed together, so we an safely ignore a port conflict
if port in appPorts and implements != "" and implements == appPorts[port]["implements"]:
return
if priority == 2:
disabledApps.append(appId)
print("App {} disabled because of port conflict".format(appId))
else:
newPort = getNewPort(appPorts, appId, containerName, True)
internalPort = port
if isDynamic:
internalPort = newPort
#print("Port conflict! Moving app {}'s container {} to port {} (from {})".format(appId, containerName, newPort, port))
appPorts[newPort] = {
"app": appId,
"port": port,
"port": internalPort,
"container": containerName,
"priority": priority,
"dynamic": isDynamic,
}
def getPortsOldApp(app, appId):
for appContainer in app["containers"]:
if "port" in appContainer:
validatePort(appContainer["name"], appContainer, appContainer["port"], appId, 0)
if "ports" in appContainer:
for port in appContainer["ports"]:
realPort = int(str(port).split(":")[0])
validatePort(appContainer["name"], appContainer, realPort, appId, 2)
def getPortsV3App(app, appId):
for appContainer in app["containers"]:
assignIpV4(appId, appContainer["name"])
if "port" in appContainer:
if "preferredOutsidePort" in appContainer and "requiresPort" in appContainer and appContainer["requiresPort"]:
validatePort(appContainer["name"], appContainer, appContainer["preferredOutsidePort"], appId, 2)
validatePort(appContainer["name"], appContainer["preferredOutsidePort"], appId, 2)
elif "preferredOutsidePort" in appContainer:
validatePort(appContainer["name"], appContainer, appContainer["preferredOutsidePort"], appId, 1)
validatePort(appContainer["name"], appContainer["preferredOutsidePort"], appId, 1)
else:
validatePort(appContainer["name"], appContainer["port"], appId, 0)
else:
validatePort(appContainer["name"], appContainer, appContainer["port"], appId, 0)
elif "requiredPorts" not in appContainer and "requiredUdpPorts" not in appContainer:
# if the container does not define a port, assume 3000, and pass it to the container as env var
validatePort(appContainer["name"], appContainer, 3000, appId, 0, True)
validatePort(appContainer["name"], 3000, appId, 0, True)
if "requiredPorts" in appContainer:
for port in appContainer["requiredPorts"]:
validatePort(appContainer["name"], appContainer, port, appId, 2)
validatePort(appContainer["name"], port, appId, 2)
if "requiredUdpPorts" in appContainer:
for port in appContainer["requiredUdpPorts"]:
validatePort(appContainer["name"], appContainer, port, appId, 2)
validatePort(appContainer["name"], port, appId, 2)
def getPortsV4App(app, appId):
implements = ""
if "implements" in app["metadata"]:
implements = app["metadata"]["implements"]
for appContainerName in app["services"].keys():
appContainer = app["services"][appContainerName]
if "enable_networking" in appContainer and not appContainer["enable_networking"]:
return
assignIpV4(appId, appContainerName)
if "port" in appContainer:
validatePort(appContainerName, appContainer, appContainer["port"], appId, 0)
validatePort(appContainerName, appContainer["port"], appId, 0, False, implements)
else:
# if the container does not define a port, assume 3000, and pass it to the container as env var
validatePort(appContainerName, 3000, appId, 0, True, implements)
if "required_ports" in appContainer:
if "tcp" in appContainer["required_ports"]:
if "tcp" in appContainer["required_ports"] and appContainer["required_ports"]["tcp"] != None:
for port in appContainer["required_ports"]["tcp"].keys():
validatePort(appContainerName, appContainer, port, appId, 2)
if "udp" in appContainer["required_ports"]:
validatePort(appContainerName, port, appId, 2, False, implements)
if "udp" in appContainer["required_ports"] and appContainer["required_ports"]["udp"] != None:
for port in appContainer["required_ports"]["udp"].keys():
validatePort(appContainerName, appContainer, port, appId, 2)
validatePort(appContainerName, port, appId, 2, False, implements)

View File

@ -2,126 +2,97 @@
#
# SPDX-License-Identifier: GPL-3.0-or-later
import json
import os
import yaml
from jsonschema import validate
import yaml
import traceback
scriptDir = os.path.join(os.path.dirname(os.path.realpath(__file__)), "..")
nodeRoot = os.path.join(scriptDir, "..")
with open(os.path.join(scriptDir, 'app-standard-v2.yml'), 'r') as f:
schemaVersion2 = yaml.safe_load(f)
with open(os.path.join(scriptDir, 'app-standard-v3.yml'), 'r') as f:
schemaVersion3 = yaml.safe_load(f)
userFile = os.path.join(nodeRoot, "db", "user.json")
appsDir = os.path.join(nodeRoot, "apps")
with open(os.path.join(nodeRoot, "db", "dependencies.yml"), "r") as file:
dependencies = yaml.safe_load(file)
# Validates app data
# Returns true if valid, false otherwise
def validateApp(app: dict):
if 'version' in app and str(app['version']) == "2":
try:
validate(app, schemaVersion2)
return True
# Catch and log any errors, and return false
except Exception as e:
print(traceback.format_exc())
return False
elif 'version' in app and str(app['version']) == "3":
try:
validate(app, schemaVersion3)
return True
# Catch and log any errors, and return false
except Exception as e:
print(traceback.format_exc())
return False
elif 'version' not in app and 'citadel_version' not in app:
print("Unsupported app version")
return False
else:
return True
def getUserData():
userData = {}
if os.path.isfile(userFile):
with open(userFile, "r") as f:
userData = json.load(f)
return userData
# Read in an app.yml file and pass it to the validation function
# Returns true if valid, false otherwise
def validateAppFile(file: str):
with open(file, 'r') as f:
return validateApp(yaml.safe_load(f))
# Returns all dirs in the dir
def findApps(dir: str):
apps = []
# Only get directories in the dir, but not recursively
for root, dirs, files in os.walk(dir, topdown=False):
for name in dirs:
app_dir = os.path.join(root, name)
if os.path.isfile(os.path.join(app_dir, "app.yml")) or os.path.isfile(os.path.join(app_dir, "docker-compose.yml")):
apps.append(name)
return apps
def getInstalledVirtualApps():
installedApps = []
try:
with open(os.path.join(appsDir, "virtual-apps.json"), "r") as f:
virtual_apps = json.load(f)
userData = getUserData()
for virtual_app in virtual_apps.keys():
for implementation in virtual_apps[virtual_app]:
if "installedApps" in userData and implementation in userData["installedApps"]:
installedApps.append(virtual_app)
except: pass
return installedApps
# Lists all folders in a directory and checks if they are valid
# A folder is valid if it contains an app.yml file
# A folder is invalid if it doesn't contain an app.yml file
def findAndValidateApps(dir: str):
services = ["lnd", "bitcoind"]
userData = getUserData()
if not "installedApps" in userData:
userData["installedApps"] = []
services.extend(userData["installedApps"])
services.extend(getInstalledVirtualApps())
service_str = ",".join(services)
apps = []
app_data = {}
for subdir in os.scandir(dir):
if not subdir.is_dir():
continue
app_dir = subdir.path
allowed_app_files = 3
if os.path.isfile(os.path.join(app_dir, "app.yml.jinja")):
allowed_app_files += 1
os.chown(app_dir, 1000, 1000)
os.system("docker run --rm -v {}:/apps -u 1000:1000 {} /app-cli preprocess --app-name '{}' /apps/{}/app.yml.jinja /apps/{}/app.yml --services 'lnd'".format(dir, dependencies['app-cli'], subdir.name, subdir.name, subdir.name))
if os.path.isfile(os.path.join(app_dir, "app.yml")):
apps.append(subdir.name)
# Read the app.yml and append it to app_data
with open(os.path.join(app_dir, "app.yml"), 'r') as f:
app_data[subdir.name] = yaml.safe_load(f)
else:
os.system(
"docker run --rm -v {}:/apps -u 1000:1000 {} /app-cli preprocess --app-name '{}' /apps/{}/app.yml.jinja /apps/{}/app.yml --services '{}'".format(
dir, dependencies["app-cli"], subdir.name, subdir.name, subdir.name, service_str
)
)
# App should be re-converted considering this may have changed the app.yml
if os.path.isfile(os.path.join(app_dir, "result.yml")):
os.remove(os.path.join(app_dir, "result.yml"))
for subfile in os.scandir(subdir):
if allowed_app_files == 0:
break
if (
subfile.is_file()
and subfile.name.endswith(".jinja")
and subfile.name != "app.yml.jinja"
):
allowed_app_files -= 1
os.chown(app_dir, 1000, 1000)
cmd = "docker run --rm -v {}:/seed -v {}:/.env -v {}:/apps -u 1000:1000 {} /app-cli preprocess-config-file --env-file /.env --app-name '{}' --app-file '/apps/{}/{}' /apps/{}/{} /apps/{}/{} --services '{}' --seed-file /seed".format(
os.path.join(nodeRoot, "db", "citadel-seed", "seed"),
os.path.join(nodeRoot, ".env"),
dir,
dependencies["app-cli"],
subdir.name,
subdir.name,
"app.yml",
subdir.name,
subfile.name,
subdir.name,
subfile.name[:-6],
service_str,
)
print(cmd)
os.system(cmd)
if not os.path.isfile(os.path.join(app_dir, "app.yml")):
print("App {} has no app.yml".format(subdir.name))
# Now validate all the apps using the validateAppFile function by passing the app.yml as an argument to it, if an app is invalid, remove it from the list
for app in apps:
appyml = app_data[app]
if not validateApp(appyml):
apps.remove(app)
print("Warning: App {} is invalid".format(app))
# Skip to the next iteration of the loop
continue
# More security validation
should_continue=True
if 'dependencies' in appyml['metadata']:
for dependency in appyml['metadata']['dependencies']:
if isinstance(dependency, str):
if dependency not in apps and dependency not in ["bitcoind", "lnd", "electrum"]:
print("WARNING: App '{}' has unknown dependency '{}'".format(app, dependency))
apps.remove(app)
should_continue=False
if dependency == app:
print("WARNING: App '{}' depends on itself".format(app))
apps.remove(app)
should_continue=False
else:
for subDependency in dependency:
if subDependency not in apps and subDependency not in ["bitcoind", "lnd", "electrum", "c-lightning"]:
print("WARNING: App '{}' has unknown dependency '{}'".format(app, subDependency))
apps.remove(app)
should_continue=False
if subDependency == app:
print("WARNING: App '{}' depends on itself".format(app))
apps.remove(app)
should_continue=False
if not should_continue:
continue
if 'containers' in appyml:
for container in appyml['containers']:
if 'permissions' in container:
for permission in container['permissions']:
if permission not in appyml['metadata']['dependencies'] and permission not in ["root", "hw"]:
print("WARNING: App {}'s container '{}' requires the '{}' permission, but the app doesn't list it in it's dependencies".format(app, container['name'], permission))
apps.remove(app)
# Skip to the next iteration of the loop
continue
apps.append(subdir.name)
return apps

0
apps/.gitkeep Normal file
View File

View File

@ -56,9 +56,9 @@ if [[ "$command" = "status" ]]; then
echo
if $long; then
docker container ls --format "table {{.Names}}\t{{.Image}}\t{{.Status}}\t{{.Ports}}"
docker container ls --all --format "table {{.Names}}\t{{.Image}}\t{{.Status}}\t{{.Ports}}"
else
docker container ls --format "table {{.Names}}\t{{.Status}}"
docker container ls --all --format "table {{.Names}}\t{{.Status}}"
fi
if [[ $(pgrep -f karen) ]]; then
@ -140,24 +140,29 @@ if [[ "$command" = "stop" ]]; then
exit
fi
# Restart Citadel
# Restart Citadel or individual services
if [[ "$command" = "restart" ]]; then
shift
# TODO: enable restarting services
# restart Docker containers
if [ ! -z ${1+x} ]; then
echo "Too many arguments."
echo "Usage: \`$CLI_NAME $command\`"
docker restart $@ || {
echo "To see all installed services & apps use \`$CLI_NAME list\`"
echo "Usage: \`$CLI_NAME $command <service>\`"
exit 1
}
exit
fi
# restart Citadel
if $(is_managed_by_systemd); then
sudo systemctl restart $SERVICE_NAME
else
sudo $CITADEL_ROOT/scripts/stop
sudo $CITADEL_ROOT/scripts/start
fi
exit
fi
@ -177,6 +182,7 @@ fi
# List all installed services apps
if [[ "$command" = "list" ]]; then
# TODO: make this a bit nicer
echo 'karen'
docker ps --format "{{.Names}}"
exit

View File

@ -1,4 +1,9 @@
#!/usr/bin/env bash
# SPDX-FileCopyrightText: 2022 Citadel and contributors
#
# SPDX-License-Identifier: GPL-3.0-or-later
set -euo pipefail
show_help() {
@ -13,20 +18,20 @@ Flags:
-v, --version Show version information for this CLI
Commands:
status Check the status of all services
status [options] Check the status of all services
start Start the Citadel service
stop Stop the Citadel service safely
restart Restart the Citadel service
restart [service] Restart Citadel or individual services
reboot Reboot the system
shutdown Shutdown the system
update Update Citadel
update [options] Update Citadel
list List all installed services apps
run <service> "<command>" Run a command inside a container
set <command> Switch between Bitcoin & Lightning implementations
app <command> Install, update or restart apps
configure <service> Edit service & app configuration files
logs <service> Show logs for an app or service
debug View logs for troubleshooting
logs [service] Show logs for an app or service
debug [options] View logs for troubleshooting
EOF
}

View File

@ -1,4 +1,9 @@
#!/usr/bin/env bash
# SPDX-FileCopyrightText: 2022 Citadel and contributors
#
# SPDX-License-Identifier: GPL-3.0-or-later
set -euo pipefail
trim() {

View File

@ -1,4 +1,9 @@
#!/usr/bin/env bash
# SPDX-FileCopyrightText: 2022 Citadel and contributors
#
# SPDX-License-Identifier: GPL-3.0-or-later
set -euo pipefail
function multiselect() {

View File

@ -1,6 +1,8 @@
#!/bin/bash
# Author: Tasos Latsas
# SPDX-FileCopyrightText: 2021 Tasos Latsas
#
# SPDX-License-Identifier: MIT
# spinner.sh
#

View File

@ -1,5 +1,10 @@
compose: v2.10.2
dashboard: ghcr.io/runcitadel/dashboard:v0.0.17@sha256:4416254a023b3060338529446068b97b2d95834c59119b75bdeae598c5c81d0e
manager: ghcr.io/runcitadel/manager:v0.0.17@sha256:ba436a07d6f96282217851756d8c81aeaa03c42dfa2246a89a78fc3384eed3cb
middleware: ghcr.io/runcitadel/middleware:main@sha256:2aa20f31001ab9e61cda548acbd1864a598728731ad6121f050c6a41503866ae
app-cli: ghcr.io/runcitadel/app-cli:main@sha256:c1073222d380797355678471155297f491a667d0bfde743271554c8d9c4c7e17
# SPDX-FileCopyrightText: 2022 Citadel and contributors
#
# SPDX-License-Identifier: GPL-3.0-or-later
compose: v2.11.2
dashboard: ghcr.io/runcitadel/dashboard:citadel-0.0.10@sha256:7ce1f0080ef9a6ef0bb990c979a422839592e165ae57c2a6df19cccb9154aef7
manager: ghcr.io/runcitadel/manager:main@sha256:0ebc76556ec9f1f37e86e55778e7d073df87ebce1a5c6cb6c70e2f5fde882722
middleware: ghcr.io/runcitadel/middleware:main@sha256:5b01a0a94152c5cf29a1d645e9186b16f72fb0b349940ad534dec62ea4a2a2dc
app-cli: ghcr.io/runcitadel/app-cli:main@sha256:7c440e728bc800a37f39f5ec7fc81279b5eaa180e4919d7aac516ae40e1b416f
tor: lncm/tor:0.4.7.9@sha256:86c2fe9d9099e6376798979110b8b9a3ee5d8adec27289ac4a5ee892514ffe92

View File

@ -1,8 +1,11 @@
version: '3.8'
# SPDX-FileCopyrightText: 2022 Citadel and contributors
#
# SPDX-License-Identifier: GPL-3.0-or-later
services:
tor:
container_name: tor
image: lncm/tor:0.4.7.8@sha256:aab30ebb496aa25934d6096951d8b200347c3c3ce5db3493695229efa2601f7b
image: lncm/tor:0.4.7.9@sha256:86c2fe9d9099e6376798979110b8b9a3ee5d8adec27289ac4a5ee892514ffe92
user: toruser
restart: on-failure
volumes:
@ -15,7 +18,7 @@ services:
ipv4_address: $TOR_PROXY_IP
app-tor:
container_name: app-tor
image: lncm/tor:0.4.7.8@sha256:aab30ebb496aa25934d6096951d8b200347c3c3ce5db3493695229efa2601f7b
image: lncm/tor:0.4.7.9@sha256:86c2fe9d9099e6376798979110b8b9a3ee5d8adec27289ac4a5ee892514ffe92
user: toruser
restart: on-failure
volumes:
@ -26,7 +29,7 @@ services:
ipv4_address: $APPS_TOR_IP
app-2-tor:
container_name: app-2-tor
image: lncm/tor:0.4.7.8@sha256:aab30ebb496aa25934d6096951d8b200347c3c3ce5db3493695229efa2601f7b
image: lncm/tor:0.4.7.9@sha256:86c2fe9d9099e6376798979110b8b9a3ee5d8adec27289ac4a5ee892514ffe92
user: toruser
restart: on-failure
volumes:
@ -37,7 +40,7 @@ services:
ipv4_address: $APPS_2_TOR_IP
app-3-tor:
container_name: app-3-tor
image: lncm/tor:0.4.7.8@sha256:aab30ebb496aa25934d6096951d8b200347c3c3ce5db3493695229efa2601f7b
image: lncm/tor:0.4.7.9@sha256:86c2fe9d9099e6376798979110b8b9a3ee5d8adec27289ac4a5ee892514ffe92
user: toruser
restart: on-failure
volumes:
@ -78,7 +81,7 @@ services:
ipv4_address: $BITCOIN_IP
lightning:
container_name: lightning
image: lightninglabs/lnd:v0.15.2-beta@sha256:a011b06c622c947a3039d76a5a08b4896fc6a02dea6add3afd345019f8737923
image: lightninglabs/lnd:v0.15.3-beta@sha256:93b4055bf4fb040907587bdf806c5bc6d42bd21b5b90f26df0c86471c8245ca8
user: 1000:1000
depends_on:
- tor
@ -98,6 +101,7 @@ services:
default:
ipv4_address: $LND_IP
dashboard:
container_name: dashboard
image: ghcr.io/runcitadel/dashboard:v0.0.17@sha256:4416254a023b3060338529446068b97b2d95834c59119b75bdeae598c5c81d0e
restart: on-failure
stop_grace_period: 1m30s
@ -106,12 +110,10 @@ services:
ipv4_address: $DASHBOARD_IP
manager:
container_name: manager
image: ghcr.io/runcitadel/manager:v0.0.17@sha256:ba436a07d6f96282217851756d8c81aeaa03c42dfa2246a89a78fc3384eed3cb
image: ghcr.io/runcitadel/manager:deno@sha256:fa5bd47fc5a19095a26f1660d8d64fb571d24b476cddf4f6e61ae0e7690caf87
depends_on:
- tor
- redis
command:
- ./start.sh
restart: on-failure
init: true
stop_grace_period: 5m30s
@ -126,7 +128,6 @@ services:
- jwt-public-key:/jwt-public-key
- jwt-private-key:/jwt-private-key
environment:
PORT: '3006'
USER_PASSWORD_FILE: /db/user.json
JWT_PUBLIC_KEY_FILE: /jwt-public-key/jwt.pem
JWT_PRIVATE_KEY_FILE: /jwt-private-key/jwt.key
@ -160,7 +161,7 @@ services:
ipv4_address: $MANAGER_IP
middleware:
container_name: middleware
image: ghcr.io/runcitadel/middleware:main@sha256:2aa20f31001ab9e61cda548acbd1864a598728731ad6121f050c6a41503866ae
image: ghcr.io/runcitadel/middleware:deno-manager@sha256:ff27301f4059a5b259bb5db79edcff682dfbf84864d24fc7fa49b11d1890e484
depends_on:
- bitcoin
- lightning
@ -204,20 +205,6 @@ services:
networks:
default:
ipv4_address: $NEUTRINO_SWITCHER_IP
electrum:
container_name: electrum
image: ghcr.io/runcitadel/electrs:v0.9.6@sha256:cf08513b8aa6f081e42ea92c5903d520db2caedbc20aaccf70f844663bbc8646
working_dir: /data
volumes:
- ${PWD}/bitcoin:/bitcoin:ro
- ${PWD}/electrs:/data
restart: on-failure
stop_grace_period: 5m
ports:
- $ELECTRUM_PORT:$ELECTRUM_PORT
networks:
default:
ipv4_address: $ELECTRUM_IP
redis:
container_name: redis
user: 1000:1000

View File

@ -1,7 +1,7 @@
{
"version": "0.0.10",
"name": "An important bug fix update",
"requires": ">=0.0.5",
"version": "0.1.0",
"name": "Citadel 0.1.0",
"requires": ">=0.0.10",
"isQuickUpdate": false,
"notes": "This update fixes an issue causing LND to crash."
"notes": "This update contains a lot of fixes and improvements. Read more on https://blog.runcitadel.space."
}

4
karen
View File

@ -1,5 +1,9 @@
#!/usr/bin/env python3
# SPDX-FileCopyrightText: 2022 Citadel and contributors
#
# SPDX-License-Identifier: GPL-3.0-or-later
import socket
import os

View File

@ -1,5 +1,9 @@
#!/usr/bin/env python3
# SPDX-FileCopyrightText: 2022 Citadel and contributors
#
# SPDX-License-Identifier: GPL-3.0-or-later
try:
import crossplane
except ImportError:

View File

@ -9,10 +9,33 @@ NODE_ROOT="$(dirname $(readlink -f "${BASH_SOURCE[0]}"))/.."
# If the first argument is stop, start, install or uninstall, and there are multiple other arguments,
# Run the "${NODE_ROOT}/app/app-manager.py" for each of the other arguments.
# Otherwise, run the "${NODE_ROOT}/app/app-manager.py" with the first argument as the command.
if [ "$1" == "stop" ] || [ "$1" == "start" ] || [ "$1" == "install" ] || [ "$1" == "uninstall" ]; then
if [ "$1" == "stop" ] || [ "$1" == "start" ] || [ "$1" == "install" ] || [ "$1" == "uninstall" ] || [ "$1" == "restart" ]; then
if [ "$2" == "installed" ]; then
# Fail if the first argument is install
if [ "$1" == "install" ]; then
echo "Cannot install all installed apps"
exit 1
fi
# Print a warning if the first argument is uninstall
# And sleep for 15 seconds to give the user time to cancel
if [ "$1" == "uninstall" ]; then
echo "WARNING: Uninstalling all installed apps!"
echo "Press Ctrl+C to cancel"
echo "Waiting 15 seconds..."
sleep 15
fi
installed_apps=$("${NODE_ROOT}/app/app-manager.py" ls-installed)
if [[ ! -z "${installed_apps:-}" ]]; then
for app in ${installed_apps}; do
"${NODE_ROOT}/app/app-manager.py" "$1" "${app}" &
done
wait
fi
else
for app in "${@:2}"; do
"${NODE_ROOT}/app/app-manager.py" "$1" "$app"
done
fi
elif [ "$1" == "update" ] && [[ "$2" != "" ]]; then
for app in "${@:2}"; do
"${NODE_ROOT}/app/app-manager.py" --invoked-by-configure update "$app"

77
scripts/backup/restore Executable file
View File

@ -0,0 +1,77 @@
#!/usr/bin/env bash
# SPDX-FileCopyrightText: 2022 Citadel and contributors. https://runcitadel.space
#
# SPDX-License-Identifier: GPL-3.0-or-later
set -euo pipefail
CITADEL_ROOT="$(readlink -f $(dirname "${BASH_SOURCE[0]}")/../..)"
BACKUP_ROOT="${CITADEL_ROOT}/.backup/restore-$RANDOM"
BACKUP_FOLDER_NAME="backup"
BACKUP_FOLDER_PATH="${BACKUP_ROOT}/${BACKUP_FOLDER_NAME}"
check_dependencies () {
for cmd in "$@"; do
if ! command -v "$cmd" >/dev/null 2>&1; then
echo "This script requires \"${cmd}\" to be installed"
exit 1
fi
done
}
check_dependencies openssl tar gpg curl
[[ -f "${CITADEL_ROOT}/.env" ]] && source "${CITADEL_ROOT}/.env"
BITCOIN_NETWORK=${BITCOIN_NETWORK:-mainnet}
if [[ $BITCOIN_NETWORK == "testnet" ]] || [[ $BITCOIN_NETWORK == "signet" ]] || [[ $BITCOIN_NETWORK == "regtest" ]]; then
echo "Backups can only be restored on mainnet"
exit
fi
# Deterministically derives 128 bits of cryptographically secure entropy
derive_entropy () {
identifier="${1}"
citadel_seed=$(cat "${CITADEL_ROOT}/db/citadel-seed/seed") || true
if [[ -z "$citadel_seed" ]] || [[ -z "$identifier" ]]; then
>&2 echo "Missing derivation parameter, this is unsafe, exiting."
exit 1
fi
# We need `sed 's/^.* //'` to trim the "(stdin)= " prefix from some versions of openssl
printf "%s" "${identifier}" | openssl dgst -sha256 -hmac "${citadel_seed}" | sed 's/^.* //'
}
echo "Deriving keys..."
backup_id=$(derive_entropy "citadel_backup_id")
encryption_key=$(derive_entropy "citadel_backup_encryption_key")
echo "Your node id is: "
echo $(derive_entropy "citadel_backup_id")
# If the first argument is not given, fail
if [[ -z "$1" ]]; then
echo "Usage: $0 <backup-id>"
exit 1
fi
echo "Downloading backup..."
mkdir -p "${BACKUP_ROOT}"
cd "${BACKUP_ROOT}"
curl -X POST https://account.runcitadel.space/api/get-backup-by-id --data "{ \"id\": \"$1\", \"name\": \"$backup_id\" }" -H "Content-Type: application/json" | jq ".data" -r | base64 -d - > channels.encrypted.backup
cat "channels.encrypted.backup" | gpg --batch --decrypt --passphrase "$encryption_key" | tar --extract --verbose --gzip
echo "Restoring backup..."
cd "${BACKUP_FOLDER_PATH}"
cp channel.backup "${CITADEL_ROOT}/channel.backup"
sudo docker exec -it lightning lncli restorechanbackup --multi_file /data/.lnd/channel.backup
echo "Backup restored successfully!"

40
scripts/configure vendored
View File

@ -78,13 +78,6 @@ os.chdir(CITADEL_ROOT)
with open("./db/dependencies.yml", "r") as file:
dependencies = yaml.safe_load(file)
updating = False
status_dir = os.path.join(CITADEL_ROOT, 'statuses')
# Make sure to use the main status dir for updates
if os.path.isfile('../.citadel'):
status_dir = os.path.join(CITADEL_ROOT, '..', 'statuses')
updating = True
# Configure for appropriate network depending
# upon the user-supplied value of $NETWORK
# If the network is not specified, then use the mainnet
@ -98,10 +91,12 @@ if BITCOIN_NETWORK not in ['mainnet', 'testnet', 'signet', 'regtest']:
with open(os.path.join(CITADEL_ROOT, "info.json"), 'r') as file:
CITADEL_VERSION=json.load(file)['version']
status_dir = os.path.join(CITADEL_ROOT, 'statuses')
print("\n======================================")
if os.path.isfile(status_dir+'/configured'):
print("=========== RECONFIGURING ============")
reconfiguring=True
reconfiguring=os.path.isfile('./.env')
else:
print("============ CONFIGURING =============")
reconfiguring=False
@ -141,9 +136,6 @@ NGINX_SSL_PORT=os.environ.get('NGINX_SSL_PORT') or "443"
UPDATE_CHANNEL="stable"
if reconfiguring:
if os.path.isfile('../.citadel'):
dotenv=parse_dotenv('../.env')
else:
dotenv=parse_dotenv('./.env')
BITCOIN_NETWORK=os.environ.get('OVERWRITE_NETWORK') or dotenv['BITCOIN_NETWORK']
@ -177,13 +169,9 @@ else:
# Pull Tor image and generate Tor password
print("Generating Tor password\n")
os.system('docker pull --quiet lncm/tor:0.4.6.8')
os.system('docker pull --quiet {}'.format(dependencies["tor"]))
TOR_PASSWORD=get_data('itdoesntmatter')['password']
# run 'docker run --rm lncm/tor:0.4.6.7 --quiet --hash-password "$TOR_PASS"' and get its output
# this is the password that is used to connect to the Tor network
# the password is stored in the .env file
TOR_HASHED_PASSWORD=os.popen('docker run --rm lncm/tor:0.4.6.8 --quiet --hash-password "{}"'.format(TOR_PASSWORD)).read()[:-1]
TOR_HASHED_PASSWORD=os.popen('docker run --rm {} --quiet --hash-password "{}"'.format(dependencies["tor"], TOR_PASSWORD)).read()[:-1]
BITCOIN_NODE="neutrino"
ALIAS_AND_COLOR=""
@ -239,11 +227,7 @@ neutrino.addpeer=testnet2-btcd.zaphq.io
elif BITCOIN_NETWORK == "signet":
BITCOIN_RPC_PORT=38332
BITCOIN_P2P_PORT=38333
NEUTRINO_PEERS='''
[neutrino]
neutrino.addpeer=testnet1-btcd.zaphq.io
neutrino.addpeer=testnet2-btcd.zaphq.io
'''
BITCOIN_NODE="bitcoind"
elif BITCOIN_NETWORK == "regtest":
BITCOIN_RPC_PORT=18334
BITCOIN_P2P_PORT=18335
@ -268,7 +252,6 @@ NEUTRINO_SWITCHER_IP="10.21.21.6"
DASHBOARD_NEW_IP="10.21.21.7"
BITCOIN_IP="10.21.21.8"
LND_IP="10.21.21.9"
ELECTRUM_IP="10.21.21.10"
TOR_PROXY_IP="10.21.21.11"
APPS_TOR_IP="10.21.21.12"
APPS_2_TOR_IP="10.21.21.13"
@ -284,7 +267,6 @@ BITCOIN_ZMQ_HASHBLOCK_PORT="28334"
BITCOIN_ZMQ_SEQUENCE_PORT="28335"
LND_GRPC_PORT="10009"
LND_REST_PORT="8080"
ELECTRUM_PORT="50001"
TOR_PROXY_PORT="9050"
TOR_CONTROL_PORT="29051"
@ -305,10 +287,6 @@ LND_FEE_URL=""
if BITCOIN_NETWORK == 'mainnet' and BITCOIN_NODE == 'neutrino':
LND_FEE_URL="feeurl=https://nodes.lightning.computer/fees/v1/btc-fee-estimates.json"
BITCOIN_NETWORK_ELECTRS = BITCOIN_NETWORK
if BITCOIN_NETWORK_ELECTRS == "mainnet":
BITCOIN_NETWORK_ELECTRS = "bitcoin"
# Checks if a variable with the name exists, if not, check if an env var with the name existts
# if neither exists, then exit with an error
def get_var(var_name, other_locals, file_name):
@ -339,8 +317,6 @@ templates_to_build = {
"./templates/lnd-sample.conf": "./lnd/lnd.conf",
"./templates/bitcoin-sample.conf": "./bitcoin/bitcoin.conf",
"./templates/.env-sample": "./.env",
"./templates/electrs-sample.toml": "./electrs/electrs.toml",
"./templates/fulcrum-sample.conf": "./fulcrum/fulcrum.conf",
"./templates/nginx-sample.conf": "./nginx/nginx.conf"
}
@ -377,13 +353,15 @@ with open("docker-compose.yml", 'r') as stream:
compose = yaml.safe_load(stream)
for service in ["manager", "middleware", "dashboard"]:
compose["services"][service]["image"] = dependencies[service]
for service in ["tor", "app-tor", "app-2-tor", "app-3-tor"]:
compose["services"][service]["image"] = dependencies["tor"]
with open("docker-compose.yml", "w") as stream:
yaml.dump(compose, stream, sort_keys=False)
if not reconfiguring:
print("Updating apps...\n")
os.system('./scripts/app --invoked-by-configure update')
elif not updating:
else:
print("Updating apps...\n")
os.system('./scripts/app --invoked-by-configure generate')
print("Configuring permissions...\n")

View File

@ -147,12 +147,6 @@ if [[ "${1}" == "--run" ]]; then
echo
docker compose logs --tail=30 lightning
echo
echo "Electrum logs"
echo "-------------"
echo
docker compose logs --tail=30 electrum
echo
echo "Tor logs"
echo "--------"

View File

@ -60,7 +60,7 @@ get_system_memory_usage() {
main() {
echo "total: $(get_total_used_mem)%"
echo "system: $(get_system_memory_usage)%"
for service in bitcoin lightning electrum tor; do
for service in bitcoin lightning tor; do
echo "${service}: $(get_memory_usage "$service")%" &
done
for app in $("${CITADEL_ROOT}/scripts/app" ls-installed); do

View File

@ -7,9 +7,7 @@ tor/*
electrs/*
logs/*
app-data/*
apps/networking.json
nginx/*
services/installed.yml
apps/sourceMap.json
apps/.updateignore
apps/*
fulcrum/*

View File

@ -1,4 +1,4 @@
SPDX-FileCopyrightText: 2020 Umbrel. https://getumbrel.com
SPDX-FileCopyrightText: 2021 Citadel and contributors.
SPDX-FileCopyrightText: 2021-2022 Citadel and contributors.
SPDX-License-Identifier: GPL-3.0-or-later

View File

@ -1,4 +1,4 @@
SPDX-FileCopyrightText: 2020 Umbrel. https://getumbrel.com
SPDX-FileCopyrightText: 2021 Citadel and contributors.
SPDX-FileCopyrightText: 2021-2022 Citadel and contributors.
SPDX-License-Identifier: GPL-3.0-or-later

View File

@ -23,8 +23,6 @@ echo
[[ -f "/etc/default/citadel" ]] && source "/etc/default/citadel"
IS_MIGRATING=0
# If ${CITADEL_ROOT}/c-lightning exists, fail
if [[ -d "${CITADEL_ROOT}/c-lightning" ]]; then
echo "This update is not compatible with the c-lightning beta."
@ -73,29 +71,13 @@ if [[ ! -z "${CITADEL_OS:-}" ]]; then
echo "source ~/citadel/setenv" | tee -a /home/citadel/.bashrc
sudo apt install -y python3-dacite python3-semver
sudo apt install -y python3-semver
fi
# Help migration from earlier versions
mv "$CITADEL_ROOT/db/umbrel-seed" "$CITADEL_ROOT/db/citadel-seed" || true
# Checkout to the new release
cd "$CITADEL_ROOT"/.citadel-"$RELEASE"
# Configure new install
echo "Configuring new release"
cat <<EOF > "$CITADEL_ROOT"/statuses/update-status.json
{"state": "installing", "progress": 40, "description": "Configuring new release", "updateTo": "$RELEASE"}
EOF
./scripts/configure || true
# Pulling new containers
echo "Pulling new containers"
cat <<EOF > "$CITADEL_ROOT"/statuses/update-status.json
{"state": "installing", "progress": 50, "description": "Pulling new containers", "updateTo": "$RELEASE"}
EOF
docker compose pull
cd "$CITADEL_ROOT"
# Stopping karen
echo "Stopping background daemon"
@ -108,7 +90,6 @@ echo "Stopping installed apps"
cat <<EOF > "$CITADEL_ROOT"/statuses/update-status.json
{"state": "installing", "progress": 60, "description": "Stopping installed apps", "updateTo": "$RELEASE"}
EOF
cd "$CITADEL_ROOT"
./scripts/app stop installed || true
# Stop old containers
@ -118,6 +99,7 @@ cat <<EOF > "$CITADEL_ROOT"/statuses/update-status.json
EOF
./scripts/stop || true
electrum_implementation=$(cat services/installed.yml | grep "electrum:" | sed "s/electrum: //g")
# Overlay home dir structure with new dir tree
echo "Overlaying $CITADEL_ROOT/ with new directory tree"
@ -134,33 +116,32 @@ echo "Fixing permissions"
find "$CITADEL_ROOT" -path "$CITADEL_ROOT/app-data" -prune -o -exec chown 1000:1000 {} +
chmod -R 700 "$CITADEL_ROOT"/tor/data/*
cd "$CITADEL_ROOT"
echo "Updating installed apps"
cat <<EOF > "$CITADEL_ROOT"/statuses/update-status.json
{"state": "installing", "progress": 70, "description": "Updating installed apps", "updateTo": "$RELEASE"}
EOF
"${CITADEL_ROOT}/scripts/app" --invoked-by-configure update
for app in $("$CITADEL_ROOT/scripts/app" ls-installed); do
if [[ "${app}" != "" ]]; then
echo "${app}..."
"${CITADEL_ROOT}/scripts/app" compose "${app}" pull
fi
done
wait
# If CITADEL_ROOT doesn't contain services/installed.json, then put '["electrs"]' into it.
# This is to ensure that the 0.5.0 update doesn't remove electrs.
if [[ ! -f "${CITADEL_ROOT}/services/installed.json" ]]; then
echo '["electrs"]' > "${CITADEL_ROOT}/services/installed.json"
fi
# Start updated containers
echo "Starting new containers"
cat <<EOF > "$CITADEL_ROOT"/statuses/update-status.json
{"state": "installing", "progress": 80, "description": "Starting new containers", "updateTo": "$RELEASE"}
EOF
cd "$CITADEL_ROOT"
./scripts/start
# Only for 0.1.0, remove after
rm -f nginx/nginx.conf || true
./scripts/start || true
# Install the electrum implementation as app
echo "Installing electrum implementation as app"
cat <<EOF > "$CITADEL_ROOT"/statuses/update-status.json
{"state": "installing", "progress": 85, "description": "Installing electrum server", "updateTo": "$RELEASE"}
EOF
./scripts/app install "$electrum_implementation"
./scripts/app stop "$electrum_implementation"
rm -rf "$CITADEL_ROOT"/app-data/"$electrum_implementation"/data
mv "$CITADEL_ROOT"/"$electrum_implementation" "$CITADEL_ROOT"/app-data/"$electrum_implementation"/data
rm -f "$CITADEL_ROOT"/app-data/"$electrum_implementation"/data/electrs.toml
rm -f "$CITADEL_ROOT"/app-data/"$electrum_implementation"/data/fulcrum.conf
./scripts/app start "$electrum_implementation"
cat <<EOF > "$CITADEL_ROOT"/statuses/update-status.json
{"state": "success", "progress": 100, "description": "Successfully installed Citadel $RELEASE", "updateTo": ""}

View File

@ -1,18 +0,0 @@
# SPDX-FileCopyrightText: 2021-2022 Citadel and contributors
#
# SPDX-License-Identifier: GPL-3.0-or-later
electrum:
container_name: electrum
image: ghcr.io/runcitadel/electrs:v0.9.6@sha256:cf08513b8aa6f081e42ea92c5903d520db2caedbc20aaccf70f844663bbc8646
working_dir: /data
volumes:
- ${PWD}/bitcoin:/bitcoin:ro
- ${PWD}/electrs:/data
restart: on-failure
stop_grace_period: 5m
ports:
- "$ELECTRUM_PORT:$ELECTRUM_PORT"
networks:
default:
ipv4_address: $ELECTRUM_IP

View File

@ -1,19 +0,0 @@
# SPDX-FileCopyrightText: 2021-2022 Citadel and contributors
#
# SPDX-License-Identifier: GPL-3.0-or-later
electrum:
container_name: electrum
image: cculianu/fulcrum:latest@sha256:c0543f8b8a5bf6b0c447d8525d6b4360a6c07532f7741f19cc2c179968e71848
working_dir: /data
volumes:
- ${PWD}/bitcoin:/bitcoin:ro
- ${PWD}/fulcrum:/data
command: /usr/bin/Fulcrum /data/fulcrum.conf
restart: on-failure
stop_grace_period: 5m
ports:
- "$ELECTRUM_PORT:$ELECTRUM_PORT"
networks:
default:
ipv4_address: $ELECTRUM_IP

View File

@ -1,6 +1,10 @@
# SPDX-FileCopyrightText: 2022 Citadel and contributors
#
# SPDX-License-Identifier: GPL-3.0-or-later
lightning:
container_name: lightning
image: lightninglabs/lnd:v0.15.2-beta@sha256:a011b06c622c947a3039d76a5a08b4896fc6a02dea6add3afd345019f8737923
image: lightninglabs/lnd:v0.15.3-beta@sha256:93b4055bf4fb040907587bdf806c5bc6d42bd21b5b90f26df0c86471c8245ca8
user: 1000:1000
depends_on:
- tor

View File

@ -67,7 +67,6 @@ def setService(name, implementation):
installed = yaml.safe_load(stream)
except FileNotFoundError:
installed = {
"electrum": "electrs",
"lightning": "lnd",
"bitcoin": "knots"
}
@ -99,7 +98,6 @@ def uninstallService(name):
installed = yaml.safe_load(stream)
except FileNotFoundError:
installed = {
"electrum": "electrs",
"lightning": "lnd",
"bitcoin": "knots"
}
@ -117,7 +115,6 @@ def installServices():
installed = yaml.safe_load(stream)
except FileNotFoundError:
installed = {
"electrum": "electrs",
"lightning": "lnd",
"bitcoin": "knots"
}

8
setenv
View File

@ -6,10 +6,10 @@
CITADEL_ROOT="$(dirname $(readlink -f "${BASH_SOURCE[0]}"))"
alias citadel-update="${CITADEL_ROOT}/scripts/update/update"
alias lncli="docker exec -it lnd lncli"
alias citadel="${CITADEL_ROOT}/bin/citadel"
alias lncli="docker exec -it lightning lncli"
alias bitcoin-cli="docker exec -it bitcoin bitcoin-cli"
alias docker-compose="sudo docker compose"
alias docker="sudo docker"
alias debug="${CITADEL_ROOT}/scripts/debug"
alias app="${CITADEL_ROOT}/scripts/app"
export BOS_DEFAULT_LND_PATH="${CITADEL_ROOT}/lnd"

View File

@ -30,8 +30,6 @@ BITCOIN_ZMQ_SEQUENCE_PORT=<bitcoin-zmq-sequence-port>
LND_IP=<lnd-ip>
LND_GRPC_PORT=<lnd-grpc-port>
LND_REST_PORT=<lnd-rest-port>
ELECTRUM_IP=<electrum-ip>
ELECTRUM_PORT=<electrum-port>
TOR_PROXY_IP=<tor-proxy-ip>
TOR_PROXY_PORT=<tor-proxy-port>
TOR_PASSWORD='<tor-password>'

View File

@ -1,15 +0,0 @@
# SPDX-FileCopyrightText: 2020 Umbrel. https://getumbrel.com
# SPDX-FileCopyrightText: 2021-2022 Citadel and contributors.
#
# SPDX-License-Identifier: GPL-3.0-or-later
# Please note: This file can't be changed, any changes will be overwritten the next time you start Citadel.
log_filters = "INFO"
network = "<bitcoin-network-electrs>"
db_dir = "/data/db"
daemon_dir = "/bitcoin"
daemon_rpc_addr = "<bitcoin-ip>:<bitcoin-rpc-port>"
daemon_p2p_addr = "<bitcoin-ip>:<bitcoin-p2p-port>"
electrum_rpc_addr = "0.0.0.0:<electrum-port>"
server_banner = "Citadel v<citadel-version>"

View File

@ -1,11 +0,0 @@
datadir = /data
bitcoind = <bitcoin-ip>:<bitcoin-rpc-port>
rpcuser = <bitcoin-rpc-user>
rpcpassword = <bitcoin-rpc-pass>
tcp = 0.0.0.0:50001
ws = 0.0.0.0:50003
peering = false
announce = false
admin = 8000
stats = 8080
tor_proxy = <tor-proxy-ip>:<tor-proxy-port>

View File

@ -27,7 +27,7 @@ http {
}
location /manager-api/ {
proxy_pass http://<manager-ip>:3006/;
proxy_pass http://<manager-ip>:3000/;
}
# dashboard (old)

View File

@ -20,10 +20,6 @@ HiddenServicePort <bitcoin-p2p-port> <bitcoin-ip>:<bitcoin-p2p-port>
HiddenServiceDir /var/lib/tor/bitcoin-rpc
HiddenServicePort <bitcoin-rpc-port> <bitcoin-ip>:<bitcoin-rpc-port>
# Electrum Server (electrs) Hidden Service
HiddenServiceDir /var/lib/tor/electrum
HiddenServicePort <electrum-port> <electrum-ip>:<electrum-port>
# LND REST Hidden Service
HiddenServiceDir /var/lib/tor/lnd-rest
HiddenServicePort <lnd-rest-port> <lnd-ip>:<lnd-rest-port>

View File

@ -1,3 +1,3 @@
SPDX-FileCopyrightText: 2021 Citadel and contributors
SPDX-FileCopyrightText: 2021-2022 Citadel and contributors
SPDX-License-Identifier: GPL-3.0-or-later