2015-03-23 13:53:44 -04:00
|
|
|
"""NginxParser is a member object of the NginxConfigurator class."""
|
2016-06-18 17:52:07 -04:00
|
|
|
import copy
|
2017-12-07 12:48:54 -05:00
|
|
|
import functools
|
2015-04-06 17:22:27 -04:00
|
|
|
import glob
|
2018-10-31 02:45:30 -04:00
|
|
|
import io
|
2015-04-06 17:22:27 -04:00
|
|
|
import logging
|
2015-04-09 18:51:58 -04:00
|
|
|
import re
|
2022-01-12 19:36:51 -05:00
|
|
|
from typing import Any
|
|
|
|
|
from typing import Callable
|
|
|
|
|
from typing import cast
|
2021-03-09 19:12:32 -05:00
|
|
|
from typing import Dict
|
2022-01-12 19:36:51 -05:00
|
|
|
from typing import Iterable
|
2021-03-09 19:12:32 -05:00
|
|
|
from typing import List
|
2022-01-12 19:36:51 -05:00
|
|
|
from typing import Mapping
|
2021-03-09 19:12:32 -05:00
|
|
|
from typing import Optional
|
2022-01-12 19:36:51 -05:00
|
|
|
from typing import Sequence
|
2021-03-09 19:12:32 -05:00
|
|
|
from typing import Set
|
|
|
|
|
from typing import Tuple
|
|
|
|
|
from typing import Union
|
2015-03-23 13:53:44 -04:00
|
|
|
|
2019-12-09 15:50:20 -05:00
|
|
|
import pyparsing
|
2017-12-06 20:45:20 -05:00
|
|
|
|
2016-04-13 19:45:54 -04:00
|
|
|
from certbot import errors
|
2019-04-12 16:32:52 -04:00
|
|
|
from certbot.compat import os
|
2023-02-10 13:51:20 -05:00
|
|
|
from certbot_nginx._internal import nginxparser
|
|
|
|
|
from certbot_nginx._internal import obj
|
|
|
|
|
from certbot_nginx._internal.nginxparser import UnspacedList
|
2015-03-23 13:53:44 -04:00
|
|
|
|
2015-06-11 09:45:41 -04:00
|
|
|
logger = logging.getLogger(__name__)
|
|
|
|
|
|
|
|
|
|
|
2021-02-25 17:59:00 -05:00
|
|
|
class NginxParser:
|
2015-03-23 13:53:44 -04:00
|
|
|
"""Class handles the fine details of parsing the Nginx Configuration.
|
|
|
|
|
|
2016-06-21 18:11:32 -04:00
|
|
|
:ivar str root: Normalized absolute path to the server root
|
2015-03-23 13:53:44 -04:00
|
|
|
directory. Without trailing slash.
|
2015-04-06 17:22:27 -04:00
|
|
|
:ivar dict parsed: Mapping of file paths to parsed trees
|
2015-03-23 13:53:44 -04:00
|
|
|
|
|
|
|
|
"""
|
|
|
|
|
|
2022-01-12 19:36:51 -05:00
|
|
|
def __init__(self, root: str) -> None:
|
|
|
|
|
self.parsed: Dict[str, UnspacedList] = {}
|
2015-03-23 13:53:44 -04:00
|
|
|
self.root = os.path.abspath(root)
|
2017-05-02 20:56:56 -04:00
|
|
|
self.config_root = self._find_config_root()
|
2015-03-23 13:53:44 -04:00
|
|
|
|
2015-04-06 21:00:21 -04:00
|
|
|
# Parse nginx.conf and included files.
|
|
|
|
|
# TODO: Check sites-available/ as well. For now, the configurator does
|
|
|
|
|
# not enable sites from there.
|
2015-04-15 17:44:51 -04:00
|
|
|
self.load()
|
|
|
|
|
|
2022-01-12 19:36:51 -05:00
|
|
|
def load(self) -> None:
|
2015-04-15 17:44:51 -04:00
|
|
|
"""Loads Nginx files into a parsed tree.
|
|
|
|
|
|
|
|
|
|
"""
|
2015-04-28 21:38:28 -04:00
|
|
|
self.parsed = {}
|
2017-05-02 20:56:56 -04:00
|
|
|
self._parse_recursively(self.config_root)
|
2015-04-06 21:00:21 -04:00
|
|
|
|
2022-01-12 19:36:51 -05:00
|
|
|
def _parse_recursively(self, filepath: str) -> None:
|
2015-04-06 21:00:21 -04:00
|
|
|
"""Parses nginx config files recursively by looking at 'include'
|
|
|
|
|
directives inside 'http' and 'server' blocks. Note that this only
|
|
|
|
|
reads Nginx files that potentially declare a virtual host.
|
|
|
|
|
|
2015-04-07 17:57:37 -04:00
|
|
|
:param str filepath: The path to the files to parse, as a glob
|
|
|
|
|
|
2015-04-06 21:00:21 -04:00
|
|
|
"""
|
2018-05-14 12:33:30 -04:00
|
|
|
# pylint: disable=too-many-nested-blocks
|
2015-04-07 17:57:37 -04:00
|
|
|
filepath = self.abs_path(filepath)
|
2015-04-06 21:00:21 -04:00
|
|
|
trees = self._parse_files(filepath)
|
|
|
|
|
for tree in trees:
|
|
|
|
|
for entry in tree:
|
2015-04-17 20:05:00 -04:00
|
|
|
if _is_include_directive(entry):
|
2015-04-06 21:00:21 -04:00
|
|
|
# Parse the top-level included file
|
|
|
|
|
self._parse_recursively(entry[1])
|
|
|
|
|
elif entry[0] == ['http'] or entry[0] == ['server']:
|
|
|
|
|
# Look for includes in the top-level 'http'/'server' context
|
|
|
|
|
for subentry in entry[1]:
|
2015-04-17 20:05:00 -04:00
|
|
|
if _is_include_directive(subentry):
|
2015-04-06 21:00:21 -04:00
|
|
|
self._parse_recursively(subentry[1])
|
|
|
|
|
elif entry[0] == ['http'] and subentry[0] == ['server']:
|
|
|
|
|
# Look for includes in a 'server' context within
|
|
|
|
|
# an 'http' context
|
|
|
|
|
for server_entry in subentry[1]:
|
2015-04-17 20:05:00 -04:00
|
|
|
if _is_include_directive(server_entry):
|
2015-04-06 21:00:21 -04:00
|
|
|
self._parse_recursively(server_entry[1])
|
|
|
|
|
|
2022-01-12 19:36:51 -05:00
|
|
|
def abs_path(self, path: str) -> str:
|
2015-04-07 17:57:37 -04:00
|
|
|
"""Converts a relative path to an absolute path relative to the root.
|
|
|
|
|
Does nothing for paths that are already absolute.
|
|
|
|
|
|
|
|
|
|
:param str path: The path
|
|
|
|
|
:returns: The absolute path
|
2015-04-09 18:51:58 -04:00
|
|
|
:rtype: str
|
2015-04-07 17:57:37 -04:00
|
|
|
|
|
|
|
|
"""
|
|
|
|
|
if not os.path.isabs(path):
|
2019-02-20 19:20:16 -05:00
|
|
|
return os.path.normpath(os.path.join(self.root, path))
|
2019-04-02 16:48:22 -04:00
|
|
|
return os.path.normpath(path)
|
2015-04-07 17:57:37 -04:00
|
|
|
|
2022-01-12 19:36:51 -05:00
|
|
|
def _build_addr_to_ssl(self) -> Dict[Tuple[str, str], bool]:
|
2016-12-05 22:17:04 -05:00
|
|
|
"""Builds a map from address to whether it listens on ssl in any server block
|
|
|
|
|
"""
|
|
|
|
|
servers = self._get_raw_servers()
|
2015-04-06 21:00:21 -04:00
|
|
|
|
2021-03-10 14:51:27 -05:00
|
|
|
addr_to_ssl: Dict[Tuple[str, str], bool] = {}
|
2021-07-15 14:03:39 -04:00
|
|
|
for server_list in servers.values():
|
|
|
|
|
for server, _ in server_list:
|
2016-12-05 22:17:04 -05:00
|
|
|
# Parse the server block to save addr info
|
|
|
|
|
parsed_server = _parse_server_raw(server)
|
|
|
|
|
for addr in parsed_server['addrs']:
|
|
|
|
|
addr_tuple = addr.normalized_tuple()
|
|
|
|
|
if addr_tuple not in addr_to_ssl:
|
|
|
|
|
addr_to_ssl[addr_tuple] = addr.ssl
|
|
|
|
|
addr_to_ssl[addr_tuple] = addr.ssl or addr_to_ssl[addr_tuple]
|
|
|
|
|
return addr_to_ssl
|
|
|
|
|
|
2022-01-12 19:36:51 -05:00
|
|
|
def _get_raw_servers(self) -> Dict[str, Union[List[Any], UnspacedList]]:
|
2016-12-05 22:17:04 -05:00
|
|
|
# pylint: disable=cell-var-from-loop
|
|
|
|
|
"""Get a map of unparsed all server blocks
|
2015-04-06 21:00:21 -04:00
|
|
|
"""
|
2022-01-12 19:36:51 -05:00
|
|
|
servers: Dict[str, Union[List[Any], nginxparser.UnspacedList]] = {}
|
2021-07-15 14:03:39 -04:00
|
|
|
for filename, tree in self.parsed.items():
|
2015-04-08 15:52:33 -04:00
|
|
|
servers[filename] = []
|
2015-04-17 20:05:00 -04:00
|
|
|
srv = servers[filename] # workaround undefined loop var in lambdas
|
2015-04-08 15:52:33 -04:00
|
|
|
|
|
|
|
|
# Find all the server blocks
|
2017-04-26 21:44:06 -04:00
|
|
|
_do_for_subarray(tree, lambda x: len(x) >= 2 and x[0] == ['server'],
|
2016-09-26 16:13:29 -04:00
|
|
|
lambda x, y: srv.append((x[1], y)))
|
2015-04-08 15:52:33 -04:00
|
|
|
|
|
|
|
|
# Find 'include' statements in server blocks and append their trees
|
2016-09-26 16:13:29 -04:00
|
|
|
for i, (server, path) in enumerate(servers[filename]):
|
2015-04-16 02:11:35 -04:00
|
|
|
new_server = self._get_included_directives(server)
|
2016-09-26 16:13:29 -04:00
|
|
|
servers[filename][i] = (new_server, path)
|
2016-12-05 22:17:04 -05:00
|
|
|
return servers
|
2015-04-08 15:52:33 -04:00
|
|
|
|
2022-01-12 19:36:51 -05:00
|
|
|
def get_vhosts(self) -> List[obj.VirtualHost]:
|
2016-12-05 22:17:04 -05:00
|
|
|
"""Gets list of all 'virtual hosts' found in Nginx configuration.
|
|
|
|
|
Technically this is a misnomer because Nginx does not have virtual
|
|
|
|
|
hosts, it has 'server blocks'.
|
|
|
|
|
|
2019-11-25 17:30:24 -05:00
|
|
|
:returns: List of :class:`~certbot_nginx._internal.obj.VirtualHost`
|
2016-12-05 22:17:04 -05:00
|
|
|
objects found in configuration
|
|
|
|
|
:rtype: list
|
|
|
|
|
|
|
|
|
|
"""
|
|
|
|
|
enabled = True # We only look at enabled vhosts for now
|
|
|
|
|
servers = self._get_raw_servers()
|
|
|
|
|
|
|
|
|
|
vhosts = []
|
2021-07-15 14:03:39 -04:00
|
|
|
for filename, server_list in servers.items():
|
|
|
|
|
for server, path in server_list:
|
2015-04-08 15:52:33 -04:00
|
|
|
# Parse the server block into a VirtualHost object
|
2016-06-18 17:52:07 -04:00
|
|
|
|
2016-12-05 22:17:04 -05:00
|
|
|
parsed_server = _parse_server_raw(server)
|
2015-04-08 15:52:33 -04:00
|
|
|
vhost = obj.VirtualHost(filename,
|
2015-04-10 21:17:17 -04:00
|
|
|
parsed_server['addrs'],
|
|
|
|
|
parsed_server['ssl'],
|
2015-04-08 15:52:33 -04:00
|
|
|
enabled,
|
2015-04-14 19:24:10 -04:00
|
|
|
parsed_server['names'],
|
2016-09-26 16:13:29 -04:00
|
|
|
server,
|
|
|
|
|
path)
|
2015-04-08 15:52:33 -04:00
|
|
|
vhosts.append(vhost)
|
|
|
|
|
|
2016-12-05 22:17:04 -05:00
|
|
|
self._update_vhosts_addrs_ssl(vhosts)
|
|
|
|
|
|
2015-04-07 19:22:34 -04:00
|
|
|
return vhosts
|
2015-03-23 13:53:44 -04:00
|
|
|
|
2022-01-12 19:36:51 -05:00
|
|
|
def _update_vhosts_addrs_ssl(self, vhosts: Iterable[obj.VirtualHost]) -> None:
|
2016-12-05 22:17:04 -05:00
|
|
|
"""Update a list of raw parsed vhosts to include global address sslishness
|
|
|
|
|
"""
|
|
|
|
|
addr_to_ssl = self._build_addr_to_ssl()
|
|
|
|
|
for vhost in vhosts:
|
|
|
|
|
for addr in vhost.addrs:
|
|
|
|
|
addr.ssl = addr_to_ssl[addr.normalized_tuple()]
|
|
|
|
|
if addr.ssl:
|
|
|
|
|
vhost.ssl = True
|
|
|
|
|
|
2022-01-12 19:36:51 -05:00
|
|
|
def _get_included_directives(self, block: UnspacedList) -> UnspacedList:
|
2015-04-16 02:11:35 -04:00
|
|
|
"""Returns array with the "include" directives expanded out by
|
|
|
|
|
concatenating the contents of the included file to the block.
|
|
|
|
|
|
|
|
|
|
:param list block:
|
|
|
|
|
:rtype: list
|
|
|
|
|
|
|
|
|
|
"""
|
2016-06-18 17:52:07 -04:00
|
|
|
result = copy.deepcopy(block) # Copy the list to keep self.parsed idempotent
|
2015-04-16 02:11:35 -04:00
|
|
|
for directive in block:
|
2015-04-17 20:05:00 -04:00
|
|
|
if _is_include_directive(directive):
|
2015-04-16 02:11:35 -04:00
|
|
|
included_files = glob.glob(
|
|
|
|
|
self.abs_path(directive[1]))
|
2015-04-17 20:05:00 -04:00
|
|
|
for incl in included_files:
|
2015-04-16 02:11:35 -04:00
|
|
|
try:
|
2015-04-17 20:05:00 -04:00
|
|
|
result.extend(self.parsed[incl])
|
|
|
|
|
except KeyError:
|
2015-04-16 02:11:35 -04:00
|
|
|
pass
|
|
|
|
|
return result
|
|
|
|
|
|
2022-01-12 19:36:51 -05:00
|
|
|
def _parse_files(self, filepath: str, override: bool = False) -> List[UnspacedList]:
|
2015-04-07 17:57:37 -04:00
|
|
|
"""Parse files from a glob
|
2015-03-23 13:53:44 -04:00
|
|
|
|
|
|
|
|
:param str filepath: Nginx config file path
|
2015-04-14 19:43:40 -04:00
|
|
|
:param bool override: Whether to parse a file that has been parsed
|
2015-04-06 21:00:21 -04:00
|
|
|
:returns: list of parsed tree structures
|
|
|
|
|
:rtype: list
|
2015-03-23 13:53:44 -04:00
|
|
|
|
|
|
|
|
"""
|
2016-06-21 18:33:57 -04:00
|
|
|
files = glob.glob(filepath) # nginx on unix calls glob(3) for this
|
|
|
|
|
# XXX Windows nginx uses FindFirstFile, and
|
|
|
|
|
# should have a narrower call here
|
2015-04-06 21:00:21 -04:00
|
|
|
trees = []
|
2015-04-17 20:05:00 -04:00
|
|
|
for item in files:
|
|
|
|
|
if item in self.parsed and not override:
|
2015-04-06 21:00:21 -04:00
|
|
|
continue
|
2015-04-06 17:22:27 -04:00
|
|
|
try:
|
2018-10-31 02:45:30 -04:00
|
|
|
with io.open(item, "r", encoding="utf-8") as _file:
|
2015-05-10 06:47:58 -04:00
|
|
|
parsed = nginxparser.load(_file)
|
2015-04-17 20:05:00 -04:00
|
|
|
self.parsed[item] = parsed
|
2015-04-07 19:22:34 -04:00
|
|
|
trees.append(parsed)
|
2015-04-06 17:22:27 -04:00
|
|
|
except IOError:
|
2016-07-19 13:13:50 -04:00
|
|
|
logger.warning("Could not open file: %s", item)
|
2018-10-31 02:45:30 -04:00
|
|
|
except UnicodeDecodeError:
|
2019-01-30 18:12:55 -05:00
|
|
|
logger.warning("Could not read file: %s due to invalid "
|
|
|
|
|
"character. Only UTF-8 encoding is "
|
|
|
|
|
"supported.", item)
|
2017-02-22 21:50:56 -05:00
|
|
|
except pyparsing.ParseException as err:
|
Command-line UX overhaul (#8852)
Streamline and reorganize Certbot's CLI output.
This change is a substantial command-line UX overhaul,
based on previous user research. The main goal was to streamline
and clarify output. To see more verbose output, use the -v or -vv flags.
---
* nginx,apache: CLI logging changes
- Add "Successfully deployed ..." message using display_util
- Remove IReporter usage and replace with display_util
- Standardize "... could not find a VirtualHost ..." error
This changes also bumps the version of certbot required by certbot-nginx
and certbot-apache to take use of the new display_util function.
* fix certbot_compatibility_test
since the http plugins now require IDisplay, we need to inject it
* fix dependency version on certbot
* use better asserts
* try fix oldest deps
because certbot 1.10.0 depends on acme>=1.8.0, we need to use
acme==1.8.0 in the -oldest tests
* cli: redesign output of new certificate reporting
Changes the output of run, certonly and certonly --csr. No longer uses
IReporter.
* cli: redesign output of failed authz reporting
* fix problem sorting to be stable between py2 & 3
* add some catch-all error text
* cli: dont use IReporter for EFF donation prompt
* add per-authenticator hints
* pass achalls to auth_hint, write some tests
* exclude static auth hints from coverage
* dont call auth_hint unless derived from .Plugin
* dns fallback hint: dont assume --dns-blah works
--dns-blah won't work for third-party plugins, they need to be specified
using --authenticator dns-blah.
* add code comments about the auth_hint interface
* renew: don't restart the installer for dry-runs
Prevents Certbot from superfluously invoking the installer restart
during dry-run renewals. (This does not affect authenticator restarts).
Additionally removes some CLI output that was reporting the fullchain
path of the renewed certificate.
* update CHANGELOG.md
* cli: redesign output when cert installation failed
- Display a message when certificate installation begins.
- Don't use IReporter, just log errors immediately if restart/rollback
fails.
- Prompt the user with a command to retry the installation process once
they have fixed any underlying problems.
* vary by preconfigured_renewal
and move expiry date to be above the renewal advice
* update code comment
Co-authored-by: ohemorange <ebportnoy@gmail.com>
* update code comment
Co-authored-by: ohemorange <ebportnoy@gmail.com>
* fix lint
* derve cert name from cert_path, if possible
* fix type annotation
* text change in nginx hint
Co-authored-by: ohemorange <ebportnoy@gmail.com>
* print message when restarting server after renewal
* log: print "advice" when exiting with an error
When running in non-quiet mode.
* try fix -oldest lock_test.py
* fix docstring
* s/Restarting/Reloading/ when notifying the user
* fix test name
Co-authored-by: ohemorange <ebportnoy@gmail.com>
* type annotations
* s/using the {} plugin/installer: {}/
* copy: avoid "plugin" where possible
* link to user guide#automated-renewals
when not running with --preconfigured-renewal
* cli: reduce default logging verbosity
* fix lock_test: -vv is needed to see logger.debug
* Change comment in log.py to match the change to default verbosity
* Audit and adjust logging levels in apache module
* Audit and adjust logging levels in nginx module
* Audit, adjust logging levels, and improve logging calls in certbot module
* Fix tests to mock correct methods and classes
* typo in non-preconfigured-renewal message
Co-authored-by: ohemorange <ebportnoy@gmail.com>
* fix test
* revert acme version bump
* catch up to python3 changes
* Revert "revert acme version bump"
This reverts commit fa83d6a51cf8d0e7e17da53c6b751ad12945d0cf.
* Change ocsp check error to warning since it's non-fatal
* Update storage_test in parallel with last change
* get rid of leading newline on "Deploying [...]"
* shrink renewal and installation success messages
* print logfile rather than logdir in exit handler
* Decrease logging level to info for idempotent operation where enhancement is already set
* Display cert not yet due for renewal message when renewing and no other action will be taken, and change cert to certificate
* also write to logger so it goes in the log file
* Don't double write to log file; fix main test
* cli: remove trailing newline on new cert reporting
* ignore type error
* revert accidental changes to dependencies
* Pass tests in any timezone by using utcfromtimestamp
* Add changelog entry
* fix nits
* Improve wording of try again message
* minor wording change to changelog
* hooks: send hook stdout to CLI stdout
includes both --manual and --{pre,post,renew} hooks
* update docstrings and remove TODO
* add a pending deprecation on execute_command
* add test coverage for both
* update deprecation text
Co-authored-by: ohemorange <ebportnoy@gmail.com>
Co-authored-by: Alex Zorin <alex@zorin.id.au>
Co-authored-by: alexzorin <alex@zor.io>
2021-05-24 20:47:39 -04:00
|
|
|
logger.warning("Could not parse file: %s due to %s", item, err)
|
2015-04-06 21:00:21 -04:00
|
|
|
return trees
|
2015-03-23 13:53:44 -04:00
|
|
|
|
2022-01-12 19:36:51 -05:00
|
|
|
def _find_config_root(self) -> str:
|
2017-05-02 20:56:56 -04:00
|
|
|
"""Return the Nginx Configuration Root file."""
|
2015-04-06 17:22:27 -04:00
|
|
|
location = ['nginx.conf']
|
2015-03-23 13:53:44 -04:00
|
|
|
|
|
|
|
|
for name in location:
|
|
|
|
|
if os.path.isfile(os.path.join(self.root, name)):
|
|
|
|
|
return os.path.join(self.root, name)
|
|
|
|
|
|
2015-06-12 10:10:39 -04:00
|
|
|
raise errors.NoInstallationError(
|
2018-09-12 19:48:50 -04:00
|
|
|
"Could not find Nginx root configuration file (nginx.conf)")
|
2015-03-23 13:53:44 -04:00
|
|
|
|
2022-01-12 19:36:51 -05:00
|
|
|
def filedump(self, ext: str = 'tmp', lazy: bool = True) -> None:
|
2015-04-07 19:22:34 -04:00
|
|
|
"""Dumps parsed configurations into files.
|
|
|
|
|
|
|
|
|
|
:param str ext: The file extension to use for the dumped files. If
|
|
|
|
|
empty, this overrides the existing conf files.
|
2016-06-24 20:14:14 -04:00
|
|
|
:param bool lazy: Only write files that have been modified
|
2015-04-07 19:22:34 -04:00
|
|
|
|
|
|
|
|
"""
|
2016-06-23 14:39:51 -04:00
|
|
|
# Best-effort atomicity is enforced above us by reverter.py
|
2021-07-15 14:03:39 -04:00
|
|
|
for filename, tree in self.parsed.items():
|
2015-04-07 19:22:34 -04:00
|
|
|
if ext:
|
|
|
|
|
filename = filename + os.path.extsep + ext
|
Upgrade to mypy 0.812 (#8748)
Fixes #8425
This PR upgrades mypy to the latest version available, 0.812.
Given the advanced type inference capabilities provided by this newer version, this PRs also fixes various type inconsistencies that are now detected. Here are the non obvious changes done to fix types:
* typing in mixins has been solved using `Protocol` classes, as recommended by mypy (https://mypy.readthedocs.io/en/latest/more_types.html#mixin-classes, https://mypy.readthedocs.io/en/stable/protocols.html)
* `cast` when we are playing with `Union` types
This PR also disables the strict optional checks that have been enable by default in recent versions of mypy. Once this PR is merged, I will create an issue to study how these checks can be enabled.
`typing.Protocol` is available only since Python 3.8. To keep compatibility with Python 3.6, I try to import the class `Protocol` from `typing`, and fallback to assign `object` to `Protocol` if that fails. This way the code is working with all versions of Python, but the mypy check can be run only with Python 3.8+ because it needs the protocol feature. As a consequence, tox runs mypy under Python 3.8.
Alternatives are:
* importing `typing_extensions`, that proposes backport of newest typing features to Python 3.6, but this implies to add a dependency to Certbot just to run mypy
* redesign the concerned classes to not use mixins, or use them differently, but this implies to modify the code itself even if there is nothing wrong with it and it is just a matter of instructing mypy to understand in which context the mixins can be used
* ignoring type for these classes with `# type: ignore` but we loose the benefit of mypy for them
* Upgrade mypy
* First step for acme
* Cast for the rescue
* Fixing types for certbot
* Fix typing for certbot-nginx
* Finalize type fixes, configure no optional strict check for mypy in tox
* Align requirements
* Isort
* Pylint
* Protocol for python 3.6
* Use Python 3.9 for mypy, make code compatible with Python 3.8<
* Pylint and mypy
* Pragma no cover
* Pythonic NotImplemented constant
* More type definitions
* Add comments
* Simplify typing logic
* Use vararg tuple
* Relax constraints on mypy
* Add more type
* Do not silence error if target is not defined
* Conditionally import Protocol for type checking only
* Clean up imports
* Add comments
* Align python version linting with mypy and coverage
* Just ignore types in an unused module
* Add comments
* Fix lint
2021-04-02 14:54:40 -04:00
|
|
|
if not isinstance(tree, UnspacedList):
|
|
|
|
|
raise ValueError(f"Error tree {tree} is not an UnspacedList")
|
2015-04-07 19:22:34 -04:00
|
|
|
try:
|
2016-06-24 20:14:14 -04:00
|
|
|
if lazy and not tree.is_dirty():
|
|
|
|
|
continue
|
2016-06-08 20:52:35 -04:00
|
|
|
out = nginxparser.dumps(tree)
|
2016-06-16 20:17:13 -04:00
|
|
|
logger.debug('Writing nginx conf tree to %s:\n%s', filename, out)
|
2020-11-27 12:15:27 -05:00
|
|
|
with io.open(filename, 'w', encoding='utf-8') as _file:
|
2016-06-08 20:52:35 -04:00
|
|
|
_file.write(out)
|
|
|
|
|
|
2015-04-07 19:22:34 -04:00
|
|
|
except IOError:
|
2015-06-11 09:45:41 -04:00
|
|
|
logger.error("Could not open file for writing: %s", filename)
|
2015-04-07 19:22:34 -04:00
|
|
|
|
2022-01-12 19:36:51 -05:00
|
|
|
def parse_server(self, server: UnspacedList) -> Dict[str, Any]:
|
2016-12-05 22:17:04 -05:00
|
|
|
"""Parses a list of server directives, accounting for global address sslishness.
|
|
|
|
|
|
|
|
|
|
:param list server: list of directives in a server block
|
|
|
|
|
:rtype: dict
|
|
|
|
|
"""
|
|
|
|
|
addr_to_ssl = self._build_addr_to_ssl()
|
|
|
|
|
parsed_server = _parse_server_raw(server)
|
|
|
|
|
_apply_global_addr_ssl(addr_to_ssl, parsed_server)
|
|
|
|
|
return parsed_server
|
|
|
|
|
|
2022-01-12 19:36:51 -05:00
|
|
|
def has_ssl_on_directive(self, vhost: obj.VirtualHost) -> bool:
|
2016-09-29 19:16:07 -04:00
|
|
|
"""Does vhost have ssl on for all ports?
|
|
|
|
|
|
2019-11-25 17:30:24 -05:00
|
|
|
:param :class:`~certbot_nginx._internal.obj.VirtualHost` vhost: The vhost in question
|
2016-09-29 19:16:07 -04:00
|
|
|
|
|
|
|
|
:returns: True if 'ssl on' directive is included
|
|
|
|
|
:rtype: bool
|
|
|
|
|
|
|
|
|
|
"""
|
|
|
|
|
server = vhost.raw
|
|
|
|
|
for directive in server:
|
2017-03-24 22:45:53 -04:00
|
|
|
if not directive:
|
2016-09-29 19:16:07 -04:00
|
|
|
continue
|
Lint certbot code on Python 3, and update Pylint to the latest version (#7551)
Part of #7550
This PR makes appropriate corrections to run pylint on Python 3.
Why not keeping the dependencies unchanged and just run pylint on Python 3?
Because the old version of pylint breaks horribly on Python 3 because of unsupported version of astroid.
Why updating pylint + astroid to the latest version ?
Because this version only fixes some internal errors occuring during the lint of Certbot code, and is also ready to run gracefully on Python 3.8.
Why upgrading mypy ?
Because the old version does not support the new version of astroid required to run pylint correctly.
Why not upgrading mypy to its latest version ?
Because this latest version includes a new typshed version, that adds a lot of new type definitions, and brings dozens of new errors on the Certbot codebase. I would like to fix that in a future PR.
That said so, the work has been to find the correct set of new dependency versions, then configure pylint for sane configuration errors in our situation, disable irrelevant lintings errors, then fixing (or ignoring for good reason) the remaining mypy errors.
I also made PyLint and MyPy checks run correctly on Windows.
* Start configuration
* Reconfigure travis
* Suspend a check specific to python 3. Start fixing code.
* Repair call_args
* Fix return + elif lints
* Reconfigure development to run mainly on python3
* Remove incompatible Python 3.4 jobs
* Suspend pylint in some assertions
* Remove pylint in dev
* Take first mypy that supports typed-ast>=1.4.0 to limit the migration path
* Various return + else lint errors
* Find a set of deps that is working with current mypy version
* Update local oldest requirements
* Remove all current pylint errors
* Rebuild letsencrypt-auto
* Update mypy to fix pylint with new astroid version, and fix mypy issues
* Explain type: ignore
* Reconfigure tox, fix none path
* Simplify pinning
* Remove useless directive
* Remove debugging code
* Remove continue
* Update requirements
* Disable unsubscriptable-object check
* Disable one check, enabling two more
* Plug certbot dev version for oldest requirements
* Remove useless disable directives
* Remove useless no-member disable
* Remove no-else-* checks. Use elif in symetric branches.
* Add back assertion
* Add new line
* Remove unused pylint disable
* Remove other pylint disable
2019-12-10 17:12:50 -05:00
|
|
|
if _is_ssl_on_directive(directive):
|
2016-09-29 19:16:07 -04:00
|
|
|
return True
|
|
|
|
|
|
|
|
|
|
return False
|
|
|
|
|
|
2022-01-12 19:36:51 -05:00
|
|
|
def add_server_directives(self, vhost: obj.VirtualHost, directives: List[Any],
|
|
|
|
|
insert_at_top: bool = False) -> None:
|
2018-03-23 19:30:13 -04:00
|
|
|
"""Add directives to the server block identified by vhost.
|
|
|
|
|
|
|
|
|
|
This method modifies vhost to be fully consistent with the new directives.
|
|
|
|
|
|
|
|
|
|
..note :: It's an error to try and add a nonrepeatable directive that already
|
|
|
|
|
exists in the config block with a conflicting value.
|
|
|
|
|
|
|
|
|
|
..todo :: Doesn't match server blocks whose server_name directives are
|
|
|
|
|
split across multiple conf files.
|
|
|
|
|
|
2019-11-25 17:30:24 -05:00
|
|
|
:param :class:`~certbot_nginx._internal.obj.VirtualHost` vhost: The vhost
|
2018-03-23 19:30:13 -04:00
|
|
|
whose information we use to match on
|
|
|
|
|
:param list directives: The directives to add
|
|
|
|
|
:param bool insert_at_top: True if the directives need to be inserted at the top
|
|
|
|
|
of the server block instead of the bottom
|
|
|
|
|
|
|
|
|
|
"""
|
|
|
|
|
self._modify_server_directives(vhost,
|
|
|
|
|
functools.partial(_add_directives, directives, insert_at_top))
|
|
|
|
|
|
2022-01-12 19:36:51 -05:00
|
|
|
def update_or_add_server_directives(self, vhost: obj.VirtualHost, directives: List[Any],
|
|
|
|
|
insert_at_top: bool = False) -> None:
|
2016-09-26 16:13:29 -04:00
|
|
|
"""Add or replace directives in the server block identified by vhost.
|
2015-04-10 14:45:05 -04:00
|
|
|
|
2016-09-26 16:13:29 -04:00
|
|
|
This method modifies vhost to be fully consistent with the new directives.
|
2015-04-28 21:38:28 -04:00
|
|
|
|
2018-03-23 19:30:13 -04:00
|
|
|
..note :: When a directive with the same name already exists in the
|
|
|
|
|
config block, the first instance will be replaced. Otherwise, the directive
|
|
|
|
|
will be appended/prepended to the config block as in add_server_directives.
|
2015-04-10 18:21:25 -04:00
|
|
|
|
|
|
|
|
..todo :: Doesn't match server blocks whose server_name directives are
|
|
|
|
|
split across multiple conf files.
|
|
|
|
|
|
2019-11-25 17:30:24 -05:00
|
|
|
:param :class:`~certbot_nginx._internal.obj.VirtualHost` vhost: The vhost
|
2016-09-26 16:13:29 -04:00
|
|
|
whose information we use to match on
|
2015-04-10 18:21:25 -04:00
|
|
|
:param list directives: The directives to add
|
2018-01-17 11:01:44 -05:00
|
|
|
:param bool insert_at_top: True if the directives need to be inserted at the top
|
|
|
|
|
of the server block instead of the bottom
|
2015-04-10 18:21:25 -04:00
|
|
|
|
|
|
|
|
"""
|
2017-12-07 12:48:54 -05:00
|
|
|
self._modify_server_directives(vhost,
|
2018-03-23 19:30:13 -04:00
|
|
|
functools.partial(_update_or_add_directives, directives, insert_at_top))
|
2017-12-07 12:48:54 -05:00
|
|
|
|
2022-01-12 19:36:51 -05:00
|
|
|
def remove_server_directives(self, vhost: obj.VirtualHost, directive_name: str,
|
|
|
|
|
match_func: Optional[Callable[[Any], bool]] = None) -> None:
|
2017-12-07 12:48:54 -05:00
|
|
|
"""Remove all directives of type directive_name.
|
|
|
|
|
|
2019-11-25 17:30:24 -05:00
|
|
|
:param :class:`~certbot_nginx._internal.obj.VirtualHost` vhost: The vhost
|
2017-12-07 12:48:54 -05:00
|
|
|
to remove directives from
|
|
|
|
|
:param string directive_name: The directive type to remove
|
|
|
|
|
:param callable match_func: Function of the directive that returns true for directives
|
|
|
|
|
to be deleted.
|
|
|
|
|
"""
|
|
|
|
|
self._modify_server_directives(vhost,
|
|
|
|
|
functools.partial(_remove_directives, directive_name, match_func))
|
|
|
|
|
|
2022-01-12 19:36:51 -05:00
|
|
|
def _update_vhost_based_on_new_directives(self, vhost: obj.VirtualHost,
|
|
|
|
|
directives_list: UnspacedList) -> None:
|
2017-12-07 12:48:54 -05:00
|
|
|
new_server = self._get_included_directives(directives_list)
|
|
|
|
|
parsed_server = self.parse_server(new_server)
|
|
|
|
|
vhost.addrs = parsed_server['addrs']
|
|
|
|
|
vhost.ssl = parsed_server['ssl']
|
|
|
|
|
vhost.names = parsed_server['names']
|
|
|
|
|
vhost.raw = new_server
|
|
|
|
|
|
2022-01-12 19:36:51 -05:00
|
|
|
def _modify_server_directives(self, vhost: obj.VirtualHost,
|
|
|
|
|
block_func: Callable[[List[Any]], None]) -> None:
|
2016-09-26 16:13:29 -04:00
|
|
|
filename = vhost.filep
|
2016-01-01 19:35:57 -05:00
|
|
|
try:
|
2016-09-26 16:13:29 -04:00
|
|
|
result = self.parsed[filename]
|
|
|
|
|
for index in vhost.path:
|
|
|
|
|
result = result[index]
|
|
|
|
|
if not isinstance(result, list) or len(result) != 2:
|
|
|
|
|
raise errors.MisconfigurationError("Not a server block.")
|
|
|
|
|
result = result[1]
|
2017-12-07 12:48:54 -05:00
|
|
|
block_func(result)
|
|
|
|
|
|
|
|
|
|
self._update_vhost_based_on_new_directives(vhost, result)
|
2016-01-01 19:35:57 -05:00
|
|
|
except errors.MisconfigurationError as err:
|
2017-03-17 16:10:02 -04:00
|
|
|
raise errors.MisconfigurationError("Problem in %s: %s" % (filename, str(err)))
|
2015-05-08 20:17:24 -04:00
|
|
|
|
2021-02-26 16:43:22 -05:00
|
|
|
def duplicate_vhost(self, vhost_template: obj.VirtualHost,
|
|
|
|
|
remove_singleton_listen_params: bool = False,
|
2022-01-12 19:36:51 -05:00
|
|
|
only_directives: Optional[List[Any]] = None) -> obj.VirtualHost:
|
2017-12-07 12:48:54 -05:00
|
|
|
"""Duplicate the vhost in the configuration files.
|
2017-12-06 20:45:20 -05:00
|
|
|
|
2019-11-25 17:30:24 -05:00
|
|
|
:param :class:`~certbot_nginx._internal.obj.VirtualHost` vhost_template: The vhost
|
2017-12-06 20:45:20 -05:00
|
|
|
whose information we copy
|
2018-03-27 18:11:39 -04:00
|
|
|
:param bool remove_singleton_listen_params: If we should remove parameters
|
|
|
|
|
from listen directives in the block that can only be used once per address
|
2017-12-07 12:48:54 -05:00
|
|
|
:param list only_directives: If it exists, only duplicate the named directives. Only
|
|
|
|
|
looks at first level of depth; does not expand includes.
|
2017-12-06 20:45:20 -05:00
|
|
|
|
|
|
|
|
:returns: A vhost object for the newly created vhost
|
2019-11-25 17:30:24 -05:00
|
|
|
:rtype: :class:`~certbot_nginx._internal.obj.VirtualHost`
|
2017-12-06 20:45:20 -05:00
|
|
|
"""
|
|
|
|
|
# TODO: https://github.com/certbot/certbot/issues/5185
|
|
|
|
|
# put it in the same file as the template, at the same level
|
2017-12-07 12:48:54 -05:00
|
|
|
new_vhost = copy.deepcopy(vhost_template)
|
|
|
|
|
|
2017-12-06 20:45:20 -05:00
|
|
|
enclosing_block = self.parsed[vhost_template.filep]
|
|
|
|
|
for index in vhost_template.path[:-1]:
|
|
|
|
|
enclosing_block = enclosing_block[index]
|
|
|
|
|
raw_in_parsed = copy.deepcopy(enclosing_block[vhost_template.path[-1]])
|
2017-12-07 12:48:54 -05:00
|
|
|
|
|
|
|
|
if only_directives is not None:
|
|
|
|
|
new_directives = nginxparser.UnspacedList([])
|
|
|
|
|
for directive in raw_in_parsed[1]:
|
2018-05-14 12:33:30 -04:00
|
|
|
if directive and directive[0] in only_directives:
|
2017-12-07 12:48:54 -05:00
|
|
|
new_directives.append(directive)
|
|
|
|
|
raw_in_parsed[1] = new_directives
|
|
|
|
|
|
|
|
|
|
self._update_vhost_based_on_new_directives(new_vhost, new_directives)
|
|
|
|
|
|
|
|
|
|
enclosing_block.append(raw_in_parsed)
|
|
|
|
|
new_vhost.path[-1] = len(enclosing_block) - 1
|
2018-03-27 18:11:39 -04:00
|
|
|
if remove_singleton_listen_params:
|
2017-12-07 12:48:54 -05:00
|
|
|
for addr in new_vhost.addrs:
|
|
|
|
|
addr.default = False
|
2018-03-27 18:11:39 -04:00
|
|
|
addr.ipv6only = False
|
2017-12-07 12:48:54 -05:00
|
|
|
for directive in enclosing_block[new_vhost.path[-1]][1]:
|
2019-04-02 16:48:22 -04:00
|
|
|
if directive and directive[0] == 'listen':
|
2018-09-12 19:38:37 -04:00
|
|
|
# Exclude one-time use parameters which will cause an error if repeated.
|
|
|
|
|
# https://nginx.org/en/docs/http/ngx_http_core_module.html#listen
|
2020-04-13 13:41:39 -04:00
|
|
|
exclude = {'default_server', 'default', 'setfib', 'fastopen', 'backlog',
|
2018-09-12 19:38:37 -04:00
|
|
|
'rcvbuf', 'sndbuf', 'accept_filter', 'deferred', 'bind',
|
2020-04-13 13:41:39 -04:00
|
|
|
'ipv6only', 'reuseport', 'so_keepalive'}
|
2018-09-12 19:38:37 -04:00
|
|
|
|
|
|
|
|
for param in exclude:
|
|
|
|
|
# See: github.com/certbot/certbot/pull/6223#pullrequestreview-143019225
|
|
|
|
|
keys = [x.split('=')[0] for x in directive]
|
|
|
|
|
if param in keys:
|
|
|
|
|
del directive[keys.index(param)]
|
2017-12-06 20:45:20 -05:00
|
|
|
return new_vhost
|
|
|
|
|
|
2018-03-16 18:27:39 -04:00
|
|
|
|
2022-01-12 19:36:51 -05:00
|
|
|
def _parse_ssl_options(ssl_options: Optional[str]) -> List[UnspacedList]:
|
2017-05-02 20:56:56 -04:00
|
|
|
if ssl_options is not None:
|
|
|
|
|
try:
|
2018-10-31 02:45:30 -04:00
|
|
|
with io.open(ssl_options, "r", encoding="utf-8") as _file:
|
2017-05-02 20:56:56 -04:00
|
|
|
return nginxparser.load(_file)
|
|
|
|
|
except IOError:
|
2018-10-31 21:05:00 -04:00
|
|
|
logger.warning("Missing NGINX TLS options file: %s", ssl_options)
|
2018-10-31 02:45:30 -04:00
|
|
|
except UnicodeDecodeError:
|
2020-02-23 11:46:41 -05:00
|
|
|
logger.warning("Could not read file: %s due to invalid character. "
|
|
|
|
|
"Only UTF-8 encoding is supported.", ssl_options)
|
2017-05-02 20:56:56 -04:00
|
|
|
except pyparsing.ParseBaseException as err:
|
Command-line UX overhaul (#8852)
Streamline and reorganize Certbot's CLI output.
This change is a substantial command-line UX overhaul,
based on previous user research. The main goal was to streamline
and clarify output. To see more verbose output, use the -v or -vv flags.
---
* nginx,apache: CLI logging changes
- Add "Successfully deployed ..." message using display_util
- Remove IReporter usage and replace with display_util
- Standardize "... could not find a VirtualHost ..." error
This changes also bumps the version of certbot required by certbot-nginx
and certbot-apache to take use of the new display_util function.
* fix certbot_compatibility_test
since the http plugins now require IDisplay, we need to inject it
* fix dependency version on certbot
* use better asserts
* try fix oldest deps
because certbot 1.10.0 depends on acme>=1.8.0, we need to use
acme==1.8.0 in the -oldest tests
* cli: redesign output of new certificate reporting
Changes the output of run, certonly and certonly --csr. No longer uses
IReporter.
* cli: redesign output of failed authz reporting
* fix problem sorting to be stable between py2 & 3
* add some catch-all error text
* cli: dont use IReporter for EFF donation prompt
* add per-authenticator hints
* pass achalls to auth_hint, write some tests
* exclude static auth hints from coverage
* dont call auth_hint unless derived from .Plugin
* dns fallback hint: dont assume --dns-blah works
--dns-blah won't work for third-party plugins, they need to be specified
using --authenticator dns-blah.
* add code comments about the auth_hint interface
* renew: don't restart the installer for dry-runs
Prevents Certbot from superfluously invoking the installer restart
during dry-run renewals. (This does not affect authenticator restarts).
Additionally removes some CLI output that was reporting the fullchain
path of the renewed certificate.
* update CHANGELOG.md
* cli: redesign output when cert installation failed
- Display a message when certificate installation begins.
- Don't use IReporter, just log errors immediately if restart/rollback
fails.
- Prompt the user with a command to retry the installation process once
they have fixed any underlying problems.
* vary by preconfigured_renewal
and move expiry date to be above the renewal advice
* update code comment
Co-authored-by: ohemorange <ebportnoy@gmail.com>
* update code comment
Co-authored-by: ohemorange <ebportnoy@gmail.com>
* fix lint
* derve cert name from cert_path, if possible
* fix type annotation
* text change in nginx hint
Co-authored-by: ohemorange <ebportnoy@gmail.com>
* print message when restarting server after renewal
* log: print "advice" when exiting with an error
When running in non-quiet mode.
* try fix -oldest lock_test.py
* fix docstring
* s/Restarting/Reloading/ when notifying the user
* fix test name
Co-authored-by: ohemorange <ebportnoy@gmail.com>
* type annotations
* s/using the {} plugin/installer: {}/
* copy: avoid "plugin" where possible
* link to user guide#automated-renewals
when not running with --preconfigured-renewal
* cli: reduce default logging verbosity
* fix lock_test: -vv is needed to see logger.debug
* Change comment in log.py to match the change to default verbosity
* Audit and adjust logging levels in apache module
* Audit and adjust logging levels in nginx module
* Audit, adjust logging levels, and improve logging calls in certbot module
* Fix tests to mock correct methods and classes
* typo in non-preconfigured-renewal message
Co-authored-by: ohemorange <ebportnoy@gmail.com>
* fix test
* revert acme version bump
* catch up to python3 changes
* Revert "revert acme version bump"
This reverts commit fa83d6a51cf8d0e7e17da53c6b751ad12945d0cf.
* Change ocsp check error to warning since it's non-fatal
* Update storage_test in parallel with last change
* get rid of leading newline on "Deploying [...]"
* shrink renewal and installation success messages
* print logfile rather than logdir in exit handler
* Decrease logging level to info for idempotent operation where enhancement is already set
* Display cert not yet due for renewal message when renewing and no other action will be taken, and change cert to certificate
* also write to logger so it goes in the log file
* Don't double write to log file; fix main test
* cli: remove trailing newline on new cert reporting
* ignore type error
* revert accidental changes to dependencies
* Pass tests in any timezone by using utcfromtimestamp
* Add changelog entry
* fix nits
* Improve wording of try again message
* minor wording change to changelog
* hooks: send hook stdout to CLI stdout
includes both --manual and --{pre,post,renew} hooks
* update docstrings and remove TODO
* add a pending deprecation on execute_command
* add test coverage for both
* update deprecation text
Co-authored-by: ohemorange <ebportnoy@gmail.com>
Co-authored-by: Alex Zorin <alex@zorin.id.au>
Co-authored-by: alexzorin <alex@zor.io>
2021-05-24 20:47:39 -04:00
|
|
|
logger.warning("Could not parse file: %s due to %s", ssl_options, err)
|
2022-01-12 19:36:51 -05:00
|
|
|
return UnspacedList([])
|
|
|
|
|
|
2015-03-23 13:53:44 -04:00
|
|
|
|
2022-01-12 19:36:51 -05:00
|
|
|
def _do_for_subarray(entry: List[Any], condition: Callable[[List[Any]], bool],
|
|
|
|
|
func: Callable[[List[Any], List[int]], None],
|
|
|
|
|
path: Optional[List[int]] = None) -> None:
|
2015-04-08 15:52:33 -04:00
|
|
|
"""Executes a function for a subarray of a nested array if it matches
|
|
|
|
|
the given condition.
|
|
|
|
|
|
|
|
|
|
:param list entry: The list to iterate over
|
|
|
|
|
:param function condition: Returns true iff func should be executed on item
|
|
|
|
|
:param function func: The function to call for each matching item
|
|
|
|
|
|
|
|
|
|
"""
|
2016-09-26 16:13:29 -04:00
|
|
|
if path is None:
|
|
|
|
|
path = []
|
2015-04-17 20:05:00 -04:00
|
|
|
if isinstance(entry, list):
|
2015-04-14 01:57:06 -04:00
|
|
|
if condition(entry):
|
2016-09-26 16:13:29 -04:00
|
|
|
func(entry, path)
|
2015-04-14 01:57:06 -04:00
|
|
|
else:
|
2016-09-26 16:13:29 -04:00
|
|
|
for index, item in enumerate(entry):
|
|
|
|
|
_do_for_subarray(item, condition, func, path + [index])
|
2015-04-09 18:51:58 -04:00
|
|
|
|
|
|
|
|
|
2022-01-12 19:36:51 -05:00
|
|
|
def get_best_match(target_name: str, names: Iterable[str]) -> Tuple[Optional[str], Optional[str]]:
|
2015-04-09 18:51:58 -04:00
|
|
|
"""Finds the best match for target_name out of names using the Nginx
|
|
|
|
|
name-matching rules (exact > longest wildcard starting with * >
|
|
|
|
|
longest wildcard ending with * > regex).
|
|
|
|
|
|
|
|
|
|
:param str target_name: The name to match
|
2015-04-10 14:45:05 -04:00
|
|
|
:param set names: The candidate server names
|
2015-04-09 18:51:58 -04:00
|
|
|
:returns: Tuple of (type of match, the name that matched)
|
|
|
|
|
:rtype: tuple
|
|
|
|
|
|
|
|
|
|
"""
|
|
|
|
|
exact = []
|
|
|
|
|
wildcard_start = []
|
|
|
|
|
wildcard_end = []
|
|
|
|
|
regex = []
|
|
|
|
|
|
|
|
|
|
for name in names:
|
|
|
|
|
if _exact_match(target_name, name):
|
|
|
|
|
exact.append(name)
|
|
|
|
|
elif _wildcard_match(target_name, name, True):
|
|
|
|
|
wildcard_start.append(name)
|
|
|
|
|
elif _wildcard_match(target_name, name, False):
|
|
|
|
|
wildcard_end.append(name)
|
|
|
|
|
elif _regex_match(target_name, name):
|
|
|
|
|
regex.append(name)
|
|
|
|
|
|
2018-05-14 12:33:30 -04:00
|
|
|
if exact:
|
2015-04-09 18:51:58 -04:00
|
|
|
# There can be more than one exact match; e.g. eff.org, .eff.org
|
2015-04-17 20:05:00 -04:00
|
|
|
match = min(exact, key=len)
|
2022-01-12 19:36:51 -05:00
|
|
|
return 'exact', match
|
2018-05-14 12:33:30 -04:00
|
|
|
if wildcard_start:
|
2015-04-09 18:51:58 -04:00
|
|
|
# Return the longest wildcard
|
2015-04-17 20:05:00 -04:00
|
|
|
match = max(wildcard_start, key=len)
|
2022-01-12 19:36:51 -05:00
|
|
|
return 'wildcard_start', match
|
2018-05-14 12:33:30 -04:00
|
|
|
if wildcard_end:
|
2015-04-09 18:51:58 -04:00
|
|
|
# Return the longest wildcard
|
2015-04-17 20:05:00 -04:00
|
|
|
match = max(wildcard_end, key=len)
|
2022-01-12 19:36:51 -05:00
|
|
|
return 'wildcard_end', match
|
2018-05-14 12:33:30 -04:00
|
|
|
if regex:
|
2015-04-09 18:51:58 -04:00
|
|
|
# Just return the first one for now
|
|
|
|
|
match = regex[0]
|
2022-01-12 19:36:51 -05:00
|
|
|
return 'regex', match
|
2015-04-09 18:51:58 -04:00
|
|
|
|
2022-01-12 19:36:51 -05:00
|
|
|
return None, None
|
2015-04-09 18:51:58 -04:00
|
|
|
|
|
|
|
|
|
2022-01-12 19:36:51 -05:00
|
|
|
def _exact_match(target_name: str, name: str) -> bool:
|
2020-09-08 17:14:54 -04:00
|
|
|
target_lower = target_name.lower()
|
|
|
|
|
return name.lower() in (target_lower, '.' + target_lower)
|
2015-04-09 18:51:58 -04:00
|
|
|
|
|
|
|
|
|
2022-01-12 19:36:51 -05:00
|
|
|
def _wildcard_match(target_name: str, name: str, start: bool) -> bool:
|
2015-04-14 01:57:06 -04:00
|
|
|
# Degenerate case
|
|
|
|
|
if name == '*':
|
|
|
|
|
return True
|
|
|
|
|
|
2015-04-09 18:51:58 -04:00
|
|
|
parts = target_name.split('.')
|
|
|
|
|
match_parts = name.split('.')
|
|
|
|
|
|
|
|
|
|
# If the domain ends in a wildcard, do the match procedure in reverse
|
|
|
|
|
if not start:
|
|
|
|
|
parts.reverse()
|
|
|
|
|
match_parts.reverse()
|
|
|
|
|
|
2015-04-14 01:57:06 -04:00
|
|
|
# The first part must be a wildcard or blank, e.g. '.eff.org'
|
|
|
|
|
first = match_parts.pop(0)
|
Lint certbot code on Python 3, and update Pylint to the latest version (#7551)
Part of #7550
This PR makes appropriate corrections to run pylint on Python 3.
Why not keeping the dependencies unchanged and just run pylint on Python 3?
Because the old version of pylint breaks horribly on Python 3 because of unsupported version of astroid.
Why updating pylint + astroid to the latest version ?
Because this version only fixes some internal errors occuring during the lint of Certbot code, and is also ready to run gracefully on Python 3.8.
Why upgrading mypy ?
Because the old version does not support the new version of astroid required to run pylint correctly.
Why not upgrading mypy to its latest version ?
Because this latest version includes a new typshed version, that adds a lot of new type definitions, and brings dozens of new errors on the Certbot codebase. I would like to fix that in a future PR.
That said so, the work has been to find the correct set of new dependency versions, then configure pylint for sane configuration errors in our situation, disable irrelevant lintings errors, then fixing (or ignoring for good reason) the remaining mypy errors.
I also made PyLint and MyPy checks run correctly on Windows.
* Start configuration
* Reconfigure travis
* Suspend a check specific to python 3. Start fixing code.
* Repair call_args
* Fix return + elif lints
* Reconfigure development to run mainly on python3
* Remove incompatible Python 3.4 jobs
* Suspend pylint in some assertions
* Remove pylint in dev
* Take first mypy that supports typed-ast>=1.4.0 to limit the migration path
* Various return + else lint errors
* Find a set of deps that is working with current mypy version
* Update local oldest requirements
* Remove all current pylint errors
* Rebuild letsencrypt-auto
* Update mypy to fix pylint with new astroid version, and fix mypy issues
* Explain type: ignore
* Reconfigure tox, fix none path
* Simplify pinning
* Remove useless directive
* Remove debugging code
* Remove continue
* Update requirements
* Disable unsubscriptable-object check
* Disable one check, enabling two more
* Plug certbot dev version for oldest requirements
* Remove useless disable directives
* Remove useless no-member disable
* Remove no-else-* checks. Use elif in symetric branches.
* Add back assertion
* Add new line
* Remove unused pylint disable
* Remove other pylint disable
2019-12-10 17:12:50 -05:00
|
|
|
if first not in ('*', ''):
|
2015-04-09 18:51:58 -04:00
|
|
|
return False
|
|
|
|
|
|
2020-09-08 17:14:54 -04:00
|
|
|
target_name_lower = '.'.join(parts).lower()
|
|
|
|
|
name_lower = '.'.join(match_parts).lower()
|
2015-04-09 18:51:58 -04:00
|
|
|
|
|
|
|
|
# Ex: www.eff.org matches *.eff.org, eff.org does not match *.eff.org
|
2020-09-08 17:14:54 -04:00
|
|
|
return target_name_lower.endswith('.' + name_lower)
|
2015-04-09 18:51:58 -04:00
|
|
|
|
|
|
|
|
|
2022-01-12 19:36:51 -05:00
|
|
|
def _regex_match(target_name: str, name: str) -> bool:
|
2015-04-09 18:51:58 -04:00
|
|
|
# Must start with a tilde
|
2015-04-14 01:57:06 -04:00
|
|
|
if len(name) < 2 or name[0] != '~':
|
2015-04-09 18:51:58 -04:00
|
|
|
return False
|
|
|
|
|
|
|
|
|
|
# After tilde is a perl-compatible regex
|
|
|
|
|
try:
|
|
|
|
|
regex = re.compile(name[1:])
|
2022-01-12 19:36:51 -05:00
|
|
|
return bool(re.match(regex, target_name))
|
2015-11-19 13:04:37 -05:00
|
|
|
except re.error: # pragma: no cover
|
2015-04-09 18:51:58 -04:00
|
|
|
# perl-compatible regexes are sometimes not recognized by python
|
|
|
|
|
return False
|
2015-04-17 20:05:00 -04:00
|
|
|
|
|
|
|
|
|
2022-01-12 19:36:51 -05:00
|
|
|
def _is_include_directive(entry: Any) -> bool:
|
2015-04-17 20:05:00 -04:00
|
|
|
"""Checks if an nginx parsed entry is an 'include' directive.
|
|
|
|
|
|
|
|
|
|
:param list entry: the parsed entry
|
|
|
|
|
:returns: Whether it's an 'include' directive
|
|
|
|
|
:rtype: bool
|
|
|
|
|
|
|
|
|
|
"""
|
|
|
|
|
return (isinstance(entry, list) and
|
2015-11-07 11:21:47 -05:00
|
|
|
len(entry) == 2 and entry[0] == 'include' and
|
2021-02-09 14:43:15 -05:00
|
|
|
isinstance(entry[1], str))
|
2015-04-17 20:05:00 -04:00
|
|
|
|
2022-01-12 19:36:51 -05:00
|
|
|
|
|
|
|
|
def _is_ssl_on_directive(entry: Any) -> bool:
|
2017-03-24 22:45:53 -04:00
|
|
|
"""Checks if an nginx parsed entry is an 'ssl on' directive.
|
2015-04-17 20:05:00 -04:00
|
|
|
|
2017-03-24 22:45:53 -04:00
|
|
|
:param list entry: the parsed entry
|
|
|
|
|
:returns: Whether it's an 'ssl on' directive
|
|
|
|
|
:rtype: bool
|
2015-04-17 20:05:00 -04:00
|
|
|
|
|
|
|
|
"""
|
2017-03-24 22:45:53 -04:00
|
|
|
return (isinstance(entry, list) and
|
|
|
|
|
len(entry) == 2 and entry[0] == 'ssl' and
|
|
|
|
|
entry[1] == 'on')
|
2015-04-17 20:05:00 -04:00
|
|
|
|
2022-01-12 19:36:51 -05:00
|
|
|
|
|
|
|
|
def _add_directives(directives: List[Any], insert_at_top: bool,
|
|
|
|
|
block: UnspacedList) -> None:
|
2018-03-23 19:30:13 -04:00
|
|
|
"""Adds directives to a config block."""
|
|
|
|
|
for directive in directives:
|
|
|
|
|
_add_directive(block, directive, insert_at_top)
|
|
|
|
|
if block and '\n' not in block[-1]: # could be " \n " or ["\n"] !
|
|
|
|
|
block.append(nginxparser.UnspacedList('\n'))
|
2015-05-08 20:17:24 -04:00
|
|
|
|
2022-01-12 19:36:51 -05:00
|
|
|
|
|
|
|
|
def _update_or_add_directives(directives: List[Any], insert_at_top: bool,
|
|
|
|
|
block: UnspacedList) -> None:
|
2018-03-23 19:30:13 -04:00
|
|
|
"""Adds or replaces directives in a config block."""
|
2015-10-11 13:20:08 -04:00
|
|
|
for directive in directives:
|
2018-03-23 19:30:13 -04:00
|
|
|
_update_or_add_directive(block, directive, insert_at_top)
|
2016-08-16 19:41:23 -04:00
|
|
|
if block and '\n' not in block[-1]: # could be " \n " or ["\n"] !
|
2016-08-05 18:36:24 -04:00
|
|
|
block.append(nginxparser.UnspacedList('\n'))
|
2016-07-21 16:26:57 -04:00
|
|
|
|
2016-07-18 18:25:09 -04:00
|
|
|
|
2017-05-02 20:56:56 -04:00
|
|
|
INCLUDE = 'include'
|
2020-04-13 13:41:39 -04:00
|
|
|
REPEATABLE_DIRECTIVES = {'server_name', 'listen', INCLUDE, 'rewrite', 'add_header'}
|
2016-08-16 20:45:43 -04:00
|
|
|
COMMENT = ' managed by Certbot'
|
|
|
|
|
COMMENT_BLOCK = [' ', '#', COMMENT]
|
2016-07-18 21:12:44 -04:00
|
|
|
|
2022-01-12 19:36:51 -05:00
|
|
|
|
|
|
|
|
def comment_directive(block: UnspacedList, location: int) -> None:
|
2017-12-07 12:48:54 -05:00
|
|
|
"""Add a ``#managed by Certbot`` comment to the end of the line at location.
|
|
|
|
|
|
|
|
|
|
:param list block: The block containing the directive to be commented
|
|
|
|
|
:param int location: The location within ``block`` of the directive to be commented
|
|
|
|
|
"""
|
2016-08-16 21:30:45 -04:00
|
|
|
next_entry = block[location + 1] if location + 1 < len(block) else None
|
|
|
|
|
if isinstance(next_entry, list) and next_entry:
|
2016-08-18 16:56:15 -04:00
|
|
|
if len(next_entry) >= 2 and next_entry[-2] == "#" and COMMENT in next_entry[-1]:
|
2016-07-18 21:19:14 -04:00
|
|
|
return
|
Lint certbot code on Python 3, and update Pylint to the latest version (#7551)
Part of #7550
This PR makes appropriate corrections to run pylint on Python 3.
Why not keeping the dependencies unchanged and just run pylint on Python 3?
Because the old version of pylint breaks horribly on Python 3 because of unsupported version of astroid.
Why updating pylint + astroid to the latest version ?
Because this version only fixes some internal errors occuring during the lint of Certbot code, and is also ready to run gracefully on Python 3.8.
Why upgrading mypy ?
Because the old version does not support the new version of astroid required to run pylint correctly.
Why not upgrading mypy to its latest version ?
Because this latest version includes a new typshed version, that adds a lot of new type definitions, and brings dozens of new errors on the Certbot codebase. I would like to fix that in a future PR.
That said so, the work has been to find the correct set of new dependency versions, then configure pylint for sane configuration errors in our situation, disable irrelevant lintings errors, then fixing (or ignoring for good reason) the remaining mypy errors.
I also made PyLint and MyPy checks run correctly on Windows.
* Start configuration
* Reconfigure travis
* Suspend a check specific to python 3. Start fixing code.
* Repair call_args
* Fix return + elif lints
* Reconfigure development to run mainly on python3
* Remove incompatible Python 3.4 jobs
* Suspend pylint in some assertions
* Remove pylint in dev
* Take first mypy that supports typed-ast>=1.4.0 to limit the migration path
* Various return + else lint errors
* Find a set of deps that is working with current mypy version
* Update local oldest requirements
* Remove all current pylint errors
* Rebuild letsencrypt-auto
* Update mypy to fix pylint with new astroid version, and fix mypy issues
* Explain type: ignore
* Reconfigure tox, fix none path
* Simplify pinning
* Remove useless directive
* Remove debugging code
* Remove continue
* Update requirements
* Disable unsubscriptable-object check
* Disable one check, enabling two more
* Plug certbot dev version for oldest requirements
* Remove useless disable directives
* Remove useless no-member disable
* Remove no-else-* checks. Use elif in symetric branches.
* Add back assertion
* Add new line
* Remove unused pylint disable
* Remove other pylint disable
2019-12-10 17:12:50 -05:00
|
|
|
if isinstance(next_entry, nginxparser.UnspacedList):
|
2016-08-16 21:30:45 -04:00
|
|
|
next_entry = next_entry.spaced[0]
|
|
|
|
|
else:
|
|
|
|
|
next_entry = next_entry[0]
|
|
|
|
|
|
2016-08-16 20:45:43 -04:00
|
|
|
block.insert(location + 1, COMMENT_BLOCK[:])
|
2016-08-16 21:30:45 -04:00
|
|
|
if next_entry is not None and "\n" not in next_entry:
|
2016-07-18 21:19:14 -04:00
|
|
|
block.insert(location + 2, '\n')
|
2016-07-18 18:25:09 -04:00
|
|
|
|
2022-01-12 19:36:51 -05:00
|
|
|
|
|
|
|
|
def _comment_out_directive(block: UnspacedList, location: int, include_location: str) -> None:
|
2017-05-02 20:56:56 -04:00
|
|
|
"""Comment out the line at location, with a note of explanation."""
|
|
|
|
|
comment_message = ' duplicated in {0}'.format(include_location)
|
|
|
|
|
# add the end comment
|
|
|
|
|
# create a dumpable object out of block[location] (so it includes the ;)
|
|
|
|
|
directive = block[location]
|
2022-01-12 19:36:51 -05:00
|
|
|
new_dir_block = nginxparser.UnspacedList([]) # just a wrapper
|
2017-05-02 20:56:56 -04:00
|
|
|
new_dir_block.append(directive)
|
|
|
|
|
dumped = nginxparser.dumps(new_dir_block)
|
2022-01-12 19:36:51 -05:00
|
|
|
commented = dumped + ' #' + comment_message # add the comment directly to the one-line string
|
|
|
|
|
new_dir = nginxparser.loads(commented) # reload into UnspacedList
|
2017-05-02 20:56:56 -04:00
|
|
|
|
|
|
|
|
# add the beginning comment
|
|
|
|
|
insert_location = 0
|
2022-01-12 19:36:51 -05:00
|
|
|
if new_dir[0].spaced[0] != new_dir[0][0]: # if there's whitespace at the beginning
|
2017-05-02 20:56:56 -04:00
|
|
|
insert_location = 1
|
2022-01-12 19:36:51 -05:00
|
|
|
new_dir[0].spaced.insert(insert_location, "# ") # comment out the line
|
|
|
|
|
new_dir[0].spaced.append(";") # directly add in the ;, because now dumping won't work properly
|
2017-05-02 20:56:56 -04:00
|
|
|
dumped = nginxparser.dumps(new_dir)
|
2022-01-12 19:36:51 -05:00
|
|
|
new_dir = nginxparser.loads(dumped) # reload into an UnspacedList
|
2017-05-02 20:56:56 -04:00
|
|
|
|
|
|
|
|
block[location] = new_dir[0] # set the now-single-line-comment directive back in place
|
2016-01-01 19:35:57 -05:00
|
|
|
|
2022-01-12 19:36:51 -05:00
|
|
|
|
|
|
|
|
def _find_location(block: UnspacedList, directive_name: str,
|
|
|
|
|
match_func: Optional[Callable[[Any], bool]] = None) -> Optional[int]:
|
2017-12-07 12:48:54 -05:00
|
|
|
"""Finds the index of the first instance of directive_name in block.
|
|
|
|
|
If no line exists, use None."""
|
2022-01-12 19:36:51 -05:00
|
|
|
return next((index for index, line in enumerate(block) if (
|
|
|
|
|
line and line[0] == directive_name and (match_func is None or match_func(line)))), None)
|
|
|
|
|
|
2017-12-07 12:48:54 -05:00
|
|
|
|
2022-01-12 19:36:51 -05:00
|
|
|
def _is_whitespace_or_comment(directive: Sequence[Any]) -> bool:
|
2018-03-23 19:30:13 -04:00
|
|
|
"""Is this directive either a whitespace or comment directive?"""
|
|
|
|
|
return len(directive) == 0 or directive[0] == '#'
|
2016-01-01 19:35:57 -05:00
|
|
|
|
2022-01-12 19:36:51 -05:00
|
|
|
|
|
|
|
|
def _add_directive(block: UnspacedList, directive: Sequence[Any], insert_at_top: bool) -> None:
|
2018-03-23 19:30:13 -04:00
|
|
|
if not isinstance(directive, nginxparser.UnspacedList):
|
|
|
|
|
directive = nginxparser.UnspacedList(directive)
|
|
|
|
|
if _is_whitespace_or_comment(directive):
|
2016-07-18 18:25:09 -04:00
|
|
|
# whitespace or comment
|
2016-01-21 19:08:38 -05:00
|
|
|
block.append(directive)
|
|
|
|
|
return
|
|
|
|
|
|
2017-12-07 12:48:54 -05:00
|
|
|
location = _find_location(block, directive[0])
|
2017-05-02 20:56:56 -04:00
|
|
|
|
2018-01-17 11:01:44 -05:00
|
|
|
# Append or prepend directive. Fail if the name is not a repeatable directive name,
|
2017-07-26 16:57:25 -04:00
|
|
|
# and there is already a copy of that directive with a different value
|
|
|
|
|
# in the config file.
|
|
|
|
|
|
|
|
|
|
# handle flat include files
|
|
|
|
|
|
|
|
|
|
directive_name = directive[0]
|
2022-01-12 19:36:51 -05:00
|
|
|
|
|
|
|
|
def can_append(loc: Optional[int], dir_name: str) -> bool:
|
2017-07-26 16:57:25 -04:00
|
|
|
""" Can we append this directive to the block? """
|
2021-02-09 14:43:15 -05:00
|
|
|
return loc is None or (isinstance(dir_name, str)
|
2022-01-12 19:36:51 -05:00
|
|
|
and dir_name in REPEATABLE_DIRECTIVES)
|
2017-07-26 16:57:25 -04:00
|
|
|
|
|
|
|
|
err_fmt = 'tried to insert directive "{0}" but found conflicting "{1}".'
|
|
|
|
|
|
|
|
|
|
# Give a better error message about the specific directive than Nginx's "fail to restart"
|
|
|
|
|
if directive_name == INCLUDE:
|
|
|
|
|
# in theory, we might want to do this recursively, but in practice, that's really not
|
|
|
|
|
# necessary because we know what file we're talking about (and if we don't recurse, we
|
|
|
|
|
# just give a worse error message)
|
|
|
|
|
included_directives = _parse_ssl_options(directive[1])
|
|
|
|
|
|
|
|
|
|
for included_directive in included_directives:
|
2017-12-07 12:48:54 -05:00
|
|
|
included_dir_loc = _find_location(block, included_directive[0])
|
2017-07-26 16:57:25 -04:00
|
|
|
included_dir_name = included_directive[0]
|
Lint certbot code on Python 3, and update Pylint to the latest version (#7551)
Part of #7550
This PR makes appropriate corrections to run pylint on Python 3.
Why not keeping the dependencies unchanged and just run pylint on Python 3?
Because the old version of pylint breaks horribly on Python 3 because of unsupported version of astroid.
Why updating pylint + astroid to the latest version ?
Because this version only fixes some internal errors occuring during the lint of Certbot code, and is also ready to run gracefully on Python 3.8.
Why upgrading mypy ?
Because the old version does not support the new version of astroid required to run pylint correctly.
Why not upgrading mypy to its latest version ?
Because this latest version includes a new typshed version, that adds a lot of new type definitions, and brings dozens of new errors on the Certbot codebase. I would like to fix that in a future PR.
That said so, the work has been to find the correct set of new dependency versions, then configure pylint for sane configuration errors in our situation, disable irrelevant lintings errors, then fixing (or ignoring for good reason) the remaining mypy errors.
I also made PyLint and MyPy checks run correctly on Windows.
* Start configuration
* Reconfigure travis
* Suspend a check specific to python 3. Start fixing code.
* Repair call_args
* Fix return + elif lints
* Reconfigure development to run mainly on python3
* Remove incompatible Python 3.4 jobs
* Suspend pylint in some assertions
* Remove pylint in dev
* Take first mypy that supports typed-ast>=1.4.0 to limit the migration path
* Various return + else lint errors
* Find a set of deps that is working with current mypy version
* Update local oldest requirements
* Remove all current pylint errors
* Rebuild letsencrypt-auto
* Update mypy to fix pylint with new astroid version, and fix mypy issues
* Explain type: ignore
* Reconfigure tox, fix none path
* Simplify pinning
* Remove useless directive
* Remove debugging code
* Remove continue
* Update requirements
* Disable unsubscriptable-object check
* Disable one check, enabling two more
* Plug certbot dev version for oldest requirements
* Remove useless disable directives
* Remove useless no-member disable
* Remove no-else-* checks. Use elif in symetric branches.
* Add back assertion
* Add new line
* Remove unused pylint disable
* Remove other pylint disable
2019-12-10 17:12:50 -05:00
|
|
|
if (not _is_whitespace_or_comment(included_directive)
|
|
|
|
|
and not can_append(included_dir_loc, included_dir_name)):
|
2022-01-12 19:36:51 -05:00
|
|
|
|
|
|
|
|
# By construction of can_append(), included_dir_loc cannot be None at that point
|
|
|
|
|
resolved_included_dir_loc = cast(int, included_dir_loc)
|
|
|
|
|
|
|
|
|
|
if block[resolved_included_dir_loc] != included_directive:
|
|
|
|
|
raise errors.MisconfigurationError(err_fmt.format(
|
|
|
|
|
included_directive, block[resolved_included_dir_loc]))
|
|
|
|
|
_comment_out_directive(block, resolved_included_dir_loc, directive[1])
|
2017-07-26 16:57:25 -04:00
|
|
|
|
|
|
|
|
if can_append(location, directive_name):
|
2018-01-17 11:01:44 -05:00
|
|
|
if insert_at_top:
|
|
|
|
|
# Add a newline so the comment doesn't comment
|
|
|
|
|
# out existing directives
|
|
|
|
|
block.insert(0, nginxparser.UnspacedList('\n'))
|
|
|
|
|
block.insert(0, directive)
|
|
|
|
|
comment_directive(block, 0)
|
|
|
|
|
else:
|
|
|
|
|
block.append(directive)
|
|
|
|
|
comment_directive(block, len(block) - 1)
|
2022-01-12 19:36:51 -05:00
|
|
|
return
|
|
|
|
|
|
|
|
|
|
# By construction of can_append(), location cannot be None at that point
|
|
|
|
|
resolved_location = cast(int, location)
|
|
|
|
|
|
|
|
|
|
if block[resolved_location] != directive:
|
|
|
|
|
raise errors.MisconfigurationError(err_fmt.format(directive, block[resolved_location]))
|
2016-07-18 18:25:09 -04:00
|
|
|
|
2022-01-12 19:36:51 -05:00
|
|
|
|
|
|
|
|
def _update_directive(block: UnspacedList, directive: Sequence[Any], location: int) -> None:
|
2018-03-23 19:30:13 -04:00
|
|
|
block[location] = directive
|
|
|
|
|
comment_directive(block, location)
|
|
|
|
|
|
2022-01-12 19:36:51 -05:00
|
|
|
|
|
|
|
|
def _update_or_add_directive(block: UnspacedList, directive: Sequence[Any],
|
|
|
|
|
insert_at_top: bool) -> None:
|
2018-03-23 19:30:13 -04:00
|
|
|
if not isinstance(directive, nginxparser.UnspacedList):
|
|
|
|
|
directive = nginxparser.UnspacedList(directive)
|
|
|
|
|
if _is_whitespace_or_comment(directive):
|
|
|
|
|
# whitespace or comment
|
|
|
|
|
block.append(directive)
|
|
|
|
|
return
|
|
|
|
|
|
|
|
|
|
location = _find_location(block, directive[0])
|
|
|
|
|
|
|
|
|
|
# we can update directive
|
|
|
|
|
if location is not None:
|
|
|
|
|
_update_directive(block, directive, location)
|
|
|
|
|
return
|
|
|
|
|
|
|
|
|
|
_add_directive(block, directive, insert_at_top)
|
|
|
|
|
|
2022-01-12 19:36:51 -05:00
|
|
|
|
|
|
|
|
def _is_certbot_comment(directive: Sequence[Any]) -> bool:
|
2018-03-16 18:27:39 -04:00
|
|
|
return '#' in directive and COMMENT in directive
|
|
|
|
|
|
2022-01-12 19:36:51 -05:00
|
|
|
|
|
|
|
|
def _remove_directives(directive_name: str, match_func: Callable[[Any], bool],
|
|
|
|
|
block: UnspacedList) -> None:
|
2017-12-07 12:48:54 -05:00
|
|
|
"""Removes directives of name directive_name from a config block if match_func matches.
|
|
|
|
|
"""
|
|
|
|
|
while True:
|
|
|
|
|
location = _find_location(block, directive_name, match_func=match_func)
|
|
|
|
|
if location is None:
|
|
|
|
|
return
|
2018-03-16 18:27:39 -04:00
|
|
|
# if the directive was made by us, remove the comment following
|
|
|
|
|
if location + 1 < len(block) and _is_certbot_comment(block[location + 1]):
|
|
|
|
|
del block[location + 1]
|
2017-12-07 12:48:54 -05:00
|
|
|
del block[location]
|
|
|
|
|
|
2022-01-12 19:36:51 -05:00
|
|
|
|
|
|
|
|
def _apply_global_addr_ssl(addr_to_ssl: Mapping[Tuple[str, str], bool],
|
|
|
|
|
parsed_server: Dict[str, Any]) -> None:
|
2016-12-05 22:17:04 -05:00
|
|
|
"""Apply global sslishness information to the parsed server block
|
|
|
|
|
"""
|
|
|
|
|
for addr in parsed_server['addrs']:
|
|
|
|
|
addr.ssl = addr_to_ssl[addr.normalized_tuple()]
|
|
|
|
|
if addr.ssl:
|
|
|
|
|
parsed_server['ssl'] = True
|
|
|
|
|
|
2022-01-12 19:36:51 -05:00
|
|
|
|
|
|
|
|
def _parse_server_raw(server: UnspacedList) -> Dict[str, Any]:
|
2016-12-05 22:17:04 -05:00
|
|
|
"""Parses a list of server directives.
|
|
|
|
|
|
|
|
|
|
:param list server: list of directives in a server block
|
|
|
|
|
:rtype: dict
|
|
|
|
|
|
|
|
|
|
"""
|
2021-03-10 14:51:27 -05:00
|
|
|
addrs: Set[obj.Addr] = set()
|
|
|
|
|
ssl: bool = False
|
|
|
|
|
names: Set[str] = set()
|
2016-12-05 22:17:04 -05:00
|
|
|
|
|
|
|
|
apply_ssl_to_all_addrs = False
|
|
|
|
|
|
|
|
|
|
for directive in server:
|
|
|
|
|
if not directive:
|
|
|
|
|
continue
|
|
|
|
|
if directive[0] == 'listen':
|
2017-03-24 22:45:53 -04:00
|
|
|
addr = obj.Addr.fromstring(" ".join(directive[1:]))
|
2017-02-27 16:35:29 -05:00
|
|
|
if addr:
|
2018-05-15 12:36:47 -04:00
|
|
|
addrs.add(addr)
|
2017-02-27 16:35:29 -05:00
|
|
|
if addr.ssl:
|
2018-05-15 12:36:47 -04:00
|
|
|
ssl = True
|
2016-12-05 22:17:04 -05:00
|
|
|
elif directive[0] == 'server_name':
|
2018-05-15 12:36:47 -04:00
|
|
|
names.update(x.strip('"\'') for x in directive[1:])
|
2017-03-24 22:45:53 -04:00
|
|
|
elif _is_ssl_on_directive(directive):
|
2018-05-15 12:36:47 -04:00
|
|
|
ssl = True
|
2016-12-05 22:17:04 -05:00
|
|
|
apply_ssl_to_all_addrs = True
|
|
|
|
|
|
|
|
|
|
if apply_ssl_to_all_addrs:
|
2018-05-15 12:36:47 -04:00
|
|
|
for addr in addrs:
|
2016-12-05 22:17:04 -05:00
|
|
|
addr.ssl = True
|
|
|
|
|
|
2018-05-15 12:36:47 -04:00
|
|
|
return {
|
|
|
|
|
'addrs': addrs,
|
|
|
|
|
'ssl': ssl,
|
|
|
|
|
'names': names
|
|
|
|
|
}
|