├── .github └── workflows │ └── ci.yml ├── .gitignore ├── CHANGELOG ├── CONTRIBUTING.md ├── LICENSE ├── README.md ├── nginx.py ├── setup.py └── tests.py /.github/workflows/ci.yml: -------------------------------------------------------------------------------- 1 | name: Python package 2 | 3 | on: [push] 4 | 5 | jobs: 6 | build: 7 | 8 | runs-on: ubuntu-latest 9 | strategy: 10 | matrix: 11 | python-version: ["2.7", "3.6", "3.7", "3.8", "3.9", "3.10"] 12 | 13 | steps: 14 | - uses: actions/checkout@v2 15 | - name: Set up Python ${{ matrix.python-version }} 16 | uses: actions/setup-python@v2 17 | with: 18 | python-version: ${{ matrix.python-version }} 19 | - name: Install dependencies 20 | run: | 21 | python -m pip install --upgrade pip 22 | pip install flake8 pytest 23 | if [ -f requirements.txt ]; then pip install -r requirements.txt; fi 24 | - name: Lint with flake8 25 | run: | 26 | # stop the build if there are Python syntax errors or undefined names 27 | flake8 . --count --select=E9,F63,F7,F82 --show-source --statistics 28 | # exit-zero treats all errors as warnings. The GitHub editor is 127 chars wide 29 | flake8 . --count --exit-zero --max-complexity=10 --max-line-length=127 --statistics 30 | - name: Test with pytest 31 | run: | 32 | python tests.py -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | MANIFEST 2 | dist 3 | build 4 | *.pyc 5 | *.egg-info 6 | .idea 7 | -------------------------------------------------------------------------------- /CHANGELOG: -------------------------------------------------------------------------------- 1 | # Change Log 2 | All notable changes to this project will be documented in this file. 3 | This project adheres to [Semantic Versioning](http://semver.org/). 4 | 5 | ## [1.5.7] - 2022-03-06 6 | ### Features 7 | - Consider parent logging settings and use module name for logging (thanks @chikko80!) 8 | 9 | ## [1.5.6] - 2021-03-20 10 | ### Fixed 11 | - Fixed additional bugs in parsing lines with semicolons or curly braces when quotation marks are involved 12 | - Fixed bug in parsing configs without a final linebreak (thanks @fulder!) 13 | 14 | ### Features 15 | - Set `nginx.DEBUG` to True to show logging output of what is being parsed 16 | 17 | ## [1.5.5] - 2021-03-11 18 | ### Fixed 19 | - Fixed bugs in parsing lines that contain a semicolon or curly brace inside of quotes 20 | - Fixed bug in creating new Keys in which the value isn't a string but is still stringable (int) 21 | 22 | ## [1.5.4] - 2020-08-21 23 | ### Fixed 24 | - Warn user if successful parsing of a config is impossible due to missing semicolon (thanks @fulder!) 25 | 26 | ## [1.5.3] - 2018-12-10 27 | ### Fixed 28 | - Fixed bug in parsing Type directives as well as misidentifying certain possible key names (thanks @SGamoff and @fulder!) 29 | 30 | ## [1.5.2] - 2018-11-28 31 | ### Fixed 32 | - Fixed bug in parsing semicolons in quoted values, notably `if` keys (thanks @fulder!) 33 | 34 | ## [1.5.1] - 2018-10-06 35 | ### Fixed 36 | - Fixed bug in parsing `limit_except` parameters (thanks @fulder!) 37 | 38 | ## [1.5.0] - 2018-08-06 39 | ### Features 40 | - Supports managing `stream` configuration blocks (thanks @xannz!) 41 | 42 | ## [1.4.1] - 2018-04-01 43 | ### Fixed 44 | - A small error in packaging that prevented installs from PyPI. 45 | 46 | ## [1.4.0] - 2018-04-01 47 | ### Fixed 48 | - Fixed bugs in parsing single key values and quoted keys/values (thanks @fulder!) 49 | - Fixed bugs when finding a `map` key in loading of nginx.conf. (thanks @fulder!) 50 | 51 | ## [1.3.0] - 2018-02-07 52 | ### Features 53 | - Full refactoring of configuration parsing. 54 | - Now supports the loading of root NGINX configurations, like the kind you see at /etc/nginx/nginx.conf. 55 | 56 | ### Fixed 57 | - Fixed several bugs involving parsing of messy files, brace locations, and individual keys with no values (thanks @lelik9 and @USSX-Hares!) 58 | 59 | ## [1.2.0] - 2017-09-06 60 | ### Fixed 61 | - Fixed several bugs involving parsing of messy files and brace locations (thanks @lelik9!) 62 | - Fixed a bug where an exception was raised if a key was found in the top level of the configuration. 63 | 64 | ## [1.1.0] - 2017-01-14 65 | ### Fixed 66 | - Fixed a bug where an exception was raised if location blocks didn't contain any normal keys. 67 | - Fixed a bug where an exception was raised if a closing brace was used inside a key's value. 68 | 69 | ## [1.0.0] - 2016-08-19 70 | ### Changed 71 | - Some API changes: 72 | - `all()` methods replaced with `children` property 73 | - `as_list()` methods replaced with `as_list` property 74 | - `as_dict()` methods replaced with `as_dict` property 75 | - `as_block()` methods replaced with `as_strings` property 76 | - `conf.server` convenience property, for getting first server found in the Conf 77 | - Added `inline` property to `Comment`: set to `True` if you want the comment to be appended to the end of the previous line on dump 78 | - Added loading of inline code comments. 79 | - Cleaned code for full PEP8 compatibility and added comments. 80 | - Added simple tests. 81 | 82 | ### Fixed 83 | - Fixed a bug where unexpected behaviour would occur when a pound symbol was used inside a key value. 84 | -------------------------------------------------------------------------------- /CONTRIBUTING.md: -------------------------------------------------------------------------------- 1 | ### Hello! 2 | 3 | If you're reading this, you'd like to contribute to one of my open source projects! Contributions are welcome and encouraged on this and any other of my projects. 4 | 5 | 6 | ### General Resources 7 | 8 | * **[Github](https://github.com/peakwinter/python-nginx)** is the primary destination for this project's source code repository, issue tracker, and contribution management (pull requests). 9 | * Testing infrastructure / CI can be found in the **[Github Action](https://github.com/peakwinter/python-nginx/blob/master/.github/workflows/ci.yml)**. 10 | * Documentation for development is kept in `README.md`, changelogs in `CHANGELOG`. 11 | 12 | 13 | ### Submitting Pull Requests 14 | 15 | Pull requests are a great way to add a new feature for yourself to use, and to help others who might be using this project along the way. Please follow the style guide below for your code submissions, add unit tests if at all possible, and don't forget to adequately test your code functionally before you make the request. I'll get to it as soon as I can, and review it with you if need be. 16 | 17 | 18 | ### Filing Bugs 19 | 20 | If you come across a bug in this project, your bug reports are welcome! Take a look at the issue tracker first to make sure the bug hasn't already been reported. If you end up filing a duplicate, don't worry - better to have an over-reported bug then one that goes unnoticed! 21 | 22 | The best bug reports are short but clear. There's a certain amount of critical information needed in order to successfully solve the problem. Please try to make sure your bug report touches on the following: 23 | 24 | * Context: information on the issue encountered 25 | * Process: an ordered list of the steps I can take to reproduce the issue 26 | * Expected result: the result you expect to happen when you follow the above steps 27 | * Actual result: the thing that happens (that is not supposed to happen) when you follow the above steps 28 | * Any suggested fixes, stack traces or supporting documentation that would be helpful. If you are running a GUI-based application, screenshots are also good to include. 29 | 30 | 31 | ### Requesting Improvements 32 | 33 | If you have suggestions regarding how this project can be improved, but are not able to submit a pull request to achieve it yourself, feel free to file an issue with "Suggestion" somewhere in the title. It doesn't have to follow the bullet points for bugs given above, but should include detailed information about your use case, and most importantly why this suggestion would be good for anyone else who would like to use this project. 34 | 35 | 36 | ### Style Guide 37 | 38 | A few things to remember when contributing code: 39 | 40 | * Commit messages should accurately enough describe the problem. 41 | * Be sure to adequately comment lengthy contributions. 42 | * Python code should use four spaces for each indent, instead of a tab. 43 | * Python code should follow [PEP8](https://www.python.org/dev/peps/pep-0008/) whenever feasible. I recommend using [flake8](http://flake8.pycqa.org/en/latest/). 44 | * Python code should support Python 3 by default. (If this is a Python 2.x-only repo or branch, disregard) 45 | * JavaScript code should support [JavaScript Standard Style](http://standardjs.com). 46 | 47 | 48 | ### Conduct 49 | 50 | I try to use all of my projects as an example of what positive and respectful effort can achieve in open source. I invite you to do the same as you contemplate contributing to this project. Feel free to offer constructive criticism when you feel its necessary, but refrain from being unnecessarily harsh, making any sort of personal attack or using inappropriate language. I have zero tolerance for harassment of any kind. 51 | 52 | 53 | ### Asking for Help 54 | 55 | If you'd like to ask questions about contributing to this project or about the code contained within, feel free! My profile page on GitHub will have links to my Twitter account or my email, I will respond whenever possible. 56 | 57 | 58 | # Thank you! 59 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | 3 | Version 3, 29 June 2007 4 | 5 | Copyright © 2007 Free Software Foundation, Inc. 6 | 7 | Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. 8 | Preamble 9 | 10 | The GNU General Public License is a free, copyleft license for software and other kinds of works. 11 | 12 | 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. 13 | 14 | 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. 15 | 16 | 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. 17 | 18 | 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. 19 | 20 | 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. 21 | 22 | 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. 23 | 24 | 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. 25 | 26 | 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. 27 | 28 | The precise terms and conditions for copying, distribution and modification follow. 29 | TERMS AND CONDITIONS 30 | 31 | 32 | 0. Definitions. 33 | 34 | “This License” refers to version 3 of the GNU General Public License. 35 | 36 | “Copyright” also means copyright-like laws that apply to other kinds of works, such as semiconductor masks. 37 | 38 | “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. 39 | 40 | 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. 41 | 42 | A “covered work” means either the unmodified Program or a work based on the Program. 43 | 44 | 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. 45 | 46 | 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. 47 | 48 | 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. 49 | 50 | 51 | 1. Source Code. 52 | 53 | 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. 54 | 55 | 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. 56 | 57 | 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. 58 | 59 | 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. 60 | 61 | The Corresponding Source need not include anything that users can regenerate automatically from other parts of the Corresponding Source. 62 | 63 | The Corresponding Source for a work in source code form is that same work. 64 | 65 | 66 | 2. Basic Permissions. 67 | 68 | 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. 69 | 70 | 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. 71 | 72 | Conveying under any other circumstances is permitted solely under the conditions stated below. Sublicensing is not allowed; section 10 makes it unnecessary. 73 | 74 | 75 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 76 | 77 | 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. 78 | 79 | 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. 80 | 81 | 82 | 4. Conveying Verbatim Copies. 83 | 84 | 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. 85 | 86 | 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. 87 | 88 | 89 | 5. Conveying Modified Source Versions. 90 | 91 | 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: 92 | 93 | a) The work must carry prominent notices stating that you modified it, and giving a relevant date. 94 | 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”. 95 | 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. 96 | 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. 97 | 98 | 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. 99 | 100 | 101 | 6. Conveying Non-Source Forms. 102 | 103 | 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: 104 | 105 | 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. 106 | 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. 107 | 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. 108 | 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. 109 | 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. 110 | 111 | 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. 112 | 113 | 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. 114 | 115 | “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. 116 | 117 | 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). 118 | 119 | 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. 120 | 121 | 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. 122 | 123 | 124 | 7. Additional Terms. 125 | 126 | “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. 127 | 128 | 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. 129 | 130 | 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: 131 | 132 | a) Disclaiming warranty or limiting liability differently from the terms of sections 15 and 16 of this License; or 133 | 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 134 | 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 135 | d) Limiting the use for publicity purposes of names of licensors or authors of the material; or 136 | e) Declining to grant rights under trademark law for use of some trade names, trademarks, or service marks; or 137 | 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. 138 | 139 | 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. 140 | 141 | 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. 142 | 143 | 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. 144 | 145 | 146 | 8. Termination. 147 | 148 | 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). 149 | 150 | 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. 151 | 152 | 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. 153 | 154 | 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. 155 | 156 | 157 | 9. Acceptance Not Required for Having Copies. 158 | 159 | 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. 160 | 161 | 162 | 10. Automatic Licensing of Downstream Recipients. 163 | 164 | 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. 165 | 166 | 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. 167 | 168 | 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. 169 | 170 | 171 | 11. Patents. 172 | 173 | 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”. 174 | 175 | 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. 176 | 177 | 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. 178 | 179 | 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. 180 | 181 | 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. 182 | 183 | 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. 184 | 185 | 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. 186 | 187 | 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. 188 | 189 | 190 | 12. No Surrender of Others' Freedom. 191 | 192 | 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. 193 | 194 | 195 | 13. Use with the GNU Affero General Public License. 196 | 197 | 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. 198 | 199 | 200 | 14. Revised Versions of this License. 201 | 202 | 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. 203 | 204 | 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. 205 | 206 | 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. 207 | 208 | 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. 209 | 210 | 211 | 15. Disclaimer of Warranty. 212 | 213 | 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. 214 | 215 | 216 | 16. Limitation of Liability. 217 | 218 | 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. 219 | 220 | 221 | 17. Interpretation of Sections 15 and 16. 222 | 223 | 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. 224 | 225 | END OF TERMS AND CONDITIONS 226 | 227 | 228 | How to Apply These Terms to Your New Programs 229 | 230 | 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. 231 | 232 | 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. 233 | 234 | 235 | Copyright (C) 236 | 237 | This program is free software: you can redistribute it and/or modify 238 | it under the terms of the GNU General Public License as published by 239 | the Free Software Foundation, either version 3 of the License, or 240 | (at your option) any later version. 241 | 242 | This program is distributed in the hope that it will be useful, 243 | but WITHOUT ANY WARRANTY; without even the implied warranty of 244 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 245 | GNU General Public License for more details. 246 | 247 | You should have received a copy of the GNU General Public License 248 | along with this program. If not, see . 249 | 250 | Also add information on how to contact you by electronic and paper mail. 251 | 252 | If the program does terminal interaction, make it output a short notice like this when it starts in an interactive mode: 253 | 254 | Copyright (C) 255 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 256 | This is free software, and you are welcome to redistribute it 257 | under certain conditions; type `show c' for details. 258 | 259 | 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”. 260 | 261 | 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 . 262 | 263 | 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 . 264 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | ## python-nginx 2 | 3 | ![build](https://github.com/peakwinter/python-nginx/actions/workflows/ci.yml/badge.svg) 4 | 5 | A module for easily creating and modifying nginx serverblock configurations in Python (including comments!). 6 | 7 | ### Install 8 | 9 | pip install python-nginx 10 | 11 | ### Examples 12 | 13 | Create an nginx serverblock and save it to file: 14 | 15 | >>> import nginx 16 | >>> c = nginx.Conf() 17 | >>> u = nginx.Upstream('php', 18 | ... nginx.Key('server', 'unix:/tmp/php-fcgi.socket') 19 | ... ) 20 | >>> c.add(u) 21 | >>> s = nginx.Server() 22 | >>> s.add( 23 | ... nginx.Key('listen', '80'), 24 | ... nginx.Comment('Yes, python-nginx can read/write comments!'), 25 | ... nginx.Key('server_name', 'localhost 127.0.0.1'), 26 | ... nginx.Key('root', '/srv/http'), 27 | ... nginx.Key('index', 'index.php'), 28 | ... nginx.Location('= /robots.txt', 29 | ... nginx.Key('allow', 'all'), 30 | ... nginx.Key('log_not_found', 'off'), 31 | ... nginx.Key('access_log', 'off') 32 | ... ), 33 | ... nginx.Location('~ \.php$', 34 | ... nginx.Key('include', 'fastcgi.conf'), 35 | ... nginx.Key('fastcgi_intercept_errors', 'on'), 36 | ... nginx.Key('fastcgi_pass', 'php') 37 | ... ) 38 | ... ) 39 | >>> c.add(s) 40 | >>> nginx.dumpf(c, '/etc/nginx/sites-available/mysite') 41 | 42 | Load an nginx serverblock from a file: 43 | 44 | >>> import nginx 45 | >>> c = nginx.loadf('/etc/nginx/sites-available/testsite') 46 | >>> c.children 47 | [] 48 | >>> c.server.children 49 | [, , , ] 50 | >>> c.as_dict 51 | {'conf': [{'server': [{'#': 'This is a test comment'}, {'server_name': 'localhost'}, {'root': '/srv/http'}, {'location /': [{'allow': 'all'}]}]}]} 52 | 53 | Format an nginx serverblock into a string (change the amount of spaces (or tabs) for each indentation level by modifying `nginx.INDENT` first): 54 | 55 | >>> c.servers 56 | [] 57 | >>> c.as_strings 58 | ['server {\n', ' # This is a test comment\n', ' server_name localhost;\n', ' root /srv/http;\n', '\n location / {\n', ' allow all;\n', ' }\n\n', '}\n'] 59 | 60 | Find where you put your keys: 61 | 62 | >>> import nginx 63 | >>> c = nginx.loadf('/etc/nginx/sites-available/testsite') 64 | >>> c.filter('Server') 65 | [] 66 | >>> c.filter('Server')[0].filter('Key', 'root') 67 | [] 68 | >>> c.filter('Server')[0].filter('Location') 69 | [] 70 | 71 | Or just get everything by its type: 72 | 73 | >>> import nginx 74 | >>> c = nginx.loadf('/etc/nginx/sites-available/testsite') 75 | >>> c.servers 76 | [] 77 | >>> c.servers[0].keys 78 | [, ] 79 | -------------------------------------------------------------------------------- /nginx.py: -------------------------------------------------------------------------------- 1 | """ 2 | Python library for editing NGINX serverblocks. 3 | 4 | python-nginx 5 | (c) 2016 Jacob Cook 6 | Licensed under GPLv3, see LICENSE.md 7 | """ 8 | 9 | import re 10 | import logging 11 | 12 | INDENT = ' ' 13 | DEBUG=False 14 | 15 | log = logging.getLogger(__name__) 16 | log.setLevel(logging.DEBUG if DEBUG else logging.INFO) 17 | 18 | class Error(Exception): 19 | pass 20 | 21 | 22 | class ParseError(Error): 23 | pass 24 | 25 | 26 | def bump_child_depth(obj, depth): 27 | children = getattr(obj, 'children', []) 28 | for child in children: 29 | child._depth = depth + 1 30 | bump_child_depth(child, child._depth) 31 | 32 | 33 | class Conf(object): 34 | """ 35 | Represents an nginx configuration. 36 | 37 | A `Conf` can consist of any number of server blocks, as well as Upstream 38 | and other types of containers. It can also include top-level comments. 39 | """ 40 | 41 | def __init__(self, *args): 42 | """ 43 | Initialize object. 44 | 45 | :param *args: Any objects to include in this Conf. 46 | """ 47 | self.children = list(args) 48 | 49 | def add(self, *args): 50 | """ 51 | Add object(s) to the Conf. 52 | 53 | :param *args: Any objects to add to the Conf. 54 | :returns: full list of Conf's child objects 55 | """ 56 | self.children.extend(args) 57 | return self.children 58 | 59 | def remove(self, *args): 60 | """ 61 | Remove object(s) from the Conf. 62 | 63 | :param *args: Any objects to remove from the Conf. 64 | :returns: full list of Conf's child objects 65 | """ 66 | for x in args: 67 | self.children.remove(x) 68 | return self.children 69 | 70 | def filter(self, btype='', name=''): 71 | """ 72 | Return child object(s) of this Conf that satisfy certain criteria. 73 | 74 | :param str btype: Type of object to filter by (e.g. 'Key') 75 | :param str name: Name of key OR container value to filter by 76 | :returns: full list of matching child objects 77 | """ 78 | filtered = [] 79 | for x in self.children: 80 | if name and isinstance(x, Key) and x.name == name: 81 | filtered.append(x) 82 | elif isinstance(x, Container) and x.__class__.__name__ == btype \ 83 | and x.value == name: 84 | filtered.append(x) 85 | elif not name and btype and x.__class__.__name__ == btype: 86 | filtered.append(x) 87 | return filtered 88 | 89 | @property 90 | def servers(self): 91 | """Return a list of child Server objects.""" 92 | return [x for x in self.children if isinstance(x, Server)] 93 | 94 | @property 95 | def server(self): 96 | """Convenience property to fetch the first available server only.""" 97 | return self.servers[0] 98 | 99 | @property 100 | def as_list(self): 101 | """Return all child objects in nested lists of strings.""" 102 | return [x.as_list for x in self.children] 103 | 104 | @property 105 | def as_dict(self): 106 | """Return all child objects in nested dict.""" 107 | return {'conf': [x.as_dict for x in self.children]} 108 | 109 | @property 110 | def as_strings(self): 111 | """Return the entire Conf as nginx config strings.""" 112 | ret = [] 113 | for x in self.children: 114 | if isinstance(x, (Key, Comment)): 115 | ret.append(x.as_strings) 116 | else: 117 | for y in x.as_strings: 118 | ret.append(y) 119 | if ret: 120 | ret[-1] = re.sub('}\n+$', '}\n', ret[-1]) 121 | return ret 122 | 123 | 124 | class Container(object): 125 | """ 126 | Represents a type of child block found in an nginx config. 127 | 128 | Intended to be subclassed by various types of child blocks, like 129 | Locations or Geo blocks. 130 | """ 131 | 132 | def __init__(self, value, *args): 133 | """ 134 | Initialize object. 135 | 136 | :param str value: Value to be used in name (e.g. regex for Location) 137 | :param *args: Any objects to include in this Conf. 138 | """ 139 | self.name = '' 140 | self.value = value 141 | self._depth = 0 142 | self.children = list(args) 143 | bump_child_depth(self, self._depth) 144 | 145 | def add(self, *args): 146 | """ 147 | Add object(s) to the Container. 148 | 149 | :param *args: Any objects to add to the Container. 150 | :returns: full list of Container's child objects 151 | """ 152 | self.children.extend(args) 153 | bump_child_depth(self, self._depth) 154 | return self.children 155 | 156 | def remove(self, *args): 157 | """ 158 | Remove object(s) from the Container. 159 | 160 | :param *args: Any objects to remove from the Container. 161 | :returns: full list of Container's child objects 162 | """ 163 | for x in args: 164 | self.children.remove(x) 165 | return self.children 166 | 167 | def filter(self, btype='', name=''): 168 | """ 169 | Return child object(s) of this Server block that meet certain criteria. 170 | 171 | :param str btype: Type of object to filter by (e.g. 'Key') 172 | :param str name: Name of key OR container value to filter by 173 | :returns: full list of matching child objects 174 | """ 175 | filtered = [] 176 | for x in self.children: 177 | if name and isinstance(x, Key) and x.name == name: 178 | filtered.append(x) 179 | elif isinstance(x, Container) and x.__class__.__name__ == btype \ 180 | and x.value == name: 181 | filtered.append(x) 182 | elif not name and btype and x.__class__.__name__ == btype: 183 | filtered.append(x) 184 | return filtered 185 | 186 | @property 187 | def locations(self): 188 | """Return a list of child Location objects.""" 189 | return [x for x in self.children if isinstance(x, Location)] 190 | 191 | @property 192 | def comments(self): 193 | """Return a list of child Comment objects.""" 194 | return [x for x in self.children if isinstance(x, Comment)] 195 | 196 | @property 197 | def keys(self): 198 | """Return a list of child Key objects.""" 199 | return [x for x in self.children if isinstance(x, Key)] 200 | 201 | @property 202 | def as_list(self): 203 | """Return all child objects in nested lists of strings.""" 204 | return [self.name, self.value, [x.as_list for x in self.children]] 205 | 206 | @property 207 | def as_dict(self): 208 | """Return all child objects in nested dict.""" 209 | dicts = [x.as_dict for x in self.children] 210 | return {'{0} {1}'.format(self.name, self.value): dicts} 211 | 212 | @property 213 | def as_strings(self): 214 | """Return the entire Container as nginx config strings.""" 215 | ret = [] 216 | container_title = (INDENT * self._depth) 217 | container_title += '{0}{1} {{\n'.format( 218 | self.name, (' {0}'.format(self.value) if self.value else '') 219 | ) 220 | ret.append(container_title) 221 | for x in self.children: 222 | if isinstance(x, Key): 223 | ret.append(INDENT + x.as_strings) 224 | elif isinstance(x, Comment): 225 | if x.inline and len(ret) >= 1: 226 | ret[-1] = ret[-1].rstrip('\n') + ' ' + x.as_strings 227 | else: 228 | ret.append(INDENT + x.as_strings) 229 | elif isinstance(x, Container): 230 | y = x.as_strings 231 | ret.append('\n' + y[0]) 232 | for z in y[1:]: 233 | ret.append(INDENT + z) 234 | else: 235 | y = x.as_strings 236 | ret.append(INDENT + y) 237 | ret[-1] = re.sub('}\n+$', '}\n', ret[-1]) 238 | ret.append('}\n\n') 239 | return ret 240 | 241 | 242 | class Comment(object): 243 | """Represents a comment in an nginx config.""" 244 | 245 | def __init__(self, comment, inline=False): 246 | """ 247 | Initialize object. 248 | 249 | :param str comment: Value of the comment 250 | :param bool inline: This comment is on the same line as preceding item 251 | """ 252 | self.comment = comment 253 | self.inline = inline 254 | 255 | @property 256 | def as_list(self): 257 | """Return comment as nested list of strings.""" 258 | return [self.comment] 259 | 260 | @property 261 | def as_dict(self): 262 | """Return comment as dict.""" 263 | return {'#': self.comment} 264 | 265 | @property 266 | def as_strings(self): 267 | """Return comment as nginx config string.""" 268 | return '# {0}\n'.format(self.comment) 269 | 270 | 271 | class Http(Container): 272 | """Container for HTTP sections in the main NGINX conf file.""" 273 | 274 | def __init__(self, *args): 275 | """Initialize.""" 276 | super(Http, self).__init__('', *args) 277 | self.name = 'http' 278 | 279 | 280 | class Server(Container): 281 | """Container for server block configurations.""" 282 | 283 | def __init__(self, *args): 284 | """Initialize.""" 285 | super(Server, self).__init__('', *args) 286 | self.name = 'server' 287 | 288 | @property 289 | def as_dict(self): 290 | """Return all child objects in nested dict.""" 291 | return {'server': [x.as_dict for x in self.children]} 292 | 293 | 294 | class Location(Container): 295 | """Container for Location-based options.""" 296 | 297 | def __init__(self, value, *args): 298 | """Initialize.""" 299 | super(Location, self).__init__(value, *args) 300 | self.name = 'location' 301 | 302 | 303 | class Events(Container): 304 | """Container for Event-based options.""" 305 | 306 | def __init__(self, *args): 307 | """Initialize.""" 308 | super(Events, self).__init__('', *args) 309 | self.name = 'events' 310 | 311 | 312 | class LimitExcept(Container): 313 | """Container for specifying HTTP method restrictions.""" 314 | 315 | def __init__(self, value, *args): 316 | """Initialize.""" 317 | super(LimitExcept, self).__init__(value, *args) 318 | self.name = 'limit_except' 319 | 320 | 321 | class Types(Container): 322 | """Container for MIME type mapping.""" 323 | 324 | def __init__(self, *args): 325 | """Initialize.""" 326 | super(Types, self).__init__('', *args) 327 | self.name = 'types' 328 | 329 | 330 | class If(Container): 331 | """Container for If conditionals.""" 332 | 333 | def __init__(self, value, *args): 334 | """Initialize.""" 335 | super(If, self).__init__(value, *args) 336 | self.name = 'if' 337 | 338 | 339 | class Upstream(Container): 340 | """Container for upstream configuration (reverse proxy).""" 341 | 342 | def __init__(self, value, *args): 343 | """Initialize.""" 344 | super(Upstream, self).__init__(value, *args) 345 | self.name = 'upstream' 346 | 347 | 348 | class Geo(Container): 349 | """ 350 | Container for geo module configuration. 351 | 352 | See docs here: http://nginx.org/en/docs/http/ngx_http_geo_module.html 353 | """ 354 | 355 | def __init__(self, value, *args): 356 | """Initialize.""" 357 | super(Geo, self).__init__(value, *args) 358 | self.name = 'geo' 359 | 360 | 361 | class Map(Container): 362 | """Container for map configuration.""" 363 | 364 | def __init__(self, value, *args): 365 | """Initialize.""" 366 | super(Map, self).__init__(value, *args) 367 | self.name = 'map' 368 | 369 | 370 | class Stream(Container): 371 | """Container for stream sections in the main NGINX conf file.""" 372 | 373 | def __init__(self, *args): 374 | """Initialize.""" 375 | super(Stream, self).__init__('', *args) 376 | self.name = 'stream' 377 | 378 | 379 | class Key(object): 380 | """Represents a simple key/value object found in an nginx config.""" 381 | 382 | def __init__(self, name, value): 383 | """ 384 | Initialize object. 385 | 386 | :param *args: Any objects to include in this Server block. 387 | """ 388 | self.name = name 389 | self.value = value 390 | 391 | @property 392 | def as_list(self): 393 | """Return key as nested list of strings.""" 394 | return [self.name, self.value] 395 | 396 | @property 397 | def as_dict(self): 398 | """Return key as dict key/value.""" 399 | return {self.name: self.value} 400 | 401 | @property 402 | def as_strings(self): 403 | """Return key as nginx config string.""" 404 | if self.value == '' or self.value is None: 405 | return '{0};\n'.format(self.name) 406 | if type(self.value) == str and '"' not in self.value and (';' in self.value or '#' in self.value): 407 | return '{0} "{1}";\n'.format(self.name, self.value) 408 | return '{0} {1};\n'.format(self.name, self.value) 409 | 410 | 411 | def loads(data, conf=True): 412 | """ 413 | Load an nginx configuration from a provided string. 414 | 415 | :param str data: nginx configuration 416 | :param bool conf: Load object(s) into a Conf object? 417 | """ 418 | f = Conf() if conf else [] 419 | lopen = [] 420 | index = 0 421 | 422 | while True: 423 | m = re.compile(r'^\s*events\s*{').search(data[index:]) 424 | if m: 425 | log.debug("Open (Events)") 426 | e = Events() 427 | lopen.insert(0, e) 428 | index += m.end() 429 | continue 430 | 431 | m = re.compile(r'^\s*http\s*{').search(data[index:]) 432 | if m: 433 | log.debug("Open (Http)") 434 | h = Http() 435 | lopen.insert(0, h) 436 | index += m.end() 437 | continue 438 | 439 | m = re.compile(r'^\s*stream\s*{').search(data[index:]) 440 | if m: 441 | log.debug("Open (Stream)") 442 | s = Stream() 443 | lopen.insert(0, s) 444 | index += m.end() 445 | continue 446 | 447 | m = re.compile(r'^\s*server\s*{').search(data[index:]) 448 | if m: 449 | log.debug("Open (Server)") 450 | s = Server() 451 | lopen.insert(0, s) 452 | index += m.end() 453 | continue 454 | 455 | n = re.compile(r'(?!\B"[^"]*);(?![^"]*"\B)') 456 | m = re.compile(r'^\s*location\s+(.*?".*?".*?|.*?)\s*{').search(data[index:]) 457 | if m and not n.search(m.group()): 458 | log.debug("Open (Location) {0}".format(m.group(1))) 459 | l = Location(m.group(1)) 460 | lopen.insert(0, l) 461 | index += m.end() 462 | continue 463 | 464 | m = re.compile(r'^\s*if\s+(.*?".*?".*?|.*?)\s*{').search(data[index:]) 465 | if m and not n.search(m.group()): 466 | log.debug("Open (If) {0}".format(m.group(1))) 467 | ifs = If(m.group(1)) 468 | lopen.insert(0, ifs) 469 | index += m.end() 470 | continue 471 | 472 | m = re.compile(r'^\s*upstream\s+(.*?)\s*{').search(data[index:]) 473 | if m and not n.search(m.group()): 474 | log.debug("Open (Upstream) {0}".format(m.group(1))) 475 | u = Upstream(m.group(1)) 476 | lopen.insert(0, u) 477 | index += m.end() 478 | continue 479 | 480 | m = re.compile(r'^\s*geo\s+(.*?".*?".*?|.*?)\s*{').search(data[index:]) 481 | if m and not n.search(m.group()): 482 | log.debug("Open (Geo) {0}".format(m.group(1))) 483 | g = Geo(m.group(1)) 484 | lopen.insert(0, g) 485 | index += m.end() 486 | continue 487 | 488 | m = re.compile(r'^\s*map\s+(.*?".*?".*?|.*?)\s*{').search(data[index:]) 489 | if m and not n.search(m.group()): 490 | log.debug("Open (Map) {0}".format(m.group(1))) 491 | g = Map(m.group(1)) 492 | lopen.insert(0, g) 493 | index += m.end() 494 | continue 495 | 496 | m = re.compile(r'^\s*limit_except\s+(.*?".*?".*?|.*?)\s*{').search(data[index:]) 497 | if m and not n.search(m.group()): 498 | log.debug("Open (LimitExcept) {0}".format(m.group(1))) 499 | l = LimitExcept(m.group(1)) 500 | lopen.insert(0, l) 501 | index += m.end() 502 | continue 503 | 504 | m = re.compile(r'^\s*types\s*{').search(data[index:]) 505 | if m: 506 | log.debug("Open (Types)") 507 | l = Types() 508 | lopen.insert(0, l) 509 | index += m.end() 510 | continue 511 | 512 | m = re.compile(r'^(\s*)#[ \r\t\f]*(.*?)\n').search(data[index:]) 513 | if m: 514 | log.debug("Comment ({0})".format(m.group(2))) 515 | c = Comment(m.group(2), inline='\n' not in m.group(1)) 516 | if lopen and isinstance(lopen[0], Container): 517 | lopen[0].add(c) 518 | else: 519 | f.add(c) if conf else f.append(c) 520 | index += m.end() - 1 521 | continue 522 | 523 | m = re.compile(r'^\s*}').search(data[index:]) 524 | if m: 525 | if isinstance(lopen[0], Container): 526 | log.debug("Close ({0})".format(lopen[0].__class__.__name__)) 527 | c = lopen[0] 528 | lopen.pop(0) 529 | if lopen and isinstance(lopen[0], Container): 530 | lopen[0].add(c) 531 | else: 532 | f.add(c) if conf else f.append(c) 533 | index += m.end() 534 | continue 535 | 536 | if ";" not in data[index:] and "}" in data[index:]: 537 | # If there is still something to parse, expect ';' otherwise 538 | # the Key regexp can get stuck due to regexp catastrophic backtracking 539 | raise ParseError("Config syntax, missing ';' at index: {}".format(index)) 540 | 541 | double = r'\s*"[^"]*"' 542 | single = r'\s*\'[^\']*\'' 543 | normal = r'\s*[^;\s]*' 544 | s1 = r'{}|{}|{}'.format(double, single, normal) 545 | s = r'^\s*({})\s*((?:{})+);'.format(s1, s1) 546 | m = re.compile(s).search(data[index:]) 547 | if m: 548 | log.debug("Key {0} {1}".format(m.group(1), m.group(2))) 549 | k = Key(m.group(1), m.group(2)) 550 | if lopen and isinstance(lopen[0], (Container, Server)): 551 | lopen[0].add(k) 552 | else: 553 | f.add(k) if conf else f.append(k) 554 | index += m.end() 555 | continue 556 | 557 | m = re.compile(r'^\s*(\S+);').search(data[index:]) 558 | if m: 559 | log.debug("Key {0}".format(m.group(1))) 560 | k = Key(m.group(1), '') 561 | if lopen and isinstance(lopen[0], (Container, Server)): 562 | lopen[0].add(k) 563 | else: 564 | f.add(k) if conf else f.append(k) 565 | index += m.end() 566 | continue 567 | 568 | break 569 | 570 | return f 571 | 572 | 573 | def load(fobj): 574 | """ 575 | Load an nginx configuration from a provided file-like object. 576 | 577 | :param obj fobj: nginx configuration 578 | """ 579 | return loads(fobj.read()) 580 | 581 | 582 | def loadf(path): 583 | """ 584 | Load an nginx configuration from a provided file path. 585 | 586 | :param file path: path to nginx configuration on disk 587 | """ 588 | with open(path, 'r') as f: 589 | return load(f) 590 | 591 | 592 | def dumps(obj): 593 | """ 594 | Dump an nginx configuration to a string. 595 | 596 | :param obj obj: nginx object (Conf, Server, Container) 597 | :returns: nginx configuration as string 598 | """ 599 | return ''.join(obj.as_strings) 600 | 601 | 602 | def dump(obj, fobj): 603 | """ 604 | Write an nginx configuration to a file-like object. 605 | 606 | :param obj obj: nginx object (Conf, Server, Container) 607 | :param obj fobj: file-like object to write to 608 | :returns: file-like object that was written to 609 | """ 610 | fobj.write(dumps(obj)) 611 | return fobj 612 | 613 | 614 | def dumpf(obj, path): 615 | """ 616 | Write an nginx configuration to file. 617 | 618 | :param obj obj: nginx object (Conf, Server, Container) 619 | :param str path: path to nginx configuration on disk 620 | :returns: path the configuration was written to 621 | """ 622 | with open(path, 'w') as f: 623 | dump(obj, f) 624 | return path 625 | -------------------------------------------------------------------------------- /setup.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | 3 | from setuptools import setup 4 | 5 | setup( 6 | name='python-nginx', 7 | version='1.5.7', 8 | description='Create and modify nginx serverblock configs in Python', 9 | author='Jacob Cook', 10 | author_email='jacob@peakwinter.net', 11 | url='https://github.com/peakwinter/python-nginx', 12 | py_modules=['nginx'], 13 | keywords=['nginx', 'web servers', 'serverblock', 'server block'], 14 | download_url='https://github.com/peakwinter/python-nginx/archive/1.5.7.zip', 15 | license='GPLv3', 16 | classifiers=[ 17 | "Development Status :: 5 - Production/Stable", 18 | "License :: OSI Approved :: GNU General Public License v3 or later (GPLv3+)", 19 | "Operating System :: Unix", 20 | "Topic :: Internet :: WWW/HTTP :: HTTP Servers", 21 | ] 22 | ) 23 | -------------------------------------------------------------------------------- /tests.py: -------------------------------------------------------------------------------- 1 | """ 2 | Testing module for python-nginx. 3 | 4 | python-nginx 5 | (c) 2016 Jacob Cook 6 | Licensed under GPLv3, see LICENSE.md 7 | """ 8 | 9 | # flake8: noqa 10 | import pytest 11 | 12 | import nginx 13 | import unittest 14 | 15 | 16 | TESTBLOCK_CASE_1 = """ 17 | include conf.d/pre/*.cfg; 18 | upstream php { 19 | server unix:/tmp/php-fcgi.socket; 20 | } 21 | 22 | server { 23 | listen 80; # This comment should be present; 24 | # And this one 25 | server_name localhost 127.0.0.1; 26 | root /srv/http; # And also this one 27 | mykey "myvalue; #notme myothervalue"; 28 | # This one too 29 | index index.php; 30 | 31 | location ~ \.php(?:$|/) { 32 | fastcgi_pass php; 33 | } 34 | } 35 | """ 36 | 37 | TESTBLOCK_CASE_2 = """ 38 | upstream php 39 | { 40 | server unix:/tmp/php-fcgi.socket; 41 | } 42 | server 43 | { 44 | listen 80; # This comment should be present; 45 | # And this one 46 | server_name localhost 127.0.0.1; 47 | root /srv/http; # And also this one 48 | mykey "myvalue; #notme myothervalue"; 49 | "quoted_key" "quoted_value"; 50 | # This one too 51 | index index.php; 52 | if (!-e $request_filename) 53 | { 54 | rewrite ^(.+)$ /index.php?q=$1 last; 55 | } 56 | 57 | if (!-e $request_filename) { 58 | rewrite ^(.+)$ /index.php?q=$1 last; 59 | } 60 | location ~ \.php(?:$|/) { 61 | fastcgi_pass php; 62 | } 63 | 64 | # location from the issue #10 65 | location / { 66 | return 301 $scheme://$host:$server_port${request_uri}bitbucket/; 67 | } 68 | } 69 | """ 70 | 71 | TESTBLOCK_CASE_3=""" 72 | upstream test0 { 73 | ip_hash; 74 | server 127.0.0.1:8080; 75 | keepalive 16; 76 | } 77 | upstream test1{ 78 | server 127.0.0.2:8080; 79 | keepalive 16; 80 | } 81 | upstream test2 82 | { 83 | server 127.0.0.3:8080; 84 | keepalive 16; 85 | } 86 | 87 | server { 88 | listen 80; 89 | server_name example.com; 90 | 91 | location = / 92 | { 93 | root html; 94 | } 95 | } 96 | """ 97 | 98 | TESTBLOCK_CASE_4 = """ 99 | # This is an example of a messy config 100 | upstream php { server unix:/tmp/php-cgi.socket; } 101 | server { server_name localhost; #this is the server server_name 102 | location /{ test_key test_value; }} 103 | """ 104 | 105 | 106 | TESTBLOCK_CASE_5 = """ 107 | upstream test0 { 108 | server 1.1.1.1:8080; 109 | send "some request"; 110 | } 111 | 112 | upstream test1 { 113 | server 1.1.1.1:8080; 114 | send 'some request'; 115 | } 116 | 117 | server { 118 | server_name "www.example.com"; 119 | 120 | location / { 121 | root html; 122 | } 123 | } 124 | """ 125 | 126 | 127 | TESTBLOCK_CASE_6 = """ 128 | upstream test0 { 129 | server 1.1.1.1:8080; 130 | check interval=3000 rise=2 fall=3 timeout=3000 type=http; 131 | check_http_send "GET /alive.html HTTP/1.0\r\n\r\n"; 132 | check_http_expect_alive http_2xx http_3xx; 133 | } 134 | 135 | upstream test1 { 136 | ip_hash; 137 | server 2.2.2.2:9000; 138 | check_http_send 'GET /alive.html HTTP/1.0\r\n\r\n'; 139 | } 140 | """ 141 | 142 | TESTBLOCK_CASE_7 = """ 143 | upstream xx.com_backend { 144 | server 10.193.2.2:9061 weight=1 max_fails=2 fail_timeout=30s; 145 | server 10.193.2.1:9061 weight=1 max_fails=2 fail_timeout=30s; 146 | session_sticky; 147 | } 148 | 149 | server { 150 | listen 80; 151 | 152 | location / { 153 | set $xlocation 'test'; 154 | proxy_pass http://xx.com_backend; 155 | } 156 | } 157 | """ 158 | 159 | TESTBLOCK_CASE_8 = """ 160 | location /M01 { 161 | proxy_pass http://backend; 162 | limit_except GET POST {deny all;} 163 | } 164 | """ 165 | 166 | TESTBLOCK_CASE_9 = """ 167 | location test9 { 168 | add_header X-XSS-Protection "1;mode-block"; 169 | } 170 | 171 | if ( $http_user_agent = "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1)" ) { 172 | return 403; 173 | } 174 | 175 | location ~* ^/portal { 176 | proxy_set_header Connection ""; 177 | rewrite ^/portal(.*) $1 break; 178 | } 179 | """ 180 | 181 | TESTBLOCK_CASE_10 = """ 182 | types { 183 | application/CEA cea; 184 | application/cellml+xml cellml cml; 185 | application/clue_info+xml clue; 186 | application/cms cmsc; 187 | } 188 | """ 189 | 190 | TESTBLOCK_CASE_11 = """ 191 | server{ 192 | listen 80; 193 | #OPEN-PORT-443 194 | listen 443 ssl; 195 | server_name www.xxx.com; 196 | root /wwww/wwww; 197 | 198 | location ~ .*\.(js|css)?$ { 199 | expires 12h; 200 | error_log off; 201 | access_log /dev/null # MISSING SEMICOLON 202 | } 203 | } 204 | """ 205 | 206 | TESTBLOCK_CASE_12 = """ 207 | server { 208 | listen 80; 209 | server_name test.example.com; 210 | 211 | location ~ "^/(test|[0-9a-zA-Z]{6})$" { 212 | if ($query_string ~ pid=(111)) { 213 | return 403; 214 | } 215 | 216 | proxy_pass http://127.0.0.1:81; 217 | } 218 | } 219 | """ 220 | 221 | TESTBLOCK_CASE_13 = """ 222 | server{ 223 | }""" 224 | 225 | TESTBLOCK_CASE_14 = """user nginx;""" 226 | 227 | 228 | class TestPythonNginx(unittest.TestCase): 229 | def test_basic_load(self): 230 | self.assertTrue(nginx.loads(TESTBLOCK_CASE_1) is not None) 231 | 232 | def test_messy_load(self): 233 | data = nginx.loads(TESTBLOCK_CASE_4) 234 | self.assertTrue(data is not None) 235 | self.assertTrue(len(data.server.comments), 1) 236 | self.assertTrue(len(data.server.locations), 1) 237 | 238 | def test_comment_parse(self): 239 | data = nginx.loads(TESTBLOCK_CASE_1) 240 | self.assertEqual(len(data.server.comments), 4) 241 | self.assertEqual(data.server.comments[2].comment, 'And also this one') 242 | 243 | def test_key_parse(self): 244 | data = nginx.loads(TESTBLOCK_CASE_1) 245 | self.assertEqual(len(data.server.keys), 5) 246 | firstKey = data.server.keys[0] 247 | thirdKey = data.server.keys[3] 248 | self.assertEqual(firstKey.name, 'listen') 249 | self.assertEqual(firstKey.value, '80') 250 | self.assertEqual(thirdKey.name, 'mykey') 251 | self.assertEqual(thirdKey.value, '"myvalue; #notme myothervalue"') 252 | 253 | def test_key_parse_complex(self): 254 | data = nginx.loads(TESTBLOCK_CASE_2) 255 | self.assertEqual(len(data.server.keys), 6) 256 | firstKey = data.server.keys[0] 257 | thirdKey = data.server.keys[3] 258 | fourthKey = data.server.keys[4] 259 | self.assertEqual(firstKey.name, 'listen') 260 | self.assertEqual(firstKey.value, '80') 261 | self.assertEqual(thirdKey.name, 'mykey') 262 | self.assertEqual(thirdKey.value, '"myvalue; #notme myothervalue"') 263 | self.assertEqual( 264 | data.server.locations[-1].keys[0].value, 265 | "301 $scheme://$host:$server_port${request_uri}bitbucket/" 266 | ) 267 | self.assertEqual(fourthKey.name, '"quoted_key"') 268 | self.assertEqual(fourthKey.value, '"quoted_value"') 269 | 270 | def test_location_parse(self): 271 | data = nginx.loads(TESTBLOCK_CASE_1) 272 | self.assertEqual(len(data.server.locations), 1) 273 | firstLoc = data.server.locations[0] 274 | self.assertEqual(firstLoc.value, '~ \.php(?:$|/)') 275 | self.assertEqual(len(firstLoc.keys), 1) 276 | 277 | def test_brace_position(self): 278 | data = nginx.loads(TESTBLOCK_CASE_3) 279 | self.assertEqual(len(data.filter('Upstream')), 3) 280 | 281 | def test_single_value_keys(self): 282 | data = nginx.loads(TESTBLOCK_CASE_3) 283 | single_value_key = data.filter('Upstream')[0].keys[0] 284 | self.assertEqual(single_value_key.name, 'ip_hash') 285 | self.assertEqual(single_value_key.value, '') 286 | 287 | def test_reflection(self): 288 | inp_data = nginx.loads(TESTBLOCK_CASE_1) 289 | out_data = '\n' + nginx.dumps(inp_data) 290 | self.assertEqual(TESTBLOCK_CASE_1, out_data) 291 | 292 | def test_quoted_key_value(self): 293 | data = nginx.loads(TESTBLOCK_CASE_5) 294 | out_data = '\n' + nginx.dumps(data) 295 | self.assertEqual(out_data, TESTBLOCK_CASE_5) 296 | 297 | def test_complex_upstream(self): 298 | inp_data = nginx.loads(TESTBLOCK_CASE_6) 299 | out_data = '\n' + nginx.dumps(inp_data) 300 | self.assertEqual(TESTBLOCK_CASE_6, out_data) 301 | 302 | def test_session_sticky(self): 303 | inp_data = nginx.loads(TESTBLOCK_CASE_7) 304 | out_data = '\n' + nginx.dumps(inp_data) 305 | self.assertEqual(TESTBLOCK_CASE_7, out_data) 306 | 307 | def test_filtering(self): 308 | data = nginx.loads(TESTBLOCK_CASE_1) 309 | self.assertEqual(len(data.server.filter('Key', 'mykey')), 1) 310 | self.assertEqual(data.server.filter('Key', 'nothere'), []) 311 | 312 | def test_limit_expect(self): 313 | data = nginx.loads(TESTBLOCK_CASE_8) 314 | self.assertEqual(len(data.filter("Location")), 1) 315 | self.assertEqual(len(data.filter("Location")[0].children), 2) 316 | self.assertEqual(len(data.filter("Location")[0].filter("LimitExcept")), 1) 317 | limit_except = data.filter("Location")[0].filter("LimitExcept")[0] 318 | self.assertEqual(limit_except.value, "GET POST") 319 | self.assertEqual(len(limit_except.children), 1) 320 | first_key = limit_except.filter("Key")[0] 321 | self.assertEqual(first_key.name, "deny") 322 | self.assertEqual(first_key.value, "all") 323 | 324 | def test_key_value_quotes(self): 325 | inp_data = nginx.loads(TESTBLOCK_CASE_9) 326 | self.assertEqual(len(inp_data.filter("Location")), 2) 327 | location_children = inp_data.filter("Location")[0].children 328 | self.assertEqual(len(location_children), 1) 329 | self.assertEqual(location_children[0].name, "add_header") 330 | self.assertEqual(location_children[0].value, 'X-XSS-Protection "1;mode-block"') 331 | self.assertEqual(len(inp_data.filter("If")), 1) 332 | self.assertEqual(inp_data.filter("If")[0].value, "( $http_user_agent = \"Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1)\" )") 333 | self.assertEqual(inp_data.filter("Location")[1].filter("Key", "proxy_set_header")[0].value, "Connection \"\"") 334 | 335 | def test_types_block(self): 336 | inp_data = nginx.loads(TESTBLOCK_CASE_10) 337 | self.assertEqual(len(inp_data.filter("Types")), 1) 338 | self.assertEqual(len(inp_data.filter("Types")[0].children), 4) 339 | self.assertEqual(len(inp_data.filter("Types")[0].filter("Key")), 4) 340 | data_type = inp_data.filter("Types")[0].filter("Key")[0] 341 | self.assertEqual(data_type.value, "cea") 342 | 343 | def test_missing_semi_colon(self): 344 | with pytest.raises(nginx.ParseError) as e: 345 | nginx.loads(TESTBLOCK_CASE_11) 346 | self.assertEqual(str(e.value), "Config syntax, missing ';' at index: 189") 347 | 348 | def test_brace_inside_block_param(self): 349 | inp_data = nginx.loads(TESTBLOCK_CASE_12) 350 | self.assertEqual(len(inp_data.server.filter("Location")), 1) 351 | self.assertEqual(inp_data.server.filter("Location")[0].value, "~ \"^/(test|[0-9a-zA-Z]{6})$\"") 352 | 353 | def test_server_without_last_linebreak(self): 354 | self.assertTrue(nginx.loads(TESTBLOCK_CASE_13) is not None) 355 | self.assertTrue(nginx.loads(TESTBLOCK_CASE_14) is not None) 356 | 357 | 358 | if __name__ == '__main__': 359 | unittest.main() 360 | --------------------------------------------------------------------------------