From f950ce98ab07d6095b5f603cff364725b36b485f Mon Sep 17 00:00:00 2001 From: Unrud Date: Sun, 16 Aug 2020 18:14:43 +0200 Subject: [PATCH 001/238] Add reverse proxy examples for Apache .htaccess --- DOCUMENTATION.md | 40 ++++++++++++++++++++++++++++++++++------ 1 file changed, 34 insertions(+), 6 deletions(-) diff --git a/DOCUMENTATION.md b/DOCUMENTATION.md index 697a3eae..590da9f7 100644 --- a/DOCUMENTATION.md +++ b/DOCUMENTATION.md @@ -348,10 +348,21 @@ RewriteRule ^/radicale$ /radicale/ [R,L] ProxyPass http://localhost:5232/ retry=0 ProxyPassReverse http://localhost:5232/ - RequestHeader set X-Script-Name /radicale/ + RequestHeader set X-Script-Name /radicale ``` +Example **Apache .htaccess** configuration: + +```apache +DirectoryIndex disabled +RewriteEngine On +RewriteRule ^(.*)$ http://localhost:5232/$1 [P,L] + +# Set to directory of .htaccess file: +RequestHeader set X-Script-Name /radicale +``` + Be reminded that Radicale's default configuration enforces limits on the maximum number of parallel connections, the maximum file size and the rate of incorrect authentication attempts. Connections are terminated after a timeout. @@ -384,18 +395,35 @@ RewriteEngine On RewriteRule ^/radicale$ /radicale/ [R,L] - AuthType Basic - AuthName "Radicale - Password Required" - AuthUserFile "/etc/radicale/htpasswd" - Require valid-user + AuthType Basic + AuthName "Radicale - Password Required" + AuthUserFile "/etc/radicale/htpasswd" + Require valid-user ProxyPass http://localhost:5232/ retry=0 ProxyPassReverse http://localhost:5232/ - RequestHeader set X-Script-Name /radicale/ + RequestHeader set X-Script-Name /radicale RequestHeader set X-Remote-User expr=%{REMOTE_USER} ``` +Example **Apache .htaccess** configuration: + +```apache +DirectoryIndex disabled +RewriteEngine On +RewriteRule ^(.*)$ http://localhost:5232/$1 [P,L] + +AuthType Basic +AuthName "Radicale - Password Required" +AuthUserFile "/etc/radicale/htpasswd" +Require valid-user + +# Set to directory of .htaccess file: +RequestHeader set X-Script-Name /radicale +RequestHeader set X-Remote-User expr=%{REMOTE_USER} +``` + > **Security:** Untrusted clients should not be able to access the Radicale > server directly. Otherwise, they can authenticate as any user. From b98cd98c4c0f987a1d6847a0f0eec497a00c222a Mon Sep 17 00:00:00 2001 From: Unrud Date: Tue, 18 Aug 2020 22:43:59 +0200 Subject: [PATCH 002/238] Fix internal server on FreeBSD --- radicale/server.py | 4 +++- radicale/tests/test_server.py | 8 +++++--- 2 files changed, 8 insertions(+), 4 deletions(-) diff --git a/radicale/server.py b/radicale/server.py index 29ba1297..3b8e5330 100644 --- a/radicale/server.py +++ b/radicale/server.py @@ -240,7 +240,9 @@ def serve(configuration, shutdown_socket): # IPV6_V6ONLY set e.errno == errno.EADDRNOTAVAIL or # Address family not supported - e.errno == errno.EAFNOSUPPORT)): + e.errno == errno.EAFNOSUPPORT or + # Protocol not supported + e.errno == errno.EPROTONOSUPPORT)): continue raise RuntimeError("Failed to start server %r: %s" % ( format_address(address), e)) from e diff --git a/radicale/tests/test_server.py b/radicale/tests/test_server.py index b1ccd5ee..c2aea6b6 100644 --- a/radicale/tests/test_server.py +++ b/radicale/tests/test_server.py @@ -132,8 +132,9 @@ class TestBaseServerRequests(BaseTest): socket.EAI_NONAME, server.COMPAT_EAI_ADDRFAMILY, server.COMPAT_EAI_NODATA) or str(exc_info.value) == "address family mismatched" or - exc_info.value.errno == errno.EADDRNOTAVAIL or - exc_info.value.errno == errno.EAFNOSUPPORT) + exc_info.value.errno in ( + errno.EADDRNOTAVAIL, errno.EAFNOSUPPORT, + errno.EPROTONOSUPPORT)) def test_ipv6(self): try: @@ -145,7 +146,8 @@ class TestBaseServerRequests(BaseTest): sock.bind(("::1", 0)) self.sockname = sock.getsockname()[:2] except OSError as e: - if e.errno in (errno.EADDRNOTAVAIL, errno.EAFNOSUPPORT): + if e.errno in (errno.EADDRNOTAVAIL, errno.EAFNOSUPPORT, + errno.EPROTONOSUPPORT): pytest.skip("IPv6 not supported") raise self.configuration.update({ From 896963dd3c307de0156bd2e0a02f4b72c7cc39ae Mon Sep 17 00:00:00 2001 From: Unrud Date: Tue, 18 Aug 2020 22:57:17 +0200 Subject: [PATCH 003/238] Update NEWS.md --- NEWS.md | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/NEWS.md b/NEWS.md index 670eee14..668295a0 100644 --- a/NEWS.md +++ b/NEWS.md @@ -2,6 +2,10 @@ ## master +## 3.0.4 + + * Fix internal server on FreeBSD + ## 3.0.3 * Fix internal server on OpenBSD From ea6649b365173e397faf7ae524924523425318b6 Mon Sep 17 00:00:00 2001 From: Unrud Date: Mon, 31 Aug 2020 13:54:46 +0200 Subject: [PATCH 004/238] Remove untested FCGI example Closes #1017 Closes #1018 --- MANIFEST.in | 2 +- radicale.fcgi | 17 ----------------- 2 files changed, 1 insertion(+), 18 deletions(-) delete mode 100755 radicale.fcgi diff --git a/MANIFEST.in b/MANIFEST.in index b7ad6546..a9c47030 100644 --- a/MANIFEST.in +++ b/MANIFEST.in @@ -1,3 +1,3 @@ include COPYING DOCUMENTATION.md NEWS.md README.md include config rights -include radicale.py radicale.fcgi radicale.wsgi +include radicale.py radicale.wsgi diff --git a/radicale.fcgi b/radicale.fcgi deleted file mode 100755 index d5203909..00000000 --- a/radicale.fcgi +++ /dev/null @@ -1,17 +0,0 @@ -#!/usr/bin/env python3 - -""" -Radicale FastCGI Example. - -Launch a Radicale FastCGI server according to configuration. - -This script relies on flup but can be easily adapted to use another -WSGI-to-FastCGI mapper. - -""" - -from flup.server.fcgi import WSGIServer -from radicale import application - -if __name__ == "__main__": - WSGIServer(application).run() From cd3fe3e73c4e99fdeea87a9cd9081097da3d6804 Mon Sep 17 00:00:00 2001 From: Unrud Date: Mon, 31 Aug 2020 13:54:47 +0200 Subject: [PATCH 005/238] Remove radicale.py script The script installed by setuptools should be used instead. --- MANIFEST.in | 2 +- radicale.py | 13 ------------- 2 files changed, 1 insertion(+), 14 deletions(-) delete mode 100755 radicale.py diff --git a/MANIFEST.in b/MANIFEST.in index a9c47030..7925b3e0 100644 --- a/MANIFEST.in +++ b/MANIFEST.in @@ -1,3 +1,3 @@ include COPYING DOCUMENTATION.md NEWS.md README.md include config rights -include radicale.py radicale.wsgi +include radicale.wsgi diff --git a/radicale.py b/radicale.py deleted file mode 100755 index 3ea4d2df..00000000 --- a/radicale.py +++ /dev/null @@ -1,13 +0,0 @@ -#!/usr/bin/env python3 - -""" -Radicale CalDAV Server. - -Launch the server according to configuration and command-line options. - -""" - -import runpy - -if __name__ == "__main__": - runpy.run_module("radicale", run_name="__main__") From 46c39b28d6405cb7a91f521d7a467fb35cf62b10 Mon Sep 17 00:00:00 2001 From: Unrud Date: Mon, 31 Aug 2020 13:54:47 +0200 Subject: [PATCH 006/238] Make shutdown_socket optional --- radicale/server.py | 15 ++++++++++++--- 1 file changed, 12 insertions(+), 3 deletions(-) diff --git a/radicale/server.py b/radicale/server.py index 3b8e5330..8cada22a 100644 --- a/radicale/server.py +++ b/radicale/server.py @@ -200,8 +200,16 @@ class RequestHandler(wsgiref.simple_server.WSGIRequestHandler): handler.run(self.server.get_app()) -def serve(configuration, shutdown_socket): - """Serve radicale from configuration.""" +def serve(configuration, shutdown_socket=None): + """Serve radicale from configuration. + + `shutdown_socket` can be used to gracefully shutdown the server. + The socket can be created with `socket.socketpair()`, when the other socket + gets closed the server stops accepting new requests by clients and the + function returns after all active requests are finished. + + """ + logger.info("Starting Radicale") # Copy configuration before modifying configuration = configuration.copy() @@ -270,7 +278,8 @@ def serve(configuration, shutdown_socket): if max_connections <= 0 or len(rlist) < max_connections: rlist.extend(servers) # Use socket to get notified of program shutdown - rlist.append(shutdown_socket) + if shutdown_socket is not None: + rlist.append(shutdown_socket) rlist, _, _ = select.select(rlist, [], [], select_timeout) rlist = set(rlist) if shutdown_socket in rlist: From 30c9c5535854c491156794bb6924cdb5804591b7 Mon Sep 17 00:00:00 2001 From: Unrud Date: Mon, 31 Aug 2020 13:54:47 +0200 Subject: [PATCH 007/238] Exit immediately after cleanup when signal is received Waiting for clients introduces the risk that we exceed some timeout (e.g. from systemd) and get killed instead. --- radicale/__main__.py | 26 ++++++++++++++------------ radicale/tests/test_server.py | 7 ++----- 2 files changed, 16 insertions(+), 17 deletions(-) diff --git a/radicale/__main__.py b/radicale/__main__.py index 9e0c3e47..d0ea10ea 100644 --- a/radicale/__main__.py +++ b/radicale/__main__.py @@ -27,7 +27,6 @@ import argparse import contextlib import os import signal -import socket import sys from radicale import VERSION, config, log, server, storage @@ -36,10 +35,22 @@ from radicale.log import logger def run(): """Run Radicale as a standalone server.""" + + # Raise SystemExit when signal arrives to run cleanup code + # (like destructors, try-finish etc.), otherwise the process exits + # without running any of them + def signal_handler(signal_number, stack_frame): + sys.exit(1) + signal.signal(signal.SIGTERM, signal_handler) + signal.signal(signal.SIGINT, signal_handler) + if os.name == "posix": + signal.signal(signal.SIGHUP, signal_handler) + log.setup() # Get command-line arguments - parser = argparse.ArgumentParser(usage="radicale [OPTIONS]") + parser = argparse.ArgumentParser( + prog="radicale", usage="%(prog)s [OPTIONS]") parser.add_argument("--version", action="version", version=VERSION) parser.add_argument("--verify-storage", action="store_true", @@ -137,17 +148,8 @@ def run(): sys.exit(1) return - # Create a socket pair to notify the server of program shutdown - shutdown_socket, shutdown_socket_out = socket.socketpair() - - # SIGTERM and SIGINT (aka KeyboardInterrupt) shutdown the server - def shutdown(signal_number, stack_frame): - shutdown_socket.close() - signal.signal(signal.SIGTERM, shutdown) - signal.signal(signal.SIGINT, shutdown) - try: - server.serve(configuration, shutdown_socket_out) + server.serve(configuration) except Exception as e: logger.fatal("An exception occurred during server startup: %s", e, exc_info=True) diff --git a/radicale/tests/test_server.py b/radicale/tests/test_server.py index c2aea6b6..a58e94ec 100644 --- a/radicale/tests/test_server.py +++ b/radicale/tests/test_server.py @@ -172,17 +172,14 @@ class TestBaseServerRequests(BaseTest): config_args.append(long_name) config_args.append( self.configuration.get_raw(section, option)) - env = os.environ.copy() - env["PYTHONPATH"] = os.pathsep.join(sys.path) p = subprocess.Popen( - [sys.executable, "-m", "radicale"] + config_args, env=env) + [sys.executable, "-m", "radicale"] + config_args, + env={**os.environ, "PYTHONPATH": os.pathsep.join(sys.path)}) try: self.get("/", is_alive_fn=lambda: p.poll() is None, check=302) finally: p.terminate() p.wait() - if os.name == "posix": - assert p.returncode == 0 def test_wsgi_server(self): config_path = os.path.join(self.colpath, "config") From dbe95641c02293be56b66af70401351b39da17de Mon Sep 17 00:00:00 2001 From: Unrud Date: Mon, 31 Aug 2020 13:54:48 +0200 Subject: [PATCH 008/238] Test Python 3.9 --- .github/workflows/test.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml index b7ceb90b..0283b04b 100644 --- a/.github/workflows/test.yml +++ b/.github/workflows/test.yml @@ -7,7 +7,7 @@ jobs: strategy: matrix: os: [ubuntu-latest, macos-latest, windows-latest] - python-version: [3.5, 3.6, 3.7, 3.8, pypy3] + python-version: [3.5, 3.6, 3.7, 3.8, '3.9.0-alpha - 3.9', pypy3] steps: - uses: actions/checkout@v2 - uses: actions/setup-python@v2 From d4af2cd1a6f1f8b2fa4824d5abc0049fb64c05a2 Mon Sep 17 00:00:00 2001 From: Unrud Date: Mon, 31 Aug 2020 13:54:48 +0200 Subject: [PATCH 009/238] Kill storage hook on error --- radicale/storage/multifilesystem/lock.py | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/radicale/storage/multifilesystem/lock.py b/radicale/storage/multifilesystem/lock.py index e3615e91..81821f2a 100644 --- a/radicale/storage/multifilesystem/lock.py +++ b/radicale/storage/multifilesystem/lock.py @@ -62,7 +62,11 @@ class StorageLockMixin: stdout=subprocess.PIPE if debug else subprocess.DEVNULL, stderr=subprocess.PIPE if debug else subprocess.DEVNULL, shell=True, universal_newlines=True, cwd=folder) - stdout_data, stderr_data = p.communicate() + try: + stdout_data, stderr_data = p.communicate() + except BaseException: # e.g. KeyboardInterrupt or SystemExit + p.kill() + raise if stdout_data: logger.debug("Captured stdout hook:\n%s", stdout_data) if stderr_data: From 1e011e70119f8f7b8b09c379df4b008d91cd6d6b Mon Sep 17 00:00:00 2001 From: Unrud Date: Mon, 31 Aug 2020 13:54:48 +0200 Subject: [PATCH 010/238] Start storage hook in own process group Prevents terminals from sending SIGINT etc. --- radicale/storage/multifilesystem/lock.py | 14 +++++++++++--- 1 file changed, 11 insertions(+), 3 deletions(-) diff --git a/radicale/storage/multifilesystem/lock.py b/radicale/storage/multifilesystem/lock.py index 81821f2a..6382ec0b 100644 --- a/radicale/storage/multifilesystem/lock.py +++ b/radicale/storage/multifilesystem/lock.py @@ -54,14 +54,22 @@ class StorageLockMixin: hook = self.configuration.get("storage", "hook") if mode == "w" and hook: folder = self.configuration.get("storage", "filesystem_folder") - logger.debug("Running hook") debug = logger.isEnabledFor(logging.DEBUG) - p = subprocess.Popen( - hook % {"user": shlex.quote(user or "Anonymous")}, + popen_kwargs = dict( stdin=subprocess.DEVNULL, stdout=subprocess.PIPE if debug else subprocess.DEVNULL, stderr=subprocess.PIPE if debug else subprocess.DEVNULL, shell=True, universal_newlines=True, cwd=folder) + # Use new process group for child to prevent terminals + # from sending SIGINT etc. + if os.name == "posix": + popen_kwargs["preexec_fn"] = os.setpgrp + elif os.name == "nt": + popen_kwargs["creationflags"] = ( + subprocess.CREATE_NEW_PROCESS_GROUP) + command = hook % {"user": shlex.quote(user or "Anonymous")} + logger.debug("Running hook") + p = subprocess.Popen(command, **popen_kwargs) try: stdout_data, stderr_data = p.communicate() except BaseException: # e.g. KeyboardInterrupt or SystemExit From 2851525e159ee9005794d22058ae3c1803b69583 Mon Sep 17 00:00:00 2001 From: Unrud Date: Mon, 31 Aug 2020 13:54:49 +0200 Subject: [PATCH 011/238] Try to kill child processes of storage hook --- radicale/storage/multifilesystem/lock.py | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/radicale/storage/multifilesystem/lock.py b/radicale/storage/multifilesystem/lock.py index 6382ec0b..e5febd22 100644 --- a/radicale/storage/multifilesystem/lock.py +++ b/radicale/storage/multifilesystem/lock.py @@ -20,6 +20,7 @@ import contextlib import logging import os import shlex +import signal import subprocess from radicale import pathutils @@ -63,6 +64,7 @@ class StorageLockMixin: # Use new process group for child to prevent terminals # from sending SIGINT etc. if os.name == "posix": + # Process group is also used to identify child processes popen_kwargs["preexec_fn"] = os.setpgrp elif os.name == "nt": popen_kwargs["creationflags"] = ( @@ -75,6 +77,11 @@ class StorageLockMixin: except BaseException: # e.g. KeyboardInterrupt or SystemExit p.kill() raise + finally: + if os.name == "posix": + # Try to kill child processes + with contextlib.suppress(OSError): + os.killpg(p.pid, signal.SIGKILL) if stdout_data: logger.debug("Captured stdout hook:\n%s", stdout_data) if stderr_data: From 41bccb265a5b59397f72f8e331cfba6288242900 Mon Sep 17 00:00:00 2001 From: Unrud Date: Mon, 31 Aug 2020 13:54:50 +0200 Subject: [PATCH 012/238] Update NEWS.md --- NEWS.md | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/NEWS.md b/NEWS.md index 668295a0..7620da0c 100644 --- a/NEWS.md +++ b/NEWS.md @@ -2,6 +2,13 @@ ## master +## 3.0.5 + + * Start storage hook in own process group + * Kill storage hook on error or exit + * Try to kill child processes of storage hook + * Internal Server: Exit immediately when signal is received (do not wait for clients or storage hook to finish) + ## 3.0.4 * Fix internal server on FreeBSD From 9d25cc6c0ae6fa72bd6c57b76cbd25f1fddedbc0 Mon Sep 17 00:00:00 2001 From: fe60 <31078918+fe60@users.noreply.github.com> Date: Thu, 10 Sep 2020 22:42:02 +0200 Subject: [PATCH 013/238] ensure group 'radicale' gets created Without the option --user-group the creation of the group depends on default values. In OpenSUSE Tumbleweed the user 'radicale' became a member of 'users'. --- DOCUMENTATION.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/DOCUMENTATION.md b/DOCUMENTATION.md index 590da9f7..3f55b9d6 100644 --- a/DOCUMENTATION.md +++ b/DOCUMENTATION.md @@ -213,7 +213,7 @@ requirements. ### Linux with systemd system-wide Create the **radicale** user and group for the Radicale service. -(Run `useradd --system --home-dir / --shell /sbin/nologin radicale` as root.) +(Run `useradd --system --user-group --home-dir / --shell /sbin/nologin radicale` as root.) The storage folder must be writable by **radicale**. (Run `mkdir -p /var/lib/radicale/collections && chown -R radicale:radicale /var/lib/radicale/collections` as root.) From 6091bd46a3fb405eb36a3cc947d5ea3ed93fc347 Mon Sep 17 00:00:00 2001 From: Unrud Date: Sat, 12 Sep 2020 20:23:45 +0200 Subject: [PATCH 014/238] Respond 405 for unsupported methods instead of server error --- radicale/app/__init__.py | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/radicale/app/__init__.py b/radicale/app/__init__.py index 85cbcc2b..e138362c 100644 --- a/radicale/app/__init__.py +++ b/radicale/app/__init__.py @@ -224,7 +224,10 @@ class Application( logger.debug("Sanitized path: %r", path) # Get function corresponding to method - function = getattr(self, "do_%s" % environ["REQUEST_METHOD"].upper()) + function = getattr( + self, "do_%s" % environ["REQUEST_METHOD"].upper(), None) + if not function: + return response(*httputils.METHOD_NOT_ALLOWED) # If "/.well-known" is not available, clients query "/" if path == "/.well-known" or path.startswith("/.well-known/"): From d3bb19800c1e88014ea058b701e891f0e7c34a15 Mon Sep 17 00:00:00 2001 From: Tom Hacohen Date: Mon, 14 Sep 2020 19:17:45 +0300 Subject: [PATCH 015/238] Web: add support for the POST HTTP method. (#1097) * Web: add support for the POST HTTP method. This patch adds support for POST in addition to the already supported GET. This is needed for implementing more complex web modules that also support configuration modifications and advanced queries. * Base web: return METHOD_NOT_ALLOWED when method isn't implemenetd. Co-authored-by: Unrud --- radicale/app/__init__.py | 4 +++- radicale/app/post.py | 30 ++++++++++++++++++++++++++++++ radicale/tests/__init__.py | 5 +++++ radicale/tests/custom/web.py | 3 +++ radicale/tests/test_web.py | 3 +++ radicale/web/__init__.py | 16 ++++++++++++++-- 6 files changed, 58 insertions(+), 3 deletions(-) create mode 100644 radicale/app/post.py diff --git a/radicale/app/__init__.py b/radicale/app/__init__.py index e138362c..0f9ba957 100644 --- a/radicale/app/__init__.py +++ b/radicale/app/__init__.py @@ -49,6 +49,7 @@ from radicale.app.mkcalendar import ApplicationMkcalendarMixin from radicale.app.mkcol import ApplicationMkcolMixin from radicale.app.move import ApplicationMoveMixin from radicale.app.options import ApplicationOptionsMixin +from radicale.app.post import ApplicationPostMixin from radicale.app.propfind import ApplicationPropfindMixin from radicale.app.proppatch import ApplicationProppatchMixin from radicale.app.put import ApplicationPutMixin @@ -63,7 +64,8 @@ class Application( ApplicationMkcalendarMixin, ApplicationMkcolMixin, ApplicationMoveMixin, ApplicationOptionsMixin, ApplicationPropfindMixin, ApplicationProppatchMixin, - ApplicationPutMixin, ApplicationReportMixin): + ApplicationPostMixin, ApplicationPutMixin, + ApplicationReportMixin): """WSGI application.""" diff --git a/radicale/app/post.py b/radicale/app/post.py new file mode 100644 index 00000000..723b8e97 --- /dev/null +++ b/radicale/app/post.py @@ -0,0 +1,30 @@ +# This file is part of Radicale Server - Calendar Server +# Copyright © 2008 Nicolas Kandel +# Copyright © 2008 Pascal Halter +# Copyright © 2008-2017 Guillaume Ayoub +# Copyright © 2017-2018 Unrud +# Copyright © 2020 Tom Hacohen +# +# This library is free software: you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation, either version 3 of the License, or +# (at your option) any later version. +# +# This library is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with Radicale. If not, see . + +from radicale import httputils + + +class ApplicationPostMixin: + def do_POST(self, environ, base_prefix, path, user): + """Manage POST request.""" + if path == "/.web" or path.startswith("/.web/"): + return self._web.post(environ, base_prefix, path, user) + + return httputils.METHOD_NOT_ALLOWED diff --git a/radicale/tests/__init__.py b/radicale/tests/__init__.py index 1e186154..1824bd13 100644 --- a/radicale/tests/__init__.py +++ b/radicale/tests/__init__.py @@ -104,6 +104,11 @@ class BaseTest: self._check_status(status, 200, check) return status, answer + def post(self, path, check=True, **args): + status, _, answer = self.request("POST", path, **args) + self._check_status(status, 200, check) + return status, answer + def put(self, path, data, check=True, **args): status, _, answer = self.request("PUT", path, data, **args) self._check_status(status, 201, check) diff --git a/radicale/tests/custom/web.py b/radicale/tests/custom/web.py index ff45feb4..7d119022 100644 --- a/radicale/tests/custom/web.py +++ b/radicale/tests/custom/web.py @@ -27,3 +27,6 @@ from radicale import web class Web(web.BaseWeb): def get(self, environ, base_prefix, path, user): return client.OK, {"Content-Type": "text/plain"}, "custom" + + def post(self, environ, base_prefix, path, user): + return client.OK, {"Content-Type": "text/plain"}, "custom post" diff --git a/radicale/tests/test_web.py b/radicale/tests/test_web.py index 578897a4..f5fed549 100644 --- a/radicale/tests/test_web.py +++ b/radicale/tests/test_web.py @@ -63,3 +63,6 @@ class TestBaseWebRequests(BaseTest): self.application = Application(self.configuration) _, answer = self.get("/.web") assert answer == "custom" + + _, answer = self.post("/.web") + assert answer == "custom post" diff --git a/radicale/web/__init__.py b/radicale/web/__init__.py index 0a402857..6d878331 100644 --- a/radicale/web/__init__.py +++ b/radicale/web/__init__.py @@ -21,7 +21,7 @@ Take a look at the class ``BaseWeb`` if you want to implement your own. """ -from radicale import utils +from radicale import httputils, utils INTERNAL_TYPES = ("none", "internal") @@ -52,4 +52,16 @@ class BaseWeb: ``user`` is empty for anonymous users. """ - raise NotImplementedError + return httputils.METHOD_NOT_ALLOWED + + def post(self, environ, base_prefix, path, user): + """POST request. + + ``base_prefix`` is sanitized and never ends with "/". + + ``path`` is sanitized and always starts with "/.web" + + ``user`` is empty for anonymous users. + + """ + return httputils.METHOD_NOT_ALLOWED From 80e8750c8aeb4a35b70ed403b1848dbca47d6389 Mon Sep 17 00:00:00 2001 From: Unrud Date: Mon, 14 Sep 2020 18:46:46 +0200 Subject: [PATCH 016/238] Add more tests --- radicale/app/post.py | 1 - radicale/tests/__init__.py | 4 ++-- radicale/tests/custom/web.py | 3 ++- radicale/tests/test_web.py | 7 ++++--- 4 files changed, 8 insertions(+), 7 deletions(-) diff --git a/radicale/app/post.py b/radicale/app/post.py index 723b8e97..a3de951e 100644 --- a/radicale/app/post.py +++ b/radicale/app/post.py @@ -26,5 +26,4 @@ class ApplicationPostMixin: """Manage POST request.""" if path == "/.web" or path.startswith("/.web/"): return self._web.post(environ, base_prefix, path, user) - return httputils.METHOD_NOT_ALLOWED diff --git a/radicale/tests/__init__.py b/radicale/tests/__init__.py index 1824bd13..e2e283e2 100644 --- a/radicale/tests/__init__.py +++ b/radicale/tests/__init__.py @@ -104,8 +104,8 @@ class BaseTest: self._check_status(status, 200, check) return status, answer - def post(self, path, check=True, **args): - status, _, answer = self.request("POST", path, **args) + def post(self, path, data=None, check=True, **args): + status, _, answer = self.request("POST", path, data, **args) self._check_status(status, 200, check) return status, answer diff --git a/radicale/tests/custom/web.py b/radicale/tests/custom/web.py index 7d119022..3a8f5bde 100644 --- a/radicale/tests/custom/web.py +++ b/radicale/tests/custom/web.py @@ -29,4 +29,5 @@ class Web(web.BaseWeb): return client.OK, {"Content-Type": "text/plain"}, "custom" def post(self, environ, base_prefix, path, user): - return client.OK, {"Content-Type": "text/plain"}, "custom post" + answer = "echo:" + environ["wsgi.input"].read().decode() + return client.OK, {"Content-Type": "text/plain"}, answer diff --git a/radicale/tests/test_web.py b/radicale/tests/test_web.py index f5fed549..5d2b7925 100644 --- a/radicale/tests/test_web.py +++ b/radicale/tests/test_web.py @@ -48,6 +48,7 @@ class TestBaseWebRequests(BaseTest): assert headers.get("Location") == ".web/" _, answer = self.get("/.web/") assert answer + self.post("/.web", check=405) def test_none(self): self.configuration.update({"web": {"type": "none"}}, "test") @@ -55,6 +56,7 @@ class TestBaseWebRequests(BaseTest): _, answer = self.get("/.web") assert answer self.get("/.web/", check=404) + self.post("/.web", check=405) def test_custom(self): """Custom web plugin.""" @@ -63,6 +65,5 @@ class TestBaseWebRequests(BaseTest): self.application = Application(self.configuration) _, answer = self.get("/.web") assert answer == "custom" - - _, answer = self.post("/.web") - assert answer == "custom post" + _, answer = self.post("/.web", "body content") + assert answer == "echo:body content" From 42ad18bc841702a2481302b127b291b005da4030 Mon Sep 17 00:00:00 2001 From: Unrud Date: Mon, 14 Sep 2020 21:17:18 +0200 Subject: [PATCH 017/238] Rename _write_xml_content to _xml_response --- radicale/app/__init__.py | 4 ++-- radicale/app/delete.py | 2 +- radicale/app/propfind.py | 2 +- radicale/app/proppatch.py | 3 +-- radicale/app/report.py | 2 +- 5 files changed, 6 insertions(+), 7 deletions(-) diff --git a/radicale/app/__init__.py b/radicale/app/__init__.py index 0f9ba957..30de7257 100644 --- a/radicale/app/__init__.py +++ b/radicale/app/__init__.py @@ -345,7 +345,7 @@ class Application( xmlutils.pretty_xml(xml_content)) return xml_content - def _write_xml_content(self, xml_content): + def _xml_response(self, xml_content): if logger.isEnabledFor(logging.DEBUG): logger.debug("Response content:\n%s", xmlutils.pretty_xml(xml_content)) @@ -357,7 +357,7 @@ class Application( def _webdav_error_response(self, status, human_tag): """Generate XML error response.""" headers = {"Content-Type": "text/xml; charset=%s" % self._encoding} - content = self._write_xml_content(xmlutils.webdav_error(human_tag)) + content = self._xml_response(xmlutils.webdav_error(human_tag)) return status, headers, content diff --git a/radicale/app/delete.py b/radicale/app/delete.py index 8d08d30f..df587a5f 100644 --- a/radicale/app/delete.py +++ b/radicale/app/delete.py @@ -68,4 +68,4 @@ class ApplicationDeleteMixin: xml_answer = xml_delete( base_prefix, path, item.collection, item.href) headers = {"Content-Type": "text/xml; charset=%s" % self._encoding} - return client.OK, headers, self._write_xml_content(xml_answer) + return client.OK, headers, self._xml_response(xml_answer) diff --git a/radicale/app/propfind.py b/radicale/app/propfind.py index 7c45395a..1c55b044 100644 --- a/radicale/app/propfind.py +++ b/radicale/app/propfind.py @@ -374,4 +374,4 @@ class ApplicationPropfindMixin: self._encoding) if status == client.FORBIDDEN and xml_answer is None: return httputils.NOT_ALLOWED - return status, headers, self._write_xml_content(xml_answer) + return status, headers, self._xml_response(xml_answer) diff --git a/radicale/app/proppatch.py b/radicale/app/proppatch.py index 53ab4822..6fde5eba 100644 --- a/radicale/app/proppatch.py +++ b/radicale/app/proppatch.py @@ -116,5 +116,4 @@ class ApplicationProppatchMixin: logger.warning( "Bad PROPPATCH request on %r: %s", path, e, exc_info=True) return httputils.BAD_REQUEST - return (client.MULTI_STATUS, headers, - self._write_xml_content(xml_answer)) + return client.MULTI_STATUS, headers, self._xml_response(xml_answer) diff --git a/radicale/app/report.py b/radicale/app/report.py index 5da4c2e8..30dac98a 100644 --- a/radicale/app/report.py +++ b/radicale/app/report.py @@ -290,4 +290,4 @@ class ApplicationReportMixin: logger.warning( "Bad REPORT request on %r: %s", path, e, exc_info=True) return httputils.BAD_REQUEST - return (status, headers, self._write_xml_content(xml_answer)) + return status, headers, self._xml_response(xml_answer) From 0ce90d6b34509deaf3e44ec05daf83b006d4fe1c Mon Sep 17 00:00:00 2001 From: Unrud Date: Mon, 14 Sep 2020 21:19:48 +0200 Subject: [PATCH 018/238] Extract read*_request_body methods --- radicale/app/__init__.py | 49 ++++++------------------------------ radicale/app/mkcalendar.py | 2 +- radicale/app/mkcol.py | 2 +- radicale/app/propfind.py | 2 +- radicale/app/proppatch.py | 2 +- radicale/app/put.py | 2 +- radicale/app/report.py | 2 +- radicale/httputils.py | 44 ++++++++++++++++++++++++++++++++ radicale/tests/custom/web.py | 6 ++--- radicale/web/__init__.py | 3 +++ 10 files changed, 63 insertions(+), 51 deletions(-) diff --git a/radicale/app/__init__.py b/radicale/app/__init__.py index 30de7257..b0c53a98 100644 --- a/radicale/app/__init__.py +++ b/radicale/app/__init__.py @@ -99,30 +99,6 @@ class Application( return request_environ - def _decode(self, text, environ): - """Try to magically decode ``text`` according to given ``environ``.""" - # List of charsets to try - charsets = [] - - # First append content charset given in the request - content_type = environ.get("CONTENT_TYPE") - if content_type and "charset=" in content_type: - charsets.append( - content_type.split("charset=")[1].split(";")[0].strip()) - # Then append default Radicale charset - charsets.append(self._encoding) - # Then append various fallbacks - charsets.append("utf-8") - charsets.append("iso8859-1") - - # Try to decode - for charset in charsets: - try: - return text.decode(charset) - except UnicodeDecodeError: - pass - raise UnicodeDecodeError - def __call__(self, environ, start_response): with log.register_stream(environ["wsgi.errors"]): try: @@ -244,8 +220,9 @@ class Application( login, password = login or "", password or "" elif authorization.startswith("Basic"): authorization = authorization[len("Basic"):].strip() - login, password = self._decode(base64.b64decode( - authorization.encode("ascii")), environ).split(":", 1) + login, password = httputils.decode_request( + self.configuration, environ, base64.b64decode( + authorization.encode("ascii"))).split(":", 1) user = self._auth.login(login, password) or "" if login else "" if user and login == user: @@ -317,22 +294,10 @@ class Application( return response(status, headers, answer) - def _read_raw_content(self, environ): - content_length = int(environ.get("CONTENT_LENGTH") or 0) - if not content_length: - return b"" - content = environ["wsgi.input"].read(content_length) - if len(content) < content_length: - raise RuntimeError("Request body too short: %d" % len(content)) - return content - - def _read_content(self, environ): - content = self._decode(self._read_raw_content(environ), environ) - logger.debug("Request content:\n%s", content) - return content - - def _read_xml_content(self, environ): - content = self._decode(self._read_raw_content(environ), environ) + def _read_xml_request_body(self, environ): + content = httputils.decode_request( + self.configuration, environ, + httputils.read_raw_request_body(self.configuration, environ)) if not content: return None try: diff --git a/radicale/app/mkcalendar.py b/radicale/app/mkcalendar.py index b7e16d94..d5c6c4db 100644 --- a/radicale/app/mkcalendar.py +++ b/radicale/app/mkcalendar.py @@ -33,7 +33,7 @@ class ApplicationMkcalendarMixin: if "w" not in self._rights.authorization(user, path): return httputils.NOT_ALLOWED try: - xml_content = self._read_xml_content(environ) + xml_content = self._read_xml_request_body(environ) except RuntimeError as e: logger.warning( "Bad MKCALENDAR request on %r: %s", path, e, exc_info=True) diff --git a/radicale/app/mkcol.py b/radicale/app/mkcol.py index b4ba961a..f7195410 100644 --- a/radicale/app/mkcol.py +++ b/radicale/app/mkcol.py @@ -34,7 +34,7 @@ class ApplicationMkcolMixin: if not rights.intersect(permissions, "Ww"): return httputils.NOT_ALLOWED try: - xml_content = self._read_xml_content(environ) + xml_content = self._read_xml_request_body(environ) except RuntimeError as e: logger.warning( "Bad MKCOL request on %r: %s", path, e, exc_info=True) diff --git a/radicale/app/propfind.py b/radicale/app/propfind.py index 1c55b044..106e2e84 100644 --- a/radicale/app/propfind.py +++ b/radicale/app/propfind.py @@ -347,7 +347,7 @@ class ApplicationPropfindMixin: if not access.check("r"): return httputils.NOT_ALLOWED try: - xml_content = self._read_xml_content(environ) + xml_content = self._read_xml_request_body(environ) except RuntimeError as e: logger.warning( "Bad PROPFIND request on %r: %s", path, e, exc_info=True) diff --git a/radicale/app/proppatch.py b/radicale/app/proppatch.py index 6fde5eba..3ec10c30 100644 --- a/radicale/app/proppatch.py +++ b/radicale/app/proppatch.py @@ -91,7 +91,7 @@ class ApplicationProppatchMixin: if not access.check("w"): return httputils.NOT_ALLOWED try: - xml_content = self._read_xml_content(environ) + xml_content = self._read_xml_request_body(environ) except RuntimeError as e: logger.warning( "Bad PROPPATCH request on %r: %s", path, e, exc_info=True) diff --git a/radicale/app/put.py b/radicale/app/put.py index 786ac00c..efaf9053 100644 --- a/radicale/app/put.py +++ b/radicale/app/put.py @@ -118,7 +118,7 @@ class ApplicationPutMixin: if not access.check("w"): return httputils.NOT_ALLOWED try: - content = self._read_content(environ) + content = httputils.read_request_body(self.configuration, environ) except RuntimeError as e: logger.warning("Bad PUT request on %r: %s", path, e, exc_info=True) return httputils.BAD_REQUEST diff --git a/radicale/app/report.py b/radicale/app/report.py index 30dac98a..18ea4e79 100644 --- a/radicale/app/report.py +++ b/radicale/app/report.py @@ -262,7 +262,7 @@ class ApplicationReportMixin: if not access.check("r"): return httputils.NOT_ALLOWED try: - xml_content = self._read_xml_content(environ) + xml_content = self._read_xml_request_body(environ) except RuntimeError as e: logger.warning( "Bad REPORT request on %r: %s", path, e, exc_info=True) diff --git a/radicale/httputils.py b/radicale/httputils.py index eb4c75cb..167a86b8 100644 --- a/radicale/httputils.py +++ b/radicale/httputils.py @@ -24,6 +24,8 @@ Helper functions for HTTP. from http import client +from radicale.log import logger + NOT_ALLOWED = ( client.FORBIDDEN, (("Content-Type", "text/plain"),), "Access to the requested resource forbidden.") @@ -61,3 +63,45 @@ INTERNAL_SERVER_ERROR = ( "A server error occurred. Please contact the administrator.") DAV_HEADERS = "1, 2, 3, calendar-access, addressbook, extended-mkcol" + + +def decode_request(configuration, environ, text): + """Try to magically decode ``text`` according to given ``environ``.""" + # List of charsets to try + charsets = [] + + # First append content charset given in the request + content_type = environ.get("CONTENT_TYPE") + if content_type and "charset=" in content_type: + charsets.append( + content_type.split("charset=")[1].split(";")[0].strip()) + # Then append default Radicale charset + charsets.append(configuration.get("encoding", "request")) + # Then append various fallbacks + charsets.append("utf-8") + charsets.append("iso8859-1") + + # Try to decode + for charset in charsets: + try: + return text.decode(charset) + except UnicodeDecodeError: + pass + raise UnicodeDecodeError + + +def read_raw_request_body(configuration, environ): + content_length = int(environ.get("CONTENT_LENGTH") or 0) + if not content_length: + return b"" + content = environ["wsgi.input"].read(content_length) + if len(content) < content_length: + raise RuntimeError("Request body too short: %d" % len(content)) + return content + + +def read_request_body(configuration, environ): + content = decode_request( + configuration, environ, read_raw_request_body(configuration, environ)) + logger.debug("Request content:\n%s", content) + return content diff --git a/radicale/tests/custom/web.py b/radicale/tests/custom/web.py index 3a8f5bde..784614f4 100644 --- a/radicale/tests/custom/web.py +++ b/radicale/tests/custom/web.py @@ -21,7 +21,7 @@ Custom web plugin. from http import client -from radicale import web +from radicale import httputils, web class Web(web.BaseWeb): @@ -29,5 +29,5 @@ class Web(web.BaseWeb): return client.OK, {"Content-Type": "text/plain"}, "custom" def post(self, environ, base_prefix, path, user): - answer = "echo:" + environ["wsgi.input"].read().decode() - return client.OK, {"Content-Type": "text/plain"}, answer + content = httputils.read_request_body(self.configuration, environ) + return client.OK, {"Content-Type": "text/plain"}, "echo:" + content diff --git a/radicale/web/__init__.py b/radicale/web/__init__.py index 6d878331..c18e8d3c 100644 --- a/radicale/web/__init__.py +++ b/radicale/web/__init__.py @@ -63,5 +63,8 @@ class BaseWeb: ``user`` is empty for anonymous users. + Use ``httputils.read*_request_body(self.configuration, environ)`` to + read the body. + """ return httputils.METHOD_NOT_ALLOWED From a3ca887a373b1781fb496d6ff42c40418d75e263 Mon Sep 17 00:00:00 2001 From: Unrud Date: Mon, 14 Sep 2020 21:20:39 +0200 Subject: [PATCH 019/238] Fix exceptions raised by decode_request --- radicale/httputils.py | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/radicale/httputils.py b/radicale/httputils.py index 167a86b8..6911e153 100644 --- a/radicale/httputils.py +++ b/radicale/httputils.py @@ -80,6 +80,10 @@ def decode_request(configuration, environ, text): # Then append various fallbacks charsets.append("utf-8") charsets.append("iso8859-1") + # Remove duplicates + for i, s in reversed(list(enumerate(charsets))): + if s in charsets[:i]: + del charsets[i] # Try to decode for charset in charsets: @@ -87,7 +91,8 @@ def decode_request(configuration, environ, text): return text.decode(charset) except UnicodeDecodeError: pass - raise UnicodeDecodeError + raise UnicodeDecodeError("decode_request", text, 0, len(text), + "all codecs failed [%s]" % ", ".join(charsets)) def read_raw_request_body(configuration, environ): From 81218906c642812ed8c3feb6ae460aec7d2aab21 Mon Sep 17 00:00:00 2001 From: Unrud Date: Mon, 14 Sep 2020 21:35:24 +0200 Subject: [PATCH 020/238] Update NEWS.md --- NEWS.md | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/NEWS.md b/NEWS.md index 7620da0c..e2d05f11 100644 --- a/NEWS.md +++ b/NEWS.md @@ -2,6 +2,10 @@ ## master +## 3.0.6 + + * Allow web plugins to handle POST requests + ## 3.0.5 * Start storage hook in own process group From dd30aea7a572f1e580b8eea2e22fdc01a638d6a2 Mon Sep 17 00:00:00 2001 From: Unrud Date: Fri, 25 Sep 2020 23:36:15 +0200 Subject: [PATCH 021/238] Add Python 3.9 classifier --- setup.py | 1 + 1 file changed, 1 insertion(+) diff --git a/setup.py b/setup.py index 0b40e02b..4f4848d2 100755 --- a/setup.py +++ b/setup.py @@ -90,4 +90,5 @@ setup( "Programming Language :: Python :: 3.6", "Programming Language :: Python :: 3.7", "Programming Language :: Python :: 3.8", + "Programming Language :: Python :: 3.9", "Topic :: Office/Business :: Groupware"]) From d31eaf79ece80bdde597c712bcbaee37a883deaf Mon Sep 17 00:00:00 2001 From: Unrud Date: Sat, 26 Sep 2020 03:20:56 +0200 Subject: [PATCH 022/238] Add Python implementation classifier --- setup.py | 2 ++ 1 file changed, 2 insertions(+) diff --git a/setup.py b/setup.py index 4f4848d2..8341be21 100755 --- a/setup.py +++ b/setup.py @@ -91,4 +91,6 @@ setup( "Programming Language :: Python :: 3.7", "Programming Language :: Python :: 3.8", "Programming Language :: Python :: 3.9", + "Programming Language :: Python :: Implementation :: CPython", + "Programming Language :: Python :: Implementation :: PyPy", "Topic :: Office/Business :: Groupware"]) From 7642d729197b86e10c1d0201e7a6f690598e77f8 Mon Sep 17 00:00:00 2001 From: Unrud Date: Sat, 26 Sep 2020 22:08:21 +0200 Subject: [PATCH 023/238] Improve variable names --- radicale/app/propfind.py | 62 ++++++++++++++++++++------------------ radicale/app/report.py | 16 +++++----- radicale/tests/__init__.py | 10 +++--- 3 files changed, 46 insertions(+), 42 deletions(-) diff --git a/radicale/app/propfind.py b/radicale/app/propfind.py index 106e2e84..59162a6e 100644 --- a/radicale/app/propfind.py +++ b/radicale/app/propfind.py @@ -40,18 +40,18 @@ def xml_propfind(base_prefix, path, xml_request, allowed_items, user, """ # A client may choose not to submit a request body. An empty PROPFIND # request body MUST be treated as if it were an 'allprop' request. - top_tag = (xml_request[0] if xml_request is not None else - ET.Element(xmlutils.make_clark("D:allprop"))) + top_element = (xml_request[0] if xml_request is not None else + ET.Element(xmlutils.make_clark("D:allprop"))) props = () allprop = False propname = False - if top_tag.tag == xmlutils.make_clark("D:allprop"): + if top_element.tag == xmlutils.make_clark("D:allprop"): allprop = True - elif top_tag.tag == xmlutils.make_clark("D:propname"): + elif top_element.tag == xmlutils.make_clark("D:propname"): propname = True - elif top_tag.tag == xmlutils.make_clark("D:prop"): - props = [prop.tag for prop in top_tag] + elif top_element.tag == xmlutils.make_clark("D:prop"): + props = [prop.tag for prop in top_element] if xmlutils.make_clark("D:current-user-principal") in props and not user: # Ask for authentication @@ -152,17 +152,17 @@ def xml_propfind_response(base_prefix, path, item, props, user, encoding, else: is404 = True elif tag == xmlutils.make_clark("D:principal-collection-set"): - tag = ET.Element(xmlutils.make_clark("D:href")) - tag.text = xmlutils.make_href(base_prefix, "/") - element.append(tag) + child_element = ET.Element(xmlutils.make_clark("D:href")) + child_element.text = xmlutils.make_href(base_prefix, "/") + element.append(child_element) elif (tag in (xmlutils.make_clark("C:calendar-user-address-set"), xmlutils.make_clark("D:principal-URL"), xmlutils.make_clark("CR:addressbook-home-set"), xmlutils.make_clark("C:calendar-home-set")) and collection.is_principal and is_collection): - tag = ET.Element(xmlutils.make_clark("D:href")) - tag.text = xmlutils.make_href(base_prefix, path) - element.append(tag) + child_element = ET.Element(xmlutils.make_clark("D:href")) + child_element.text = xmlutils.make_href(base_prefix, path) + element.append(child_element) elif tag == xmlutils.make_clark("C:supported-calendar-component-set"): human_tag = xmlutils.make_human_tag(tag) if is_collection and is_leaf: @@ -179,9 +179,10 @@ def xml_propfind_response(base_prefix, path, item, props, user, encoding, is404 = True elif tag == xmlutils.make_clark("D:current-user-principal"): if user: - tag = ET.Element(xmlutils.make_clark("D:href")) - tag.text = xmlutils.make_href(base_prefix, "/%s/" % user) - element.append(tag) + child_element = ET.Element(xmlutils.make_clark("D:href")) + child_element.text = xmlutils.make_href( + base_prefix, "/%s/" % user) + element.append(child_element) else: element.append(ET.Element( xmlutils.make_clark("D:unauthenticated"))) @@ -213,9 +214,10 @@ def xml_propfind_response(base_prefix, path, item, props, user, encoding, for human_tag in reports: supported_report = ET.Element( xmlutils.make_clark("D:supported-report")) - report_tag = ET.Element(xmlutils.make_clark("D:report")) - report_tag.append(ET.Element(xmlutils.make_clark(human_tag))) - supported_report.append(report_tag) + report_element = ET.Element(xmlutils.make_clark("D:report")) + report_element.append( + ET.Element(xmlutils.make_clark(human_tag))) + supported_report.append(report_element) element.append(supported_report) elif tag == xmlutils.make_clark("D:getcontentlength"): if not is_collection or is_leaf: @@ -225,10 +227,10 @@ def xml_propfind_response(base_prefix, path, item, props, user, encoding, elif tag == xmlutils.make_clark("D:owner"): # return empty elment, if no owner available (rfc3744-5.1) if collection.owner: - tag = ET.Element(xmlutils.make_clark("D:href")) - tag.text = xmlutils.make_href( + child_element = ET.Element(xmlutils.make_clark("D:href")) + child_element.text = xmlutils.make_href( base_prefix, "/%s/" % collection.owner) - element.append(tag) + element.append(child_element) elif is_collection: if tag == xmlutils.make_clark("D:getcontenttype"): if is_leaf: @@ -237,18 +239,20 @@ def xml_propfind_response(base_prefix, path, item, props, user, encoding, is404 = True elif tag == xmlutils.make_clark("D:resourcetype"): if item.is_principal: - tag = ET.Element(xmlutils.make_clark("D:principal")) - element.append(tag) + child_element = ET.Element( + xmlutils.make_clark("D:principal")) + element.append(child_element) if is_leaf: if item.get_meta("tag") == "VADDRESSBOOK": - tag = ET.Element( + child_element = ET.Element( xmlutils.make_clark("CR:addressbook")) - element.append(tag) + element.append(child_element) elif item.get_meta("tag") == "VCALENDAR": - tag = ET.Element(xmlutils.make_clark("C:calendar")) - element.append(tag) - tag = ET.Element(xmlutils.make_clark("D:collection")) - element.append(tag) + child_element = ET.Element( + xmlutils.make_clark("C:calendar")) + element.append(child_element) + child_element = ET.Element(xmlutils.make_clark("D:collection")) + element.append(child_element) elif tag == xmlutils.make_clark("RADICALE:displayname"): # Only for internal use by the web interface displayname = item.get_meta("D:displayname") diff --git a/radicale/app/report.py b/radicale/app/report.py index 18ea4e79..528b17f5 100644 --- a/radicale/app/report.py +++ b/radicale/app/report.py @@ -104,8 +104,8 @@ def xml_report(base_prefix, path, xml_request, collection, encoding, else: hreferences = (path,) filters = ( - root.findall("./%s" % xmlutils.make_clark("C:filter")) + - root.findall("./%s" % xmlutils.make_clark("CR:filter"))) + root.findall(xmlutils.make_clark("C:filter")) + + root.findall(xmlutils.make_clark("CR:filter"))) def retrieve_items(collection, hreferences, multistatus): """Retrieves all items that are referenced in ``hreferences`` from @@ -231,9 +231,9 @@ def xml_item_response(base_prefix, href, found_props=(), not_found_props=(), found_item=True): response = ET.Element(xmlutils.make_clark("D:response")) - href_tag = ET.Element(xmlutils.make_clark("D:href")) - href_tag.text = xmlutils.make_href(base_prefix, href) - response.append(href_tag) + href_element = ET.Element(xmlutils.make_clark("D:href")) + href_element.text = xmlutils.make_href(base_prefix, href) + response.append(href_element) if found_item: for code, props in ((200, found_props), (404, not_found_props)): @@ -241,10 +241,10 @@ def xml_item_response(base_prefix, href, found_props=(), not_found_props=(), propstat = ET.Element(xmlutils.make_clark("D:propstat")) status = ET.Element(xmlutils.make_clark("D:status")) status.text = xmlutils.make_response(code) - prop_tag = ET.Element(xmlutils.make_clark("D:prop")) + prop_element = ET.Element(xmlutils.make_clark("D:prop")) for prop in props: - prop_tag.append(prop) - propstat.append(prop_tag) + prop_element.append(prop) + propstat.append(prop_element) propstat.append(status) response.append(propstat) else: diff --git a/radicale/tests/__init__.py b/radicale/tests/__init__.py index e2e283e2..a3de3007 100644 --- a/radicale/tests/__init__.py +++ b/radicale/tests/__init__.py @@ -76,11 +76,11 @@ class BaseTest: status = propstat.find(xmlutils.make_clark("D:status")) assert status.text.startswith("HTTP/1.1 ") status_code = int(status.text.split(" ")[1]) - for prop in propstat.findall(xmlutils.make_clark("D:prop")): - for element in prop: - human_tag = xmlutils.make_human_tag(element.tag) - assert human_tag not in prop_respones - prop_respones[human_tag] = (status_code, element) + for element in propstat.findall( + "./%s/*" % xmlutils.make_clark("D:prop")): + human_tag = xmlutils.make_human_tag(element.tag) + assert human_tag not in prop_respones + prop_respones[human_tag] = (status_code, element) status = response.find(xmlutils.make_clark("D:status")) if status is not None: assert not prop_respones From 1fe011020b534dbe1f8f3ef02eab4c016043d7d9 Mon Sep 17 00:00:00 2001 From: Unrud Date: Sat, 26 Sep 2020 22:08:21 +0200 Subject: [PATCH 024/238] Single element in PROPPATCH response Instead of multiple elements with the same status --- radicale/app/proppatch.py | 36 +++++++++++------------------------- 1 file changed, 11 insertions(+), 25 deletions(-) diff --git a/radicale/app/proppatch.py b/radicale/app/proppatch.py index 3ec10c30..9c6b5918 100644 --- a/radicale/app/proppatch.py +++ b/radicale/app/proppatch.py @@ -27,29 +27,6 @@ from radicale import storage, xmlutils from radicale.log import logger -def xml_add_propstat_to(element, tag, status_number): - """Add a PROPSTAT response structure to an element. - - The PROPSTAT answer structure is defined in rfc4918-9.1. It is added to the - given ``element``, for the following ``tag`` with the given - ``status_number``. - - """ - propstat = ET.Element(xmlutils.make_clark("D:propstat")) - element.append(propstat) - - prop = ET.Element(xmlutils.make_clark("D:prop")) - propstat.append(prop) - - clark_tag = xmlutils.make_clark(tag) - prop_tag = ET.Element(clark_tag) - prop.append(prop_tag) - - status = ET.Element(xmlutils.make_clark("D:status")) - status.text = xmlutils.make_response(status_number) - propstat.append(status) - - def xml_proppatch(base_prefix, path, xml_request, collection): """Read and answer PROPPATCH requests. @@ -68,16 +45,25 @@ def xml_proppatch(base_prefix, path, xml_request, collection): href.text = xmlutils.make_href(base_prefix, path) response.append(href) + # Create D:propstat element for props with status 200 OK + propstat = ET.Element(xmlutils.make_clark("D:propstat")) + status = ET.Element(xmlutils.make_clark("D:status")) + status.text = xmlutils.make_response(200) + props_ok = ET.Element(xmlutils.make_clark("D:prop")) + propstat.append(props_ok) + propstat.append(status) + response.append(propstat) + new_props = collection.get_meta() for short_name, value in props_to_set.items(): new_props[short_name] = value - xml_add_propstat_to(response, short_name, 200) + props_ok.append(ET.Element(xmlutils.make_clark(short_name))) for short_name in props_to_remove: try: del new_props[short_name] except KeyError: pass - xml_add_propstat_to(response, short_name, 200) + props_ok.append(ET.Element(xmlutils.make_clark(short_name))) radicale_item.check_and_sanitize_props(new_props) collection.set_meta(new_props) From 10dafde32dc01a561f886865e974cc46fdd19dea Mon Sep 17 00:00:00 2001 From: Unrud Date: Sat, 26 Sep 2020 22:08:22 +0200 Subject: [PATCH 025/238] Allow multiple and elements and consider order --- radicale/app/mkcalendar.py | 1 + radicale/app/mkcol.py | 1 + radicale/app/proppatch.py | 21 +++++---------- radicale/xmlutils.py | 52 +++++++++++++++++++++++--------------- 4 files changed, 40 insertions(+), 35 deletions(-) diff --git a/radicale/app/mkcalendar.py b/radicale/app/mkcalendar.py index d5c6c4db..5b2c76f5 100644 --- a/radicale/app/mkcalendar.py +++ b/radicale/app/mkcalendar.py @@ -43,6 +43,7 @@ class ApplicationMkcalendarMixin: return httputils.REQUEST_TIMEOUT # Prepare before locking props = xmlutils.props_from_request(xml_content) + props = {k: v for k, v in props.items() if v is not None} props["tag"] = "VCALENDAR" # TODO: use this? # timezone = props.get("C:calendar-timezone") diff --git a/radicale/app/mkcol.py b/radicale/app/mkcol.py index f7195410..2cef253c 100644 --- a/radicale/app/mkcol.py +++ b/radicale/app/mkcol.py @@ -44,6 +44,7 @@ class ApplicationMkcolMixin: return httputils.REQUEST_TIMEOUT # Prepare before locking props = xmlutils.props_from_request(xml_content) + props = {k: v for k, v in props.items() if v is not None} try: radicale_item.check_and_sanitize_props(props) except ValueError as e: diff --git a/radicale/app/proppatch.py b/radicale/app/proppatch.py index 9c6b5918..fc2ef3d1 100644 --- a/radicale/app/proppatch.py +++ b/radicale/app/proppatch.py @@ -17,6 +17,7 @@ # You should have received a copy of the GNU General Public License # along with Radicale. If not, see . +import contextlib import socket from http import client from xml.etree import ElementTree as ET @@ -33,18 +34,12 @@ def xml_proppatch(base_prefix, path, xml_request, collection): Read rfc4918-9.2 for info. """ - props_to_set = xmlutils.props_from_request(xml_request, actions=("set",)) - props_to_remove = xmlutils.props_from_request(xml_request, - actions=("remove",)) - multistatus = ET.Element(xmlutils.make_clark("D:multistatus")) response = ET.Element(xmlutils.make_clark("D:response")) multistatus.append(response) - href = ET.Element(xmlutils.make_clark("D:href")) href.text = xmlutils.make_href(base_prefix, path) response.append(href) - # Create D:propstat element for props with status 200 OK propstat = ET.Element(xmlutils.make_clark("D:propstat")) status = ET.Element(xmlutils.make_clark("D:status")) @@ -55,14 +50,12 @@ def xml_proppatch(base_prefix, path, xml_request, collection): response.append(propstat) new_props = collection.get_meta() - for short_name, value in props_to_set.items(): - new_props[short_name] = value - props_ok.append(ET.Element(xmlutils.make_clark(short_name))) - for short_name in props_to_remove: - try: - del new_props[short_name] - except KeyError: - pass + for short_name, value in xmlutils.props_from_request(xml_request).items(): + if value is None: + with contextlib.suppress(KeyError): + del new_props[short_name] + else: + new_props[short_name] = value props_ok.append(ET.Element(xmlutils.make_clark(short_name))) radicale_item.check_and_sanitize_props(new_props) collection.set_meta(new_props) diff --git a/radicale/xmlutils.py b/radicale/xmlutils.py index af60ce6b..fa6f6bf8 100644 --- a/radicale/xmlutils.py +++ b/radicale/xmlutils.py @@ -146,36 +146,46 @@ def get_content_type(item, encoding): return content_type -def props_from_request(xml_request, actions=("set", "remove")): - """Return a list of properties as a dictionary.""" +def props_from_request(xml_request): + """Return a list of properties as a dictionary. + + Properties that should be removed are set to `None`. + + """ result = OrderedDict() if xml_request is None: return result - for action in actions: - action_element = xml_request.find(make_clark("D:%s" % action)) - if action_element is not None: - break - else: - action_element = xml_request - - prop_element = action_element.find(make_clark("D:prop")) - if prop_element is not None: - for prop in prop_element: - if prop.tag == make_clark("D:resourcetype"): + # Requests can contain multipe and elements. + # Each of these elements must contain exactly one element which + # can contain multpile properties. + # The order of the elements in the document must be respected. + props = [] + for element in xml_request: + if element.tag in (make_clark("D:set"), make_clark("D:remove")): + for prop in element.findall("./%s/*" % make_clark("D:prop")): + props.append((element.tag == make_clark("D:set"), prop)) + for is_set, prop in props: + key = make_human_tag(prop.tag) + value = None + if prop.tag == make_clark("D:resourcetype"): + key = "tag" + if is_set: for resource_type in prop: if resource_type.tag == make_clark("C:calendar"): - result["tag"] = "VCALENDAR" + value = "VCALENDAR" break if resource_type.tag == make_clark("CR:addressbook"): - result["tag"] = "VADDRESSBOOK" + value = "VADDRESSBOOK" break - elif prop.tag == make_clark("C:supported-calendar-component-set"): - result[make_human_tag(prop.tag)] = ",".join( - supported_comp.attrib["name"] - for supported_comp in prop + elif prop.tag == make_clark("C:supported-calendar-component-set"): + if is_set: + value = ",".join( + supported_comp.attrib["name"] for supported_comp in prop if supported_comp.tag == make_clark("C:comp")) - else: - result[make_human_tag(prop.tag)] = prop.text + elif is_set: + value = prop.text or "" + result[key] = value + result.move_to_end(key) return result From ca27156605c02dbcd528924936f76d396e93f269 Mon Sep 17 00:00:00 2001 From: Unrud Date: Sat, 26 Sep 2020 22:08:22 +0200 Subject: [PATCH 026/238] More tests for PROPPATCH, PROPFIND, MKCALENDAR and MKCOL --- radicale/tests/static/mkcol_make_calendar.xml | 9 ++ ...pfind1.xml => propfind_calendar_color.xml} | 0 radicale/tests/static/propfind_multiple.xml | 7 + .../proppatch_remove_calendar_color.xml | 8 + .../static/proppatch_remove_multiple1.xml | 9 ++ .../static/proppatch_remove_multiple2.xml | 13 ++ .../tests/static/proppatch_set_and_remove.xml | 13 ++ ...1.xml => proppatch_set_calendar_color.xml} | 0 .../tests/static/proppatch_set_multiple1.xml | 9 ++ .../tests/static/proppatch_set_multiple2.xml | 13 ++ radicale/tests/test_base.py | 147 +++++++++++++++++- 11 files changed, 223 insertions(+), 5 deletions(-) create mode 100644 radicale/tests/static/mkcol_make_calendar.xml rename radicale/tests/static/{propfind1.xml => propfind_calendar_color.xml} (100%) create mode 100644 radicale/tests/static/propfind_multiple.xml create mode 100644 radicale/tests/static/proppatch_remove_calendar_color.xml create mode 100644 radicale/tests/static/proppatch_remove_multiple1.xml create mode 100644 radicale/tests/static/proppatch_remove_multiple2.xml create mode 100644 radicale/tests/static/proppatch_set_and_remove.xml rename radicale/tests/static/{proppatch1.xml => proppatch_set_calendar_color.xml} (100%) create mode 100644 radicale/tests/static/proppatch_set_multiple1.xml create mode 100644 radicale/tests/static/proppatch_set_multiple2.xml diff --git a/radicale/tests/static/mkcol_make_calendar.xml b/radicale/tests/static/mkcol_make_calendar.xml new file mode 100644 index 00000000..cfffd5f9 --- /dev/null +++ b/radicale/tests/static/mkcol_make_calendar.xml @@ -0,0 +1,9 @@ + + + + + + #BADA55 + + + \ No newline at end of file diff --git a/radicale/tests/static/propfind1.xml b/radicale/tests/static/propfind_calendar_color.xml similarity index 100% rename from radicale/tests/static/propfind1.xml rename to radicale/tests/static/propfind_calendar_color.xml diff --git a/radicale/tests/static/propfind_multiple.xml b/radicale/tests/static/propfind_multiple.xml new file mode 100644 index 00000000..9b5d03b5 --- /dev/null +++ b/radicale/tests/static/propfind_multiple.xml @@ -0,0 +1,7 @@ + + + + + + + \ No newline at end of file diff --git a/radicale/tests/static/proppatch_remove_calendar_color.xml b/radicale/tests/static/proppatch_remove_calendar_color.xml new file mode 100644 index 00000000..d92edd70 --- /dev/null +++ b/radicale/tests/static/proppatch_remove_calendar_color.xml @@ -0,0 +1,8 @@ + + + + + + + + \ No newline at end of file diff --git a/radicale/tests/static/proppatch_remove_multiple1.xml b/radicale/tests/static/proppatch_remove_multiple1.xml new file mode 100644 index 00000000..0ade9b0f --- /dev/null +++ b/radicale/tests/static/proppatch_remove_multiple1.xml @@ -0,0 +1,9 @@ + + + + + + + + + \ No newline at end of file diff --git a/radicale/tests/static/proppatch_remove_multiple2.xml b/radicale/tests/static/proppatch_remove_multiple2.xml new file mode 100644 index 00000000..c0cfaf6f --- /dev/null +++ b/radicale/tests/static/proppatch_remove_multiple2.xml @@ -0,0 +1,13 @@ + + + + + + + + + + + + + \ No newline at end of file diff --git a/radicale/tests/static/proppatch_set_and_remove.xml b/radicale/tests/static/proppatch_set_and_remove.xml new file mode 100644 index 00000000..d4d56492 --- /dev/null +++ b/radicale/tests/static/proppatch_set_and_remove.xml @@ -0,0 +1,13 @@ + + + + + + + + + + test2 + + + \ No newline at end of file diff --git a/radicale/tests/static/proppatch1.xml b/radicale/tests/static/proppatch_set_calendar_color.xml similarity index 100% rename from radicale/tests/static/proppatch1.xml rename to radicale/tests/static/proppatch_set_calendar_color.xml diff --git a/radicale/tests/static/proppatch_set_multiple1.xml b/radicale/tests/static/proppatch_set_multiple1.xml new file mode 100644 index 00000000..f5cd26f4 --- /dev/null +++ b/radicale/tests/static/proppatch_set_multiple1.xml @@ -0,0 +1,9 @@ + + + + + #BADA55 + test + + + \ No newline at end of file diff --git a/radicale/tests/static/proppatch_set_multiple2.xml b/radicale/tests/static/proppatch_set_multiple2.xml new file mode 100644 index 00000000..8977eb37 --- /dev/null +++ b/radicale/tests/static/proppatch_set_multiple2.xml @@ -0,0 +1,13 @@ + + + + + #BADA55 + + + + + test + + + \ No newline at end of file diff --git a/radicale/tests/test_base.py b/radicale/tests/test_base.py index 97acbec0..5aef8494 100644 --- a/radicale/tests/test_base.py +++ b/radicale/tests/test_base.py @@ -235,7 +235,7 @@ class BaseRequestsMixIn: assert "END:VCALENDAR" in answer def test_mkcalendar_overwrite(self): - """Make a calendar.""" + """Try to overwrite an existing calendar.""" self.mkcalendar("/calendar.ics/") status, answer = self.mkcalendar("/calendar.ics/", check=False) assert status in (403, 409) @@ -244,6 +244,40 @@ class BaseRequestsMixIn: assert xml.find(xmlutils.make_clark( "D:resource-must-be-null")) is not None + def test_mkcalendar_intermediate(self): + """Try make a calendar in a unmapped collection.""" + status, _ = self.mkcalendar("/unmapped/calendar.ics/", check=False) + assert status == 409 + + def test_mkcol(self): + """Make a collection.""" + self.mkcol("/user/") + + def test_mkcol_overwrite(self): + """Try to overwrite an existing collection.""" + self.mkcol("/user/") + status = self.mkcol("/user/", check=False) + assert status == 405 + + def test_mkcol_intermediate(self): + """Try make a collection in a unmapped collection.""" + status = self.mkcol("/unmapped/user/", check=False) + assert status == 409 + + def test_mkcol_make_calendar(self): + """Make a calendar with additional props.""" + mkcol_make_calendar = get_file_content("mkcol_make_calendar.xml") + self.mkcol("/calendar.ics/", mkcol_make_calendar) + _, answer = self.get("/calendar.ics/") + assert "BEGIN:VCALENDAR" in answer + assert "END:VCALENDAR" in answer + # Read additional properties + propfind = get_file_content("propfind_calendar_color.xml") + _, responses = self.propfind("/calendar.ics/", propfind) + assert len(responses["/calendar.ics/"]) == 1 + status, prop = responses["/calendar.ics/"]["ICAL:calendar-color"] + assert status == 200 and prop.text == "#BADA55" + def test_move(self): """Move a item.""" self.mkcalendar("/calendar.ics/") @@ -390,22 +424,22 @@ class BaseRequestsMixIn: def test_propfind_nonexistent(self): """Read a property that does not exist.""" self.mkcalendar("/calendar.ics/") - propfind = get_file_content("propfind1.xml") + propfind = get_file_content("propfind_calendar_color.xml") _, responses = self.propfind("/calendar.ics/", propfind) assert len(responses["/calendar.ics/"]) == 1 status, prop = responses["/calendar.ics/"]["ICAL:calendar-color"] assert status == 404 and not prop.text def test_proppatch(self): - """Write a property and read it back.""" + """Set/Remove a property and read it back.""" self.mkcalendar("/calendar.ics/") - proppatch = get_file_content("proppatch1.xml") + proppatch = get_file_content("proppatch_set_calendar_color.xml") _, responses = self.proppatch("/calendar.ics/", proppatch) assert len(responses["/calendar.ics/"]) == 1 status, prop = responses["/calendar.ics/"]["ICAL:calendar-color"] assert status == 200 and not prop.text # Read property back - propfind = get_file_content("propfind1.xml") + propfind = get_file_content("propfind_calendar_color.xml") _, responses = self.propfind("/calendar.ics/", propfind) assert len(responses["/calendar.ics/"]) == 1 status, prop = responses["/calendar.ics/"]["ICAL:calendar-color"] @@ -414,6 +448,109 @@ class BaseRequestsMixIn: _, responses = self.propfind("/calendar.ics/", propfind) status, prop = responses["/calendar.ics/"]["ICAL:calendar-color"] assert status == 200 and prop.text == "#BADA55" + # Remove property + proppatch = get_file_content("proppatch_remove_calendar_color.xml") + _, responses = self.proppatch("/calendar.ics/", proppatch) + assert len(responses["/calendar.ics/"]) == 1 + status, prop = responses["/calendar.ics/"]["ICAL:calendar-color"] + assert status == 200 and not prop.text + # Read property back + propfind = get_file_content("propfind_calendar_color.xml") + _, responses = self.propfind("/calendar.ics/", propfind) + assert len(responses["/calendar.ics/"]) == 1 + status, prop = responses["/calendar.ics/"]["ICAL:calendar-color"] + assert status == 404 + + def test_proppatch_multiple1(self): + """Set/Remove a multiple properties and read them back.""" + self.mkcalendar("/calendar.ics/") + propfind = get_file_content("propfind_multiple.xml") + proppatch = get_file_content("proppatch_set_multiple1.xml") + _, responses = self.proppatch("/calendar.ics/", proppatch) + assert len(responses["/calendar.ics/"]) == 2 + status, prop = responses["/calendar.ics/"]["ICAL:calendar-color"] + assert status == 200 and not prop.text + status, prop = responses["/calendar.ics/"]["C:calendar-description"] + assert status == 200 and not prop.text + # Read properties back + _, responses = self.propfind("/calendar.ics/", propfind) + assert len(responses["/calendar.ics/"]) == 2 + status, prop = responses["/calendar.ics/"]["ICAL:calendar-color"] + assert status == 200 and prop.text == "#BADA55" + status, prop = responses["/calendar.ics/"]["C:calendar-description"] + assert status == 200 and prop.text == "test" + # Remove properties + proppatch = get_file_content("proppatch_remove_multiple1.xml") + _, responses = self.proppatch("/calendar.ics/", proppatch) + assert len(responses["/calendar.ics/"]) == 2 + status, prop = responses["/calendar.ics/"]["ICAL:calendar-color"] + assert status == 200 and not prop.text + status, prop = responses["/calendar.ics/"]["C:calendar-description"] + assert status == 200 and not prop.text + # Read properties back + _, responses = self.propfind("/calendar.ics/", propfind) + assert len(responses["/calendar.ics/"]) == 2 + status, prop = responses["/calendar.ics/"]["ICAL:calendar-color"] + assert status == 404 + status, prop = responses["/calendar.ics/"]["C:calendar-description"] + assert status == 404 + + def test_proppatch_multiple2(self): + """Set/Remove a multiple properties and read them back.""" + self.mkcalendar("/calendar.ics/") + propfind = get_file_content("propfind_multiple.xml") + proppatch = get_file_content("proppatch_set_multiple2.xml") + _, responses = self.proppatch("/calendar.ics/", proppatch) + assert len(responses["/calendar.ics/"]) == 2 + status, prop = responses["/calendar.ics/"]["ICAL:calendar-color"] + assert status == 200 and not prop.text + status, prop = responses["/calendar.ics/"]["C:calendar-description"] + assert status == 200 and not prop.text + # Read properties back + _, responses = self.propfind("/calendar.ics/", propfind) + assert len(responses["/calendar.ics/"]) == 2 + status, prop = responses["/calendar.ics/"]["ICAL:calendar-color"] + assert status == 200 and prop.text == "#BADA55" + status, prop = responses["/calendar.ics/"]["C:calendar-description"] + assert status == 200 and prop.text == "test" + # Remove properties + proppatch = get_file_content("proppatch_remove_multiple2.xml") + _, responses = self.proppatch("/calendar.ics/", proppatch) + assert len(responses["/calendar.ics/"]) == 2 + status, prop = responses["/calendar.ics/"]["ICAL:calendar-color"] + assert status == 200 and not prop.text + status, prop = responses["/calendar.ics/"]["C:calendar-description"] + assert status == 200 and not prop.text + # Read properties back + _, responses = self.propfind("/calendar.ics/", propfind) + assert len(responses["/calendar.ics/"]) == 2 + status, prop = responses["/calendar.ics/"]["ICAL:calendar-color"] + assert status == 404 + status, prop = responses["/calendar.ics/"]["C:calendar-description"] + assert status == 404 + + def test_proppatch_set_and_remove(self): + """Set and remove multiple properties in single request.""" + self.mkcalendar("/calendar.ics/") + propfind = get_file_content("propfind_multiple.xml") + # Prepare + proppatch = get_file_content("proppatch_set_multiple1.xml") + self.proppatch("/calendar.ics/", proppatch) + # Remove and set properties in single request + proppatch = get_file_content("proppatch_set_and_remove.xml") + _, responses = self.proppatch("/calendar.ics/", proppatch) + assert len(responses["/calendar.ics/"]) == 2 + status, prop = responses["/calendar.ics/"]["ICAL:calendar-color"] + assert status == 200 and not prop.text + status, prop = responses["/calendar.ics/"]["C:calendar-description"] + assert status == 200 and not prop.text + # Read properties back + _, responses = self.propfind("/calendar.ics/", propfind) + assert len(responses["/calendar.ics/"]) == 2 + status, prop = responses["/calendar.ics/"]["ICAL:calendar-color"] + assert status == 404 + status, prop = responses["/calendar.ics/"]["C:calendar-description"] + assert status == 200 and prop.text == "test2" def test_put_whole_calendar_multiple_events_with_same_uid(self): """Add two events with the same UID.""" From d48bacc8e3414ffba7c3c8c21987f2ada8f0ab48 Mon Sep 17 00:00:00 2001 From: Unrud Date: Sat, 26 Sep 2020 22:08:23 +0200 Subject: [PATCH 027/238] Improve log messages Log failed login attempts with remote host as warning (closes #1104) Add component UID to log message about invalid recurrence rules (reference #602) Use "forwarded for" instead of "forwarded by" for remote host --- radicale/app/__init__.py | 7 ++++--- radicale/app/mkcalendar.py | 2 +- radicale/app/mkcol.py | 2 +- radicale/app/propfind.py | 2 +- radicale/app/proppatch.py | 2 +- radicale/app/put.py | 2 +- radicale/app/report.py | 4 ++-- radicale/config.py | 2 +- radicale/item/__init__.py | 8 ++++---- 9 files changed, 16 insertions(+), 15 deletions(-) diff --git a/radicale/app/__init__.py b/radicale/app/__init__.py index b0c53a98..564a45b3 100644 --- a/radicale/app/__init__.py +++ b/radicale/app/__init__.py @@ -167,8 +167,8 @@ class Application( elif environ.get("REMOTE_ADDR"): remote_host = environ["REMOTE_ADDR"] if environ.get("HTTP_X_FORWARDED_FOR"): - remote_host = "%r (forwarded by %s)" % ( - environ["HTTP_X_FORWARDED_FOR"], remote_host) + remote_host = "%s (forwarded for %r)" % ( + remote_host, environ["HTTP_X_FORWARDED_FOR"]) remote_useragent = "" if environ.get("HTTP_USER_AGENT"): remote_useragent = " using %r" % environ["HTTP_USER_AGENT"] @@ -230,7 +230,8 @@ class Application( elif user: logger.info("Successful login: %r -> %r", login, user) elif login: - logger.info("Failed login attempt: %r", login) + logger.warning("Failed login attempt from %s: %r", + remote_host, login) # Random delay to avoid timing oracles and bruteforce attacks delay = self.configuration.get("auth", "delay") if delay > 0: diff --git a/radicale/app/mkcalendar.py b/radicale/app/mkcalendar.py index 5b2c76f5..ae141819 100644 --- a/radicale/app/mkcalendar.py +++ b/radicale/app/mkcalendar.py @@ -39,7 +39,7 @@ class ApplicationMkcalendarMixin: "Bad MKCALENDAR request on %r: %s", path, e, exc_info=True) return httputils.BAD_REQUEST except socket.timeout: - logger.debug("client timed out", exc_info=True) + logger.debug("Client timed out", exc_info=True) return httputils.REQUEST_TIMEOUT # Prepare before locking props = xmlutils.props_from_request(xml_content) diff --git a/radicale/app/mkcol.py b/radicale/app/mkcol.py index 2cef253c..4118141d 100644 --- a/radicale/app/mkcol.py +++ b/radicale/app/mkcol.py @@ -40,7 +40,7 @@ class ApplicationMkcolMixin: "Bad MKCOL request on %r: %s", path, e, exc_info=True) return httputils.BAD_REQUEST except socket.timeout: - logger.debug("client timed out", exc_info=True) + logger.debug("Client timed out", exc_info=True) return httputils.REQUEST_TIMEOUT # Prepare before locking props = xmlutils.props_from_request(xml_content) diff --git a/radicale/app/propfind.py b/radicale/app/propfind.py index 59162a6e..cacbed93 100644 --- a/radicale/app/propfind.py +++ b/radicale/app/propfind.py @@ -357,7 +357,7 @@ class ApplicationPropfindMixin: "Bad PROPFIND request on %r: %s", path, e, exc_info=True) return httputils.BAD_REQUEST except socket.timeout: - logger.debug("client timed out", exc_info=True) + logger.debug("Client timed out", exc_info=True) return httputils.REQUEST_TIMEOUT with self._storage.acquire_lock("r", user): items = self._storage.discover( diff --git a/radicale/app/proppatch.py b/radicale/app/proppatch.py index fc2ef3d1..a77228f6 100644 --- a/radicale/app/proppatch.py +++ b/radicale/app/proppatch.py @@ -76,7 +76,7 @@ class ApplicationProppatchMixin: "Bad PROPPATCH request on %r: %s", path, e, exc_info=True) return httputils.BAD_REQUEST except socket.timeout: - logger.debug("client timed out", exc_info=True) + logger.debug("Client timed out", exc_info=True) return httputils.REQUEST_TIMEOUT with self._storage.acquire_lock("w", user): item = next(self._storage.discover(path), None) diff --git a/radicale/app/put.py b/radicale/app/put.py index efaf9053..29519745 100644 --- a/radicale/app/put.py +++ b/radicale/app/put.py @@ -123,7 +123,7 @@ class ApplicationPutMixin: logger.warning("Bad PUT request on %r: %s", path, e, exc_info=True) return httputils.BAD_REQUEST except socket.timeout: - logger.debug("client timed out", exc_info=True) + logger.debug("Client timed out", exc_info=True) return httputils.REQUEST_TIMEOUT # Prepare before locking content_type = environ.get("CONTENT_TYPE", "").split(";")[0] diff --git a/radicale/app/report.py b/radicale/app/report.py index 528b17f5..99cd01a2 100644 --- a/radicale/app/report.py +++ b/radicale/app/report.py @@ -181,7 +181,7 @@ def xml_report(base_prefix, path, xml_request, collection, encoding, radicale_filter.prop_match(item.vobject_item, f, "CR") for f in filter_) raise ValueError("Unsupported filter test: %r" % test) - raise ValueError("unsupported filter %r for %r" % (filter_.tag, tag)) + raise ValueError("Unsupported filter %r for %r" % (filter_.tag, tag)) while retrieved_items: # ``item.vobject_item`` might be accessed during filtering. @@ -268,7 +268,7 @@ class ApplicationReportMixin: "Bad REPORT request on %r: %s", path, e, exc_info=True) return httputils.BAD_REQUEST except socket.timeout: - logger.debug("client timed out", exc_info=True) + logger.debug("Client timed out", exc_info=True) return httputils.REQUEST_TIMEOUT with contextlib.ExitStack() as lock_stack: lock_stack.enter_context(self._storage.acquire_lock("r", user)) diff --git a/radicale/config.py b/radicale/config.py index d30e677c..10dd59f5 100644 --- a/radicale/config.py +++ b/radicale/config.py @@ -94,7 +94,7 @@ def unspecified_type(value): def _convert_to_bool(value): if value.lower() not in RawConfigParser.BOOLEAN_STATES: - raise ValueError("Not a boolean: %r" % value) + raise ValueError("not a boolean: %r" % value) return RawConfigParser.BOOLEAN_STATES[value.lower()] diff --git a/radicale/item/__init__.py b/radicale/item/__init__.py index 53a21137..3bbc55e9 100644 --- a/radicale/item/__init__.py +++ b/radicale/item/__init__.py @@ -134,8 +134,8 @@ def check_and_sanitize_items(vobject_items, is_collection=False, tag=None): try: component.rruleset except Exception as e: - raise ValueError("invalid recurrence rules in %s" % - component.name) from e + raise ValueError("Invalid recurrence rules in %s in object %r" + % (component.name, component_uid)) from e elif tag == "VADDRESSBOOK": # https://tools.ietf.org/html/rfc6352#section-5.1 object_uids = set() @@ -311,10 +311,10 @@ class Item: """ if text is None and vobject_item is None: raise ValueError( - "at least one of 'text' or 'vobject_item' must be set") + "At least one of 'text' or 'vobject_item' must be set") if collection_path is None: if collection is None: - raise ValueError("at least one of 'collection_path' or " + raise ValueError("At least one of 'collection_path' or " "'collection' must be set") collection_path = collection.path assert collection_path == pathutils.strip_path( From 236eedb555222901575977346a2a166b870f8c76 Mon Sep 17 00:00:00 2001 From: Unrud Date: Sun, 27 Sep 2020 18:08:29 +0200 Subject: [PATCH 028/238] Merge pull request #1110 from pbiering/url-fix-fedora Squashed commit of the following: commit 9f1a11c832e1e5fd552f193bd8cd9614a738cb85 Author: Peter Bieringer Date: Sun Sep 27 16:56:35 2020 +0200 url fix for Fedora commit 240af9803fbd3f1b6c5920d27516cf2a5d370f58 Merge: 1e55a31 d48bacc Author: Peter Bieringer Date: Sun Sep 27 16:49:49 2020 +0200 Merge remote-tracking branch 'upstream/master' commit 1e55a314d5700d2851e19988cda8c651382c99b5 Merge: d61f4e7 d31eaf7 Author: Peter Bieringer Date: Sat Sep 26 10:14:53 2020 +0200 Merge remote-tracking branch 'upstream/master' commit d61f4e7b819ee68dbcb2b740500a314c3e356e2b Author: Unrud Date: Mon Apr 30 00:18:36 2018 +0200 Auth: Introduce login(login, password) method This deprecates map_login_to_user, is_authenticated and is_authenticated2 commit 7ecd7343baf7c7b5f10dc5a7de3847c07aa092f5 Author: Unrud Date: Sun Jun 25 11:18:05 2017 +0200 Empty commit for release of 2.1.0 --- DOCUMENTATION.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/DOCUMENTATION.md b/DOCUMENTATION.md index 3f55b9d6..95c5f649 100644 --- a/DOCUMENTATION.md +++ b/DOCUMENTATION.md @@ -1392,7 +1392,7 @@ Radicale has been packaged for: * [Debian](http://packages.debian.org/radicale) by Jonas Smedegaard * [Gentoo](https://packages.gentoo.org/packages/www-apps/radicale) by René Neumann, Maxim Koltsov and Manuel Rüger - * [Fedora](https://admin.fedoraproject.org/pkgdb/package/radicale/) by Jorti + * [Fedora/RHEL/CentOS](https://src.fedoraproject.org/rpms/radicale) by Jorti and Peter Bieringer * [Mageia](http://madb.mageia.org/package/show/application/0/name/radicale) by Jani Välimaa * [OpenBSD](http://openports.se/productivity/radicale) by Sergey Bronnikov, From 7096ab74e8122cc28f8de43476739001c1750218 Mon Sep 17 00:00:00 2001 From: Unrud Date: Sun, 4 Oct 2020 05:38:58 +0200 Subject: [PATCH 029/238] Don't modify global constants --- radicale/__main__.py | 2 +- radicale/config.py | 10 +++++----- 2 files changed, 6 insertions(+), 6 deletions(-) diff --git a/radicale/__main__.py b/radicale/__main__.py index d0ea10ea..a657cae4 100644 --- a/radicale/__main__.py +++ b/radicale/__main__.py @@ -71,7 +71,7 @@ def run(): continue kwargs = data.copy() long_name = "--%s-%s" % (section, option.replace("_", "-")) - args = kwargs.pop("aliases", []) + args = list(kwargs.pop("aliases", ())) args.append(long_name) kwargs["dest"] = "%s_%s" % (section, option) groups[group].append(kwargs["dest"]) diff --git a/radicale/config.py b/radicale/config.py index 10dd59f5..ae5c9c5e 100644 --- a/radicale/config.py +++ b/radicale/config.py @@ -105,7 +105,7 @@ DEFAULT_CONFIG_SCHEMA = OrderedDict([ ("hosts", { "value": "localhost:5232", "help": "set server hostnames including ports", - "aliases": ["-H", "--hosts"], + "aliases": ("-H", "--hosts",), "type": list_of_ip_address}), ("max_connections", { "value": "8", @@ -122,23 +122,23 @@ DEFAULT_CONFIG_SCHEMA = OrderedDict([ ("ssl", { "value": "False", "help": "use SSL connection", - "aliases": ["-s", "--ssl"], + "aliases": ("-s", "--ssl",), "opposite": ["-S", "--no-ssl"], "type": bool}), ("certificate", { "value": "/etc/ssl/radicale.cert.pem", "help": "set certificate file", - "aliases": ["-c", "--certificate"], + "aliases": ("-c", "--certificate",), "type": filepath}), ("key", { "value": "/etc/ssl/radicale.key.pem", "help": "set private key file", - "aliases": ["-k", "--key"], + "aliases": ("-k", "--key",), "type": filepath}), ("certificate_authority", { "value": "", "help": "set CA certificate for validating clients", - "aliases": ["--certificate-authority"], + "aliases": ("--certificate-authority",), "type": filepath}), ("_internal_server", { "value": "False", From a9804dd55062708c6857d4790ffb2d4028c26f3e Mon Sep 17 00:00:00 2001 From: Unrud Date: Sun, 4 Oct 2020 05:39:58 +0200 Subject: [PATCH 030/238] Don't use assertion for expected error --- radicale/server.py | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/radicale/server.py b/radicale/server.py index 8cada22a..d6e52fa7 100644 --- a/radicale/server.py +++ b/radicale/server.py @@ -260,7 +260,8 @@ def serve(configuration, shutdown_socket=None): logger.info("Listening on %r%s", format_address(server.server_address), " with SSL" if use_ssl else "") - assert servers, "no servers started" + if not servers: + raise RuntimeError("No servers started") # Mainloop select_timeout = None From 18f21e26d526a1c3d18f3a6f2dc95862a5eece1e Mon Sep 17 00:00:00 2001 From: Unrud Date: Sun, 4 Oct 2020 05:40:46 +0200 Subject: [PATCH 031/238] Improve log message --- radicale/server.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/radicale/server.py b/radicale/server.py index d6e52fa7..9cca4162 100644 --- a/radicale/server.py +++ b/radicale/server.py @@ -97,7 +97,7 @@ class ParallelHTTPServer(socketserver.ThreadingMixIn, def handle_error(self, request, client_address): if issubclass(sys.exc_info()[0], socket.timeout): - logger.info("client timed out", exc_info=True) + logger.info("Client timed out", exc_info=True) else: logger.error("An exception occurred during request: %s", sys.exc_info()[1], exc_info=True) From 0b3e4204a55e30bc48b76479c9d82c100d6ab0cd Mon Sep 17 00:00:00 2001 From: Unrud Date: Sun, 4 Oct 2020 10:14:57 +0200 Subject: [PATCH 032/238] Cosmetics --- radicale/app/__init__.py | 2 +- radicale/app/delete.py | 2 +- radicale/app/propfind.py | 2 +- radicale/app/proppatch.py | 2 +- radicale/app/report.py | 2 +- 5 files changed, 5 insertions(+), 5 deletions(-) diff --git a/radicale/app/__init__.py b/radicale/app/__init__.py index 564a45b3..3e95d8f7 100644 --- a/radicale/app/__init__.py +++ b/radicale/app/__init__.py @@ -33,9 +33,9 @@ import posixpath import pprint import random import time +import xml.etree.ElementTree as ET import zlib from http import client -from xml.etree import ElementTree as ET import defusedxml.ElementTree as DefusedET import pkg_resources diff --git a/radicale/app/delete.py b/radicale/app/delete.py index df587a5f..05437c81 100644 --- a/radicale/app/delete.py +++ b/radicale/app/delete.py @@ -17,8 +17,8 @@ # You should have received a copy of the GNU General Public License # along with Radicale. If not, see . +import xml.etree.ElementTree as ET from http import client -from xml.etree import ElementTree as ET from radicale import app, httputils, storage, xmlutils diff --git a/radicale/app/propfind.py b/radicale/app/propfind.py index cacbed93..55ca2d3a 100644 --- a/radicale/app/propfind.py +++ b/radicale/app/propfind.py @@ -21,8 +21,8 @@ import collections import itertools import posixpath import socket +import xml.etree.ElementTree as ET from http import client -from xml.etree import ElementTree as ET from radicale import app, httputils, pathutils, rights, storage, xmlutils from radicale.log import logger diff --git a/radicale/app/proppatch.py b/radicale/app/proppatch.py index a77228f6..38804dd1 100644 --- a/radicale/app/proppatch.py +++ b/radicale/app/proppatch.py @@ -19,8 +19,8 @@ import contextlib import socket +import xml.etree.ElementTree as ET from http import client -from xml.etree import ElementTree as ET from radicale import app, httputils from radicale import item as radicale_item diff --git a/radicale/app/report.py b/radicale/app/report.py index 99cd01a2..0c35783f 100644 --- a/radicale/app/report.py +++ b/radicale/app/report.py @@ -20,9 +20,9 @@ import contextlib import posixpath import socket +import xml.etree.ElementTree as ET from http import client from urllib.parse import unquote, urlparse -from xml.etree import ElementTree as ET from radicale import app, httputils, pathutils, storage, xmlutils from radicale.item import filter as radicale_filter From b14889e17087672952c7f009641e90d507ea90f1 Mon Sep 17 00:00:00 2001 From: Unrud Date: Sun, 4 Oct 2020 10:15:16 +0200 Subject: [PATCH 033/238] Workaround: defusedxml messes up subsequent imports of ElementTree See https://github.com/tiran/defusedxml/issues/54 --- radicale/app/__init__.py | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/radicale/app/__init__.py b/radicale/app/__init__.py index 3e95d8f7..21dcd11c 100644 --- a/radicale/app/__init__.py +++ b/radicale/app/__init__.py @@ -32,12 +32,12 @@ import logging import posixpath import pprint import random +import sys import time import xml.etree.ElementTree as ET import zlib from http import client -import defusedxml.ElementTree as DefusedET import pkg_resources from radicale import (auth, httputils, log, pathutils, rights, storage, web, @@ -56,6 +56,10 @@ from radicale.app.put import ApplicationPutMixin from radicale.app.report import ApplicationReportMixin from radicale.log import logger +# WORKAROUND: https://github.com/tiran/defusedxml/issues/54 +import defusedxml.ElementTree as DefusedET # isort: skip +sys.modules["xml.etree"].ElementTree = ET + VERSION = pkg_resources.get_distribution("radicale").version From c8b31637ef1e94e7953ea1bf737e2e12fcb9f86c Mon Sep 17 00:00:00 2001 From: Unrud Date: Sun, 4 Oct 2020 13:40:30 +0200 Subject: [PATCH 034/238] Improve log messages --- radicale/storage/multifilesystem/lock.py | 9 +++++---- 1 file changed, 5 insertions(+), 4 deletions(-) diff --git a/radicale/storage/multifilesystem/lock.py b/radicale/storage/multifilesystem/lock.py index e5febd22..3060dd72 100644 --- a/radicale/storage/multifilesystem/lock.py +++ b/radicale/storage/multifilesystem/lock.py @@ -70,21 +70,22 @@ class StorageLockMixin: popen_kwargs["creationflags"] = ( subprocess.CREATE_NEW_PROCESS_GROUP) command = hook % {"user": shlex.quote(user or "Anonymous")} - logger.debug("Running hook") + logger.debug("Running storage hook") p = subprocess.Popen(command, **popen_kwargs) try: stdout_data, stderr_data = p.communicate() except BaseException: # e.g. KeyboardInterrupt or SystemExit p.kill() + p.wait() raise finally: if os.name == "posix": - # Try to kill child processes + # Kill remaining children identified by process group with contextlib.suppress(OSError): os.killpg(p.pid, signal.SIGKILL) if stdout_data: - logger.debug("Captured stdout hook:\n%s", stdout_data) + logger.debug("Captured stdout from hook:\n%s", stdout_data) if stderr_data: - logger.debug("Captured stderr hook:\n%s", stderr_data) + logger.debug("Captured stderr from hook:\n%s", stderr_data) if p.returncode != 0: raise subprocess.CalledProcessError(p.returncode, p.args) From 0e8949ff7146260c86c238667e1371a412b67721 Mon Sep 17 00:00:00 2001 From: Unrud Date: Sun, 4 Oct 2020 14:11:43 +0200 Subject: [PATCH 035/238] Internal server: Shutdown server via socket --- radicale/__main__.py | 26 ++++++++++++++++++++------ radicale/server.py | 1 + radicale/tests/test_server.py | 2 ++ 3 files changed, 23 insertions(+), 6 deletions(-) diff --git a/radicale/__main__.py b/radicale/__main__.py index a657cae4..6cef2ad3 100644 --- a/radicale/__main__.py +++ b/radicale/__main__.py @@ -27,6 +27,7 @@ import argparse import contextlib import os import signal +import socket import sys from radicale import VERSION, config, log, server, storage @@ -35,16 +36,20 @@ from radicale.log import logger def run(): """Run Radicale as a standalone server.""" + exit_signal_numbers = [signal.SIGTERM, signal.SIGINT] + if os.name == "posix": + exit_signal_numbers.append(signal.SIGHUP) + exit_signal_numbers.append(signal.SIGQUIT) + elif os.name == "nt": + exit_signal_numbers.append(signal.SIGBREAK) # Raise SystemExit when signal arrives to run cleanup code # (like destructors, try-finish etc.), otherwise the process exits # without running any of them - def signal_handler(signal_number, stack_frame): + def exit_signal_handler(signal_number, stack_frame): sys.exit(1) - signal.signal(signal.SIGTERM, signal_handler) - signal.signal(signal.SIGINT, signal_handler) - if os.name == "posix": - signal.signal(signal.SIGHUP, signal_handler) + for signal_number in exit_signal_numbers: + signal.signal(signal_number, exit_signal_handler) log.setup() @@ -148,8 +153,17 @@ def run(): sys.exit(1) return + # Create a socket pair to notify the server of program shutdown + shutdown_socket, shutdown_socket_out = socket.socketpair() + + # Shutdown server when signal arrives + def shutdown_signal_handler(signal_number, stack_frame): + shutdown_socket.close() + for signal_number in exit_signal_numbers: + signal.signal(signal_number, shutdown_signal_handler) + try: - server.serve(configuration) + server.serve(configuration, shutdown_socket_out) except Exception as e: logger.fatal("An exception occurred during server startup: %s", e, exc_info=True) diff --git a/radicale/server.py b/radicale/server.py index 9cca4162..97f6afe1 100644 --- a/radicale/server.py +++ b/radicale/server.py @@ -61,6 +61,7 @@ class ParallelHTTPServer(socketserver.ThreadingMixIn, # We wait for child threads ourself block_on_close = False + daemon_threads = True def __init__(self, configuration, family, address, RequestHandlerClass): self.configuration = configuration diff --git a/radicale/tests/test_server.py b/radicale/tests/test_server.py index a58e94ec..90beefdc 100644 --- a/radicale/tests/test_server.py +++ b/radicale/tests/test_server.py @@ -180,6 +180,8 @@ class TestBaseServerRequests(BaseTest): finally: p.terminate() p.wait() + if os.name == "posix": + assert p.returncode == 0 def test_wsgi_server(self): config_path = os.path.join(self.colpath, "config") From 571567a4ecfca6832c2302f9c6e50ce9f32c5b26 Mon Sep 17 00:00:00 2001 From: Unrud Date: Sun, 4 Oct 2020 15:13:01 +0200 Subject: [PATCH 036/238] Drop support for Python 3.5 (end-of-life) --- .github/workflows/test.yml | 2 +- setup.py | 3 +-- 2 files changed, 2 insertions(+), 3 deletions(-) diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml index 0283b04b..7ac76f2d 100644 --- a/.github/workflows/test.yml +++ b/.github/workflows/test.yml @@ -7,7 +7,7 @@ jobs: strategy: matrix: os: [ubuntu-latest, macos-latest, windows-latest] - python-version: [3.5, 3.6, 3.7, 3.8, '3.9.0-alpha - 3.9', pypy3] + python-version: [3.6, 3.7, 3.8, '3.9.0-alpha - 3.9', pypy3] steps: - uses: actions/checkout@v2 - uses: actions/setup-python@v2 diff --git a/setup.py b/setup.py index 8341be21..b6786e99 100755 --- a/setup.py +++ b/setup.py @@ -76,7 +76,7 @@ setup( extras_require={"test": tests_require, "bcrypt": ["passlib[bcrypt]", "bcrypt"]}, keywords=["calendar", "addressbook", "CalDAV", "CardDAV"], - python_requires=">=3.5.2", + python_requires=">=3.6.0", classifiers=[ "Development Status :: 5 - Production/Stable", "Environment :: Console", @@ -86,7 +86,6 @@ setup( "License :: OSI Approved :: GNU General Public License (GPL)", "Operating System :: OS Independent", "Programming Language :: Python :: 3", - "Programming Language :: Python :: 3.5", "Programming Language :: Python :: 3.6", "Programming Language :: Python :: 3.7", "Programming Language :: Python :: 3.8", From 9909454761cf1b0f2ecaac25c421b539a211c395 Mon Sep 17 00:00:00 2001 From: Unrud Date: Mon, 5 Oct 2020 15:33:32 +0200 Subject: [PATCH 037/238] Fix matching of date property --- radicale/item/filter.py | 9 ++++++--- 1 file changed, 6 insertions(+), 3 deletions(-) diff --git a/radicale/item/filter.py b/radicale/item/filter.py index 2d1d179b..c3143dbd 100644 --- a/radicale/item/filter.py +++ b/radicale/item/filter.py @@ -410,9 +410,12 @@ def visit_time_ranges(vobject_item, child_name, range_fn, infinity_fn): # Match a property child = getattr(vobject_item, child_name.lower()) if isinstance(child, date): - range_fn(child, child + DAY, False) - elif isinstance(child, datetime): - range_fn(child, child + SECOND, False) + child_is_datetime = isinstance(child, datetime) + child = date_to_datetime(child) + if child_is_datetime: + range_fn(child, child + SECOND, False) + else: + range_fn(child, child + DAY, False) def text_match(vobject_item, filter_, child_name, ns, attrib_name=None): From 4d4b040b81ef66d91454fce163118fafd6f4ed2f Mon Sep 17 00:00:00 2001 From: Unrud Date: Sun, 11 Oct 2020 18:42:09 +0200 Subject: [PATCH 038/238] Improve sanitization of collection properties --- radicale/item/__init__.py | 19 ++++++++++++++++--- 1 file changed, 16 insertions(+), 3 deletions(-) diff --git a/radicale/item/__init__.py b/radicale/item/__init__.py index 3bbc55e9..ce6d7751 100644 --- a/radicale/item/__init__.py +++ b/radicale/item/__init__.py @@ -171,9 +171,22 @@ def check_and_sanitize_items(vobject_items, is_collection=False, tag=None): def check_and_sanitize_props(props): """Check collection properties for common errors.""" - tag = props.get("tag") - if tag and tag not in ("VCALENDAR", "VADDRESSBOOK"): - raise ValueError("Unsupported collection tag: %r" % tag) + for k, v in props.copy().items(): # Make copy to be able to delete items + if not isinstance(k, str): + raise ValueError("Key must be %r not %r: %r" % ( + str.__name__, type(k).__name__, k)) + if not isinstance(v, str): + if v is None: + del props[k] + continue + raise ValueError("Value of %r must be %r not %r: %r" % ( + k, str.__name__, type(v).__name__, v)) + if k == "tag": + if not v: + del props[k] + continue + if v not in ("VCALENDAR", "VADDRESSBOOK"): + raise ValueError("Unsupported collection tag: %r" % v) def find_available_uid(exists_fn, suffix=""): From b4c76c94ad7dad3905f914c2b3ec1bfa6dba0c72 Mon Sep 17 00:00:00 2001 From: Unrud Date: Sun, 11 Oct 2020 19:13:10 +0200 Subject: [PATCH 039/238] Cancel mkcalendar request on error --- radicale/app/mkcalendar.py | 1 + 1 file changed, 1 insertion(+) diff --git a/radicale/app/mkcalendar.py b/radicale/app/mkcalendar.py index ae141819..f0649d76 100644 --- a/radicale/app/mkcalendar.py +++ b/radicale/app/mkcalendar.py @@ -52,6 +52,7 @@ class ApplicationMkcalendarMixin: except ValueError as e: logger.warning( "Bad MKCALENDAR request on %r: %s", path, e, exc_info=True) + return httputils.BAD_REQUEST with self._storage.acquire_lock("w", user): item = next(self._storage.discover(path), None) if item: From f05251bd012e39cedf7235ec43bff2d2a6589cdc Mon Sep 17 00:00:00 2001 From: Unrud Date: Fri, 23 Oct 2020 21:20:16 +0200 Subject: [PATCH 040/238] Improve error messages for locking problems on Windows --- radicale/pathutils.py | 12 ++++++++---- 1 file changed, 8 insertions(+), 4 deletions(-) diff --git a/radicale/pathutils.py b/radicale/pathutils.py index 3d3df42b..6a2cb1b4 100644 --- a/radicale/pathutils.py +++ b/radicale/pathutils.py @@ -45,7 +45,8 @@ if os.name == "nt": ("offset_high", ctypes.wintypes.DWORD), ("h_event", ctypes.wintypes.HANDLE)] - lock_file_ex = ctypes.windll.kernel32.LockFileEx + kernel32 = ctypes.WinDLL("kernel32", use_last_error=True) + lock_file_ex = kernel32.LockFileEx lock_file_ex.argtypes = [ ctypes.wintypes.HANDLE, ctypes.wintypes.DWORD, @@ -54,7 +55,7 @@ if os.name == "nt": ctypes.wintypes.DWORD, ctypes.POINTER(Overlapped)] lock_file_ex.restype = ctypes.wintypes.BOOL - unlock_file_ex = ctypes.windll.kernel32.UnlockFileEx + unlock_file_ex = kernel32.UnlockFileEx unlock_file_ex.argtypes = [ ctypes.wintypes.HANDLE, ctypes.wintypes.DWORD, @@ -93,9 +94,12 @@ class RwLock: handle = msvcrt.get_osfhandle(lock_file.fileno()) flags = LOCKFILE_EXCLUSIVE_LOCK if mode == "w" else 0 overlapped = Overlapped() - if not lock_file_ex(handle, flags, 0, 1, 0, overlapped): + try: + if not lock_file_ex(handle, flags, 0, 1, 0, overlapped): + raise ctypes.WinError() + except OSError as e: raise RuntimeError("Locking the storage failed: %s" % - ctypes.FormatError()) + e) from e elif os.name == "posix": _cmd = fcntl.LOCK_EX if mode == "w" else fcntl.LOCK_SH try: From 2aafcd5df547f8d009b6d2e197a517906ad37c8a Mon Sep 17 00:00:00 2001 From: Unrud Date: Fri, 23 Oct 2020 21:28:19 +0200 Subject: [PATCH 041/238] Use renameat2 on Linux for atomic exchanging of files --- radicale/pathutils.py | 58 +++++++++++++++++++ .../multifilesystem/create_collection.py | 10 ++-- 2 files changed, 62 insertions(+), 6 deletions(-) diff --git a/radicale/pathutils.py b/radicale/pathutils.py index 6a2cb1b4..400a604c 100644 --- a/radicale/pathutils.py +++ b/radicale/pathutils.py @@ -24,7 +24,9 @@ Helper functions for working with the file system. import contextlib import os import posixpath +import sys import threading +from tempfile import TemporaryDirectory if os.name == "nt": import ctypes @@ -66,6 +68,23 @@ if os.name == "nt": elif os.name == "posix": import fcntl +HAVE_RENAMEAT2 = False +if sys.platform == "linux": + import ctypes + + RENAME_EXCHANGE = 2 + try: + renameat2 = ctypes.CDLL(None, use_errno=True).renameat2 + except AttributeError: + pass + else: + HAVE_RENAMEAT2 = True + renameat2.argtypes = [ + ctypes.c_int, ctypes.c_char_p, + ctypes.c_int, ctypes.c_char_p, + ctypes.c_uint] + renameat2.restype = ctypes.c_int + class RwLock: """A readers-Writer lock that locks a file.""" @@ -127,6 +146,45 @@ class RwLock: self._writer = False +def rename_exchange(src, dst): + """Exchange the files or directories `src` and `dst`. + + Both `src` and `dst` must exist but may be of different types. + + On Linux with renameat2 the operation is atomic. + On other platforms it's not atomic. + + """ + src_dir, src_base = os.path.split(src) + dst_dir, dst_base = os.path.split(dst) + src_dir = src_dir or os.curdir + dst_dir = dst_dir or os.curdir + if not src_base or not dst_base: + raise ValueError("Invalid arguments: %r -> %r" % (src, dst)) + if HAVE_RENAMEAT2: + src_base_bytes = os.fsencode(src_base) + dst_base_bytes = os.fsencode(dst_base) + src_dir_fd = os.open(src_dir, 0) + try: + dst_dir_fd = os.open(dst_dir, 0) + try: + if renameat2(src_dir_fd, src_base_bytes, + dst_dir_fd, dst_base_bytes, + RENAME_EXCHANGE) != 0: + errno = ctypes.get_errno() + raise OSError(errno, os.strerror(errno)) + finally: + os.close(dst_dir_fd) + finally: + os.close(src_dir_fd) + else: + with TemporaryDirectory( + prefix=".Radicale.tmp-", dir=src_dir) as tmp_dir: + os.rename(dst, os.path.join(tmp_dir, "interim")) + os.rename(src, dst) + os.rename(os.path.join(tmp_dir, "interim"), src) + + def fsync(fd): if os.name == "posix" and hasattr(fcntl, "F_FULLFSYNC"): fcntl.fcntl(fd, fcntl.F_FULLFSYNC) diff --git a/radicale/storage/multifilesystem/create_collection.py b/radicale/storage/multifilesystem/create_collection.py index 6be63453..fe0290e9 100644 --- a/radicale/storage/multifilesystem/create_collection.py +++ b/radicale/storage/multifilesystem/create_collection.py @@ -55,12 +55,10 @@ class StorageCreateCollectionMixin: elif props.get("tag") == "VADDRESSBOOK": col._upload_all_nonatomic(items, suffix=".vcf") - # This operation is not atomic on the filesystem level but it's - # very unlikely that one rename operations succeeds while the - # other fails or that only one gets written to disk. - if os.path.exists(filesystem_path): - os.rename(filesystem_path, os.path.join(tmp_dir, "delete")) - os.rename(tmp_filesystem_path, filesystem_path) + if os.path.lexists(filesystem_path): + pathutils.rename_exchange(tmp_filesystem_path, filesystem_path) + else: + os.rename(tmp_filesystem_path, filesystem_path) self._sync_directory(parent_dir) return self._collection_class( From 742a067171d409f896434c517692b190d6cc72ad Mon Sep 17 00:00:00 2001 From: Unrud Date: Fri, 23 Oct 2020 22:26:28 +0200 Subject: [PATCH 042/238] Disallow abbreviated arguments --- radicale/__main__.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/radicale/__main__.py b/radicale/__main__.py index 6cef2ad3..d3cb1dff 100644 --- a/radicale/__main__.py +++ b/radicale/__main__.py @@ -55,7 +55,7 @@ def run(): # Get command-line arguments parser = argparse.ArgumentParser( - prog="radicale", usage="%(prog)s [OPTIONS]") + prog="radicale", usage="%(prog)s [OPTIONS]", allow_abbrev=False) parser.add_argument("--version", action="version", version=VERSION) parser.add_argument("--verify-storage", action="store_true", From 5333751e45eae08539a6d0f89073a63c05bc5db5 Mon Sep 17 00:00:00 2001 From: Unrud Date: Sun, 25 Oct 2020 20:27:26 +0100 Subject: [PATCH 043/238] Allow float for server->timeout setting --- radicale/config.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/radicale/config.py b/radicale/config.py index ae5c9c5e..abb33099 100644 --- a/radicale/config.py +++ b/radicale/config.py @@ -118,7 +118,7 @@ DEFAULT_CONFIG_SCHEMA = OrderedDict([ ("timeout", { "value": "30", "help": "socket timeout", - "type": positive_int}), + "type": positive_float}), ("ssl", { "value": "False", "help": "use SSL connection", From 0cabc64584108f1d0b91eebb6561bec6c916e2b2 Mon Sep 17 00:00:00 2001 From: Unrud Date: Tue, 23 Mar 2021 00:17:30 +0100 Subject: [PATCH 044/238] CI: Remove Python 3.9.0-alpha --- .github/workflows/test.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml index 7ac76f2d..ef1788a4 100644 --- a/.github/workflows/test.yml +++ b/.github/workflows/test.yml @@ -7,7 +7,7 @@ jobs: strategy: matrix: os: [ubuntu-latest, macos-latest, windows-latest] - python-version: [3.6, 3.7, 3.8, '3.9.0-alpha - 3.9', pypy3] + python-version: [3.6, 3.7, 3.8, 3.9, pypy3] steps: - uses: actions/checkout@v2 - uses: actions/setup-python@v2 From 9997a32629590ef66ec35710b69c3052fc812f73 Mon Sep 17 00:00:00 2001 From: Unrud Date: Tue, 23 Mar 2021 00:26:27 +0100 Subject: [PATCH 045/238] Try to fix coveralls See https://github.com/TheKevJames/coveralls-python/issues/252 --- .github/workflows/test.yml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml index ef1788a4..8316185e 100644 --- a/.github/workflows/test.yml +++ b/.github/workflows/test.yml @@ -24,7 +24,7 @@ jobs: GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} run: | python -m pip install coveralls - python -m coveralls + python -m coveralls --service=github coveralls-finish: needs: test @@ -39,4 +39,4 @@ jobs: GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} run: | python -m pip install coveralls - python -m coveralls --finish + python -m coveralls --service=github --finish From 21099f22409d0638b061fbfbb35db3cb6ec9cea7 Mon Sep 17 00:00:00 2001 From: Tim Gates Date: Tue, 23 Mar 2021 10:48:25 +1100 Subject: [PATCH 046/238] docs: fix simple typo, errornous -> erroneous (#1126) * docs: fix simple typo, errornous -> erroneous There is a small typo in radicale/storage/__init__.py. Should read `erroneous` rather than `errornous`. * Update __init__.py --- radicale/storage/__init__.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/radicale/storage/__init__.py b/radicale/storage/__init__.py index b957451e..7d2f1e72 100644 --- a/radicale/storage/__init__.py +++ b/radicale/storage/__init__.py @@ -195,7 +195,7 @@ class BaseCollection: # Concatenate all child elements of VCALENDAR from all items # together, while preventing duplicated VTIMEZONE entries. # VTIMEZONEs are only distinguished by their TZID, if different - # timezones share the same TZID this produces errornous ouput. + # timezones share the same TZID this produces erroneous output. # VObject fails at this too. for item in self.get_all(): depth = 0 From 398e93e215df72f352da2c0156cb478737c1945c Mon Sep 17 00:00:00 2001 From: Michael Stilkerich Date: Fri, 22 Jan 2021 15:25:18 +0100 Subject: [PATCH 047/238] Fix is-not-defined filter in addressbook-query report --- radicale/item/filter.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/radicale/item/filter.py b/radicale/item/filter.py index c3143dbd..17919cf5 100644 --- a/radicale/item/filter.py +++ b/radicale/item/filter.py @@ -115,7 +115,7 @@ def prop_match(vobject_item, filter_, ns): # Point #1 of rfc4791-9.7.2 return name in vobject_item.contents if len(filter_) == 1: - if filter_[0].tag == xmlutils.make_clark("C:is-not-defined"): + if filter_[0].tag == xmlutils.make_clark("%s:is-not-defined" % ns): # Point #2 of rfc4791-9.7.2 return name not in vobject_item.contents if name not in vobject_item.contents: From b8848348d667da519c2953423bddf766c5427950 Mon Sep 17 00:00:00 2001 From: Unrud Date: Tue, 30 Mar 2021 08:27:21 +0200 Subject: [PATCH 048/238] Exclude flake8 hacking plugins --- setup.cfg | 3 +++ 1 file changed, 3 insertions(+) diff --git a/setup.cfg b/setup.cfg index 9a62478d..a883f15c 100644 --- a/setup.cfg +++ b/setup.cfg @@ -12,6 +12,9 @@ norecursedirs = dist .cache .git build Radicale.egg-info .eggs venv known_standard_library = _dummy_thread,_thread,abc,aifc,argparse,array,ast,asynchat,asyncio,asyncore,atexit,audioop,base64,bdb,binascii,binhex,bisect,builtins,bz2,cProfile,calendar,cgi,cgitb,chunk,cmath,cmd,code,codecs,codeop,collections,colorsys,compileall,concurrent,configparser,contextlib,contextvars,copy,copyreg,crypt,csv,ctypes,curses,dataclasses,datetime,dbm,decimal,difflib,dis,distutils,doctest,dummy_threading,email,encodings,ensurepip,enum,errno,faulthandler,fcntl,filecmp,fileinput,fnmatch,formatter,fpectl,fractions,ftplib,functools,gc,getopt,getpass,gettext,glob,grp,gzip,hashlib,heapq,hmac,html,http,imaplib,imghdr,imp,importlib,inspect,io,ipaddress,itertools,json,keyword,lib2to3,linecache,locale,logging,lzma,macpath,mailbox,mailcap,marshal,math,mimetypes,mmap,modulefinder,msilib,msvcrt,multiprocessing,netrc,nis,nntplib,ntpath,numbers,operator,optparse,os,ossaudiodev,parser,pathlib,pdb,pickle,pickletools,pipes,pkgutil,platform,plistlib,poplib,posix,posixpath,pprint,profile,pstats,pty,pwd,py_compile,pyclbr,pydoc,queue,quopri,random,re,readline,reprlib,resource,rlcompleter,runpy,sched,secrets,select,selectors,shelve,shlex,shutil,signal,site,smtpd,smtplib,sndhdr,socket,socketserver,spwd,sqlite3,sre,sre_compile,sre_constants,sre_parse,ssl,stat,statistics,string,stringprep,struct,subprocess,sunau,symbol,symtable,sys,sysconfig,syslog,tabnanny,tarfile,telnetlib,tempfile,termios,test,textwrap,threading,time,timeit,tkinter,token,tokenize,trace,traceback,tracemalloc,tty,turtle,turtledemo,types,typing,unicodedata,unittest,urllib,uu,uuid,venv,warnings,wave,weakref,webbrowser,winreg,winsound,wsgiref,xdrlib,xml,xmlrpc,zipapp,zipfile,zipimport,zlib known_third_party = defusedxml,passlib,pkg_resources,pytest,vobject +[flake8] +select = E,W,F + [coverage:run] branch = True source = radicale From 8f9734d7977d52838a186521e735238e15fd46fa Mon Sep 17 00:00:00 2001 From: Unrud Date: Wed, 31 Mar 2021 00:06:03 +0200 Subject: [PATCH 049/238] Fix "Exclude flake8 hacking plugins" Apparently setting "select" overrides the default "ignore" values. --- setup.cfg | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/setup.cfg b/setup.cfg index a883f15c..7c2b51db 100644 --- a/setup.cfg +++ b/setup.cfg @@ -13,7 +13,7 @@ known_standard_library = _dummy_thread,_thread,abc,aifc,argparse,array,ast,async known_third_party = defusedxml,passlib,pkg_resources,pytest,vobject [flake8] -select = E,W,F +extend-ignore = H [coverage:run] branch = True From 34bec01c9bcb04cfee5d92d89baa1e8bac572a11 Mon Sep 17 00:00:00 2001 From: Unrud Date: Fri, 14 May 2021 00:07:09 +0200 Subject: [PATCH 050/238] Fail when test file can't be read --- radicale/tests/helpers.py | 7 ++----- 1 file changed, 2 insertions(+), 5 deletions(-) diff --git a/radicale/tests/helpers.py b/radicale/tests/helpers.py index 97ae6a70..face22ba 100644 --- a/radicale/tests/helpers.py +++ b/radicale/tests/helpers.py @@ -34,11 +34,8 @@ def get_file_path(file_name): def get_file_content(file_name): - try: - with open(get_file_path(file_name), encoding="utf-8") as fd: - return fd.read() - except IOError: - print("Couldn't open the file %s" % file_name) + with open(get_file_path(file_name), encoding="utf-8") as fd: + return fd.read() def configuration_to_dict(configuration): From 73e42f81011ccb8aac6a4f73ab5ad2a83098492e Mon Sep 17 00:00:00 2001 From: Unrud Date: Sun, 4 Oct 2020 15:13:01 +0200 Subject: [PATCH 051/238] Enable static type checking --- .gitignore | 1 + radicale/app/__init__.py | 2 +- radicale/config.py | 3 ++- radicale/pathutils.py | 5 ++++- radicale/server.py | 8 ++++++-- radicale/tests/test_base.py | 4 +++- radicale/tests/test_server.py | 9 ++++++++- setup.cfg | 5 +++++ setup.py | 6 ++++++ 9 files changed, 36 insertions(+), 7 deletions(-) diff --git a/.gitignore b/.gitignore index d61615ae..5a0363a0 100644 --- a/.gitignore +++ b/.gitignore @@ -15,6 +15,7 @@ coverage.xml .coverage .coverage.* .eggs +.mypy_cache .project .pydevproject .settings diff --git a/radicale/app/__init__.py b/radicale/app/__init__.py index 21dcd11c..4bf1e9ae 100644 --- a/radicale/app/__init__.py +++ b/radicale/app/__init__.py @@ -58,7 +58,7 @@ from radicale.log import logger # WORKAROUND: https://github.com/tiran/defusedxml/issues/54 import defusedxml.ElementTree as DefusedET # isort: skip -sys.modules["xml.etree"].ElementTree = ET +sys.modules["xml.etree"].ElementTree = ET # type: ignore[attr-defined] VERSION = pkg_resources.get_distribution("radicale").version diff --git a/radicale/config.py b/radicale/config.py index abb33099..880f2a52 100644 --- a/radicale/config.py +++ b/radicale/config.py @@ -31,6 +31,7 @@ import os import string from collections import OrderedDict from configparser import RawConfigParser +from typing import Any, ClassVar from radicale import auth, rights, storage, web @@ -285,7 +286,7 @@ def load(paths=()): class Configuration: - SOURCE_MISSING = {} + SOURCE_MISSING: ClassVar[Any] = {} def __init__(self, schema): """Initialize configuration. diff --git a/radicale/pathutils.py b/radicale/pathutils.py index 400a604c..7a2e675a 100644 --- a/radicale/pathutils.py +++ b/radicale/pathutils.py @@ -27,6 +27,7 @@ import posixpath import sys import threading from tempfile import TemporaryDirectory +from typing import Type, Union if os.name == "nt": import ctypes @@ -34,6 +35,7 @@ if os.name == "nt": import msvcrt LOCKFILE_EXCLUSIVE_LOCK = 2 + ULONG_PTR: Union[Type[ctypes.c_uint32], Type[ctypes.c_uint64]] if ctypes.sizeof(ctypes.c_void_p) == 4: ULONG_PTR = ctypes.c_uint32 else: @@ -47,7 +49,8 @@ if os.name == "nt": ("offset_high", ctypes.wintypes.DWORD), ("h_event", ctypes.wintypes.HANDLE)] - kernel32 = ctypes.WinDLL("kernel32", use_last_error=True) + kernel32 = ctypes.WinDLL( # type: ignore[attr-defined] + "kernel32", use_last_error=True) lock_file_ex = kernel32.LockFileEx lock_file_ex.argtypes = [ ctypes.wintypes.HANDLE, diff --git a/radicale/server.py b/radicale/server.py index 97f6afe1..ceeda835 100644 --- a/radicale/server.py +++ b/radicale/server.py @@ -30,21 +30,25 @@ import socketserver import ssl import sys import wsgiref.simple_server +from typing import MutableMapping from urllib.parse import unquote from radicale import Application, config from radicale.log import logger +COMPAT_EAI_ADDRFAMILY: int if hasattr(socket, "EAI_ADDRFAMILY"): - COMPAT_EAI_ADDRFAMILY = socket.EAI_ADDRFAMILY + COMPAT_EAI_ADDRFAMILY = socket.EAI_ADDRFAMILY # type: ignore[attr-defined] elif hasattr(socket, "EAI_NONAME"): # Windows and BSD don't have a special error code for this COMPAT_EAI_ADDRFAMILY = socket.EAI_NONAME +COMPAT_EAI_NODATA: int if hasattr(socket, "EAI_NODATA"): COMPAT_EAI_NODATA = socket.EAI_NODATA elif hasattr(socket, "EAI_NONAME"): # Windows and BSD don't have a special error code for this COMPAT_EAI_NODATA = socket.EAI_NONAME +COMPAT_IPPROTO_IPV6: int if hasattr(socket, "IPPROTO_IPV6"): COMPAT_IPPROTO_IPV6 = socket.IPPROTO_IPV6 elif os.name == "nt": @@ -155,7 +159,7 @@ class ParallelHTTPSServer(ParallelHTTPServer): class ServerHandler(wsgiref.simple_server.ServerHandler): # Don't pollute WSGI environ with OS environment - os_environ = {} + os_environ: MutableMapping[str, str] = {} def log_exception(self, exc_info): logger.error("An exception occurred during request: %s", diff --git a/radicale/tests/test_base.py b/radicale/tests/test_base.py index 5aef8494..e8ad347b 100644 --- a/radicale/tests/test_base.py +++ b/radicale/tests/test_base.py @@ -25,6 +25,7 @@ import posixpath import shutil import sys import tempfile +from typing import Any, ClassVar import defusedxml.ElementTree as DefusedET import pytest @@ -1549,7 +1550,8 @@ class BaseRequestsMixIn: class BaseFileSystemTest(BaseTest): """Base class for filesystem backend tests.""" - storage_type = None + + storage_type: ClassVar[Any] def setup(self): self.configuration = config.load() diff --git a/radicale/tests/test_server.py b/radicale/tests/test_server.py index 90beefdc..72ff52be 100644 --- a/radicale/tests/test_server.py +++ b/radicale/tests/test_server.py @@ -41,10 +41,17 @@ from radicale.tests.helpers import configuration_to_dict, get_file_path class DisabledRedirectHandler(request.HTTPRedirectHandler): + def http_error_301(self, req, fp, code, msg, headers): + raise HTTPError(req.full_url, code, msg, headers, fp) + def http_error_302(self, req, fp, code, msg, headers): raise HTTPError(req.full_url, code, msg, headers, fp) - http_error_301 = http_error_303 = http_error_307 = http_error_302 + def http_error_303(self, req, fp, code, msg, headers): + raise HTTPError(req.full_url, code, msg, headers, fp) + + def http_error_307(self, req, fp, code, msg, headers): + raise HTTPError(req.full_url, code, msg, headers, fp) class TestBaseServerRequests(BaseTest): diff --git a/setup.cfg b/setup.cfg index 7c2b51db..ae23eb4b 100644 --- a/setup.cfg +++ b/setup.cfg @@ -5,6 +5,7 @@ test = pytest python-tag = py3 [tool:pytest] +# More options are set in `setup.py` via environment variable `PYTEST_ADDOPTS` addopts = --flake8 --isort --cov --cov-report=term --cov-report=xml -r s norecursedirs = dist .cache .git build Radicale.egg-info .eggs venv @@ -15,6 +16,10 @@ known_third_party = defusedxml,passlib,pkg_resources,pytest,vobject [flake8] extend-ignore = H +[mypy] +ignore_missing_imports = True +show_error_codes = True + [coverage:run] branch = True source = radicale diff --git a/setup.py b/setup.py index b6786e99..55a61c00 100755 --- a/setup.py +++ b/setup.py @@ -36,6 +36,7 @@ For further information, please visit the `Radicale Website """ +import os import sys from setuptools import find_packages, setup @@ -52,6 +53,11 @@ needs_pytest = {"pytest", "test", "ptr"}.intersection(sys.argv) pytest_runner = ["pytest-runner"] if needs_pytest else [] tests_require = ["pytest-runner", "pytest", "pytest-cov", "pytest-flake8", "pytest-isort", "waitress"] +os.environ["PYTEST_ADDOPTS"] = os.environ.get("PYTEST_ADDOPTS", "") +# Mypy only supports CPython +if sys.implementation.name == "cpython": + tests_require.extend(["pytest-mypy", "types-setuptools"]) + os.environ["PYTEST_ADDOPTS"] += " --mypy" setup( name="Radicale", From 12fe5ce637c373edd39885011b561d2b789295fa Mon Sep 17 00:00:00 2001 From: Unrud Date: Sun, 4 Oct 2020 15:13:02 +0200 Subject: [PATCH 052/238] Enable run-time type checking during tests --- setup.cfg | 2 +- setup.py | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) mode change 100755 => 100644 setup.py diff --git a/setup.cfg b/setup.cfg index ae23eb4b..8ed34d51 100644 --- a/setup.cfg +++ b/setup.cfg @@ -6,7 +6,7 @@ python-tag = py3 [tool:pytest] # More options are set in `setup.py` via environment variable `PYTEST_ADDOPTS` -addopts = --flake8 --isort --cov --cov-report=term --cov-report=xml -r s +addopts = --flake8 --isort --typeguard-packages=radicale --cov --cov-report=term --cov-report=xml -r s norecursedirs = dist .cache .git build Radicale.egg-info .eggs venv [tool:isort] diff --git a/setup.py b/setup.py old mode 100755 new mode 100644 index 55a61c00..a118cc12 --- a/setup.py +++ b/setup.py @@ -52,7 +52,7 @@ WEB_FILES = ["web/internal_data/css/icon.png", needs_pytest = {"pytest", "test", "ptr"}.intersection(sys.argv) pytest_runner = ["pytest-runner"] if needs_pytest else [] tests_require = ["pytest-runner", "pytest", "pytest-cov", "pytest-flake8", - "pytest-isort", "waitress"] + "pytest-isort", "typeguard", "waitress"] os.environ["PYTEST_ADDOPTS"] = os.environ.get("PYTEST_ADDOPTS", "") # Mypy only supports CPython if sys.implementation.name == "cpython": From cecb17df03006830076d164ae890a061114d6a9f Mon Sep 17 00:00:00 2001 From: Unrud Date: Mon, 26 Jul 2021 20:56:46 +0200 Subject: [PATCH 053/238] More type hints --- radicale/__init__.py | 56 ++--- radicale/__main__.py | 52 ++-- radicale/app/__init__.py | 253 +++++++------------- radicale/app/base.py | 131 ++++++++++ radicale/app/delete.py | 27 ++- radicale/app/get.py | 28 ++- radicale/app/head.py | 10 +- radicale/app/mkcalendar.py | 29 +-- radicale/app/mkcol.py | 23 +- radicale/app/move.py | 29 ++- radicale/app/options.py | 9 +- radicale/app/post.py | 9 +- radicale/app/propfind.py | 131 +++++----- radicale/app/proppatch.py | 38 +-- radicale/app/put.py | 72 +++--- radicale/app/report.py | 216 +++++++++-------- radicale/auth/__init__.py | 20 +- radicale/auth/htpasswd.py | 21 +- radicale/auth/http_x_remote_user.py | 9 +- radicale/auth/none.py | 3 +- radicale/auth/remote_user.py | 9 +- radicale/config.py | 108 +++++---- radicale/httputils.py | 50 ++-- radicale/item/__init__.py | 136 +++++++---- radicale/item/filter.py | 112 +++++---- radicale/log.py | 54 +++-- radicale/pathutils.py | 83 ++++--- radicale/rights/__init__.py | 19 +- radicale/rights/authenticated.py | 9 +- radicale/rights/from_file.py | 14 +- radicale/rights/owner_only.py | 3 +- radicale/rights/owner_write.py | 3 +- radicale/server.py | 172 ++++++++----- radicale/storage/__init__.py | 135 +++++++---- radicale/storage/multifilesystem/cache.py | 13 +- radicale/storage/multifilesystem/get.py | 9 +- radicale/storage/multifilesystem/history.py | 18 +- radicale/storage/multifilesystem/lock.py | 5 +- radicale/storage/multifilesystem/meta.py | 11 +- radicale/storage/multifilesystem/sync.py | 14 +- radicale/storage/multifilesystem/upload.py | 7 +- radicale/storage/multifilesystem/verify.py | 4 +- radicale/tests/__init__.py | 2 +- radicale/tests/test_auth.py | 3 +- radicale/tests/test_base.py | 20 +- radicale/types.py | 61 +++++ radicale/utils.py | 10 +- radicale/web/__init__.py | 22 +- radicale/web/internal.py | 15 +- radicale/web/none.py | 6 +- radicale/xmlutils.py | 38 +-- 51 files changed, 1374 insertions(+), 957 deletions(-) create mode 100644 radicale/app/base.py create mode 100644 radicale/types.py diff --git a/radicale/__init__.py b/radicale/__init__.py index 6dd9545e..ef98635d 100644 --- a/radicale/__init__.py +++ b/radicale/__init__.py @@ -27,46 +27,48 @@ Configuration files can be specified in the environment variable import os import threading +from typing import Iterable, Optional, cast import pkg_resources -from radicale import config, log +from radicale import config, log, types from radicale.app import Application from radicale.log import logger -VERSION = pkg_resources.get_distribution("radicale").version +VERSION: str = pkg_resources.get_distribution("radicale").version -_application = None -_application_config_path = None +_application_instance: Optional[Application] = None +_application_config_path: Optional[str] = None _application_lock = threading.Lock() -def _init_application(config_path, wsgi_errors): - global _application, _application_config_path +def _get_application_instance(config_path: str, wsgi_errors: types.ErrorStream + ) -> Application: + global _application_instance, _application_config_path with _application_lock: - if _application is not None: - return - log.setup() - with log.register_stream(wsgi_errors): - _application_config_path = config_path - configuration = config.load(config.parse_compound_paths( - config.DEFAULT_CONFIG_PATH, - config_path)) - log.set_level(configuration.get("logging", "level")) - # Log configuration after logger is configured - for source, miss in configuration.sources(): - logger.info("%s %s", "Skipped missing" if miss else "Loaded", - source) - _application = Application(configuration) + if _application_instance is None: + log.setup() + with log.register_stream(wsgi_errors): + _application_config_path = config_path + configuration = config.load(config.parse_compound_paths( + config.DEFAULT_CONFIG_PATH, + config_path)) + log.set_level(cast(str, configuration.get("logging", "level"))) + # Log configuration after logger is configured + for source, miss in configuration.sources(): + logger.info("%s %s", "Skipped missing" if miss + else "Loaded", source) + _application_instance = Application(configuration) + if _application_config_path != config_path: + raise ValueError("RADICALE_CONFIG must not change: %r != %r" % + (config_path, _application_config_path)) + return _application_instance -def application(environ, start_response): +def application(environ: types.WSGIEnviron, + start_response: types.WSGIStartResponse) -> Iterable[bytes]: """Entry point for external WSGI servers.""" config_path = environ.get("RADICALE_CONFIG", os.environ.get("RADICALE_CONFIG")) - if _application is None: - _init_application(config_path, environ["wsgi.errors"]) - if _application_config_path != config_path: - raise ValueError("RADICALE_CONFIG must not change: %s != %s" % - (repr(config_path), repr(_application_config_path))) - return _application(environ, start_response) + app = _get_application_instance(config_path, environ["wsgi.errors"]) + return app(environ, start_response) diff --git a/radicale/__main__.py b/radicale/__main__.py index d3cb1dff..d88aeeb1 100644 --- a/radicale/__main__.py +++ b/radicale/__main__.py @@ -29,24 +29,27 @@ import os import signal import socket import sys +from types import FrameType +from typing import Dict, List, cast from radicale import VERSION, config, log, server, storage from radicale.log import logger -def run(): +def run() -> None: """Run Radicale as a standalone server.""" exit_signal_numbers = [signal.SIGTERM, signal.SIGINT] if os.name == "posix": exit_signal_numbers.append(signal.SIGHUP) exit_signal_numbers.append(signal.SIGQUIT) - elif os.name == "nt": + if sys.platform == "win32": exit_signal_numbers.append(signal.SIGBREAK) # Raise SystemExit when signal arrives to run cleanup code # (like destructors, try-finish etc.), otherwise the process exits # without running any of them - def exit_signal_handler(signal_number, stack_frame): + def exit_signal_handler(signal_number: "signal.Signals", + stack_frame: FrameType) -> None: sys.exit(1) for signal_number in exit_signal_numbers: signal.signal(signal_number, exit_signal_handler) @@ -60,12 +63,12 @@ def run(): parser.add_argument("--version", action="version", version=VERSION) parser.add_argument("--verify-storage", action="store_true", help="check the storage for errors and exit") - parser.add_argument( - "-C", "--config", help="use specific configuration files", nargs="*") + parser.add_argument("-C", "--config", + help="use specific configuration files", nargs="*") parser.add_argument("-D", "--debug", action="store_true", help="print debug information") - groups = {} + groups: Dict["argparse._ArgumentGroup", List[str]] = {} for section, values in config.DEFAULT_CONFIG_SCHEMA.items(): if section.startswith("_"): continue @@ -76,7 +79,7 @@ def run(): continue kwargs = data.copy() long_name = "--%s-%s" % (section, option.replace("_", "-")) - args = list(kwargs.pop("aliases", ())) + args: List[str] = list(kwargs.pop("aliases", ())) args.append(long_name) kwargs["dest"] = "%s_%s" % (section, option) groups[group].append(kwargs["dest"]) @@ -100,22 +103,22 @@ def run(): del kwargs["type"] group.add_argument(*args, **kwargs) - args = parser.parse_args() + args_ns = parser.parse_args() # Preliminary configure logging - if args.debug: - args.logging_level = "debug" + if args_ns.debug: + args_ns.logging_level = "debug" with contextlib.suppress(ValueError): log.set_level(config.DEFAULT_CONFIG_SCHEMA["logging"]["level"]["type"]( - args.logging_level)) + args_ns.logging_level)) # Update Radicale configuration according to arguments arguments_config = {} for group, actions in groups.items(): - section = group.title + section = group.title or "" section_config = {} for action in actions: - value = getattr(args, action) + value = getattr(args_ns, action) if value is not None: section_config[action.split('_', 1)[1]] = value if section_config: @@ -125,31 +128,31 @@ def run(): configuration = config.load(config.parse_compound_paths( config.DEFAULT_CONFIG_PATH, os.environ.get("RADICALE_CONFIG"), - os.pathsep.join(args.config) if args.config else None)) + os.pathsep.join(args_ns.config) if args_ns.config else None)) if arguments_config: - configuration.update(arguments_config, "arguments") + configuration.update(arguments_config, "command line arguments") except Exception as e: - logger.fatal("Invalid configuration: %s", e, exc_info=True) + logger.critical("Invalid configuration: %s", e, exc_info=True) sys.exit(1) # Configure logging - log.set_level(configuration.get("logging", "level")) + log.set_level(cast(str, configuration.get("logging", "level"))) # Log configuration after logger is configured for source, miss in configuration.sources(): logger.info("%s %s", "Skipped missing" if miss else "Loaded", source) - if args.verify_storage: + if args_ns.verify_storage: logger.info("Verifying storage") try: storage_ = storage.load(configuration) with storage_.acquire_lock("r"): if not storage_.verify(): - logger.fatal("Storage verifcation failed") + logger.critical("Storage verifcation failed") sys.exit(1) except Exception as e: - logger.fatal("An exception occurred during storage verification: " - "%s", e, exc_info=True) + logger.critical("An exception occurred during storage " + "verification: %s", e, exc_info=True) sys.exit(1) return @@ -157,7 +160,8 @@ def run(): shutdown_socket, shutdown_socket_out = socket.socketpair() # Shutdown server when signal arrives - def shutdown_signal_handler(signal_number, stack_frame): + def shutdown_signal_handler(signal_number: "signal.Signals", + stack_frame: FrameType) -> None: shutdown_socket.close() for signal_number in exit_signal_numbers: signal.signal(signal_number, shutdown_signal_handler) @@ -165,8 +169,8 @@ def run(): try: server.serve(configuration, shutdown_socket_out) except Exception as e: - logger.fatal("An exception occurred during server startup: %s", e, - exc_info=True) + logger.critical("An exception occurred during server startup: %s", e, + exc_info=True) sys.exit(1) diff --git a/radicale/app/__init__.py b/radicale/app/__init__.py index 4bf1e9ae..c1bd0905 100644 --- a/radicale/app/__init__.py +++ b/radicale/app/__init__.py @@ -27,53 +27,53 @@ the built-in server (see ``radicale.server`` module). import base64 import datetime -import io -import logging -import posixpath import pprint import random -import sys import time -import xml.etree.ElementTree as ET import zlib from http import client +from typing import Iterable, List, Mapping, Tuple, Union import pkg_resources -from radicale import (auth, httputils, log, pathutils, rights, storage, web, - xmlutils) -from radicale.app.delete import ApplicationDeleteMixin -from radicale.app.get import ApplicationGetMixin -from radicale.app.head import ApplicationHeadMixin -from radicale.app.mkcalendar import ApplicationMkcalendarMixin -from radicale.app.mkcol import ApplicationMkcolMixin -from radicale.app.move import ApplicationMoveMixin -from radicale.app.options import ApplicationOptionsMixin -from radicale.app.post import ApplicationPostMixin -from radicale.app.propfind import ApplicationPropfindMixin -from radicale.app.proppatch import ApplicationProppatchMixin -from radicale.app.put import ApplicationPutMixin -from radicale.app.report import ApplicationReportMixin +from radicale import config, httputils, log, pathutils, types +from radicale.app.base import ApplicationBase +from radicale.app.delete import ApplicationPartDelete +from radicale.app.get import ApplicationPartGet +from radicale.app.head import ApplicationPartHead +from radicale.app.mkcalendar import ApplicationPartMkcalendar +from radicale.app.mkcol import ApplicationPartMkcol +from radicale.app.move import ApplicationPartMove +from radicale.app.options import ApplicationPartOptions +from radicale.app.post import ApplicationPartPost +from radicale.app.propfind import ApplicationPartPropfind +from radicale.app.proppatch import ApplicationPartProppatch +from radicale.app.put import ApplicationPartPut +from radicale.app.report import ApplicationPartReport from radicale.log import logger -# WORKAROUND: https://github.com/tiran/defusedxml/issues/54 -import defusedxml.ElementTree as DefusedET # isort: skip -sys.modules["xml.etree"].ElementTree = ET # type: ignore[attr-defined] +VERSION: str = pkg_resources.get_distribution("radicale").version -VERSION = pkg_resources.get_distribution("radicale").version +# Combination of types.WSGIStartResponse and WSGI application return value +_IntermediateResponse = Tuple[str, List[Tuple[str, str]], Iterable[bytes]] -class Application( - ApplicationDeleteMixin, ApplicationGetMixin, ApplicationHeadMixin, - ApplicationMkcalendarMixin, ApplicationMkcolMixin, - ApplicationMoveMixin, ApplicationOptionsMixin, - ApplicationPropfindMixin, ApplicationProppatchMixin, - ApplicationPostMixin, ApplicationPutMixin, - ApplicationReportMixin): - +class Application(ApplicationPartDelete, ApplicationPartHead, + ApplicationPartGet, ApplicationPartMkcalendar, + ApplicationPartMkcol, ApplicationPartMove, + ApplicationPartOptions, ApplicationPartPropfind, + ApplicationPartProppatch, ApplicationPartPost, + ApplicationPartPut, ApplicationPartReport, ApplicationBase): """WSGI application.""" - def __init__(self, configuration): + _mask_passwords: bool + _auth_delay: float + _internal_server: bool + _max_content_length: int + _auth_realm: str + _extra_headers: Mapping[str, str] + + def __init__(self, configuration: config.Configuration) -> None: """Initialize Application. ``configuration`` see ``radicale.config`` module. @@ -81,60 +81,59 @@ class Application( this object, it is kept as an internal reference. """ - super().__init__() - self.configuration = configuration - self._auth = auth.load(configuration) - self._storage = storage.load(configuration) - self._rights = rights.load(configuration) - self._web = web.load(configuration) - self._encoding = configuration.get("encoding", "request") + super().__init__(configuration) + self._mask_passwords = configuration.get("logging", "mask_passwords") + self._auth_delay = configuration.get("auth", "delay") + self._internal_server = configuration.get("server", "_internal_server") + self._max_content_length = configuration.get( + "server", "max_content_length") + self._auth_realm = configuration.get("auth", "realm") + self._extra_headers = dict() + for key in self.configuration.options("headers"): + self._extra_headers[key] = configuration.get("headers", key) - def _headers_log(self, environ): - """Sanitize headers for logging.""" - request_environ = dict(environ) + def _scrub_headers(self, environ: types.WSGIEnviron) -> types.WSGIEnviron: + """Mask passwords and cookies.""" + headers = dict(environ) + if (self._mask_passwords and + headers.get("HTTP_AUTHORIZATION", "").startswith("Basic")): + headers["HTTP_AUTHORIZATION"] = "Basic **masked**" + if headers.get("HTTP_COOKIE"): + headers["HTTP_COOKIE"] = "**masked**" + return headers - # Mask passwords - mask_passwords = self.configuration.get("logging", "mask_passwords") - authorization = request_environ.get("HTTP_AUTHORIZATION", "") - if mask_passwords and authorization.startswith("Basic"): - request_environ["HTTP_AUTHORIZATION"] = "Basic **masked**" - if request_environ.get("HTTP_COOKIE"): - request_environ["HTTP_COOKIE"] = "**masked**" - - return request_environ - - def __call__(self, environ, start_response): + def __call__(self, environ: types.WSGIEnviron, start_response: + types.WSGIStartResponse) -> Iterable[bytes]: with log.register_stream(environ["wsgi.errors"]): try: - status, headers, answers = self._handle_request(environ) + status_text, headers, answers = self._handle_request(environ) except Exception as e: - try: - method = str(environ["REQUEST_METHOD"]) - except Exception: - method = "unknown" - try: - path = str(environ.get("PATH_INFO", "")) - except Exception: - path = "" logger.error("An exception occurred during %s request on %r: " - "%s", method, path, e, exc_info=True) - status, headers, answer = httputils.INTERNAL_SERVER_ERROR - answer = answer.encode("ascii") - status = "%d %s" % ( - status.value, client.responses.get(status, "Unknown")) - headers = [ - ("Content-Length", str(len(answer)))] + list(headers) + "%s", environ.get("REQUEST_METHOD", "unknown"), + environ.get("PATH_INFO", ""), e, exc_info=True) + # Make minimal response + status, raw_headers, raw_answer = ( + httputils.INTERNAL_SERVER_ERROR) + assert isinstance(raw_answer, str) + answer = raw_answer.encode("ascii") + status_text = "%d %s" % ( + status, client.responses.get(status, "Unknown")) + headers = [*raw_headers, ("Content-Length", str(len(answer)))] answers = [answer] - start_response(status, headers) + start_response(status_text, headers) return answers - def _handle_request(self, environ): + def _handle_request(self, environ: types.WSGIEnviron + ) -> _IntermediateResponse: """Manage a request.""" - def response(status, headers=(), answer=None): + def response(status: int, headers: types.WSGIResponseHeaders, + answer: Union[None, str, bytes]) -> _IntermediateResponse: + """Helper to create response from internal types.WSGIResponse""" headers = dict(headers) # Set content length - if answer: - if hasattr(answer, "encode"): + answers = [] + if answer is not None: + if isinstance(answer, str): logger.debug("Response content:\n%s", answer) headers["Content-Type"] += "; charset=%s" % self._encoding answer = answer.encode(self._encoding) @@ -149,21 +148,22 @@ class Application( headers["Content-Encoding"] = "gzip" headers["Content-Length"] = str(len(answer)) + answers.append(answer) # Add extra headers set in configuration - for key in self.configuration.options("headers"): - headers[key] = self.configuration.get("headers", key) + headers.update(self._extra_headers) # Start response time_end = datetime.datetime.now() - status = "%d %s" % ( + status_text = "%d %s" % ( status, client.responses.get(status, "Unknown")) logger.info( "%s response status for %r%s in %.3f seconds: %s", environ["REQUEST_METHOD"], environ.get("PATH_INFO", ""), - depthinfo, (time_end - time_begin).total_seconds(), status) + depthinfo, (time_end - time_begin).total_seconds(), + status_text) # Return response content - return status, list(headers.items()), [answer] if answer else [] + return status_text, list(headers.items()), answers remote_host = "unknown" if environ.get("REMOTE_HOST"): @@ -184,8 +184,8 @@ class Application( "%s request for %r%s received from %s%s", environ["REQUEST_METHOD"], environ.get("PATH_INFO", ""), depthinfo, remote_host, remote_useragent) - headers = pprint.pformat(self._headers_log(environ)) - logger.debug("Request headers:\n%s", headers) + logger.debug("Request headers:\n%s", + pprint.pformat(self._scrub_headers(environ))) # Let reverse proxies overwrite SCRIPT_NAME if "HTTP_X_SCRIPT_NAME" in environ: @@ -237,9 +237,8 @@ class Application( logger.warning("Failed login attempt from %s: %r", remote_host, login) # Random delay to avoid timing oracles and bruteforce attacks - delay = self.configuration.get("auth", "delay") - if delay > 0: - random_delay = delay * (0.5 + random.random()) + if self._auth_delay > 0: + random_delay = self._auth_delay * (0.5 + random.random()) logger.debug("Sleeping %.3f seconds", random_delay) time.sleep(random_delay) @@ -252,8 +251,8 @@ class Application( if user: principal_path = "/%s/" % user with self._storage.acquire_lock("r", user): - principal = next(self._storage.discover( - principal_path, depth="1"), None) + principal = next(iter(self._storage.discover( + principal_path, depth="1")), None) if not principal: if "W" in self._rights.authorization(user, principal_path): with self._storage.acquire_lock("w", user): @@ -267,13 +266,12 @@ class Application( logger.warning("Access to principal path %r denied by " "rights backend", principal_path) - if self.configuration.get("server", "_internal_server"): + if self._internal_server: # Verify content length content_length = int(environ.get("CONTENT_LENGTH") or 0) if content_length: - max_content_length = self.configuration.get( - "server", "max_content_length") - if max_content_length and content_length > max_content_length: + if (self._max_content_length > 0 and + content_length > self._max_content_length): logger.info("Request body too large: %d", content_length) return response(*httputils.REQUEST_ENTITY_TOO_LARGE) @@ -291,82 +289,9 @@ class Application( # Unknown or unauthorized user logger.debug("Asking client for authentication") status = client.UNAUTHORIZED - realm = self.configuration.get("auth", "realm") headers = dict(headers) headers.update({ "WWW-Authenticate": - "Basic realm=\"%s\"" % realm}) + "Basic realm=\"%s\"" % self._auth_realm}) return response(status, headers, answer) - - def _read_xml_request_body(self, environ): - content = httputils.decode_request( - self.configuration, environ, - httputils.read_raw_request_body(self.configuration, environ)) - if not content: - return None - try: - xml_content = DefusedET.fromstring(content) - except ET.ParseError as e: - logger.debug("Request content (Invalid XML):\n%s", content) - raise RuntimeError("Failed to parse XML: %s" % e) from e - if logger.isEnabledFor(logging.DEBUG): - logger.debug("Request content:\n%s", - xmlutils.pretty_xml(xml_content)) - return xml_content - - def _xml_response(self, xml_content): - if logger.isEnabledFor(logging.DEBUG): - logger.debug("Response content:\n%s", - xmlutils.pretty_xml(xml_content)) - f = io.BytesIO() - ET.ElementTree(xml_content).write(f, encoding=self._encoding, - xml_declaration=True) - return f.getvalue() - - def _webdav_error_response(self, status, human_tag): - """Generate XML error response.""" - headers = {"Content-Type": "text/xml; charset=%s" % self._encoding} - content = self._xml_response(xmlutils.webdav_error(human_tag)) - return status, headers, content - - -class Access: - """Helper class to check access rights of an item""" - - def __init__(self, rights, user, path): - self._rights = rights - self.user = user - self.path = path - self.parent_path = pathutils.unstrip_path( - posixpath.dirname(pathutils.strip_path(path)), True) - self.permissions = self._rights.authorization(self.user, self.path) - self._parent_permissions = None - - @property - def parent_permissions(self): - if self.path == self.parent_path: - return self.permissions - if self._parent_permissions is None: - self._parent_permissions = self._rights.authorization( - self.user, self.parent_path) - return self._parent_permissions - - def check(self, permission, item=None): - if permission not in "rw": - raise ValueError("Invalid permission argument: %r" % permission) - if not item: - permissions = permission + permission.upper() - parent_permissions = permission - elif isinstance(item, storage.BaseCollection): - if item.get_meta("tag"): - permissions = permission - else: - permissions = permission.upper() - parent_permissions = "" - else: - permissions = "" - parent_permissions = permission - return bool(rights.intersect(self.permissions, permissions) or ( - self.path != self.parent_path and - rights.intersect(self.parent_permissions, parent_permissions))) diff --git a/radicale/app/base.py b/radicale/app/base.py new file mode 100644 index 00000000..7b139a26 --- /dev/null +++ b/radicale/app/base.py @@ -0,0 +1,131 @@ +# This file is part of Radicale Server - Calendar Server +# Copyright © 2020 Unrud +# +# This library is free software: you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation, either version 3 of the License, or +# (at your option) any later version. +# +# This library is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with Radicale. If not, see . + +import io +import logging +import posixpath +import sys +import xml.etree.ElementTree as ET +from typing import Optional + +from radicale import (auth, config, httputils, pathutils, rights, storage, + types, web, xmlutils) +from radicale.log import logger + +# HACK: https://github.com/tiran/defusedxml/issues/54 +import defusedxml.ElementTree as DefusedET # isort:skip +sys.modules["xml.etree"].ElementTree = ET # type:ignore[attr-defined] + + +class ApplicationBase: + + configuration: config.Configuration + _auth: auth.BaseAuth + _storage: storage.BaseStorage + _rights: rights.BaseRights + _web: web.BaseWeb + _encoding: str + + def __init__(self, configuration: config.Configuration) -> None: + self.configuration = configuration + self._auth = auth.load(configuration) + self._storage = storage.load(configuration) + self._rights = rights.load(configuration) + self._web = web.load(configuration) + self._encoding = configuration.get("encoding", "request") + + def _read_xml_request_body(self, environ: types.WSGIEnviron + ) -> Optional[ET.Element]: + content = httputils.decode_request( + self.configuration, environ, + httputils.read_raw_request_body(self.configuration, environ)) + if not content: + return None + try: + xml_content = DefusedET.fromstring(content) + except ET.ParseError as e: + logger.debug("Request content (Invalid XML):\n%s", content) + raise RuntimeError("Failed to parse XML: %s" % e) from e + if logger.isEnabledFor(logging.DEBUG): + logger.debug("Request content:\n%s", + xmlutils.pretty_xml(xml_content)) + return xml_content + + def _xml_response(self, xml_content: ET.Element) -> bytes: + if logger.isEnabledFor(logging.DEBUG): + logger.debug("Response content:\n%s", + xmlutils.pretty_xml(xml_content)) + f = io.BytesIO() + ET.ElementTree(xml_content).write(f, encoding=self._encoding, + xml_declaration=True) + return f.getvalue() + + def _webdav_error_response(self, status: int, human_tag: str + ) -> types.WSGIResponse: + """Generate XML error response.""" + headers = {"Content-Type": "text/xml; charset=%s" % self._encoding} + content = self._xml_response(xmlutils.webdav_error(human_tag)) + return status, headers, content + + +class Access: + """Helper class to check access rights of an item""" + + user: str + path: str + parent_path: str + permissions: str + _rights: rights.BaseRights + _parent_permissions: Optional[str] + + def __init__(self, rights: rights.BaseRights, user: str, path: str + ) -> None: + self._rights = rights + self.user = user + self.path = path + self.parent_path = pathutils.unstrip_path( + posixpath.dirname(pathutils.strip_path(path)), True) + self.permissions = self._rights.authorization(self.user, self.path) + self._parent_permissions = None + + @property + def parent_permissions(self) -> str: + if self.path == self.parent_path: + return self.permissions + if self._parent_permissions is None: + self._parent_permissions = self._rights.authorization( + self.user, self.parent_path) + return self._parent_permissions + + def check(self, permission: str, + item: Optional[types.CollectionOrItem] = None) -> bool: + if permission not in "rw": + raise ValueError("Invalid permission argument: %r" % permission) + if not item: + permissions = permission + permission.upper() + parent_permissions = permission + elif isinstance(item, storage.BaseCollection): + if item.tag: + permissions = permission + else: + permissions = permission.upper() + parent_permissions = "" + else: + permissions = "" + parent_permissions = permission + return bool(rights.intersect(self.permissions, permissions) or ( + self.path != self.parent_path and + rights.intersect(self.parent_permissions, parent_permissions))) diff --git a/radicale/app/delete.py b/radicale/app/delete.py index 05437c81..c47fea3f 100644 --- a/radicale/app/delete.py +++ b/radicale/app/delete.py @@ -19,25 +19,28 @@ import xml.etree.ElementTree as ET from http import client +from typing import Optional -from radicale import app, httputils, storage, xmlutils +from radicale import httputils, storage, types, xmlutils +from radicale.app.base import Access, ApplicationBase -def xml_delete(base_prefix, path, collection, href=None): +def xml_delete(base_prefix: str, path: str, collection: storage.BaseCollection, + item_href: Optional[str] = None) -> ET.Element: """Read and answer DELETE requests. Read rfc4918-9.6 for info. """ - collection.delete(href) + collection.delete(item_href) multistatus = ET.Element(xmlutils.make_clark("D:multistatus")) response = ET.Element(xmlutils.make_clark("D:response")) multistatus.append(response) - href = ET.Element(xmlutils.make_clark("D:href")) - href.text = xmlutils.make_href(base_prefix, path) - response.append(href) + href_element = ET.Element(xmlutils.make_clark("D:href")) + href_element.text = xmlutils.make_href(base_prefix, path) + response.append(href_element) status = ET.Element(xmlutils.make_clark("D:status")) status.text = xmlutils.make_response(200) @@ -46,14 +49,16 @@ def xml_delete(base_prefix, path, collection, href=None): return multistatus -class ApplicationDeleteMixin: - def do_DELETE(self, environ, base_prefix, path, user): +class ApplicationPartDelete(ApplicationBase): + + def do_DELETE(self, environ: types.WSGIEnviron, base_prefix: str, + path: str, user: str) -> types.WSGIResponse: """Manage DELETE request.""" - access = app.Access(self._rights, user, path) + access = Access(self._rights, user, path) if not access.check("w"): return httputils.NOT_ALLOWED with self._storage.acquire_lock("w", user): - item = next(self._storage.discover(path), None) + item = next(iter(self._storage.discover(path)), None) if not item: return httputils.NOT_FOUND if not access.check("w", item): @@ -65,6 +70,8 @@ class ApplicationDeleteMixin: if isinstance(item, storage.BaseCollection): xml_answer = xml_delete(base_prefix, path, item) else: + assert item.collection is not None + assert item.href is not None xml_answer = xml_delete( base_prefix, path, item.collection, item.href) headers = {"Content-Type": "text/xml; charset=%s" % self._encoding} diff --git a/radicale/app/get.py b/radicale/app/get.py index 79e068a6..7e990027 100644 --- a/radicale/app/get.py +++ b/radicale/app/get.py @@ -21,17 +21,17 @@ import posixpath from http import client from urllib.parse import quote -from radicale import app, httputils, pathutils, storage, xmlutils +from radicale import httputils, pathutils, storage, types, xmlutils +from radicale.app.base import Access, ApplicationBase from radicale.log import logger -def propose_filename(collection): +def propose_filename(collection: storage.BaseCollection) -> str: """Propose a filename for a collection.""" - tag = collection.get_meta("tag") - if tag == "VADDRESSBOOK": + if collection.tag == "VADDRESSBOOK": fallback_title = "Address book" suffix = ".vcf" - elif tag == "VCALENDAR": + elif collection.tag == "VCALENDAR": fallback_title = "Calendar" suffix = ".ics" else: @@ -43,8 +43,9 @@ def propose_filename(collection): return title -class ApplicationGetMixin: - def _content_disposition_attachement(self, filename): +class ApplicationPartGet(ApplicationBase): + + def _content_disposition_attachement(self, filename: str) -> str: value = "attachement" try: encoded_filename = quote(filename, encoding=self._encoding) @@ -56,7 +57,8 @@ class ApplicationGetMixin: value += "; filename*=%s''%s" % (self._encoding, encoded_filename) return value - def do_GET(self, environ, base_prefix, path, user): + def do_GET(self, environ: types.WSGIEnviron, base_prefix: str, path: str, + user: str) -> types.WSGIResponse: """Manage GET request.""" # Redirect to .web if the root URL is requested if not pathutils.strip_path(path): @@ -70,11 +72,11 @@ class ApplicationGetMixin: # Dispatch .web URL to web module if path == "/.web" or path.startswith("/.web/"): return self._web.get(environ, base_prefix, path, user) - access = app.Access(self._rights, user, path) + access = Access(self._rights, user, path) if not access.check("r") and "i" not in access.permissions: return httputils.NOT_ALLOWED with self._storage.acquire_lock("r", user): - item = next(self._storage.discover(path), None) + item = next(iter(self._storage.discover(path)), None) if not item: return httputils.NOT_FOUND if access.check("r", item): @@ -84,11 +86,10 @@ class ApplicationGetMixin: else: return httputils.NOT_ALLOWED if isinstance(item, storage.BaseCollection): - tag = item.get_meta("tag") - if not tag: + if not item.tag: return (httputils.NOT_ALLOWED if limited_access else httputils.DIRECTORY_LISTING) - content_type = xmlutils.MIMETYPES[tag] + content_type = xmlutils.MIMETYPES[item.tag] content_disposition = self._content_disposition_attachement( propose_filename(item)) elif limited_access: @@ -96,6 +97,7 @@ class ApplicationGetMixin: else: content_type = xmlutils.OBJECT_MIMETYPES[item.name] content_disposition = "" + assert item.last_modified headers = { "Content-Type": content_type, "Last-Modified": item.last_modified, diff --git a/radicale/app/head.py b/radicale/app/head.py index 7ba004fd..357682d2 100644 --- a/radicale/app/head.py +++ b/radicale/app/head.py @@ -17,9 +17,15 @@ # You should have received a copy of the GNU General Public License # along with Radicale. If not, see . +from radicale import types +from radicale.app.base import ApplicationBase +from radicale.app.get import ApplicationPartGet -class ApplicationHeadMixin: - def do_HEAD(self, environ, base_prefix, path, user): + +class ApplicationPartHead(ApplicationPartGet, ApplicationBase): + + def do_HEAD(self, environ: types.WSGIEnviron, base_prefix: str, path: str, + user: str) -> types.WSGIResponse: """Manage HEAD request.""" status, headers, _ = self.do_GET(environ, base_prefix, path, user) return status, headers, None diff --git a/radicale/app/mkcalendar.py b/radicale/app/mkcalendar.py index f0649d76..67b6c3fc 100644 --- a/radicale/app/mkcalendar.py +++ b/radicale/app/mkcalendar.py @@ -21,14 +21,16 @@ import posixpath import socket from http import client -from radicale import httputils -from radicale import item as radicale_item -from radicale import pathutils, storage, xmlutils +import radicale.item as radicale_item +from radicale import httputils, pathutils, storage, types, xmlutils +from radicale.app.base import ApplicationBase from radicale.log import logger -class ApplicationMkcalendarMixin: - def do_MKCALENDAR(self, environ, base_prefix, path, user): +class ApplicationPartMkcalendar(ApplicationBase): + + def do_MKCALENDAR(self, environ: types.WSGIEnviron, base_prefix: str, + path: str, user: str) -> types.WSGIResponse: """Manage MKCALENDAR request.""" if "w" not in self._rights.authorization(user, path): return httputils.NOT_ALLOWED @@ -42,29 +44,28 @@ class ApplicationMkcalendarMixin: logger.debug("Client timed out", exc_info=True) return httputils.REQUEST_TIMEOUT # Prepare before locking - props = xmlutils.props_from_request(xml_content) - props = {k: v for k, v in props.items() if v is not None} - props["tag"] = "VCALENDAR" - # TODO: use this? - # timezone = props.get("C:calendar-timezone") + props_with_remove = xmlutils.props_from_request(xml_content) + props_with_remove["tag"] = "VCALENDAR" try: - radicale_item.check_and_sanitize_props(props) + props = radicale_item.check_and_sanitize_props(props_with_remove) except ValueError as e: logger.warning( "Bad MKCALENDAR request on %r: %s", path, e, exc_info=True) return httputils.BAD_REQUEST + # TODO: use this? + # timezone = props.get("C:calendar-timezone") with self._storage.acquire_lock("w", user): - item = next(self._storage.discover(path), None) + item = next(iter(self._storage.discover(path)), None) if item: return self._webdav_error_response( client.CONFLICT, "D:resource-must-be-null") parent_path = pathutils.unstrip_path( posixpath.dirname(pathutils.strip_path(path)), True) - parent_item = next(self._storage.discover(parent_path), None) + parent_item = next(iter(self._storage.discover(parent_path)), None) if not parent_item: return httputils.CONFLICT if (not isinstance(parent_item, storage.BaseCollection) or - parent_item.get_meta("tag")): + parent_item.tag): return httputils.FORBIDDEN try: self._storage.create_collection(path, props=props) diff --git a/radicale/app/mkcol.py b/radicale/app/mkcol.py index 4118141d..5d871697 100644 --- a/radicale/app/mkcol.py +++ b/radicale/app/mkcol.py @@ -21,14 +21,16 @@ import posixpath import socket from http import client -from radicale import httputils -from radicale import item as radicale_item -from radicale import pathutils, rights, storage, xmlutils +import radicale.item as radicale_item +from radicale import httputils, pathutils, rights, storage, types, xmlutils +from radicale.app.base import ApplicationBase from radicale.log import logger -class ApplicationMkcolMixin: - def do_MKCOL(self, environ, base_prefix, path, user): +class ApplicationPartMkcol(ApplicationBase): + + def do_MKCOL(self, environ: types.WSGIEnviron, base_prefix: str, + path: str, user: str) -> types.WSGIResponse: """Manage MKCOL request.""" permissions = self._rights.authorization(user, path) if not rights.intersect(permissions, "Ww"): @@ -43,10 +45,9 @@ class ApplicationMkcolMixin: logger.debug("Client timed out", exc_info=True) return httputils.REQUEST_TIMEOUT # Prepare before locking - props = xmlutils.props_from_request(xml_content) - props = {k: v for k, v in props.items() if v is not None} + props_with_remove = xmlutils.props_from_request(xml_content) try: - radicale_item.check_and_sanitize_props(props) + props = radicale_item.check_and_sanitize_props(props_with_remove) except ValueError as e: logger.warning( "Bad MKCOL request on %r: %s", path, e, exc_info=True) @@ -55,16 +56,16 @@ class ApplicationMkcolMixin: not props.get("tag") and "W" not in permissions): return httputils.NOT_ALLOWED with self._storage.acquire_lock("w", user): - item = next(self._storage.discover(path), None) + item = next(iter(self._storage.discover(path)), None) if item: return httputils.METHOD_NOT_ALLOWED parent_path = pathutils.unstrip_path( posixpath.dirname(pathutils.strip_path(path)), True) - parent_item = next(self._storage.discover(parent_path), None) + parent_item = next(iter(self._storage.discover(parent_path)), None) if not parent_item: return httputils.CONFLICT if (not isinstance(parent_item, storage.BaseCollection) or - parent_item.get_meta("tag")): + parent_item.tag): return httputils.FORBIDDEN try: self._storage.create_collection(path, props=props) diff --git a/radicale/app/move.py b/radicale/app/move.py index c2fe71a1..37a72946 100644 --- a/radicale/app/move.py +++ b/radicale/app/move.py @@ -21,12 +21,15 @@ import posixpath from http import client from urllib.parse import urlparse -from radicale import app, httputils, pathutils, storage +from radicale import httputils, pathutils, storage, types +from radicale.app.base import Access, ApplicationBase from radicale.log import logger -class ApplicationMoveMixin: - def do_MOVE(self, environ, base_prefix, path, user): +class ApplicationPartMove(ApplicationBase): + + def do_MOVE(self, environ: types.WSGIEnviron, base_prefix: str, + path: str, user: str) -> types.WSGIResponse: """Manage MOVE request.""" raw_dest = environ.get("HTTP_DESTINATION", "") to_url = urlparse(raw_dest) @@ -34,7 +37,7 @@ class ApplicationMoveMixin: logger.info("Unsupported destination address: %r", raw_dest) # Remote destination server, not supported return httputils.REMOTE_DESTINATION - access = app.Access(self._rights, user, path) + access = Access(self._rights, user, path) if not access.check("w"): return httputils.NOT_ALLOWED to_path = pathutils.sanitize_path(to_url.path) @@ -43,12 +46,12 @@ class ApplicationMoveMixin: "start with base prefix", to_path, path) return httputils.NOT_ALLOWED to_path = to_path[len(base_prefix):] - to_access = app.Access(self._rights, user, to_path) + to_access = Access(self._rights, user, to_path) if not to_access.check("w"): return httputils.NOT_ALLOWED with self._storage.acquire_lock("w", user): - item = next(self._storage.discover(path), None) + item = next(iter(self._storage.discover(path)), None) if not item: return httputils.NOT_FOUND if (not access.check("w", item) or @@ -58,17 +61,19 @@ class ApplicationMoveMixin: # TODO: support moving collections return httputils.METHOD_NOT_ALLOWED - to_item = next(self._storage.discover(to_path), None) + to_item = next(iter(self._storage.discover(to_path)), None) if isinstance(to_item, storage.BaseCollection): return httputils.FORBIDDEN to_parent_path = pathutils.unstrip_path( posixpath.dirname(pathutils.strip_path(to_path)), True) - to_collection = next( - self._storage.discover(to_parent_path), None) + to_collection = next(iter( + self._storage.discover(to_parent_path)), None) if not to_collection: return httputils.CONFLICT - tag = item.collection.get_meta("tag") - if not tag or tag != to_collection.get_meta("tag"): + assert isinstance(to_collection, storage.BaseCollection) + assert item.collection is not None + collection_tag = item.collection.tag + if not collection_tag or collection_tag != to_collection.tag: return httputils.FORBIDDEN if to_item and environ.get("HTTP_OVERWRITE", "F") != "T": return httputils.PRECONDITION_FAILED @@ -78,7 +83,7 @@ class ApplicationMoveMixin: to_collection.has_uid(item.uid)): return self._webdav_error_response( client.CONFLICT, "%s:no-uid-conflict" % ( - "C" if tag == "VCALENDAR" else "CR")) + "C" if collection_tag == "VCALENDAR" else "CR")) to_href = posixpath.basename(pathutils.strip_path(to_path)) try: self._storage.move(item, to_collection, to_href) diff --git a/radicale/app/options.py b/radicale/app/options.py index c110a286..19f00f07 100644 --- a/radicale/app/options.py +++ b/radicale/app/options.py @@ -19,11 +19,14 @@ from http import client -from radicale import httputils +from radicale import httputils, types +from radicale.app.base import ApplicationBase -class ApplicationOptionsMixin: - def do_OPTIONS(self, environ, base_prefix, path, user): +class ApplicationPartOptions(ApplicationBase): + + def do_OPTIONS(self, environ: types.WSGIEnviron, base_prefix: str, + path: str, user: str) -> types.WSGIResponse: """Manage OPTIONS request.""" headers = { "Allow": ", ".join( diff --git a/radicale/app/post.py b/radicale/app/post.py index a3de951e..e350a103 100644 --- a/radicale/app/post.py +++ b/radicale/app/post.py @@ -18,11 +18,14 @@ # You should have received a copy of the GNU General Public License # along with Radicale. If not, see . -from radicale import httputils +from radicale import httputils, types +from radicale.app.base import ApplicationBase -class ApplicationPostMixin: - def do_POST(self, environ, base_prefix, path, user): +class ApplicationPartPost(ApplicationBase): + + def do_POST(self, environ: types.WSGIEnviron, base_prefix: str, + path: str, user: str) -> types.WSGIResponse: """Manage POST request.""" if path == "/.web" or path.startswith("/.web/"): return self._web.post(environ, base_prefix, path, user) diff --git a/radicale/app/propfind.py b/radicale/app/propfind.py index 55ca2d3a..e4f674e9 100644 --- a/radicale/app/propfind.py +++ b/radicale/app/propfind.py @@ -23,13 +23,17 @@ import posixpath import socket import xml.etree.ElementTree as ET from http import client +from typing import Dict, Iterable, Iterator, List, Optional, Sequence, Tuple -from radicale import app, httputils, pathutils, rights, storage, xmlutils +from radicale import httputils, pathutils, rights, storage, types, xmlutils +from radicale.app.base import Access, ApplicationBase from radicale.log import logger -def xml_propfind(base_prefix, path, xml_request, allowed_items, user, - encoding): +def xml_propfind(base_prefix: str, path: str, + xml_request: Optional[ET.Element], + allowed_items: Iterable[Tuple[types.CollectionOrItem, str]], + user: str, encoding: str) -> Optional[ET.Element]: """Read and answer PROPFIND requests. Read rfc4918-9.1 for info. @@ -43,7 +47,7 @@ def xml_propfind(base_prefix, path, xml_request, allowed_items, user, top_element = (xml_request[0] if xml_request is not None else ET.Element(xmlutils.make_clark("D:allprop"))) - props = () + props: List[str] = [] allprop = False propname = False if top_element.tag == xmlutils.make_clark("D:allprop"): @@ -51,13 +55,13 @@ def xml_propfind(base_prefix, path, xml_request, allowed_items, user, elif top_element.tag == xmlutils.make_clark("D:propname"): propname = True elif top_element.tag == xmlutils.make_clark("D:prop"): - props = [prop.tag for prop in top_element] + props.extend(prop.tag for prop in top_element) if xmlutils.make_clark("D:current-user-principal") in props and not user: # Ask for authentication # Returning the DAV:unauthenticated pseudo-principal as specified in # RFC 5397 doesn't seem to work with DAVx5. - return client.FORBIDDEN, None + return None # Writing answer multistatus = ET.Element(xmlutils.make_clark("D:multistatus")) @@ -68,29 +72,32 @@ def xml_propfind(base_prefix, path, xml_request, allowed_items, user, base_prefix, path, item, props, user, encoding, write=write, allprop=allprop, propname=propname)) - return client.MULTI_STATUS, multistatus + return multistatus -def xml_propfind_response(base_prefix, path, item, props, user, encoding, - write=False, propname=False, allprop=False): +def xml_propfind_response( + base_prefix: str, path: str, item: types.CollectionOrItem, + props: Sequence[str], user: str, encoding: str, write: bool = False, + propname: bool = False, allprop: bool = False) -> ET.Element: """Build and return a PROPFIND response.""" if propname and allprop or (props and (propname or allprop)): raise ValueError("Only use one of props, propname and allprops") - is_collection = isinstance(item, storage.BaseCollection) - if is_collection: - is_leaf = item.get_meta("tag") in ("VADDRESSBOOK", "VCALENDAR") - collection = item - else: - collection = item.collection - response = ET.Element(xmlutils.make_clark("D:response")) - href = ET.Element(xmlutils.make_clark("D:href")) - if is_collection: - # Some clients expect collections to end with / + if isinstance(item, storage.BaseCollection): + is_collection = True + is_leaf = item.tag in ("VADDRESSBOOK", "VCALENDAR") + collection = item + # Some clients expect collections to end with `/` uri = pathutils.unstrip_path(item.path, True) else: - uri = pathutils.unstrip_path( - posixpath.join(collection.path, item.href)) + is_collection = is_leaf = False + assert item.collection is not None + assert item.href + collection = item.collection + uri = pathutils.unstrip_path(posixpath.join( + collection.path, item.href)) + response = ET.Element(xmlutils.make_clark("D:response")) + href = ET.Element(xmlutils.make_clark("D:href")) href.text = xmlutils.make_href(base_prefix, uri) response.append(href) @@ -120,12 +127,12 @@ def xml_propfind_response(base_prefix, path, item, props, user, encoding, if is_leaf: props.append(xmlutils.make_clark("D:displayname")) props.append(xmlutils.make_clark("D:sync-token")) - if collection.get_meta("tag") == "VCALENDAR": + if collection.tag == "VCALENDAR": props.append(xmlutils.make_clark("CS:getctag")) props.append( xmlutils.make_clark("C:supported-calendar-component-set")) - meta = item.get_meta() + meta = collection.get_meta() for tag in meta: if tag == "tag": continue @@ -133,11 +140,11 @@ def xml_propfind_response(base_prefix, path, item, props, user, encoding, if clark_tag not in props: props.append(clark_tag) - responses = collections.defaultdict(list) + responses: Dict[int, List[ET.Element]] = collections.defaultdict(list) if propname: for tag in props: responses[200].append(ET.Element(tag)) - props = () + props = [] for tag in props: element = ET.Element(tag) is404 = False @@ -159,18 +166,18 @@ def xml_propfind_response(base_prefix, path, item, props, user, encoding, xmlutils.make_clark("D:principal-URL"), xmlutils.make_clark("CR:addressbook-home-set"), xmlutils.make_clark("C:calendar-home-set")) and - collection.is_principal and is_collection): + is_collection and collection.is_principal): child_element = ET.Element(xmlutils.make_clark("D:href")) child_element.text = xmlutils.make_href(base_prefix, path) element.append(child_element) elif tag == xmlutils.make_clark("C:supported-calendar-component-set"): human_tag = xmlutils.make_human_tag(tag) if is_collection and is_leaf: - meta = item.get_meta(human_tag) - if meta: - components = meta.split(",") + components_text = collection.get_meta(human_tag) + if components_text: + components = components_text.split(",") else: - components = ("VTODO", "VEVENT", "VJOURNAL") + components = ["VTODO", "VEVENT", "VJOURNAL"] for component in components: comp = ET.Element(xmlutils.make_clark("C:comp")) comp.set("name", component) @@ -205,10 +212,10 @@ def xml_propfind_response(base_prefix, path, item, props, user, encoding, "D:principal-property-search"] if is_collection and is_leaf: reports.append("D:sync-collection") - if item.get_meta("tag") == "VADDRESSBOOK": + if collection.tag == "VADDRESSBOOK": reports.append("CR:addressbook-multiget") reports.append("CR:addressbook-query") - elif item.get_meta("tag") == "VCALENDAR": + elif collection.tag == "VCALENDAR": reports.append("C:calendar-multiget") reports.append("C:calendar-query") for human_tag in reports: @@ -234,20 +241,21 @@ def xml_propfind_response(base_prefix, path, item, props, user, encoding, elif is_collection: if tag == xmlutils.make_clark("D:getcontenttype"): if is_leaf: - element.text = xmlutils.MIMETYPES[item.get_meta("tag")] + element.text = xmlutils.MIMETYPES[ + collection.tag] else: is404 = True elif tag == xmlutils.make_clark("D:resourcetype"): - if item.is_principal: + if collection.is_principal: child_element = ET.Element( xmlutils.make_clark("D:principal")) element.append(child_element) if is_leaf: - if item.get_meta("tag") == "VADDRESSBOOK": + if collection.tag == "VADDRESSBOOK": child_element = ET.Element( xmlutils.make_clark("CR:addressbook")) element.append(child_element) - elif item.get_meta("tag") == "VCALENDAR": + elif collection.tag == "VCALENDAR": child_element = ET.Element( xmlutils.make_clark("C:calendar")) element.append(child_element) @@ -255,38 +263,39 @@ def xml_propfind_response(base_prefix, path, item, props, user, encoding, element.append(child_element) elif tag == xmlutils.make_clark("RADICALE:displayname"): # Only for internal use by the web interface - displayname = item.get_meta("D:displayname") + displayname = collection.get_meta("D:displayname") if displayname is not None: element.text = displayname else: is404 = True elif tag == xmlutils.make_clark("D:displayname"): - displayname = item.get_meta("D:displayname") + displayname = collection.get_meta("D:displayname") if not displayname and is_leaf: - displayname = item.path + displayname = collection.path if displayname is not None: element.text = displayname else: is404 = True elif tag == xmlutils.make_clark("CS:getctag"): if is_leaf: - element.text = item.etag + element.text = collection.etag else: is404 = True elif tag == xmlutils.make_clark("D:sync-token"): if is_leaf: - element.text, _ = item.sync() + element.text, _ = collection.sync() else: is404 = True else: human_tag = xmlutils.make_human_tag(tag) - meta = item.get_meta(human_tag) - if meta is not None: - element.text = meta + tag_text = collection.get_meta(human_tag) + if tag_text is not None: + element.text = tag_text else: is404 = True # Not for collections elif tag == xmlutils.make_clark("D:getcontenttype"): + assert not isinstance(item, storage.BaseCollection) element.text = xmlutils.get_content_type(item, encoding) elif tag == xmlutils.make_clark("D:resourcetype"): # resourcetype must be returned empty for non-collection elements @@ -311,13 +320,16 @@ def xml_propfind_response(base_prefix, path, item, props, user, encoding, return response -class ApplicationPropfindMixin: - def _collect_allowed_items(self, items, user): +class ApplicationPartPropfind(ApplicationBase): + + def _collect_allowed_items( + self, items: Iterable[types.CollectionOrItem], user: str + ) -> Iterator[Tuple[types.CollectionOrItem, str]]: """Get items from request that user is allowed to access.""" for item in items: if isinstance(item, storage.BaseCollection): path = pathutils.unstrip_path(item.path, True) - if item.get_meta("tag"): + if item.tag: permissions = rights.intersect( self._rights.authorization(user, path), "rw") target = "collection with tag %r" % item.path @@ -326,6 +338,7 @@ class ApplicationPropfindMixin: self._rights.authorization(user, path), "RW") target = "collection %r" % item.path else: + assert item.collection is not None path = pathutils.unstrip_path(item.collection.path, True) permissions = rights.intersect( self._rights.authorization(user, path), "rw") @@ -345,9 +358,10 @@ class ApplicationPropfindMixin: if permission: yield item, permission - def do_PROPFIND(self, environ, base_prefix, path, user): + def do_PROPFIND(self, environ: types.WSGIEnviron, base_prefix: str, + path: str, user: str) -> types.WSGIResponse: """Manage PROPFIND request.""" - access = app.Access(self._rights, user, path) + access = Access(self._rights, user, path) if not access.check("r"): return httputils.NOT_ALLOWED try: @@ -360,22 +374,21 @@ class ApplicationPropfindMixin: logger.debug("Client timed out", exc_info=True) return httputils.REQUEST_TIMEOUT with self._storage.acquire_lock("r", user): - items = self._storage.discover( - path, environ.get("HTTP_DEPTH", "0")) + items_iter = iter(self._storage.discover( + path, environ.get("HTTP_DEPTH", "0"))) # take root item for rights checking - item = next(items, None) + item = next(items_iter, None) if not item: return httputils.NOT_FOUND if not access.check("r", item): return httputils.NOT_ALLOWED # put item back - items = itertools.chain([item], items) - allowed_items = self._collect_allowed_items(items, user) + items_iter = itertools.chain([item], items_iter) + allowed_items = self._collect_allowed_items(items_iter, user) headers = {"DAV": httputils.DAV_HEADERS, "Content-Type": "text/xml; charset=%s" % self._encoding} - status, xml_answer = xml_propfind( - base_prefix, path, xml_content, allowed_items, user, - self._encoding) - if status == client.FORBIDDEN and xml_answer is None: + xml_answer = xml_propfind(base_prefix, path, xml_content, + allowed_items, user, self._encoding) + if xml_answer is None: return httputils.NOT_ALLOWED - return status, headers, self._xml_response(xml_answer) + return client.MULTI_STATUS, headers, self._xml_response(xml_answer) diff --git a/radicale/app/proppatch.py b/radicale/app/proppatch.py index 38804dd1..7170266f 100644 --- a/radicale/app/proppatch.py +++ b/radicale/app/proppatch.py @@ -17,18 +17,20 @@ # You should have received a copy of the GNU General Public License # along with Radicale. If not, see . -import contextlib import socket import xml.etree.ElementTree as ET from http import client +from typing import Dict, Optional, cast -from radicale import app, httputils -from radicale import item as radicale_item -from radicale import storage, xmlutils +import radicale.item as radicale_item +from radicale import httputils, storage, types, xmlutils +from radicale.app.base import Access, ApplicationBase from radicale.log import logger -def xml_proppatch(base_prefix, path, xml_request, collection): +def xml_proppatch(base_prefix: str, path: str, + xml_request: Optional[ET.Element], + collection: storage.BaseCollection) -> ET.Element: """Read and answer PROPPATCH requests. Read rfc4918-9.2 for info. @@ -49,24 +51,24 @@ def xml_proppatch(base_prefix, path, xml_request, collection): propstat.append(status) response.append(propstat) - new_props = collection.get_meta() - for short_name, value in xmlutils.props_from_request(xml_request).items(): - if value is None: - with contextlib.suppress(KeyError): - del new_props[short_name] - else: - new_props[short_name] = value + props_with_remove = xmlutils.props_from_request(xml_request) + all_props_with_remove = cast(Dict[str, Optional[str]], + dict(collection.get_meta())) + all_props_with_remove.update(props_with_remove) + all_props = radicale_item.check_and_sanitize_props(all_props_with_remove) + collection.set_meta(all_props) + for short_name in props_with_remove: props_ok.append(ET.Element(xmlutils.make_clark(short_name))) - radicale_item.check_and_sanitize_props(new_props) - collection.set_meta(new_props) return multistatus -class ApplicationProppatchMixin: - def do_PROPPATCH(self, environ, base_prefix, path, user): +class ApplicationPartProppatch(ApplicationBase): + + def do_PROPPATCH(self, environ: types.WSGIEnviron, base_prefix: str, + path: str, user: str) -> types.WSGIResponse: """Manage PROPPATCH request.""" - access = app.Access(self._rights, user, path) + access = Access(self._rights, user, path) if not access.check("w"): return httputils.NOT_ALLOWED try: @@ -79,7 +81,7 @@ class ApplicationProppatchMixin: logger.debug("Client timed out", exc_info=True) return httputils.REQUEST_TIMEOUT with self._storage.acquire_lock("w", user): - item = next(self._storage.discover(path), None) + item = next(iter(self._storage.discover(path)), None) if not item: return httputils.NOT_FOUND if not access.check("w", item): diff --git a/radicale/app/put.py b/radicale/app/put.py index 29519745..bdb9faee 100644 --- a/radicale/app/put.py +++ b/radicale/app/put.py @@ -22,20 +22,30 @@ import posixpath import socket import sys from http import client +from types import TracebackType +from typing import Iterator, List, Mapping, MutableMapping, Optional, Tuple import vobject -from radicale import app, httputils -from radicale import item as radicale_item -from radicale import pathutils, rights, storage, xmlutils +import radicale.item as radicale_item +from radicale import httputils, pathutils, rights, storage, types, xmlutils +from radicale.app.base import Access, ApplicationBase from radicale.log import logger -MIMETYPE_TAGS = {value: key for key, value in xmlutils.MIMETYPES.items()} +MIMETYPE_TAGS: Mapping[str, str] = {value: key for key, value in + xmlutils.MIMETYPES.items()} -def prepare(vobject_items, path, content_type, permissions, parent_permissions, - tag=None, write_whole_collection=None): - if (write_whole_collection or permissions and not parent_permissions): +def prepare(vobject_items: List[vobject.base.Component], path: str, + content_type: str, permission: bool, parent_permission: bool, + tag: Optional[str] = None, + write_whole_collection: Optional[bool] = None) -> Tuple[ + Iterator[radicale_item.Item], # items + Optional[str], # tag + Optional[bool], # write_whole_collection + Optional[MutableMapping[str, str]], # props + Optional[Tuple[type, BaseException, Optional[TracebackType]]]]: + if (write_whole_collection or permission and not parent_permission): write_whole_collection = True tag = radicale_item.predict_tag_of_whole_collection( vobject_items, MIMETYPE_TAGS.get(content_type)) @@ -43,20 +53,20 @@ def prepare(vobject_items, path, content_type, permissions, parent_permissions, raise ValueError("Can't determine collection tag") collection_path = pathutils.strip_path(path) elif (write_whole_collection is not None and not write_whole_collection or - not permissions and parent_permissions): + not permission and parent_permission): write_whole_collection = False if tag is None: tag = radicale_item.predict_tag_of_parent_collection(vobject_items) collection_path = posixpath.dirname(pathutils.strip_path(path)) - props = None + props: Optional[MutableMapping[str, str]] = None stored_exc_info = None items = [] try: - if tag: + if tag and write_whole_collection is not None: radicale_item.check_and_sanitize_items( vobject_items, is_collection=write_whole_collection, tag=tag) if write_whole_collection and tag == "VCALENDAR": - vobject_components = [] + vobject_components: List[vobject.base.Component] = [] vobject_item, = vobject_items for content in ("vevent", "vtodo", "vjournal"): vobject_components.extend( @@ -98,23 +108,25 @@ def prepare(vobject_items, path, content_type, permissions, parent_permissions, caldesc = vobject_items[0].x_wr_caldesc.value if caldesc: props["C:calendar-description"] = caldesc - radicale_item.check_and_sanitize_props(props) + props = radicale_item.check_and_sanitize_props(props) except Exception: - stored_exc_info = sys.exc_info() + exc_info_or_none_tuple = sys.exc_info() + assert exc_info_or_none_tuple[0] is not None + stored_exc_info = exc_info_or_none_tuple - # Use generator for items and delete references to free memory - # early - def items_generator(): + # Use iterator for items and delete references to free memory early + def items_iter() -> Iterator[radicale_item.Item]: while items: yield items.pop(0) - return (items_generator(), tag, write_whole_collection, props, - stored_exc_info) + return items_iter(), tag, write_whole_collection, props, stored_exc_info -class ApplicationPutMixin: - def do_PUT(self, environ, base_prefix, path, user): +class ApplicationPartPut(ApplicationBase): + + def do_PUT(self, environ: types.WSGIEnviron, base_prefix: str, + path: str, user: str) -> types.WSGIResponse: """Manage PUT request.""" - access = app.Access(self._rights, user, path) + access = Access(self._rights, user, path) if not access.check("w"): return httputils.NOT_ALLOWED try: @@ -126,9 +138,10 @@ class ApplicationPutMixin: logger.debug("Client timed out", exc_info=True) return httputils.REQUEST_TIMEOUT # Prepare before locking - content_type = environ.get("CONTENT_TYPE", "").split(";")[0] + content_type = environ.get("CONTENT_TYPE", "").split(";", + maxsplit=1)[0] try: - vobject_items = tuple(vobject.readComponents(content or "")) + vobject_items = list(vobject.readComponents(content or "")) except Exception as e: logger.warning( "Bad PUT request on %r: %s", path, e, exc_info=True) @@ -140,20 +153,20 @@ class ApplicationPutMixin: bool(rights.intersect(access.parent_permissions, "w"))) with self._storage.acquire_lock("w", user): - item = next(self._storage.discover(path), None) - parent_item = next( - self._storage.discover(access.parent_path), None) - if not parent_item: + item = next(iter(self._storage.discover(path)), None) + parent_item = next(iter( + self._storage.discover(access.parent_path)), None) + if not isinstance(parent_item, storage.BaseCollection): return httputils.CONFLICT write_whole_collection = ( isinstance(item, storage.BaseCollection) or - not parent_item.get_meta("tag")) + not parent_item.tag) if write_whole_collection: tag = prepared_tag else: - tag = parent_item.get_meta("tag") + tag = parent_item.tag if write_whole_collection: if ("w" if tag else "W") not in access.permissions: @@ -198,6 +211,7 @@ class ApplicationPutMixin: "Bad PUT request on %r: %s", path, e, exc_info=True) return httputils.BAD_REQUEST else: + assert not isinstance(item, storage.BaseCollection) prepared_item, = prepared_items if (item and item.uid != prepared_item.uid or not item and parent_item.has_uid(prepared_item.uid)): diff --git a/radicale/app/report.py b/radicale/app/report.py index 0c35783f..b2e6335a 100644 --- a/radicale/app/report.py +++ b/radicale/app/report.py @@ -22,15 +22,20 @@ import posixpath import socket import xml.etree.ElementTree as ET from http import client +from typing import Callable, Iterable, Iterator, Optional, Sequence, Tuple from urllib.parse import unquote, urlparse -from radicale import app, httputils, pathutils, storage, xmlutils +import radicale.item as radicale_item +from radicale import httputils, pathutils, storage, types, xmlutils +from radicale.app.base import Access, ApplicationBase from radicale.item import filter as radicale_filter from radicale.log import logger -def xml_report(base_prefix, path, xml_request, collection, encoding, - unlock_storage_fn): +def xml_report(base_prefix: str, path: str, xml_request: Optional[ET.Element], + collection: storage.BaseCollection, encoding: str, + unlock_storage_fn: Callable[[], None] + ) -> Tuple[int, ET.Element]: """Read and answer REPORT requests. Read rfc3253-3.6 for info. @@ -40,10 +45,9 @@ def xml_report(base_prefix, path, xml_request, collection, encoding, if xml_request is None: return client.MULTI_STATUS, multistatus root = xml_request - if root.tag in ( - xmlutils.make_clark("D:principal-search-property-set"), - xmlutils.make_clark("D:principal-property-search"), - xmlutils.make_clark("D:expand-property")): + if root.tag in (xmlutils.make_clark("D:principal-search-property-set"), + xmlutils.make_clark("D:principal-property-search"), + xmlutils.make_clark("D:expand-property")): # We don't support searching for principals or indirect retrieving of # properties, just return an empty result. # InfCloud asks for expand-property reports (even if we don't announce @@ -52,28 +56,28 @@ def xml_report(base_prefix, path, xml_request, collection, encoding, xmlutils.make_human_tag(root.tag), path) return client.MULTI_STATUS, multistatus if (root.tag == xmlutils.make_clark("C:calendar-multiget") and - collection.get_meta("tag") != "VCALENDAR" or + collection.tag != "VCALENDAR" or root.tag == xmlutils.make_clark("CR:addressbook-multiget") and - collection.get_meta("tag") != "VADDRESSBOOK" or + collection.tag != "VADDRESSBOOK" or root.tag == xmlutils.make_clark("D:sync-collection") and - collection.get_meta("tag") not in ("VADDRESSBOOK", "VCALENDAR")): + collection.tag not in ("VADDRESSBOOK", "VCALENDAR")): logger.warning("Invalid REPORT method %r on %r requested", xmlutils.make_human_tag(root.tag), path) - return (client.FORBIDDEN, - xmlutils.webdav_error("D:supported-report")) + return client.FORBIDDEN, xmlutils.webdav_error("D:supported-report") prop_element = root.find(xmlutils.make_clark("D:prop")) - props = ( - [prop.tag for prop in prop_element] - if prop_element is not None else []) + props = ([prop.tag for prop in prop_element] + if prop_element is not None else []) + hreferences: Iterable[str] if root.tag in ( xmlutils.make_clark("C:calendar-multiget"), xmlutils.make_clark("CR:addressbook-multiget")): # Read rfc4791-7.9 for info hreferences = set() for href_element in root.findall(xmlutils.make_clark("D:href")): - href_path = pathutils.sanitize_path( - unquote(urlparse(href_element.text).path)) + temp_url_path = urlparse(href_element.text).path + assert isinstance(temp_url_path, str) + href_path = pathutils.sanitize_path(unquote(temp_url_path)) if (href_path + "/").startswith(base_prefix + "/"): hreferences.add(href_path[len(base_prefix):]) else: @@ -107,82 +111,13 @@ def xml_report(base_prefix, path, xml_request, collection, encoding, root.findall(xmlutils.make_clark("C:filter")) + root.findall(xmlutils.make_clark("CR:filter"))) - def retrieve_items(collection, hreferences, multistatus): - """Retrieves all items that are referenced in ``hreferences`` from - ``collection`` and adds 404 responses for missing and invalid items - to ``multistatus``.""" - collection_requested = False - - def get_names(): - """Extracts all names from references in ``hreferences`` and adds - 404 responses for invalid references to ``multistatus``. - If the whole collections is referenced ``collection_requested`` - gets set to ``True``.""" - nonlocal collection_requested - for hreference in hreferences: - try: - name = pathutils.name_from_path(hreference, collection) - except ValueError as e: - logger.warning("Skipping invalid path %r in REPORT request" - " on %r: %s", hreference, path, e) - response = xml_item_response(base_prefix, hreference, - found_item=False) - multistatus.append(response) - continue - if name: - # Reference is an item - yield name - else: - # Reference is a collection - collection_requested = True - - for name, item in collection.get_multi(get_names()): - if not item: - uri = pathutils.unstrip_path( - posixpath.join(collection.path, name)) - response = xml_item_response(base_prefix, uri, - found_item=False) - multistatus.append(response) - else: - yield item, False - if collection_requested: - yield from collection.get_filtered(filters) - # Retrieve everything required for finishing the request. - retrieved_items = list(retrieve_items(collection, hreferences, - multistatus)) - collection_tag = collection.get_meta("tag") - # Don't access storage after this! + retrieved_items = list(retrieve_items( + base_prefix, path, collection, hreferences, filters, multistatus)) + collection_tag = collection.tag + # !!! Don't access storage after this !!! unlock_storage_fn() - def match(item, filter_): - tag = collection_tag - if (tag == "VCALENDAR" and - filter_.tag != xmlutils.make_clark("C:%s" % filter_)): - if len(filter_) == 0: - return True - if len(filter_) > 1: - raise ValueError("Filter with %d children" % len(filter_)) - if filter_[0].tag != xmlutils.make_clark("C:comp-filter"): - raise ValueError("Unexpected %r in filter" % filter_[0].tag) - return radicale_filter.comp_match(item, filter_[0]) - if (tag == "VADDRESSBOOK" and - filter_.tag != xmlutils.make_clark("CR:%s" % filter_)): - for child in filter_: - if child.tag != xmlutils.make_clark("CR:prop-filter"): - raise ValueError("Unexpected %r in filter" % child.tag) - test = filter_.get("test", "anyof") - if test == "anyof": - return any( - radicale_filter.prop_match(item.vobject_item, f, "CR") - for f in filter_) - if test == "allof": - return all( - radicale_filter.prop_match(item.vobject_item, f, "CR") - for f in filter_) - raise ValueError("Unsupported filter test: %r" % test) - raise ValueError("Unsupported filter %r for %r" % (filter_.tag, tag)) - while retrieved_items: # ``item.vobject_item`` might be accessed during filtering. # Don't keep reference to ``item``, because VObject requires a lot of @@ -190,7 +125,8 @@ def xml_report(base_prefix, path, xml_request, collection, encoding, item, filters_matched = retrieved_items.pop(0) if filters and not filters_matched: try: - if not all(match(item, filter_) for filter_ in filters): + if not all(test_filter(collection_tag, item, filter_) + for filter_ in filters): continue except ValueError as e: raise ValueError("Failed to filter item %r from %r: %s" % @@ -218,6 +154,7 @@ def xml_report(base_prefix, path, xml_request, collection, encoding, else: not_found_props.append(element) + assert item.href uri = pathutils.unstrip_path( posixpath.join(collection.path, item.href)) multistatus.append(xml_item_response( @@ -227,8 +164,10 @@ def xml_report(base_prefix, path, xml_request, collection, encoding, return client.MULTI_STATUS, multistatus -def xml_item_response(base_prefix, href, found_props=(), not_found_props=(), - found_item=True): +def xml_item_response(base_prefix: str, href: str, + found_props: Sequence[ET.Element] = (), + not_found_props: Sequence[ET.Element] = (), + found_item: bool = True) -> ET.Element: response = ET.Element(xmlutils.make_clark("D:response")) href_element = ET.Element(xmlutils.make_clark("D:href")) @@ -255,24 +194,98 @@ def xml_item_response(base_prefix, href, found_props=(), not_found_props=(), return response -class ApplicationReportMixin: - def do_REPORT(self, environ, base_prefix, path, user): +def retrieve_items( + base_prefix: str, path: str, collection: storage.BaseCollection, + hreferences: Iterable[str], filters: Sequence[ET.Element], + multistatus: ET.Element) -> Iterator[Tuple[radicale_item.Item, bool]]: + """Retrieves all items that are referenced in ``hreferences`` from + ``collection`` and adds 404 responses for missing and invalid items + to ``multistatus``.""" + collection_requested = False + + def get_names() -> Iterator[str]: + """Extracts all names from references in ``hreferences`` and adds + 404 responses for invalid references to ``multistatus``. + If the whole collections is referenced ``collection_requested`` + gets set to ``True``.""" + nonlocal collection_requested + for hreference in hreferences: + try: + name = pathutils.name_from_path(hreference, collection) + except ValueError as e: + logger.warning("Skipping invalid path %r in REPORT request on " + "%r: %s", hreference, path, e) + response = xml_item_response(base_prefix, hreference, + found_item=False) + multistatus.append(response) + continue + if name: + # Reference is an item + yield name + else: + # Reference is a collection + collection_requested = True + + for name, item in collection.get_multi(get_names()): + if not item: + uri = pathutils.unstrip_path(posixpath.join(collection.path, name)) + response = xml_item_response(base_prefix, uri, found_item=False) + multistatus.append(response) + else: + yield item, False + if collection_requested: + yield from collection.get_filtered(filters) + + +def test_filter(collection_tag: str, item: radicale_item.Item, + filter_: ET.Element) -> bool: + """Match an item against a filter.""" + if (collection_tag == "VCALENDAR" and + filter_.tag != xmlutils.make_clark("C:%s" % filter_)): + if len(filter_) == 0: + return True + if len(filter_) > 1: + raise ValueError("Filter with %d children" % len(filter_)) + if filter_[0].tag != xmlutils.make_clark("C:comp-filter"): + raise ValueError("Unexpected %r in filter" % filter_[0].tag) + return radicale_filter.comp_match(item, filter_[0]) + if (collection_tag == "VADDRESSBOOK" and + filter_.tag != xmlutils.make_clark("CR:%s" % filter_)): + for child in filter_: + if child.tag != xmlutils.make_clark("CR:prop-filter"): + raise ValueError("Unexpected %r in filter" % child.tag) + test = filter_.get("test", "anyof") + if test == "anyof": + return any(radicale_filter.prop_match(item.vobject_item, f, "CR") + for f in filter_) + if test == "allof": + return all(radicale_filter.prop_match(item.vobject_item, f, "CR") + for f in filter_) + raise ValueError("Unsupported filter test: %r" % test) + raise ValueError("Unsupported filter %r for %r" % + (filter_.tag, collection_tag)) + + +class ApplicationPartReport(ApplicationBase): + + def do_REPORT(self, environ: types.WSGIEnviron, base_prefix: str, + path: str, user: str) -> types.WSGIResponse: """Manage REPORT request.""" - access = app.Access(self._rights, user, path) + access = Access(self._rights, user, path) if not access.check("r"): return httputils.NOT_ALLOWED try: xml_content = self._read_xml_request_body(environ) except RuntimeError as e: - logger.warning( - "Bad REPORT request on %r: %s", path, e, exc_info=True) + logger.warning("Bad REPORT request on %r: %s", path, e, + exc_info=True) return httputils.BAD_REQUEST except socket.timeout: logger.debug("Client timed out", exc_info=True) return httputils.REQUEST_TIMEOUT with contextlib.ExitStack() as lock_stack: lock_stack.enter_context(self._storage.acquire_lock("r", user)) - item = next(self._storage.discover(path), None) + item = next(iter(self._storage.discover(path)), None) if not item: return httputils.NOT_FOUND if not access.check("r", item): @@ -280,8 +293,8 @@ class ApplicationReportMixin: if isinstance(item, storage.BaseCollection): collection = item else: + assert item.collection is not None collection = item.collection - headers = {"Content-Type": "text/xml; charset=%s" % self._encoding} try: status, xml_answer = xml_report( base_prefix, path, xml_content, collection, self._encoding, @@ -290,4 +303,5 @@ class ApplicationReportMixin: logger.warning( "Bad REPORT request on %r: %s", path, e, exc_info=True) return httputils.BAD_REQUEST - return status, headers, self._xml_response(xml_answer) + headers = {"Content-Type": "text/xml; charset=%s" % self._encoding} + return status, headers, self._xml_response(xml_answer) diff --git a/radicale/auth/__init__.py b/radicale/auth/__init__.py index fcd6c901..8de6c5f0 100644 --- a/radicale/auth/__init__.py +++ b/radicale/auth/__init__.py @@ -28,18 +28,23 @@ Take a look at the class ``BaseAuth`` if you want to implement your own. """ -from radicale import utils +from typing import Sequence, Tuple, Union -INTERNAL_TYPES = ("none", "remote_user", "http_x_remote_user", "htpasswd") +from radicale import config, types, utils + +INTERNAL_TYPES: Sequence[str] = ("none", "remote_user", "http_x_remote_user", + "htpasswd") -def load(configuration): +def load(configuration: "config.Configuration") -> "BaseAuth": """Load the authentication module chosen in configuration.""" - return utils.load_plugin(INTERNAL_TYPES, "auth", "Auth", configuration) + return utils.load_plugin(INTERNAL_TYPES, "auth", "Auth", BaseAuth, + configuration) class BaseAuth: - def __init__(self, configuration): + + def __init__(self, configuration: "config.Configuration") -> None: """Initialize BaseAuth. ``configuration`` see ``radicale.config`` module. @@ -49,7 +54,8 @@ class BaseAuth: """ self.configuration = configuration - def get_external_login(self, environ): + def get_external_login(self, environ: types.WSGIEnviron) -> Union[ + Tuple[()], Tuple[str, str]]: """Optionally provide the login and password externally. ``environ`` a dict with the WSGI environment @@ -61,7 +67,7 @@ class BaseAuth: """ return () - def login(self, login, password): + def login(self, login: str, password: str) -> str: """Check credentials and map login to internal user ``login`` the login name diff --git a/radicale/auth/htpasswd.py b/radicale/auth/htpasswd.py index 18a09e36..35e30f9f 100644 --- a/radicale/auth/htpasswd.py +++ b/radicale/auth/htpasswd.py @@ -49,18 +49,23 @@ When passlib[bcrypt] is installed: import functools import hmac +from typing import Any from passlib.hash import apr_md5_crypt -from radicale import auth +from radicale import auth, config class Auth(auth.BaseAuth): - def __init__(self, configuration): + + _filename: str + _encoding: str + + def __init__(self, configuration: config.Configuration) -> None: super().__init__(configuration) self._filename = configuration.get("auth", "htpasswd_filename") - self._encoding = self.configuration.get("encoding", "stock") - encryption = configuration.get("auth", "htpasswd_encryption") + self._encoding = configuration.get("encoding", "stock") + encryption: str = configuration.get("auth", "htpasswd_encryption") if encryption == "plain": self._verify = self._plain @@ -82,17 +87,17 @@ class Auth(auth.BaseAuth): raise RuntimeError("The htpasswd encryption method %r is not " "supported." % encryption) - def _plain(self, hash_value, password): + def _plain(self, hash_value: str, password: str) -> bool: """Check if ``hash_value`` and ``password`` match, plain method.""" return hmac.compare_digest(hash_value.encode(), password.encode()) - def _bcrypt(self, bcrypt, hash_value, password): + def _bcrypt(self, bcrypt: Any, hash_value: str, password: str) -> bool: return bcrypt.verify(password, hash_value.strip()) - def _md5apr1(self, hash_value, password): + def _md5apr1(self, hash_value: str, password: str) -> bool: return apr_md5_crypt.verify(password, hash_value.strip()) - def login(self, login, password): + def login(self, login: str, password: str) -> str: """Validate credentials. Iterate through htpasswd credential file until login matches, extract diff --git a/radicale/auth/http_x_remote_user.py b/radicale/auth/http_x_remote_user.py index aa353f22..8c0f236d 100644 --- a/radicale/auth/http_x_remote_user.py +++ b/radicale/auth/http_x_remote_user.py @@ -26,9 +26,14 @@ if the reverse proxy is not configured properly. """ -import radicale.auth.none as none +from typing import Tuple, Union + +from radicale import types +from radicale.auth import none class Auth(none.Auth): - def get_external_login(self, environ): + + def get_external_login(self, environ: types.WSGIEnviron) -> Union[ + Tuple[()], Tuple[str, str]]: return environ.get("HTTP_X_REMOTE_USER", ""), "" diff --git a/radicale/auth/none.py b/radicale/auth/none.py index b785e7ee..b75a33c1 100644 --- a/radicale/auth/none.py +++ b/radicale/auth/none.py @@ -26,5 +26,6 @@ from radicale import auth class Auth(auth.BaseAuth): - def login(self, login, password): + + def login(self, login: str, password: str) -> str: return login diff --git a/radicale/auth/remote_user.py b/radicale/auth/remote_user.py index 1c2d49a8..81175913 100644 --- a/radicale/auth/remote_user.py +++ b/radicale/auth/remote_user.py @@ -25,9 +25,14 @@ It's intended for use with an external WSGI server. """ -import radicale.auth.none as none +from typing import Tuple, Union + +from radicale import types +from radicale.auth import none class Auth(none.Auth): - def get_external_login(self, environ): + + def get_external_login(self, environ: types.WSGIEnviron + ) -> Union[Tuple[()], Tuple[str, str]]: return environ.get("REMOTE_USER", ""), "" diff --git a/radicale/config.py b/radicale/config.py index 880f2a52..c0947112 100644 --- a/radicale/config.py +++ b/radicale/config.py @@ -29,25 +29,27 @@ import contextlib import math import os import string +import sys from collections import OrderedDict from configparser import RawConfigParser -from typing import Any, ClassVar +from typing import (Any, Callable, ClassVar, Iterable, List, Optional, + Sequence, Tuple, TypeVar, Union) -from radicale import auth, rights, storage, web +from radicale import auth, rights, storage, types, web -DEFAULT_CONFIG_PATH = os.pathsep.join([ +DEFAULT_CONFIG_PATH: str = os.pathsep.join([ "?/etc/radicale/config", "?~/.config/radicale/config"]) -def positive_int(value): +def positive_int(value: Any) -> int: value = int(value) if value < 0: raise ValueError("value is negative: %d" % value) return value -def positive_float(value): +def positive_float(value: Any) -> float: value = float(value) if not math.isfinite(value): raise ValueError("value is infinite") @@ -58,22 +60,22 @@ def positive_float(value): return value -def logging_level(value): +def logging_level(value: Any) -> str: if value not in ("debug", "info", "warning", "error", "critical"): raise ValueError("unsupported level: %r" % value) return value -def filepath(value): +def filepath(value: Any) -> str: if not value: return "" value = os.path.expanduser(value) - if os.name == "nt": + if sys.platform == "win32": value = os.path.expandvars(value) return os.path.abspath(value) -def list_of_ip_address(value): +def list_of_ip_address(value: Any) -> List[Tuple[str, int]]: def ip_address(value): try: address, port = value.rsplit(":", 1) @@ -83,25 +85,25 @@ def list_of_ip_address(value): return [ip_address(s) for s in value.split(",")] -def str_or_callable(value): +def str_or_callable(value: Any) -> Union[str, Callable]: if callable(value): return value return str(value) -def unspecified_type(value): +def unspecified_type(value: Any) -> Any: return value -def _convert_to_bool(value): +def _convert_to_bool(value: Any) -> bool: if value.lower() not in RawConfigParser.BOOLEAN_STATES: raise ValueError("not a boolean: %r" % value) return RawConfigParser.BOOLEAN_STATES[value.lower()] -INTERNAL_OPTIONS = ("_allow_extra",) +INTERNAL_OPTIONS: Sequence[str] = ("_allow_extra",) # Default configuration -DEFAULT_CONFIG_SCHEMA = OrderedDict([ +DEFAULT_CONFIG_SCHEMA: types.CONFIG_SCHEMA = OrderedDict([ ("server", OrderedDict([ ("hosts", { "value": "localhost:5232", @@ -227,7 +229,8 @@ DEFAULT_CONFIG_SCHEMA = OrderedDict([ ("_allow_extra", str)]))]) -def parse_compound_paths(*compound_paths): +def parse_compound_paths(*compound_paths: Optional[str] + ) -> List[Tuple[str, bool]]: """Parse a compound path and return the individual paths. Paths in a compound path are joined by ``os.pathsep``. If a path starts with ``?`` the return value ``IGNORE_IF_MISSING`` is set. @@ -253,7 +256,8 @@ def parse_compound_paths(*compound_paths): return paths -def load(paths=()): +def load(paths: Optional[Iterable[Tuple[str, bool]]] = None + ) -> "Configuration": """ Create instance of ``Configuration`` for use with ``radicale.app.Application``. @@ -266,6 +270,8 @@ def load(paths=()): The configuration can later be changed with ``Configuration.update()``. """ + if paths is None: + paths = [] configuration = Configuration(DEFAULT_CONFIG_SCHEMA) for path, ignore_if_missing in paths: parser = RawConfigParser() @@ -279,16 +285,24 @@ def load(paths=()): config = {s: {o: parser[s][o] for o in parser.options(s)} for s in parser.sections()} except Exception as e: - raise RuntimeError( - "Failed to load %s: %s" % (config_source, e)) from e + raise RuntimeError("Failed to load %s: %s" % (config_source, e) + ) from e configuration.update(config, config_source) return configuration -class Configuration: - SOURCE_MISSING: ClassVar[Any] = {} +_Self = TypeVar("_Self", bound="Configuration") - def __init__(self, schema): + +class Configuration: + + SOURCE_MISSING: ClassVar[types.CONFIG] = {} + + _schema: types.CONFIG_SCHEMA + _values: types.MUTABLE_CONFIG + _configs: List[Tuple[types.CONFIG, str, bool]] + + def __init__(self, schema: types.CONFIG_SCHEMA) -> None: """Initialize configuration. ``schema`` a dict that describes the configuration format. @@ -309,7 +323,8 @@ class Configuration: for section in self._schema} self.update(default, "default config", privileged=True) - def update(self, config, source=None, privileged=False): + def update(self, config: types.CONFIG, source: Optional[str] = None, + privileged: bool = False) -> None: """Update the configuration. ``config`` a dict of the format {SECTION: {OPTION: VALUE, ...}, ...}. @@ -323,8 +338,9 @@ class Configuration: ``privileged`` allows updating sections and options starting with "_". """ - source = source or "unspecified config" - new_values = {} + if source is None: + source = "unspecified config" + new_values: types.MUTABLE_CONFIG = {} for section in config: if (section not in self._schema or section.startswith("_") and not privileged): @@ -363,40 +379,41 @@ class Configuration: self._values[section] = self._values.get(section, {}) self._values[section].update(new_values[section]) - def get(self, section, option): + def get(self, section: str, option: str) -> Any: """Get the value of ``option`` in ``section``.""" with contextlib.suppress(KeyError): return self._values[section][option] raise KeyError(section, option) - def get_raw(self, section, option): + def get_raw(self, section: str, option: str) -> Any: """Get the raw value of ``option`` in ``section``.""" for config, _, _ in reversed(self._configs): if option in config.get(section, {}): return config[section][option] raise KeyError(section, option) - def get_source(self, section, option): + def get_source(self, section: str, option: str) -> str: """Get the source that provides ``option`` in ``section``.""" for config, source, _ in reversed(self._configs): if option in config.get(section, {}): return source raise KeyError(section, option) - def sections(self): + def sections(self) -> List[str]: """List all sections.""" - return self._values.keys() + return list(self._values.keys()) - def options(self, section): + def options(self, section: str) -> List[str]: """List all options in ``section``""" - return self._values[section].keys() + return list(self._values[section].keys()) - def sources(self): + def sources(self) -> List[Tuple[str, bool]]: """List all config sources.""" return [(source, config is self.SOURCE_MISSING) for config, source, _ in self._configs] - def copy(self, plugin_schema=None): + def copy(self: _Self, plugin_schema: Optional[types.CONFIG_SCHEMA] = None + ) -> _Self: """Create a copy of the configuration ``plugin_schema`` is a optional dict that contains additional options @@ -406,20 +423,23 @@ class Configuration: if plugin_schema is None: schema = self._schema else: - schema = self._schema.copy() + new_schema = dict(self._schema) for section, options in plugin_schema.items(): - if (section not in schema or "type" not in schema[section] or - "internal" not in schema[section]["type"]): + if (section not in new_schema or + "type" not in new_schema[section] or + "internal" not in new_schema[section]["type"]): raise ValueError("not a plugin section: %r" % section) - schema[section] = schema[section].copy() - schema[section]["type"] = schema[section]["type"].copy() - schema[section]["type"]["internal"] = [ - self.get(section, "type")] + new_section = dict(new_schema[section]) + new_type = dict(new_section["type"]) + new_type["internal"] = (self.get(section, "type"),) + new_section["type"] = new_type for option, value in options.items(): - if option in schema[section]: - raise ValueError("option already exists in %r: %r" % ( - section, option)) - schema[section][option] = value + if option in new_section: + raise ValueError("option already exists in %r: %r" % + (section, option)) + new_section[option] = value + new_schema[section] = new_section + schema = new_schema copy = type(self)(schema) for config, source, privileged in self._configs: copy.update(config, source, privileged) diff --git a/radicale/httputils.py b/radicale/httputils.py index 6911e153..d8a31b61 100644 --- a/radicale/httputils.py +++ b/radicale/httputils.py @@ -22,53 +22,57 @@ Helper functions for HTTP. """ +import contextlib from http import client +from typing import List, cast +from radicale import config, types from radicale.log import logger -NOT_ALLOWED = ( +NOT_ALLOWED: types.WSGIResponse = ( client.FORBIDDEN, (("Content-Type", "text/plain"),), "Access to the requested resource forbidden.") -FORBIDDEN = ( +FORBIDDEN: types.WSGIResponse = ( client.FORBIDDEN, (("Content-Type", "text/plain"),), "Action on the requested resource refused.") -BAD_REQUEST = ( +BAD_REQUEST: types.WSGIResponse = ( client.BAD_REQUEST, (("Content-Type", "text/plain"),), "Bad Request") -NOT_FOUND = ( +NOT_FOUND: types.WSGIResponse = ( client.NOT_FOUND, (("Content-Type", "text/plain"),), "The requested resource could not be found.") -CONFLICT = ( +CONFLICT: types.WSGIResponse = ( client.CONFLICT, (("Content-Type", "text/plain"),), "Conflict in the request.") -METHOD_NOT_ALLOWED = ( +METHOD_NOT_ALLOWED: types.WSGIResponse = ( client.METHOD_NOT_ALLOWED, (("Content-Type", "text/plain"),), "The method is not allowed on the requested resource.") -PRECONDITION_FAILED = ( +PRECONDITION_FAILED: types.WSGIResponse = ( client.PRECONDITION_FAILED, (("Content-Type", "text/plain"),), "Precondition failed.") -REQUEST_TIMEOUT = ( +REQUEST_TIMEOUT: types.WSGIResponse = ( client.REQUEST_TIMEOUT, (("Content-Type", "text/plain"),), "Connection timed out.") -REQUEST_ENTITY_TOO_LARGE = ( +REQUEST_ENTITY_TOO_LARGE: types.WSGIResponse = ( client.REQUEST_ENTITY_TOO_LARGE, (("Content-Type", "text/plain"),), "Request body too large.") -REMOTE_DESTINATION = ( +REMOTE_DESTINATION: types.WSGIResponse = ( client.BAD_GATEWAY, (("Content-Type", "text/plain"),), "Remote destination not supported.") -DIRECTORY_LISTING = ( +DIRECTORY_LISTING: types.WSGIResponse = ( client.FORBIDDEN, (("Content-Type", "text/plain"),), "Directory listings are not supported.") -INTERNAL_SERVER_ERROR = ( +INTERNAL_SERVER_ERROR: types.WSGIResponse = ( client.INTERNAL_SERVER_ERROR, (("Content-Type", "text/plain"),), "A server error occurred. Please contact the administrator.") -DAV_HEADERS = "1, 2, 3, calendar-access, addressbook, extended-mkcol" +DAV_HEADERS: str = "1, 2, 3, calendar-access, addressbook, extended-mkcol" -def decode_request(configuration, environ, text): +def decode_request(configuration: "config.Configuration", + environ: types.WSGIEnviron, text: bytes) -> str: """Try to magically decode ``text`` according to given ``environ``.""" # List of charsets to try - charsets = [] + charsets: List[str] = [] # First append content charset given in the request content_type = environ.get("CONTENT_TYPE") @@ -76,7 +80,7 @@ def decode_request(configuration, environ, text): charsets.append( content_type.split("charset=")[1].split(";")[0].strip()) # Then append default Radicale charset - charsets.append(configuration.get("encoding", "request")) + charsets.append(cast(str, configuration.get("encoding", "request"))) # Then append various fallbacks charsets.append("utf-8") charsets.append("iso8859-1") @@ -87,15 +91,14 @@ def decode_request(configuration, environ, text): # Try to decode for charset in charsets: - try: + with contextlib.suppress(UnicodeDecodeError): return text.decode(charset) - except UnicodeDecodeError: - pass raise UnicodeDecodeError("decode_request", text, 0, len(text), "all codecs failed [%s]" % ", ".join(charsets)) -def read_raw_request_body(configuration, environ): +def read_raw_request_body(configuration: "config.Configuration", + environ: types.WSGIEnviron) -> bytes: content_length = int(environ.get("CONTENT_LENGTH") or 0) if not content_length: return b"" @@ -105,8 +108,9 @@ def read_raw_request_body(configuration, environ): return content -def read_request_body(configuration, environ): - content = decode_request( - configuration, environ, read_raw_request_body(configuration, environ)) +def read_request_body(configuration: "config.Configuration", + environ: types.WSGIEnviron) -> str: + content = decode_request(configuration, environ, + read_raw_request_body(configuration, environ)) logger.debug("Request content:\n%s", content) return content diff --git a/radicale/item/__init__.py b/radicale/item/__init__.py index ce6d7751..3c9c59d3 100644 --- a/radicale/item/__init__.py +++ b/radicale/item/__init__.py @@ -27,27 +27,35 @@ import binascii import math import os import sys -from datetime import timedelta +from datetime import datetime, timedelta from hashlib import sha256 +from typing import (Any, Callable, List, MutableMapping, Optional, Sequence, + Tuple) import vobject +from radicale import storage # noqa:F401 from radicale import pathutils from radicale.item import filter as radicale_filter from radicale.log import logger -def predict_tag_of_parent_collection(vobject_items): +def predict_tag_of_parent_collection( + vobject_items: Sequence[vobject.base.Component]) -> Optional[str]: + """Returns the predicted tag or `None`""" if len(vobject_items) != 1: - return "" + return None if vobject_items[0].name == "VCALENDAR": return "VCALENDAR" if vobject_items[0].name in ("VCARD", "VLIST"): return "VADDRESSBOOK" - return "" + return None -def predict_tag_of_whole_collection(vobject_items, fallback_tag=None): +def predict_tag_of_whole_collection( + vobject_items: Sequence[vobject.base.Component], + fallback_tag: Optional[str] = None) -> Optional[str]: + """Returns the predicted tag or `fallback_tag`""" if vobject_items and vobject_items[0].name == "VCALENDAR": return "VCALENDAR" if vobject_items and vobject_items[0].name in ("VCARD", "VLIST"): @@ -58,9 +66,13 @@ def predict_tag_of_whole_collection(vobject_items, fallback_tag=None): return fallback_tag -def check_and_sanitize_items(vobject_items, is_collection=False, tag=None): +def check_and_sanitize_items( + vobject_items: List[vobject.base.Component], + is_collection: bool = False, tag: str = "") -> None: """Check vobject items for common errors and add missing UIDs. + Modifies the list `vobject_items`. + ``is_collection`` indicates that vobject_item contains unrelated components. @@ -169,9 +181,14 @@ def check_and_sanitize_items(vobject_items, is_collection=False, tag=None): (i.name, repr(tag) if tag else "generic")) -def check_and_sanitize_props(props): - """Check collection properties for common errors.""" - for k, v in props.copy().items(): # Make copy to be able to delete items +def check_and_sanitize_props(props: MutableMapping[Any, Any] + ) -> MutableMapping[str, str]: + """Check collection properties for common errors. + + Modifies the dict `props`. + + """ + for k, v in list(props.items()): # Make copy to be able to delete items if not isinstance(k, str): raise ValueError("Key must be %r not %r: %r" % ( str.__name__, type(k).__name__, k)) @@ -182,14 +199,13 @@ def check_and_sanitize_props(props): raise ValueError("Value of %r must be %r not %r: %r" % ( k, str.__name__, type(v).__name__, v)) if k == "tag": - if not v: - del props[k] - continue - if v not in ("VCALENDAR", "VADDRESSBOOK"): + if v not in ("", "VCALENDAR", "VADDRESSBOOK"): raise ValueError("Unsupported collection tag: %r" % v) + return props -def find_available_uid(exists_fn, suffix=""): +def find_available_uid(exists_fn: Callable[[str], bool], suffix: str = "" + ) -> str: """Generate a pseudo-random UID""" # Prevent infinite loop for _ in range(1000): @@ -202,7 +218,7 @@ def find_available_uid(exists_fn, suffix=""): raise RuntimeError("No unique random sequence found") -def get_etag(text): +def get_etag(text: str) -> str: """Etag from collection or item. Encoded as quoted-string (see RFC 2616). @@ -213,13 +229,13 @@ def get_etag(text): return '"%s"' % etag.hexdigest() -def get_uid(vobject_component): +def get_uid(vobject_component: vobject.base.Component) -> str: """UID value of an item if defined.""" - return (vobject_component.uid.value - if hasattr(vobject_component, "uid") else None) + return (vobject_component.uid.value or "" + if hasattr(vobject_component, "uid") else "") -def get_uid_from_object(vobject_item): +def get_uid_from_object(vobject_item: vobject.base.Component) -> str: """UID value of an calendar/addressbook object.""" if vobject_item.name == "VCALENDAR": if hasattr(vobject_item, "vevent"): @@ -230,10 +246,10 @@ def get_uid_from_object(vobject_item): return get_uid(vobject_item.vtodo) elif vobject_item.name == "VCARD": return get_uid(vobject_item) - return None + return "" -def find_tag(vobject_item): +def find_tag(vobject_item: vobject.base.Component) -> str: """Find component name from ``vobject_item``.""" if vobject_item.name == "VCALENDAR": for component in vobject_item.components(): @@ -242,22 +258,24 @@ def find_tag(vobject_item): return "" -def find_tag_and_time_range(vobject_item): - """Find component name and enclosing time range from ``vobject item``. +def find_time_range(vobject_item: vobject.base.Component, tag: str + ) -> Tuple[int, int]: + """Find enclosing time range from ``vobject item``. - Returns a tuple (``tag``, ``start``, ``end``) where ``tag`` is a string - and ``start`` and ``end`` are POSIX timestamps (as int). + ``tag`` must be set to the return value of ``find_tag``. + + Returns a tuple (``start``, ``end``) where ``start`` and ``end`` are + POSIX timestamps. This is intened to be used for matching against simplified prefilters. """ - tag = find_tag(vobject_item) if not tag: - return ( - tag, radicale_filter.TIMESTAMP_MIN, radicale_filter.TIMESTAMP_MAX) + return radicale_filter.TIMESTAMP_MIN, radicale_filter.TIMESTAMP_MAX start = end = None - def range_fn(range_start, range_end, is_recurrence): + def range_fn(range_start: datetime, range_end: datetime, + is_recurrence: bool) -> bool: nonlocal start, end if start is None or range_start < start: start = range_start @@ -265,7 +283,7 @@ def find_tag_and_time_range(vobject_item): end = range_end return False - def infinity_fn(range_start): + def infinity_fn(range_start: datetime) -> bool: nonlocal start, end if start is None or range_start < start: start = range_start @@ -278,7 +296,7 @@ def find_tag_and_time_range(vobject_item): if end is None: end = radicale_filter.DATETIME_MAX try: - return tag, math.floor(start.timestamp()), math.ceil(end.timestamp()) + return math.floor(start.timestamp()), math.ceil(end.timestamp()) except ValueError as e: if str(e) == ("offset must be a timedelta representing a whole " "number of minutes") and sys.version_info < (3, 6): @@ -289,10 +307,31 @@ def find_tag_and_time_range(vobject_item): class Item: """Class for address book and calendar entries.""" - def __init__(self, collection_path=None, collection=None, - vobject_item=None, href=None, last_modified=None, text=None, - etag=None, uid=None, name=None, component_name=None, - time_range=None): + collection: Optional["storage.BaseCollection"] + href: Optional[str] + last_modified: Optional[str] + + _collection_path: str + _text: Optional[str] + _vobject_item: Optional[vobject.base.Component] + _etag: Optional[str] + _uid: Optional[str] + _name: Optional[str] + _component_name: Optional[str] + _time_range: Optional[Tuple[int, int]] + + def __init__(self, + collection_path: Optional[str] = None, + collection: Optional["storage.BaseCollection"] = None, + vobject_item: Optional[vobject.base.Component] = None, + href: Optional[str] = None, + last_modified: Optional[str] = None, + text: Optional[str] = None, + etag: Optional[str] = None, + uid: Optional[str] = None, + name: Optional[str] = None, + component_name: Optional[str] = None, + time_range: Optional[Tuple[int, int]] = None): """Initialize an item. ``collection_path`` the path of the parent collection (optional if @@ -318,8 +357,7 @@ class Item: ``component_name`` the name of the primary component (optional). See ``find_tag``. - ``time_range`` the enclosing time range. - See ``find_tag_and_time_range``. + ``time_range`` the enclosing time range. See ``find_time_range``. """ if text is None and vobject_item is None: @@ -344,7 +382,7 @@ class Item: self._component_name = component_name self._time_range = time_range - def serialize(self): + def serialize(self) -> str: if self._text is None: try: self._text = self.vobject_item.serialize() @@ -366,38 +404,38 @@ class Item: return self._vobject_item @property - def etag(self): + def etag(self) -> str: """Encoded as quoted-string (see RFC 2616).""" if self._etag is None: self._etag = get_etag(self.serialize()) return self._etag @property - def uid(self): + def uid(self) -> str: if self._uid is None: self._uid = get_uid_from_object(self.vobject_item) return self._uid @property - def name(self): + def name(self) -> str: if self._name is None: self._name = self.vobject_item.name or "" return self._name @property - def component_name(self): - if self._component_name is not None: - return self._component_name - return find_tag(self.vobject_item) + def component_name(self) -> str: + if self._component_name is None: + self._component_name = find_tag(self.vobject_item) + return self._component_name @property - def time_range(self): + def time_range(self) -> Tuple[int, int]: if self._time_range is None: - self._component_name, *self._time_range = ( - find_tag_and_time_range(self.vobject_item)) + self._time_range = find_time_range( + self.vobject_item, self.component_name) return self._time_range - def prepare(self): + def prepare(self) -> None: """Fill cache with values.""" orig_vobject_item = self._vobject_item self.serialize() diff --git a/radicale/item/filter.py b/radicale/item/filter.py index 17919cf5..973f4ddb 100644 --- a/radicale/item/filter.py +++ b/radicale/item/filter.py @@ -19,35 +19,40 @@ import math +import xml.etree.ElementTree as ET from datetime import date, datetime, timedelta, timezone from itertools import chain +from typing import (Callable, Iterable, Iterator, List, Optional, Sequence, + Tuple) -from radicale import xmlutils +import vobject + +from radicale import item, xmlutils from radicale.log import logger -DAY = timedelta(days=1) -SECOND = timedelta(seconds=1) -DATETIME_MIN = datetime.min.replace(tzinfo=timezone.utc) -DATETIME_MAX = datetime.max.replace(tzinfo=timezone.utc) -TIMESTAMP_MIN = math.floor(DATETIME_MIN.timestamp()) -TIMESTAMP_MAX = math.ceil(DATETIME_MAX.timestamp()) +DAY: timedelta = timedelta(days=1) +SECOND: timedelta = timedelta(seconds=1) +DATETIME_MIN: datetime = datetime.min.replace(tzinfo=timezone.utc) +DATETIME_MAX: datetime = datetime.max.replace(tzinfo=timezone.utc) +TIMESTAMP_MIN: int = math.floor(DATETIME_MIN.timestamp()) +TIMESTAMP_MAX: int = math.ceil(DATETIME_MAX.timestamp()) -def date_to_datetime(date_): - """Transform a date to a UTC datetime. +def date_to_datetime(d: date) -> datetime: + """Transform any date to a UTC datetime. - If date_ is a datetime without timezone, return as UTC datetime. If date_ + If ``d`` is a datetime without timezone, return as UTC datetime. If ``d`` is already a datetime with timezone, return as is. """ - if not isinstance(date_, datetime): - date_ = datetime.combine(date_, datetime.min.time()) - if not date_.tzinfo: - date_ = date_.replace(tzinfo=timezone.utc) - return date_ + if not isinstance(d, datetime): + d = datetime.combine(d, datetime.min.time()) + if not d.tzinfo: + d = d.replace(tzinfo=timezone.utc) + return d -def comp_match(item, filter_, level=0): +def comp_match(item: "item.Item", filter_: ET.Element, level: int = 0) -> bool: """Check whether the ``item`` matches the comp ``filter_``. If ``level`` is ``0``, the filter is applied on the @@ -70,7 +75,7 @@ def comp_match(item, filter_, level=0): return True if not tag: return False - name = filter_.get("name").upper() + name = filter_.get("name", "").upper() if len(filter_) == 0: # Point #1 of rfc4791-9.7.1 return name == tag @@ -104,13 +109,14 @@ def comp_match(item, filter_, level=0): return True -def prop_match(vobject_item, filter_, ns): +def prop_match(vobject_item: vobject.base.Component, + filter_: ET.Element, ns: str) -> bool: """Check whether the ``item`` matches the prop ``filter_``. See rfc4791-9.7.2 and rfc6352-10.5.1. """ - name = filter_.get("name").lower() + name = filter_.get("name", "").lower() if len(filter_) == 0: # Point #1 of rfc4791-9.7.2 return name in vobject_item.contents @@ -136,20 +142,21 @@ def prop_match(vobject_item, filter_, ns): return True -def time_range_match(vobject_item, filter_, child_name): +def time_range_match(vobject_item: vobject.base.Component, + filter_: ET.Element, child_name: str) -> bool: """Check whether the component/property ``child_name`` of ``vobject_item`` matches the time-range ``filter_``.""" - start = filter_.get("start") - end = filter_.get("end") - if not start and not end: + start_text = filter_.get("start") + end_text = filter_.get("end") + if not start_text and not end_text: return False - if start: - start = datetime.strptime(start, "%Y%m%dT%H%M%SZ") + if start_text: + start = datetime.strptime(start_text, "%Y%m%dT%H%M%SZ") else: start = datetime.min - if end: - end = datetime.strptime(end, "%Y%m%dT%H%M%SZ") + if end_text: + end = datetime.strptime(end_text, "%Y%m%dT%H%M%SZ") else: end = datetime.max start = start.replace(tzinfo=timezone.utc) @@ -157,7 +164,8 @@ def time_range_match(vobject_item, filter_, child_name): matched = False - def range_fn(range_start, range_end, is_recurrence): + def range_fn(range_start: datetime, range_end: datetime, + is_recurrence: bool) -> bool: nonlocal matched if start < range_end and range_start < end: matched = True @@ -166,14 +174,16 @@ def time_range_match(vobject_item, filter_, child_name): return True return False - def infinity_fn(start): + def infinity_fn(start: datetime) -> bool: return False visit_time_ranges(vobject_item, child_name, range_fn, infinity_fn) return matched -def visit_time_ranges(vobject_item, child_name, range_fn, infinity_fn): +def visit_time_ranges(vobject_item: vobject.base.Component, child_name: str, + range_fn: Callable[[datetime, datetime, bool], bool], + infinity_fn: Callable[[datetime], bool]) -> None: """Visit all time ranges in the component/property ``child_name`` of `vobject_item`` with visitors ``range_fn`` and ``infinity_fn``. @@ -194,7 +204,8 @@ def visit_time_ranges(vobject_item, child_name, range_fn, infinity_fn): # recurrences too. This is not respected and client don't seem to bother # either. - def getrruleset(child, ignore=()): + def getrruleset(child: vobject.base.Component, ignore: Sequence[date] + ) -> Tuple[Iterable[date], bool]: if (hasattr(child, "rrule") and ";UNTIL=" not in child.rrule.value.upper() and ";COUNT=" not in child.rrule.value.upper()): @@ -207,7 +218,8 @@ def visit_time_ranges(vobject_item, child_name, range_fn, infinity_fn): return filter(lambda dtstart: dtstart not in ignore, child.getrruleset(addRDate=True)), False - def get_children(components): + def get_children(components: Iterable[vobject.base.Component]) -> Iterator[ + Tuple[vobject.base.Component, bool, List[date]]]: main = None recurrences = [] for comp in components: @@ -216,7 +228,7 @@ def visit_time_ranges(vobject_item, child_name, range_fn, infinity_fn): if comp.rruleset: # Prevent possible infinite loop raise ValueError("Overwritten recurrence with RRULESET") - yield comp, True, () + yield comp, True, [] else: if main is not None: raise ValueError("Multiple main components") @@ -418,7 +430,9 @@ def visit_time_ranges(vobject_item, child_name, range_fn, infinity_fn): range_fn(child, child + DAY, False) -def text_match(vobject_item, filter_, child_name, ns, attrib_name=None): +def text_match(vobject_item: vobject.base.Component, + filter_: ET.Element, child_name: str, ns: str, + attrib_name: Optional[str] = None) -> bool: """Check whether the ``item`` matches the text-match ``filter_``. See rfc4791-9.7.5. @@ -432,7 +446,7 @@ def text_match(vobject_item, filter_, child_name, ns, attrib_name=None): if ns == "CR": match_type = filter_.get("match-type", match_type) - def match(value): + def match(value: str) -> bool: value = value.lower() if match_type == "equals": return value == text @@ -445,7 +459,7 @@ def text_match(vobject_item, filter_, child_name, ns, attrib_name=None): raise ValueError("Unexpected text-match match-type: %r" % match_type) children = getattr(vobject_item, "%s_list" % child_name, []) - if attrib_name: + if attrib_name is not None: condition = any( match(attrib) for child in children for attrib in child.params.get(attrib_name, [])) @@ -456,13 +470,14 @@ def text_match(vobject_item, filter_, child_name, ns, attrib_name=None): return condition -def param_filter_match(vobject_item, filter_, parent_name, ns): +def param_filter_match(vobject_item: vobject.base.Component, + filter_: ET.Element, parent_name: str, ns: str) -> bool: """Check whether the ``item`` matches the param-filter ``filter_``. See rfc4791-9.7.3. """ - name = filter_.get("name").upper() + name = filter_.get("name", "").upper() children = getattr(vobject_item, "%s_list" % parent_name, []) condition = any(name in child.params for child in children) if len(filter_) > 0: @@ -474,7 +489,8 @@ def param_filter_match(vobject_item, filter_, parent_name, ns): return condition -def simplify_prefilters(filters, collection_tag="VCALENDAR"): +def simplify_prefilters(filters: Iterable[ET.Element], collection_tag: str + ) -> Tuple[Optional[str], int, int, bool]: """Creates a simplified condition from ``filters``. Returns a tuple (``tag``, ``start``, ``end``, ``simple``) where ``tag`` is @@ -483,14 +499,14 @@ def simplify_prefilters(filters, collection_tag="VCALENDAR"): and the simplified condition are identical. """ - flat_filters = tuple(chain.from_iterable(filters)) + flat_filters = list(chain.from_iterable(filters)) simple = len(flat_filters) <= 1 for col_filter in flat_filters: if collection_tag != "VCALENDAR": simple = False break if (col_filter.tag != xmlutils.make_clark("C:comp-filter") or - col_filter.get("name").upper() != "VCALENDAR"): + col_filter.get("name", "").upper() != "VCALENDAR"): simple = False continue simple &= len(col_filter) <= 1 @@ -498,7 +514,7 @@ def simplify_prefilters(filters, collection_tag="VCALENDAR"): if comp_filter.tag != xmlutils.make_clark("C:comp-filter"): simple = False continue - tag = comp_filter.get("name").upper() + tag = comp_filter.get("name", "").upper() if comp_filter.find( xmlutils.make_clark("C:is-not-defined")) is not None: simple = False @@ -511,17 +527,17 @@ def simplify_prefilters(filters, collection_tag="VCALENDAR"): if time_filter.tag != xmlutils.make_clark("C:time-range"): simple = False continue - start = time_filter.get("start") - end = time_filter.get("end") - if start: + start_text = time_filter.get("start") + end_text = time_filter.get("end") + if start_text: start = math.floor(datetime.strptime( - start, "%Y%m%dT%H%M%SZ").replace( + start_text, "%Y%m%dT%H%M%SZ").replace( tzinfo=timezone.utc).timestamp()) else: start = TIMESTAMP_MIN - if end: + if end_text: end = math.ceil(datetime.strptime( - end, "%Y%m%dT%H%M%SZ").replace( + end_text, "%Y%m%dT%H%M%SZ").replace( tzinfo=timezone.utc).timestamp()) else: end = TIMESTAMP_MAX diff --git a/radicale/log.py b/radicale/log.py index a31fe174..708a36f5 100644 --- a/radicale/log.py +++ b/radicale/log.py @@ -25,42 +25,46 @@ Log messages are sent to the first available target of: """ -import contextlib import logging import os import sys import threading +from typing import Any, Callable, ClassVar, Dict, Iterator, Union -LOGGER_NAME = "radicale" -LOGGER_FORMAT = "[%(asctime)s] [%(ident)s] [%(levelname)s] %(message)s" -DATE_FORMAT = "%Y-%m-%d %H:%M:%S %z" +from radicale import types -logger = logging.getLogger(LOGGER_NAME) +LOGGER_NAME: str = "radicale" +LOGGER_FORMAT: str = "[%(asctime)s] [%(ident)s] [%(levelname)s] %(message)s" +DATE_FORMAT: str = "%Y-%m-%d %H:%M:%S %z" + +logger: logging.Logger = logging.getLogger(LOGGER_NAME) class RemoveTracebackFilter(logging.Filter): - def filter(self, record): + + def filter(self, record: logging.LogRecord) -> bool: record.exc_info = None return True -REMOVE_TRACEBACK_FILTER = RemoveTracebackFilter() +REMOVE_TRACEBACK_FILTER: logging.Filter = RemoveTracebackFilter() class IdentLogRecordFactory: """LogRecordFactory that adds ``ident`` attribute.""" - def __init__(self, upstream_factory): - self.upstream_factory = upstream_factory + def __init__(self, upstream_factory: Callable[..., logging.LogRecord] + ) -> None: + self._upstream_factory = upstream_factory - def __call__(self, *args, **kwargs): - record = self.upstream_factory(*args, **kwargs) + def __call__(self, *args: Any, **kwargs: Any) -> logging.LogRecord: + record = self._upstream_factory(*args, **kwargs) ident = "%d" % os.getpid() main_thread = threading.main_thread() current_thread = threading.current_thread() if current_thread.name and main_thread != current_thread: ident += "/%s" % current_thread.name - record.ident = ident + record.ident = ident # type:ignore[attr-defined] return record @@ -68,13 +72,15 @@ class ThreadedStreamHandler(logging.Handler): """Sends logging output to the stream registered for the current thread or ``sys.stderr`` when no stream was registered.""" - terminator = "\n" + terminator: ClassVar[str] = "\n" - def __init__(self): + _streams: Dict[int, types.ErrorStream] + + def __init__(self) -> None: super().__init__() self._streams = {} - def emit(self, record): + def emit(self, record: logging.LogRecord) -> None: try: stream = self._streams.get(threading.get_ident(), sys.stderr) msg = self.format(record) @@ -85,8 +91,8 @@ class ThreadedStreamHandler(logging.Handler): except Exception: self.handleError(record) - @contextlib.contextmanager - def register_stream(self, stream): + @types.contextmanager + def register_stream(self, stream: types.ErrorStream) -> Iterator[None]: """Register stream for logging output of the current thread.""" key = threading.get_ident() self._streams[key] = stream @@ -96,13 +102,13 @@ class ThreadedStreamHandler(logging.Handler): del self._streams[key] -@contextlib.contextmanager -def register_stream(stream): +@types.contextmanager +def register_stream(stream: types.ErrorStream) -> Iterator[None]: """Register stream for logging output of the current thread.""" yield -def setup(): +def setup() -> None: """Set global logging up.""" global register_stream handler = ThreadedStreamHandler() @@ -114,12 +120,12 @@ def setup(): set_level(logging.WARNING) -def set_level(level): +def set_level(level: Union[int, str]) -> None: """Set logging level for global logger.""" if isinstance(level, str): level = getattr(logging, level.upper()) + assert isinstance(level, int) logger.setLevel(level) - if level == logging.DEBUG: - logger.removeFilter(REMOVE_TRACEBACK_FILTER) - else: + logger.removeFilter(REMOVE_TRACEBACK_FILTER) + if level > logging.DEBUG: logger.addFilter(REMOVE_TRACEBACK_FILTER) diff --git a/radicale/pathutils.py b/radicale/pathutils.py index 7a2e675a..fdbff5d3 100644 --- a/radicale/pathutils.py +++ b/radicale/pathutils.py @@ -21,20 +21,21 @@ Helper functions for working with the file system. """ -import contextlib import os import posixpath import sys import threading from tempfile import TemporaryDirectory -from typing import Type, Union +from typing import Iterator, Type, Union -if os.name == "nt": +from radicale import storage, types + +if sys.platform == "win32": import ctypes import ctypes.wintypes import msvcrt - LOCKFILE_EXCLUSIVE_LOCK = 2 + LOCKFILE_EXCLUSIVE_LOCK: int = 2 ULONG_PTR: Union[Type[ctypes.c_uint32], Type[ctypes.c_uint64]] if ctypes.sizeof(ctypes.c_void_p) == 4: ULONG_PTR = ctypes.c_uint32 @@ -49,8 +50,7 @@ if os.name == "nt": ("offset_high", ctypes.wintypes.DWORD), ("h_event", ctypes.wintypes.HANDLE)] - kernel32 = ctypes.WinDLL( # type: ignore[attr-defined] - "kernel32", use_last_error=True) + kernel32 = ctypes.WinDLL("kernel32", use_last_error=True) lock_file_ex = kernel32.LockFileEx lock_file_ex.argtypes = [ ctypes.wintypes.HANDLE, @@ -71,13 +71,13 @@ if os.name == "nt": elif os.name == "posix": import fcntl -HAVE_RENAMEAT2 = False +HAVE_RENAMEAT2: bool = False if sys.platform == "linux": import ctypes - RENAME_EXCHANGE = 2 + RENAME_EXCHANGE: int = 2 try: - renameat2 = ctypes.CDLL(None, use_errno=True).renameat2 + renameat2 = ctypes.CDLL("", use_errno=True).renameat2 except AttributeError: pass else: @@ -92,14 +92,19 @@ if sys.platform == "linux": class RwLock: """A readers-Writer lock that locks a file.""" - def __init__(self, path): + _path: str + _readers: int + _writer: bool + _lock: threading.Lock + + def __init__(self, path: str) -> None: self._path = path self._readers = 0 self._writer = False self._lock = threading.Lock() @property - def locked(self): + def locked(self) -> str: with self._lock: if self._readers > 0: return "r" @@ -107,12 +112,12 @@ class RwLock: return "w" return "" - @contextlib.contextmanager - def acquire(self, mode): + @types.contextmanager + def acquire(self, mode: str) -> Iterator[None]: if mode not in "rw": raise ValueError("Invalid mode: %r" % mode) with open(self._path, "w+") as lock_file: - if os.name == "nt": + if sys.platform == "win32": handle = msvcrt.get_osfhandle(lock_file.fileno()) flags = LOCKFILE_EXCLUSIVE_LOCK if mode == "w" else 0 overlapped = Overlapped() @@ -120,15 +125,15 @@ class RwLock: if not lock_file_ex(handle, flags, 0, 1, 0, overlapped): raise ctypes.WinError() except OSError as e: - raise RuntimeError("Locking the storage failed: %s" % - e) from e + raise RuntimeError("Locking the storage failed: %s" % e + ) from e elif os.name == "posix": _cmd = fcntl.LOCK_EX if mode == "w" else fcntl.LOCK_SH try: fcntl.flock(lock_file.fileno(), _cmd) except OSError as e: - raise RuntimeError("Locking the storage failed: %s" % - e) from e + raise RuntimeError("Locking the storage failed: %s" % e + ) from e else: raise RuntimeError("Locking the storage failed: " "Unsupported operating system") @@ -149,7 +154,7 @@ class RwLock: self._writer = False -def rename_exchange(src, dst): +def rename_exchange(src: str, dst: str) -> None: """Exchange the files or directories `src` and `dst`. Both `src` and `dst` must exist but may be of different types. @@ -181,26 +186,26 @@ def rename_exchange(src, dst): finally: os.close(src_dir_fd) else: - with TemporaryDirectory( - prefix=".Radicale.tmp-", dir=src_dir) as tmp_dir: + with TemporaryDirectory(prefix=".Radicale.tmp-", dir=src_dir + ) as tmp_dir: os.rename(dst, os.path.join(tmp_dir, "interim")) os.rename(src, dst) os.rename(os.path.join(tmp_dir, "interim"), src) -def fsync(fd): +def fsync(fd: int) -> None: if os.name == "posix" and hasattr(fcntl, "F_FULLFSYNC"): fcntl.fcntl(fd, fcntl.F_FULLFSYNC) else: os.fsync(fd) -def strip_path(path): +def strip_path(path: str) -> str: assert sanitize_path(path) == path return path.strip("/") -def unstrip_path(stripped_path, trailing_slash=False): +def unstrip_path(stripped_path: str, trailing_slash: bool = False) -> str: assert strip_path(sanitize_path(stripped_path)) == stripped_path assert stripped_path or trailing_slash path = "/%s" % stripped_path @@ -209,7 +214,7 @@ def unstrip_path(stripped_path, trailing_slash=False): return path -def sanitize_path(path): +def sanitize_path(path: str) -> str: """Make path absolute with leading slash to prevent access to other data. Preserve potential trailing slash. @@ -226,16 +231,16 @@ def sanitize_path(path): return new_path + trailing_slash -def is_safe_path_component(path): +def is_safe_path_component(path: str) -> bool: """Check if path is a single component of a path. Check that the path is safe to join too. """ - return path and "/" not in path and path not in (".", "..") + return bool(path) and "/" not in path and path not in (".", "..") -def is_safe_filesystem_path_component(path): +def is_safe_filesystem_path_component(path: str) -> bool: """Check if path is a single component of a local and posix filesystem path. @@ -243,13 +248,13 @@ def is_safe_filesystem_path_component(path): """ return ( - path and not os.path.splitdrive(path)[0] and + bool(path) and not os.path.splitdrive(path)[0] and not os.path.split(path)[0] and path not in (os.curdir, os.pardir) and not path.startswith(".") and not path.endswith("~") and is_safe_path_component(path)) -def path_to_filesystem(root, sane_path): +def path_to_filesystem(root: str, sane_path: str) -> str: """Convert `sane_path` to a local filesystem path relative to `root`. `root` must be a secure filesystem path, it will be prepend to the path. @@ -271,25 +276,25 @@ def path_to_filesystem(root, sane_path): # Check for conflicting files (e.g. case-insensitive file systems # or short names on Windows file systems) if (os.path.lexists(safe_path) and - part not in (e.name for e in - os.scandir(safe_path_parent))): + part not in (e.name for e in os.scandir(safe_path_parent))): raise CollidingPathError(part) return safe_path class UnsafePathError(ValueError): - def __init__(self, path): - message = "Can't translate name safely to filesystem: %r" % path - super().__init__(message) + + def __init__(self, path: str) -> None: + super().__init__("Can't translate name safely to filesystem: %r" % + path) class CollidingPathError(ValueError): - def __init__(self, path): - message = "File name collision: %r" % path - super().__init__(message) + + def __init__(self, path: str) -> None: + super().__init__("File name collision: %r" % path) -def name_from_path(path, collection): +def name_from_path(path: str, collection: "storage.BaseCollection") -> str: """Return Radicale item name from ``path``.""" assert sanitize_path(path) == path start = unstrip_path(collection.path, True) diff --git a/radicale/rights/__init__.py b/radicale/rights/__init__.py index 1f0a534f..62a79cb0 100644 --- a/radicale/rights/__init__.py +++ b/radicale/rights/__init__.py @@ -32,17 +32,21 @@ Take a look at the class ``BaseRights`` if you want to implement your own. """ -from radicale import utils +from typing import Sequence -INTERNAL_TYPES = ("authenticated", "owner_write", "owner_only", "from_file") +from radicale import config, utils + +INTERNAL_TYPES: Sequence[str] = ("authenticated", "owner_write", "owner_only", + "from_file") -def load(configuration): +def load(configuration: "config.Configuration") -> "BaseRights": """Load the rights module chosen in configuration.""" - return utils.load_plugin(INTERNAL_TYPES, "rights", "Rights", configuration) + return utils.load_plugin(INTERNAL_TYPES, "rights", "Rights", BaseRights, + configuration) -def intersect(a, b): +def intersect(a: str, b: str) -> str: """Intersect two lists of rights. Returns all rights that are both in ``a`` and ``b``. @@ -52,7 +56,8 @@ def intersect(a, b): class BaseRights: - def __init__(self, configuration): + + def __init__(self, configuration: "config.Configuration") -> None: """Initialize BaseRights. ``configuration`` see ``radicale.config`` module. @@ -62,7 +67,7 @@ class BaseRights: """ self.configuration = configuration - def authorization(self, user, path): + def authorization(self, user: str, path: str) -> str: """Get granted rights of ``user`` for the collection ``path``. If ``user`` is empty, check for anonymous rights. diff --git a/radicale/rights/authenticated.py b/radicale/rights/authenticated.py index 1d171d37..fc669b4f 100644 --- a/radicale/rights/authenticated.py +++ b/radicale/rights/authenticated.py @@ -21,15 +21,16 @@ calendars and address books. """ -from radicale import pathutils, rights +from radicale import config, pathutils, rights class Rights(rights.BaseRights): - def __init__(self, *args, **kwargs): - super().__init__(*args, **kwargs) + + def __init__(self, configuration: config.Configuration) -> None: + super().__init__(configuration) self._verify_user = self.configuration.get("auth", "type") != "none" - def authorization(self, user, path): + def authorization(self, user: str, path: str) -> str: if self._verify_user and not user: return "" sane_path = pathutils.strip_path(path) diff --git a/radicale/rights/from_file.py b/radicale/rights/from_file.py index d6626fb2..5ec90cea 100644 --- a/radicale/rights/from_file.py +++ b/radicale/rights/from_file.py @@ -37,16 +37,19 @@ Leading or ending slashes are trimmed from collection's path. import configparser import re -from radicale import pathutils, rights +from radicale import config, pathutils, rights from radicale.log import logger class Rights(rights.BaseRights): - def __init__(self, configuration): + + _filename: str + + def __init__(self, configuration: config.Configuration) -> None: super().__init__(configuration) self._filename = configuration.get("rights", "file") - def authorization(self, user, path): + def authorization(self, user: str, path: str) -> str: user = user or "" sane_path = pathutils.strip_path(path) # Prevent "regex injection" @@ -54,8 +57,7 @@ class Rights(rights.BaseRights): rights_config = configparser.ConfigParser() try: if not rights_config.read(self._filename): - raise RuntimeError("No such file: %r" % - self._filename) + raise RuntimeError("No such file: %r" % self._filename) except Exception as e: raise RuntimeError("Failed to load rights file %r: %s" % (self._filename, e)) from e @@ -67,7 +69,7 @@ class Rights(rights.BaseRights): user_match = re.fullmatch(user_pattern.format(), user) collection_match = user_match and re.fullmatch( collection_pattern.format( - *map(re.escape, user_match.groups()), + *(re.escape(s) for s in user_match.groups()), user=escaped_user), sane_path) except Exception as e: raise RuntimeError("Error in section %r of rights file %r: " diff --git a/radicale/rights/owner_only.py b/radicale/rights/owner_only.py index 339e6fc5..bfcad8ee 100644 --- a/radicale/rights/owner_only.py +++ b/radicale/rights/owner_only.py @@ -26,7 +26,8 @@ from radicale import pathutils class Rights(authenticated.Rights): - def authorization(self, user, path): + + def authorization(self, user: str, path: str) -> str: if self._verify_user and not user: return "" sane_path = pathutils.strip_path(path) diff --git a/radicale/rights/owner_write.py b/radicale/rights/owner_write.py index e718e02a..be4c92db 100644 --- a/radicale/rights/owner_write.py +++ b/radicale/rights/owner_write.py @@ -26,7 +26,8 @@ from radicale import pathutils class Rights(authenticated.Rights): - def authorization(self, user, path): + + def authorization(self, user: str, path: str) -> str: if self._verify_user and not user: return "" sane_path = pathutils.strip_path(path) diff --git a/radicale/server.py b/radicale/server.py index ceeda835..7ec5b3c4 100644 --- a/radicale/server.py +++ b/radicale/server.py @@ -23,14 +23,15 @@ Built-in WSGI server. """ import errno -import os +import http import select import socket import socketserver import ssl import sys import wsgiref.simple_server -from typing import MutableMapping +from typing import (Any, Callable, Dict, List, MutableMapping, Optional, Set, + Tuple, Union) from urllib.parse import unquote from radicale import Application, config @@ -38,7 +39,7 @@ from radicale.log import logger COMPAT_EAI_ADDRFAMILY: int if hasattr(socket, "EAI_ADDRFAMILY"): - COMPAT_EAI_ADDRFAMILY = socket.EAI_ADDRFAMILY # type: ignore[attr-defined] + COMPAT_EAI_ADDRFAMILY = socket.EAI_ADDRFAMILY # type:ignore[attr-defined] elif hasattr(socket, "EAI_NONAME"): # Windows and BSD don't have a special error code for this COMPAT_EAI_ADDRFAMILY = socket.EAI_NONAME @@ -51,57 +52,99 @@ elif hasattr(socket, "EAI_NONAME"): COMPAT_IPPROTO_IPV6: int if hasattr(socket, "IPPROTO_IPV6"): COMPAT_IPPROTO_IPV6 = socket.IPPROTO_IPV6 -elif os.name == "nt": - # Workaround: https://bugs.python.org/issue29515 +elif sys.platform == "win32": + # HACK: https://bugs.python.org/issue29515 COMPAT_IPPROTO_IPV6 = 41 -def format_address(address): +# IPv4 (host, port) and IPv6 (host, port, flowinfo, scopeid) +ADDRESS_TYPE = Union[Tuple[str, int], Tuple[str, int, int, int]] + + +def format_address(address: ADDRESS_TYPE) -> str: return "[%s]:%d" % address[:2] class ParallelHTTPServer(socketserver.ThreadingMixIn, wsgiref.simple_server.WSGIServer): - # We wait for child threads ourself - block_on_close = False - daemon_threads = True + configuration: config.Configuration + worker_sockets: Set[socket.socket] + _timeout: float - def __init__(self, configuration, family, address, RequestHandlerClass): + # We wait for child threads ourself (ThreadingMixIn) + block_on_close: bool = False + daemon_threads: bool = True + + def __init__(self, configuration: config.Configuration, family: int, + address: Tuple[str, int], RequestHandlerClass: + Callable[..., http.server.BaseHTTPRequestHandler]) -> None: self.configuration = configuration self.address_family = family super().__init__(address, RequestHandlerClass) - self.client_sockets = set() + self.worker_sockets = set() + self._timeout = configuration.get("server", "timeout") - def server_bind(self): + def server_bind(self) -> None: if self.address_family == socket.AF_INET6: # Only allow IPv6 connections to the IPv6 socket self.socket.setsockopt(COMPAT_IPPROTO_IPV6, socket.IPV6_V6ONLY, 1) super().server_bind() - def get_request(self): + def get_request( # type:ignore[override] + self) -> Tuple[socket.socket, Tuple[ADDRESS_TYPE, socket.socket]]: # Set timeout for client - request, client_address = super().get_request() - timeout = self.configuration.get("server", "timeout") - if timeout: - request.settimeout(timeout) - client_socket, client_socket_out = socket.socketpair() - self.client_sockets.add(client_socket_out) - return request, (*client_address, client_socket) + request: socket.socket + client_address: ADDRESS_TYPE + request, client_address = super().get_request() # type:ignore[misc] + if self._timeout > 0: + request.settimeout(self._timeout) + worker_socket, worker_socket_out = socket.socketpair() + self.worker_sockets.add(worker_socket_out) + # HACK: Forward `worker_socket` via `client_address` return value + # to worker thread. + # The super class calls `verify_request`, `process_request` and + # `handle_error` with modified `client_address` value. + return request, (client_address, worker_socket) - def finish_request_locked(self, request, client_address): - return super().finish_request(request, client_address) + def verify_request( # type:ignore[override] + self, request: socket.socket, client_address_and_socket: + Tuple[ADDRESS_TYPE, socket.socket]) -> bool: + return True - def finish_request(self, request, client_address): - *client_address, client_socket = client_address - client_address = tuple(client_address) + def process_request( # type:ignore[override] + self, request: socket.socket, client_address_and_socket: + Tuple[ADDRESS_TYPE, socket.socket]) -> None: + # HACK: Super class calls `finish_request` in new thread with + # `client_address_and_socket` + return super().process_request( + request, client_address_and_socket) # type:ignore[arg-type] + + def finish_request( # type:ignore[override] + self, request: socket.socket, client_address_and_socket: + Tuple[ADDRESS_TYPE, socket.socket]) -> None: + # HACK: Unpack `client_address_and_socket` and call super class + # `finish_request` with original `client_address` + client_address, worker_socket = client_address_and_socket try: return self.finish_request_locked(request, client_address) finally: - client_socket.close() + worker_socket.close() - def handle_error(self, request, client_address): - if issubclass(sys.exc_info()[0], socket.timeout): + def finish_request_locked(self, request: socket.socket, + client_address: ADDRESS_TYPE) -> None: + return super().finish_request( + request, client_address) # type:ignore[arg-type] + + def handle_error( # type:ignore[override] + self, request: socket.socket, + client_address_or_client_address_and_socket: + Union[ADDRESS_TYPE, Tuple[ADDRESS_TYPE, socket.socket]]) -> None: + # HACK: This method can be called with the modified + # `client_address_and_socket` or the original `client_address` value + e = sys.exc_info()[1] + assert e is not None + if isinstance(e, socket.timeout): logger.info("Client timed out", exc_info=True) else: logger.error("An exception occurred during request: %s", @@ -110,12 +153,12 @@ class ParallelHTTPServer(socketserver.ThreadingMixIn, class ParallelHTTPSServer(ParallelHTTPServer): - def server_bind(self): + def server_bind(self) -> None: super().server_bind() # Wrap the TCP socket in an SSL socket - certfile = self.configuration.get("server", "certificate") - keyfile = self.configuration.get("server", "key") - cafile = self.configuration.get("server", "certificate_authority") + certfile: str = self.configuration.get("server", "certificate") + keyfile: str = self.configuration.get("server", "key") + cafile: str = self.configuration.get("server", "certificate_authority") # Test if the files can be read for name, filename in [("certificate", certfile), ("key", keyfile), ("certificate_authority", cafile)]: @@ -139,7 +182,9 @@ class ParallelHTTPSServer(ParallelHTTPServer): self.socket = context.wrap_socket( self.socket, server_side=True, do_handshake_on_connect=False) - def finish_request_locked(self, request, client_address): + def finish_request_locked( # type:ignore[override] + self, request: ssl.SSLSocket, client_address: ADDRESS_TYPE + ) -> None: try: try: request.do_handshake() @@ -151,7 +196,7 @@ class ParallelHTTPSServer(ParallelHTTPServer): try: self.handle_error(request, client_address) finally: - self.shutdown_request(request) + self.shutdown_request(request) # type:ignore[attr-defined] return return super().finish_request_locked(request, client_address) @@ -161,30 +206,34 @@ class ServerHandler(wsgiref.simple_server.ServerHandler): # Don't pollute WSGI environ with OS environment os_environ: MutableMapping[str, str] = {} - def log_exception(self, exc_info): + def log_exception(self, exc_info: "wsgiref.handlers._exc_info") -> None: logger.error("An exception occurred during request: %s", - exc_info[1], exc_info=exc_info) + exc_info[1], exc_info=exc_info) # type:ignore[arg-type] class RequestHandler(wsgiref.simple_server.WSGIRequestHandler): """HTTP requests handler.""" - def log_request(self, code="-", size="-"): + # HACK: Assigned in `socketserver.StreamRequestHandler` + connection: socket.socket + + def log_request(self, code: Union[int, str] = "-", + size: Union[int, str] = "-") -> None: pass # Disable request logging. - def log_error(self, format_, *args): + def log_error(self, format_: str, *args: Any) -> None: logger.error("An error occurred during request: %s", format_ % args) - def get_environ(self): + def get_environ(self) -> Dict[str, Any]: env = super().get_environ() - if hasattr(self.connection, "getpeercert"): + if isinstance(self.connection, ssl.SSLSocket): # The certificate can be evaluated by the auth module env["REMOTE_CERTIFICATE"] = self.connection.getpeercert() # Parent class only tries latin1 encoding env["PATH_INFO"] = unquote(self.path.split("?", 1)[0]) return env - def handle(self): + def handle(self) -> None: """Copy of WSGIRequestHandler.handle with different ServerHandler""" self.raw_requestline = self.rfile.readline(65537) @@ -201,11 +250,13 @@ class RequestHandler(wsgiref.simple_server.WSGIRequestHandler): handler = ServerHandler( self.rfile, self.wfile, self.get_stderr(), self.get_environ() ) - handler.request_handler = self - handler.run(self.server.get_app()) + handler.request_handler = self # type:ignore[attr-defined] + app = self.server.get_app() # type:ignore[attr-defined] + handler.run(app) -def serve(configuration, shutdown_socket=None): +def serve(configuration: config.Configuration, + shutdown_socket: Optional[socket.socket] = None) -> None: """Serve radicale from configuration. `shutdown_socket` can be used to gracefully shutdown the server. @@ -221,12 +272,13 @@ def serve(configuration, shutdown_socket=None): configuration.update({"server": {"_internal_server": "True"}}, "server", privileged=True) - use_ssl = configuration.get("server", "ssl") + use_ssl: bool = configuration.get("server", "ssl") server_class = ParallelHTTPSServer if use_ssl else ParallelHTTPServer application = Application(configuration) servers = {} try: - for address in configuration.get("server", "hosts"): + hosts: List[Tuple[str, int]] = configuration.get("server", "hosts") + for address in hosts: # Try to bind sockets for IPv4 and IPv6 possible_families = (socket.AF_INET, socket.AF_INET6) bind_ok = False @@ -270,16 +322,16 @@ def serve(configuration, shutdown_socket=None): # Mainloop select_timeout = None - if os.name == "nt": + if sys.platform == "win32": # Fallback to busy waiting. (select(...) blocks SIGINT on Windows.) select_timeout = 1.0 - max_connections = configuration.get("server", "max_connections") + max_connections: int = configuration.get("server", "max_connections") logger.info("Radicale server ready") while True: - rlist = [] + rlist: List[socket.socket] = [] # Wait for finished clients for server in servers.values(): - rlist.extend(server.client_sockets) + rlist.extend(server.worker_sockets) # Accept new connections if max_connections is not reached if max_connections <= 0 or len(rlist) < max_connections: rlist.extend(servers) @@ -287,26 +339,26 @@ def serve(configuration, shutdown_socket=None): if shutdown_socket is not None: rlist.append(shutdown_socket) rlist, _, _ = select.select(rlist, [], [], select_timeout) - rlist = set(rlist) - if shutdown_socket in rlist: + rset = set(rlist) + if shutdown_socket in rset: logger.info("Stopping Radicale") break for server in servers.values(): - finished_sockets = server.client_sockets.intersection(rlist) + finished_sockets = server.worker_sockets.intersection(rset) for s in finished_sockets: s.close() - server.client_sockets.remove(s) - rlist.remove(s) + server.worker_sockets.remove(s) + rset.remove(s) if finished_sockets: server.service_actions() - if rlist: - server = servers.get(rlist.pop()) - if server: - server.handle_request() + if rset: + active_server = servers.get(rset.pop()) + if active_server: + active_server.handle_request() finally: # Wait for clients to finish and close servers for server in servers.values(): - for s in server.client_sockets: + for s in server.worker_sockets: s.recv(1) s.close() server.server_close() diff --git a/radicale/storage/__init__.py b/radicale/storage/__init__.py index 7d2f1e72..0163c7ca 100644 --- a/radicale/storage/__init__.py +++ b/radicale/storage/__init__.py @@ -23,37 +23,44 @@ Take a look at the class ``BaseCollection`` if you want to implement your own. """ -import contextlib import json +import xml.etree.ElementTree as ET from hashlib import sha256 +from typing import (Iterable, Iterator, Mapping, Optional, Sequence, Set, + Tuple, Union, overload) import pkg_resources import vobject -from radicale import utils +from radicale import config +from radicale import item as radicale_item +from radicale import types, utils from radicale.item import filter as radicale_filter -INTERNAL_TYPES = ("multifilesystem",) +INTERNAL_TYPES: Sequence[str] = ("multifilesystem",) -CACHE_DEPS = ("radicale", "vobject", "python-dateutil",) -CACHE_VERSION = (";".join(pkg_resources.get_distribution(pkg).version - for pkg in CACHE_DEPS) + ";").encode() +CACHE_DEPS: Sequence[str] = ("radicale", "vobject", "python-dateutil",) +CACHE_VERSION: bytes = "".join( + "%s=%s;" % (pkg, pkg_resources.get_distribution(pkg).version) + for pkg in CACHE_DEPS).encode() -def load(configuration): +def load(configuration: "config.Configuration") -> "BaseStorage": """Load the storage module chosen in configuration.""" - return utils.load_plugin( - INTERNAL_TYPES, "storage", "Storage", configuration) + return utils.load_plugin(INTERNAL_TYPES, "storage", "Storage", BaseStorage, + configuration) class ComponentExistsError(ValueError): - def __init__(self, path): + + def __init__(self, path: str) -> None: message = "Component already exists: %r" % path super().__init__(message) class ComponentNotFoundError(ValueError): - def __init__(self, path): + + def __init__(self, path: str) -> None: message = "Component doesn't exist: %r" % path super().__init__(message) @@ -61,47 +68,58 @@ class ComponentNotFoundError(ValueError): class BaseCollection: @property - def path(self): + def path(self) -> str: """The sanitized path of the collection without leading or trailing ``/``.""" raise NotImplementedError @property - def owner(self): + def owner(self) -> str: """The owner of the collection.""" return self.path.split("/", maxsplit=1)[0] @property - def is_principal(self): + def is_principal(self) -> bool: """Collection is a principal.""" return bool(self.path) and "/" not in self.path @property - def etag(self): + def etag(self) -> str: """Encoded as quoted-string (see RFC 2616).""" etag = sha256() for item in self.get_all(): + assert item.href etag.update((item.href + "/" + item.etag).encode()) etag.update(json.dumps(self.get_meta(), sort_keys=True).encode()) return '"%s"' % etag.hexdigest() - def sync(self, old_token=None): + @property + def tag(self) -> str: + """The tag of the collection.""" + return self.get_meta("tag") or "" + + def sync(self, old_token: str = "") -> Tuple[str, Iterable[str]]: """Get the current sync token and changed items for synchronization. ``old_token`` an old sync token which is used as the base of the - delta update. If sync token is missing, all items are returned. + delta update. If sync token is empty, all items are returned. ValueError is raised for invalid or old tokens. WARNING: This simple default implementation treats all sync-token as invalid. """ + def hrefs_iter() -> Iterator[str]: + for item in self.get_all(): + assert item.href + yield item.href token = "http://radicale.org/ns/sync/%s" % self.etag.strip("\"") if old_token: raise ValueError("Sync token are not supported") - return token, (item.href for item in self.get_all()) + return token, hrefs_iter() - def get_multi(self, hrefs): + def get_multi(self, hrefs: Iterable[str] + ) -> Iterable[Tuple[str, Optional["radicale_item.Item"]]]: """Fetch multiple items. It's not required to return the requested items in the correct order. @@ -113,11 +131,12 @@ class BaseCollection: """ raise NotImplementedError - def get_all(self): + def get_all(self) -> Iterable["radicale_item.Item"]: """Fetch all items.""" raise NotImplementedError - def get_filtered(self, filters): + def get_filtered(self, filters: Iterable[ET.Element] + ) -> Iterable[Tuple["radicale_item.Item", bool]]: """Fetch all items with optional filtering. This can largely improve performance of reports depending on @@ -128,32 +147,31 @@ class BaseCollection: matched. """ + if not self.tag: + return tag, start, end, simple = radicale_filter.simplify_prefilters( - filters, collection_tag=self.get_meta("tag")) + filters, self.tag) for item in self.get_all(): - if tag: - if tag != item.component_name: - continue - istart, iend = item.time_range - if istart >= end or iend <= start: - continue - item_simple = simple and (start <= istart or iend <= end) - else: - item_simple = simple - yield item, item_simple + if tag is not None and tag != item.component_name: + continue + istart, iend = item.time_range + if istart >= end or iend <= start: + continue + yield item, simple and (start <= istart or iend <= end) - def has_uid(self, uid): + def has_uid(self, uid: str) -> bool: """Check if a UID exists in the collection.""" for item in self.get_all(): if item.uid == uid: return True return False - def upload(self, href, item): + def upload(self, href: str, item: "radicale_item.Item") -> ( + "radicale_item.Item"): """Upload a new or replace an existing item.""" raise NotImplementedError - def delete(self, href=None): + def delete(self, href: Optional[str] = None) -> None: """Delete an item. When ``href`` is ``None``, delete the collection. @@ -161,7 +179,14 @@ class BaseCollection: """ raise NotImplementedError - def get_meta(self, key=None): + @overload + def get_meta(self, key: None = None) -> Mapping[str, str]: ... + + @overload + def get_meta(self, key: str) -> Optional[str]: ... + + def get_meta(self, key: Optional[str] = None + ) -> Union[Mapping[str, str], Optional[str]]: """Get metadata value for collection. Return the value of the property ``key``. If ``key`` is ``None`` return @@ -170,7 +195,7 @@ class BaseCollection: """ raise NotImplementedError - def set_meta(self, props): + def set_meta(self, props: Mapping[str, str]) -> None: """Set metadata values for collection. ``props`` a dict with values for properties. @@ -179,16 +204,16 @@ class BaseCollection: raise NotImplementedError @property - def last_modified(self): + def last_modified(self) -> str: """Get the HTTP-datetime of when the collection was modified.""" raise NotImplementedError - def serialize(self): + def serialize(self) -> str: """Get the unicode string representing the whole collection.""" - if self.get_meta("tag") == "VCALENDAR": + if self.tag == "VCALENDAR": in_vcalendar = False vtimezones = "" - included_tzids = set() + included_tzids: Set[str] = set() vtimezone = [] tzid = None components = "" @@ -216,6 +241,7 @@ class BaseCollection: elif depth == 2 and line.startswith("END:"): if tzid is None or tzid not in included_tzids: vtimezones += "".join(vtimezone) + if tzid is not None: included_tzids.add(tzid) vtimezone.clear() tzid = None @@ -240,13 +266,14 @@ class BaseCollection: return (template[:template_insert_pos] + vtimezones + components + template[template_insert_pos:]) - if self.get_meta("tag") == "VADDRESSBOOK": + if self.tag == "VADDRESSBOOK": return "".join((item.serialize() for item in self.get_all())) return "" class BaseStorage: - def __init__(self, configuration): + + def __init__(self, configuration: "config.Configuration") -> None: """Initialize BaseStorage. ``configuration`` see ``radicale.config`` module. @@ -256,7 +283,8 @@ class BaseStorage: """ self.configuration = configuration - def discover(self, path, depth="0"): + def discover(self, path: str, depth: str = "0") -> Iterable[ + "types.CollectionOrItem"]: """Discover a list of collections under the given ``path``. ``path`` is sanitized. @@ -272,7 +300,8 @@ class BaseStorage: """ raise NotImplementedError - def move(self, item, to_collection, to_href): + def move(self, item: "radicale_item.Item", to_collection: BaseCollection, + to_href: str) -> None: """Move an object. ``item`` is the item to move. @@ -285,7 +314,10 @@ class BaseStorage: """ raise NotImplementedError - def create_collection(self, href, items=None, props=None): + def create_collection( + self, href: str, + items: Optional[Iterable["radicale_item.Item"]] = None, + props: Optional[Mapping[str, str]] = None) -> BaseCollection: """Create a collection. ``href`` is the sanitized path. @@ -298,15 +330,14 @@ class BaseStorage: ``props`` are metadata values for the collection. - ``props["tag"]`` is the type of collection (VCALENDAR or - VADDRESSBOOK). If the key ``tag`` is missing, it is guessed from the - collection. + ``props["tag"]`` is the type of collection (VCALENDAR or VADDRESSBOOK). + If the key ``tag`` is missing, ``items`` is ignored. """ raise NotImplementedError - @contextlib.contextmanager - def acquire_lock(self, mode, user=None): + @types.contextmanager + def acquire_lock(self, mode: str, user: str = "") -> Iterator[None]: """Set a context manager to lock the whole storage. ``mode`` must either be "r" for shared access or "w" for exclusive @@ -317,6 +348,6 @@ class BaseStorage: """ raise NotImplementedError - def verify(self): + def verify(self) -> bool: """Check the storage for errors.""" raise NotImplementedError diff --git a/radicale/storage/multifilesystem/cache.py b/radicale/storage/multifilesystem/cache.py index c143a713..74327b32 100644 --- a/radicale/storage/multifilesystem/cache.py +++ b/radicale/storage/multifilesystem/cache.py @@ -16,6 +16,7 @@ # You should have received a copy of the GNU General Public License # along with Radicale. If not, see . +import contextlib import os import pickle import time @@ -72,14 +73,10 @@ class CollectionCacheMixin: "item") content = self._item_cache_content(item, cache_hash) self._storage._makedirs_synced(cache_folder) - try: - # Race: Other processes might have created and locked the - # file. - with self._atomic_write(os.path.join(cache_folder, href), - "wb") as f: - pickle.dump(content, f) - except PermissionError: - pass + # Race: Other processes might have created and locked the file. + with contextlib.suppress(PermissionError), self._atomic_write( + os.path.join(cache_folder, href), "wb") as f: + pickle.dump(content, f) return content def _load_item_cache(self, href, input_hash): diff --git a/radicale/storage/multifilesystem/get.py b/radicale/storage/multifilesystem/get.py index 07214502..d1b63227 100644 --- a/radicale/storage/multifilesystem/get.py +++ b/radicale/storage/multifilesystem/get.py @@ -17,11 +17,12 @@ # along with Radicale. If not, see . import os +import sys import time import vobject -from radicale import item as radicale_item +import radicale.item as radicale_item from radicale import pathutils from radicale.log import logger @@ -63,7 +64,7 @@ class CollectionGetMixin: return None except PermissionError: # Windows raises ``PermissionError`` when ``path`` is a directory - if (os.name == "nt" and + if (sys.platform == "win32" and os.path.isdir(path) and os.access(path, os.R_OK)): return None raise @@ -83,10 +84,10 @@ class CollectionGetMixin: self._load_item_cache(href, input_hash) if input_hash != cache_hash: try: - vobject_items = tuple(vobject.readComponents( + vobject_items = list(vobject.readComponents( raw_text.decode(self._encoding))) radicale_item.check_and_sanitize_items( - vobject_items, tag=self.get_meta("tag")) + vobject_items, tag=self.tag) vobject_item, = vobject_items temp_item = radicale_item.Item( collection=self, vobject_item=vobject_item) diff --git a/radicale/storage/multifilesystem/history.py b/radicale/storage/multifilesystem/history.py index 36d42192..56afd01c 100644 --- a/radicale/storage/multifilesystem/history.py +++ b/radicale/storage/multifilesystem/history.py @@ -17,10 +17,11 @@ # along with Radicale. If not, see . import binascii +import contextlib import os import pickle -from radicale import item as radicale_item +import radicale.item as radicale_item from radicale import pathutils from radicale.log import logger @@ -53,13 +54,10 @@ class CollectionHistoryMixin: self._storage._makedirs_synced(history_folder) history_etag = radicale_item.get_etag( history_etag + "/" + etag).strip("\"") - try: - # Race: Other processes might have created and locked the file. - with self._atomic_write(os.path.join(history_folder, href), - "wb") as f: - pickle.dump([etag, history_etag], f) - except PermissionError: - pass + # Race: Other processes might have created and locked the file. + with contextlib.suppress(PermissionError), self._atomic_write( + os.path.join(history_folder, href), "wb") as f: + pickle.dump([etag, history_etag], f) return history_etag def _get_deleted_history_hrefs(self): @@ -67,7 +65,7 @@ class CollectionHistoryMixin: history cache.""" history_folder = os.path.join(self._filesystem_path, ".Radicale.cache", "history") - try: + with contextlib.suppress(FileNotFoundError): for entry in os.scandir(history_folder): href = entry.name if not pathutils.is_safe_filesystem_path_component(href): @@ -75,8 +73,6 @@ class CollectionHistoryMixin: if os.path.isfile(os.path.join(self._filesystem_path, href)): continue yield href - except FileNotFoundError: - pass def _clean_history(self): # Delete all expired history entries of deleted items. diff --git a/radicale/storage/multifilesystem/lock.py b/radicale/storage/multifilesystem/lock.py index 3060dd72..87b2edcb 100644 --- a/radicale/storage/multifilesystem/lock.py +++ b/radicale/storage/multifilesystem/lock.py @@ -22,6 +22,7 @@ import os import shlex import signal import subprocess +import sys from radicale import pathutils from radicale.log import logger @@ -48,7 +49,7 @@ class StorageLockMixin: self._lock = pathutils.RwLock(lock_path) @contextlib.contextmanager - def acquire_lock(self, mode, user=None): + def acquire_lock(self, mode, user=""): with self._lock.acquire(mode): yield # execute hook @@ -66,7 +67,7 @@ class StorageLockMixin: if os.name == "posix": # Process group is also used to identify child processes popen_kwargs["preexec_fn"] = os.setpgrp - elif os.name == "nt": + elif sys.platform == "win32": popen_kwargs["creationflags"] = ( subprocess.CREATE_NEW_PROCESS_GROUP) command = hook % {"user": shlex.quote(user or "Anonymous")} diff --git a/radicale/storage/multifilesystem/meta.py b/radicale/storage/multifilesystem/meta.py index c0dfa9b2..7b196fad 100644 --- a/radicale/storage/multifilesystem/meta.py +++ b/radicale/storage/multifilesystem/meta.py @@ -19,7 +19,7 @@ import json import os -from radicale import item as radicale_item +import radicale.item as radicale_item class CollectionMetaMixin: @@ -35,14 +35,15 @@ class CollectionMetaMixin: try: try: with open(self._props_path, encoding=self._encoding) as f: - self._meta_cache = json.load(f) + temp_meta = json.load(f) except FileNotFoundError: - self._meta_cache = {} - radicale_item.check_and_sanitize_props(self._meta_cache) + temp_meta = {} + self._meta_cache = radicale_item.check_and_sanitize_props( + temp_meta) except ValueError as e: raise RuntimeError("Failed to load properties of collection " "%r: %s" % (self.path, e)) from e - return self._meta_cache.get(key) if key else self._meta_cache + return self._meta_cache if key is None else self._meta_cache.get(key) def set_meta(self, props): with self._atomic_write(self._props_path, "w") as f: diff --git a/radicale/storage/multifilesystem/sync.py b/radicale/storage/multifilesystem/sync.py index 21c00c18..03fe773e 100644 --- a/radicale/storage/multifilesystem/sync.py +++ b/radicale/storage/multifilesystem/sync.py @@ -16,6 +16,7 @@ # You should have received a copy of the GNU General Public License # along with Radicale. If not, see . +import contextlib import itertools import os import pickle @@ -25,7 +26,7 @@ from radicale.log import logger class CollectionSyncMixin: - def sync(self, old_token=None): + def sync(self, old_token=""): # The sync token has the form http://radicale.org/ns/sync/TOKEN_NAME # where TOKEN_NAME is the sha256 hash of all history etags of present # and past items of the collection. @@ -37,7 +38,7 @@ class CollectionSyncMixin: return False return True - old_token_name = None + old_token_name = "" if old_token: # Extract the token name from the sync token if not old_token.startswith("http://radicale.org/ns/sync/"): @@ -78,10 +79,9 @@ class CollectionSyncMixin: "Failed to load stored sync token %r in %r: %s", old_token_name, self.path, e, exc_info=True) # Delete the damaged file - try: + with contextlib.suppress(FileNotFoundError, + PermissionError): os.remove(old_token_path) - except (FileNotFoundError, PermissionError): - pass raise ValueError("Token not found: %r" % old_token) # write the new token state or update the modification time of # existing token state @@ -101,11 +101,9 @@ class CollectionSyncMixin: self._clean_history() else: # Try to update the modification time - try: + with contextlib.suppress(FileNotFoundError): # Race: Another process might have deleted the file. os.utime(token_path) - except FileNotFoundError: - pass changes = [] # Find all new, changed and deleted (that are still in the item cache) # items diff --git a/radicale/storage/multifilesystem/upload.py b/radicale/storage/multifilesystem/upload.py index d0dc5fbf..cf0f9983 100644 --- a/radicale/storage/multifilesystem/upload.py +++ b/radicale/storage/multifilesystem/upload.py @@ -18,8 +18,9 @@ import os import pickle +import sys -from radicale import item as radicale_item +import radicale.item as radicale_item from radicale import pathutils @@ -63,7 +64,7 @@ class CollectionUploadMixin: "Failed to store item %r in temporary collection %r: %s" % (uid, self.path, e)) from e href_candidate_funtions = [] - if os.name in ("nt", "posix"): + if os.name == "posix" or sys.platform == "win32": href_candidate_funtions.append( lambda: uid if uid.lower().endswith(suffix.lower()) else uid + suffix) @@ -88,7 +89,7 @@ class CollectionUploadMixin: except OSError as e: if href_candidate_funtions and ( os.name == "posix" and e.errno == 22 or - os.name == "nt" and e.errno == 123): + sys.platform == "win32" and e.errno == 123): continue raise with f: diff --git a/radicale/storage/multifilesystem/verify.py b/radicale/storage/multifilesystem/verify.py index 61b81d7b..93a05099 100644 --- a/radicale/storage/multifilesystem/verify.py +++ b/radicale/storage/multifilesystem/verify.py @@ -67,8 +67,8 @@ class StorageVerifyMixin: item.href, sane_path) if item_errors == saved_item_errors: collection.sync() - if has_child_collections and collection.get_meta("tag"): + if has_child_collections and collection.tag: logger.error("Invalid collection %r: %r must not have " "child collections", sane_path, - collection.get_meta("tag")) + collection.tag) return item_errors == 0 and collection_errors == 0 diff --git a/radicale/tests/__init__.py b/radicale/tests/__init__.py index a3de3007..f8900b1b 100644 --- a/radicale/tests/__init__.py +++ b/radicale/tests/__init__.py @@ -119,7 +119,7 @@ class BaseTest: if not self._check_status(status, 207, check): return status, None responses = self.parse_responses(answer) - if args.get("HTTP_DEPTH", 0) == 0: + if args.get("HTTP_DEPTH", "0") == "0": assert len(responses) == 1 and path in responses return status, responses diff --git a/radicale/tests/test_auth.py b/radicale/tests/test_auth.py index 8061fddd..5379be72 100644 --- a/radicale/tests/test_auth.py +++ b/radicale/tests/test_auth.py @@ -23,6 +23,7 @@ Radicale tests with simple requests and authentication. import os import shutil +import sys import tempfile import pytest @@ -114,7 +115,7 @@ class TestBaseAuthRequests(BaseTest): def test_htpasswd_multi(self): self._test_htpasswd("plain", "ign:ign\ntmp:bepo") - @pytest.mark.skipif(os.name == "nt", reason="leading and trailing " + @pytest.mark.skipif(sys.platform == "win32", reason="leading and trailing " "whitespaces not allowed in file names") def test_htpasswd_whitespace_user(self): for user in (" tmp", "tmp ", " tmp "): diff --git a/radicale/tests/test_base.py b/radicale/tests/test_base.py index e8ad347b..5952615f 100644 --- a/radicale/tests/test_base.py +++ b/radicale/tests/test_base.py @@ -391,10 +391,10 @@ class BaseRequestsMixIn: event = get_file_content("event1.ics") event_path = posixpath.join(calendar_path, "event.ics") self.put(event_path, event) - _, responses = self.propfind("/", HTTP_DEPTH=1) + _, responses = self.propfind("/", HTTP_DEPTH="1") assert len(responses) == 2 assert "/" in responses and calendar_path in responses - _, responses = self.propfind(calendar_path, HTTP_DEPTH=1) + _, responses = self.propfind(calendar_path, HTTP_DEPTH="1") assert len(responses) == 2 assert calendar_path in responses and event_path in responses @@ -1653,8 +1653,8 @@ class TestMultiFileSystem(BaseFileSystemTest, BaseRequestsMixIn): assert answer1 == answer2 assert os.path.exists(os.path.join(cache_folder, "event1.ics")) - @pytest.mark.skipif(os.name not in ("nt", "posix"), - reason="Only supported on 'nt' and 'posix'") + @pytest.mark.skipif(os.name != "posix" and sys.platform != "win32", + reason="Only supported on 'posix' and 'win32'") def test_put_whole_calendar_uids_used_as_file_names(self): """Test if UIDs are used as file names.""" BaseRequestsMixIn.test_put_whole_calendar(self) @@ -1662,8 +1662,8 @@ class TestMultiFileSystem(BaseFileSystemTest, BaseRequestsMixIn): _, answer = self.get("/calendar.ics/%s.ics" % uid) assert "\r\nUID:%s\r\n" % uid in answer - @pytest.mark.skipif(os.name not in ("nt", "posix"), - reason="Only supported on 'nt' and 'posix'") + @pytest.mark.skipif(os.name != "posix" and sys.platform != "win32", + reason="Only supported on 'posix' and 'win32'") def test_put_whole_calendar_random_uids_used_as_file_names(self): """Test if UIDs are used as file names.""" BaseRequestsMixIn.test_put_whole_calendar_without_uids(self) @@ -1676,8 +1676,8 @@ class TestMultiFileSystem(BaseFileSystemTest, BaseRequestsMixIn): _, answer = self.get("/calendar.ics/%s.ics" % uid) assert "\r\nUID:%s\r\n" % uid in answer - @pytest.mark.skipif(os.name not in ("nt", "posix"), - reason="Only supported on 'nt' and 'posix'") + @pytest.mark.skipif(os.name != "posix" and sys.platform != "win32", + reason="Only supported on 'posix' and 'win32'") def test_put_whole_addressbook_uids_used_as_file_names(self): """Test if UIDs are used as file names.""" BaseRequestsMixIn.test_put_whole_addressbook(self) @@ -1685,8 +1685,8 @@ class TestMultiFileSystem(BaseFileSystemTest, BaseRequestsMixIn): _, answer = self.get("/contacts.vcf/%s.vcf" % uid) assert "\r\nUID:%s\r\n" % uid in answer - @pytest.mark.skipif(os.name not in ("nt", "posix"), - reason="Only supported on 'nt' and 'posix'") + @pytest.mark.skipif(os.name != "posix" and sys.platform != "win32", + reason="Only supported on 'posix' and 'win32'") def test_put_whole_addressbook_random_uids_used_as_file_names(self): """Test if UIDs are used as file names.""" BaseRequestsMixIn.test_put_whole_addressbook_without_uids(self) diff --git a/radicale/types.py b/radicale/types.py new file mode 100644 index 00000000..f0393e3a --- /dev/null +++ b/radicale/types.py @@ -0,0 +1,61 @@ +# This file is part of Radicale Server - Calendar Server +# Copyright © 2020 Unrud +# +# This library is free software: you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation, either version 3 of the License, or +# (at your option) any later version. +# +# This library is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with Radicale. If not, see . + +import contextlib +import sys +from typing import (Any, Callable, ContextManager, Iterator, List, Mapping, + MutableMapping, Sequence, Tuple, TypeVar, Union) + +WSGIResponseHeaders = Union[Mapping[str, str], Sequence[Tuple[str, str]]] +WSGIResponse = Tuple[int, WSGIResponseHeaders, Union[None, str, bytes]] +WSGIEnviron = Mapping[str, Any] +WSGIStartResponse = Callable[[str, List[Tuple[str, str]]], Any] + +CONFIG = Mapping[str, Mapping[str, Any]] +MUTABLE_CONFIG = MutableMapping[str, MutableMapping[str, Any]] +CONFIG_SCHEMA = Mapping[str, Mapping[str, Any]] + +_T = TypeVar("_T") + + +def contextmanager(func: Callable[..., Iterator[_T]] + ) -> Callable[..., ContextManager[_T]]: + """Compatibility wrapper for `contextlib.contextmanager` with + `typeguard`""" + result = contextlib.contextmanager(func) + result.__annotations__ = {**func.__annotations__, + "return": ContextManager[_T]} + return result + + +if sys.version_info >= (3, 8): + from typing import Protocol, runtime_checkable + + @runtime_checkable + class InputStream(Protocol): + def read(self, size: int = ...) -> bytes: ... + + @runtime_checkable + class ErrorStream(Protocol): + def flush(self) -> None: ... + def write(self, s: str) -> None: ... +else: + ErrorStream = Any + InputStream = Any + +from radicale import item, storage # noqa:E402 isort:skip + +CollectionOrItem = Union[item.Item, storage.BaseCollection] diff --git a/radicale/utils.py b/radicale/utils.py index 656912d9..8163ea7e 100644 --- a/radicale/utils.py +++ b/radicale/utils.py @@ -17,12 +17,18 @@ # along with Radicale. If not, see . from importlib import import_module +from typing import Callable, Sequence, Type, TypeVar, Union +from radicale import config from radicale.log import logger +_T_co = TypeVar("_T_co", covariant=True) -def load_plugin(internal_types, module_name, class_name, configuration): - type_ = configuration.get(module_name, "type") + +def load_plugin(internal_types: Sequence[str], module_name: str, + class_name: str, base_class: Type[_T_co], + configuration: "config.Configuration") -> _T_co: + type_: Union[str, Callable] = configuration.get(module_name, "type") if callable(type_): logger.info("%s type is %r", module_name, type_) return type_(configuration) diff --git a/radicale/web/__init__.py b/radicale/web/__init__.py index c18e8d3c..efcbf618 100644 --- a/radicale/web/__init__.py +++ b/radicale/web/__init__.py @@ -21,18 +21,24 @@ Take a look at the class ``BaseWeb`` if you want to implement your own. """ -from radicale import httputils, utils +from typing import Sequence -INTERNAL_TYPES = ("none", "internal") +from radicale import config, httputils, types, utils + +INTERNAL_TYPES: Sequence[str] = ("none", "internal") -def load(configuration): +def load(configuration: "config.Configuration") -> "BaseWeb": """Load the web module chosen in configuration.""" - return utils.load_plugin(INTERNAL_TYPES, "web", "Web", configuration) + return utils.load_plugin(INTERNAL_TYPES, "web", "Web", BaseWeb, + configuration) class BaseWeb: - def __init__(self, configuration): + + configuration: "config.Configuration" + + def __init__(self, configuration: "config.Configuration") -> None: """Initialize BaseWeb. ``configuration`` see ``radicale.config`` module. @@ -42,7 +48,8 @@ class BaseWeb: """ self.configuration = configuration - def get(self, environ, base_prefix, path, user): + def get(self, environ: types.WSGIEnviron, base_prefix: str, path: str, + user: str) -> types.WSGIResponse: """GET request. ``base_prefix`` is sanitized and never ends with "/". @@ -54,7 +61,8 @@ class BaseWeb: """ return httputils.METHOD_NOT_ALLOWED - def post(self, environ, base_prefix, path, user): + def post(self, environ: types.WSGIEnviron, base_prefix: str, path: str, + user: str) -> types.WSGIResponse: """POST request. ``base_prefix`` is sanitized and never ends with "/". diff --git a/radicale/web/internal.py b/radicale/web/internal.py index eb88c42b..0a3b3b77 100644 --- a/radicale/web/internal.py +++ b/radicale/web/internal.py @@ -30,13 +30,14 @@ import os import posixpath import time from http import client +from typing import Mapping import pkg_resources -from radicale import httputils, pathutils, web +from radicale import config, httputils, pathutils, types, web from radicale.log import logger -MIMETYPES = { +MIMETYPES: Mapping[str, str] = { ".css": "text/css", ".eot": "application/vnd.ms-fontobject", ".gif": "image/gif", @@ -50,16 +51,20 @@ MIMETYPES = { ".woff": "application/font-woff", ".woff2": "font/woff2", ".xml": "text/xml"} -FALLBACK_MIMETYPE = "application/octet-stream" +FALLBACK_MIMETYPE: str = "application/octet-stream" class Web(web.BaseWeb): - def __init__(self, configuration): + + folder: str + + def __init__(self, configuration: config.Configuration) -> None: super().__init__(configuration) self.folder = pkg_resources.resource_filename(__name__, "internal_data") - def get(self, environ, base_prefix, path, user): + def get(self, environ: types.WSGIEnviron, base_prefix: str, path: str, + user: str) -> types.WSGIResponse: assert path == "/.web" or path.startswith("/.web/") assert pathutils.sanitize_path(path) == path try: diff --git a/radicale/web/none.py b/radicale/web/none.py index ab49011e..423579e4 100644 --- a/radicale/web/none.py +++ b/radicale/web/none.py @@ -21,11 +21,13 @@ A dummy web backend that shows a simple message. from http import client -from radicale import httputils, pathutils, web +from radicale import httputils, pathutils, types, web class Web(web.BaseWeb): - def get(self, environ, base_prefix, path, user): + + def get(self, environ: types.WSGIEnviron, base_prefix: str, path: str, + user: str) -> types.WSGIResponse: assert path == "/.web" or path.startswith("/.web/") assert pathutils.sanitize_path(path) == path if path != "/.web": diff --git a/radicale/xmlutils.py b/radicale/xmlutils.py index fa6f6bf8..5fb86283 100644 --- a/radicale/xmlutils.py +++ b/radicale/xmlutils.py @@ -26,20 +26,21 @@ import copy import xml.etree.ElementTree as ET from collections import OrderedDict from http import client +from typing import Dict, Mapping, Optional from urllib.parse import quote -from radicale import pathutils +from radicale import item, pathutils -MIMETYPES = { +MIMETYPES: Mapping[str, str] = { "VADDRESSBOOK": "text/vcard", "VCALENDAR": "text/calendar"} -OBJECT_MIMETYPES = { +OBJECT_MIMETYPES: Mapping[str, str] = { "VCARD": "text/vcard", "VLIST": "text/x-vlist", "VCALENDAR": "text/calendar"} -NAMESPACES = { +NAMESPACES: Mapping[str, str] = { "C": "urn:ietf:params:xml:ns:caldav", "CR": "urn:ietf:params:xml:ns:carddav", "D": "DAV:", @@ -48,15 +49,15 @@ NAMESPACES = { "ME": "http://me.com/_namespace/", "RADICALE": "http://radicale.org/ns/"} -NAMESPACES_REV = {} +NAMESPACES_REV: Mapping[str, str] = {v: k for k, v in NAMESPACES.items()} + for short, url in NAMESPACES.items(): - NAMESPACES_REV[url] = short ET.register_namespace("" if short == "D" else short, url) -def pretty_xml(element): +def pretty_xml(element: ET.Element) -> str: """Indent an ElementTree ``element`` and its children.""" - def pretty_xml_recursive(element, level): + def pretty_xml_recursive(element: ET.Element, level: int) -> None: indent = "\n" + level * " " if len(element) > 0: if not (element.text or "").strip(): @@ -74,7 +75,7 @@ def pretty_xml(element): return '\n%s' % ET.tostring(element, "unicode") -def make_clark(human_tag): +def make_clark(human_tag: str) -> str: """Get XML Clark notation from human tag ``human_tag``. If ``human_tag`` is already in XML Clark notation it is returned as-is. @@ -88,13 +89,13 @@ def make_clark(human_tag): ns_prefix, tag = human_tag.split(":", maxsplit=1) if not ns_prefix or not tag: raise ValueError("Invalid XML tag: %r" % human_tag) - ns = NAMESPACES.get(ns_prefix) + ns = NAMESPACES.get(ns_prefix, "") if not ns: raise ValueError("Unknown XML namespace prefix: %r" % human_tag) return "{%s}%s" % (ns, tag) -def make_human_tag(clark_tag): +def make_human_tag(clark_tag: str) -> str: """Replace known namespaces in XML Clark notation ``clark_tag`` with prefix. @@ -111,31 +112,31 @@ def make_human_tag(clark_tag): ns, tag = clark_tag[len("{"):].split("}", maxsplit=1) if not ns or not tag: raise ValueError("Invalid XML tag: %r" % clark_tag) - ns_prefix = NAMESPACES_REV.get(ns) + ns_prefix = NAMESPACES_REV.get(ns, "") if ns_prefix: return "%s:%s" % (ns_prefix, tag) return clark_tag -def make_response(code): +def make_response(code: int) -> str: """Return full W3C names from HTTP status codes.""" return "HTTP/1.1 %i %s" % (code, client.responses[code]) -def make_href(base_prefix, href): +def make_href(base_prefix: str, href: str) -> str: """Return prefixed href.""" assert href == pathutils.sanitize_path(href) return quote("%s%s" % (base_prefix, href)) -def webdav_error(human_tag): +def webdav_error(human_tag: str) -> ET.Element: """Generate XML error message.""" root = ET.Element(make_clark("D:error")) root.append(ET.Element(make_clark(human_tag))) return root -def get_content_type(item, encoding): +def get_content_type(item: "item.Item", encoding: str) -> str: """Get the content-type of an item with charset and component parameters. """ mimetype = OBJECT_MIMETYPES[item.name] @@ -146,13 +147,14 @@ def get_content_type(item, encoding): return content_type -def props_from_request(xml_request): +def props_from_request(xml_request: Optional[ET.Element] + ) -> Dict[str, Optional[str]]: """Return a list of properties as a dictionary. Properties that should be removed are set to `None`. """ - result = OrderedDict() + result: OrderedDict = OrderedDict() if xml_request is None: return result From 698ae875cef3b71c97bfaebc00dd5ac56a58ace9 Mon Sep 17 00:00:00 2001 From: Unrud Date: Mon, 26 Jul 2021 20:56:47 +0200 Subject: [PATCH 054/238] Type hints for multifilesystem --- radicale/storage/multifilesystem/__init__.py | 144 +++++------------- radicale/storage/multifilesystem/base.py | 121 +++++++++++++++ radicale/storage/multifilesystem/cache.py | 55 ++++--- .../multifilesystem/create_collection.py | 23 ++- radicale/storage/multifilesystem/delete.py | 12 +- radicale/storage/multifilesystem/discover.py | 40 +++-- radicale/storage/multifilesystem/get.py | 68 +++++---- radicale/storage/multifilesystem/history.py | 22 ++- radicale/storage/multifilesystem/lock.py | 57 ++++--- radicale/storage/multifilesystem/meta.py | 28 +++- radicale/storage/multifilesystem/move.py | 22 ++- radicale/storage/multifilesystem/sync.py | 20 ++- radicale/storage/multifilesystem/upload.py | 36 +++-- radicale/storage/multifilesystem/verify.py | 26 ++-- 14 files changed, 428 insertions(+), 246 deletions(-) create mode 100644 radicale/storage/multifilesystem/base.py diff --git a/radicale/storage/multifilesystem/__init__.py b/radicale/storage/multifilesystem/__init__.py index f78458d4..e044fb17 100644 --- a/radicale/storage/multifilesystem/__init__.py +++ b/radicale/storage/multifilesystem/__init__.py @@ -23,75 +23,57 @@ Uses one folder per collection and one file per collection entry. """ -import contextlib import os import time -from itertools import chain -from tempfile import TemporaryDirectory +from typing import Iterator, Optional -from radicale import pathutils, storage -from radicale.storage.multifilesystem.cache import CollectionCacheMixin +from radicale import config +from radicale.storage.multifilesystem.base import CollectionBase, StorageBase +from radicale.storage.multifilesystem.cache import CollectionPartCache from radicale.storage.multifilesystem.create_collection import \ - StorageCreateCollectionMixin -from radicale.storage.multifilesystem.delete import CollectionDeleteMixin -from radicale.storage.multifilesystem.discover import StorageDiscoverMixin -from radicale.storage.multifilesystem.get import CollectionGetMixin -from radicale.storage.multifilesystem.history import CollectionHistoryMixin -from radicale.storage.multifilesystem.lock import (CollectionLockMixin, - StorageLockMixin) -from radicale.storage.multifilesystem.meta import CollectionMetaMixin -from radicale.storage.multifilesystem.move import StorageMoveMixin -from radicale.storage.multifilesystem.sync import CollectionSyncMixin -from radicale.storage.multifilesystem.upload import CollectionUploadMixin -from radicale.storage.multifilesystem.verify import StorageVerifyMixin + StoragePartCreateCollection +from radicale.storage.multifilesystem.delete import CollectionPartDelete +from radicale.storage.multifilesystem.discover import StoragePartDiscover +from radicale.storage.multifilesystem.get import CollectionPartGet +from radicale.storage.multifilesystem.history import CollectionPartHistory +from radicale.storage.multifilesystem.lock import (CollectionPartLock, + StoragePartLock) +from radicale.storage.multifilesystem.meta import CollectionPartMeta +from radicale.storage.multifilesystem.move import StoragePartMove +from radicale.storage.multifilesystem.sync import CollectionPartSync +from radicale.storage.multifilesystem.upload import CollectionPartUpload +from radicale.storage.multifilesystem.verify import StoragePartVerify class Collection( - CollectionCacheMixin, CollectionDeleteMixin, CollectionGetMixin, - CollectionHistoryMixin, CollectionLockMixin, CollectionMetaMixin, - CollectionSyncMixin, CollectionUploadMixin, storage.BaseCollection): + CollectionPartDelete, CollectionPartMeta, CollectionPartSync, + CollectionPartUpload, CollectionPartGet, CollectionPartCache, + CollectionPartLock, CollectionPartHistory, CollectionBase): - def __init__(self, storage_, path, filesystem_path=None): - self._storage = storage_ - folder = self._storage._get_collection_root_folder() - # Path should already be sanitized - self._path = pathutils.strip_path(path) - self._encoding = self._storage.configuration.get("encoding", "stock") - if filesystem_path is None: - filesystem_path = pathutils.path_to_filesystem(folder, self.path) - self._filesystem_path = filesystem_path + _etag_cache: Optional[str] + + def __init__(self, storage_: "Storage", path: str, + filesystem_path: Optional[str] = None) -> None: + super().__init__(storage_, path, filesystem_path) self._etag_cache = None - super().__init__() @property - def path(self): + def path(self) -> str: return self._path - @contextlib.contextmanager - def _atomic_write(self, path, mode="w", newline=None): - parent_dir, name = os.path.split(path) - # Do not use mkstemp because it creates with permissions 0o600 - with TemporaryDirectory( - prefix=".Radicale.tmp-", dir=parent_dir) as tmp_dir: - with open(os.path.join(tmp_dir, name), mode, newline=newline, - encoding=None if "b" in mode else self._encoding) as tmp: - yield tmp - tmp.flush() - self._storage._fsync(tmp) - os.replace(os.path.join(tmp_dir, name), path) - self._storage._sync_directory(parent_dir) - @property - def last_modified(self): - relevant_files = chain( - (self._filesystem_path,), - (self._props_path,) if os.path.exists(self._props_path) else (), - (os.path.join(self._filesystem_path, h) for h in self._list())) - last = max(map(os.path.getmtime, relevant_files)) + def last_modified(self) -> str: + def relevant_files_iter() -> Iterator[str]: + yield self._filesystem_path + if os.path.exists(self._props_path): + yield self._props_path + for href in self._list(): + yield os.path.join(self._filesystem_path, href) + last = max(map(os.path.getmtime, relevant_files_iter())) return time.strftime("%a, %d %b %Y %H:%M:%S GMT", time.gmtime(last)) @property - def etag(self): + def etag(self) -> str: # reuse cached value if the storage is read-only if self._storage._lock.locked == "w" or self._etag_cache is None: self._etag_cache = super().etag @@ -99,61 +81,11 @@ class Collection( class Storage( - StorageCreateCollectionMixin, StorageDiscoverMixin, StorageLockMixin, - StorageMoveMixin, StorageVerifyMixin, storage.BaseStorage): + StoragePartCreateCollection, StoragePartLock, StoragePartMove, + StoragePartVerify, StoragePartDiscover, StorageBase): _collection_class = Collection - def __init__(self, configuration): + def __init__(self, configuration: config.Configuration) -> None: super().__init__(configuration) - folder = configuration.get("storage", "filesystem_folder") - self._makedirs_synced(folder) - - def _get_collection_root_folder(self): - filesystem_folder = self.configuration.get( - "storage", "filesystem_folder") - return os.path.join(filesystem_folder, "collection-root") - - def _fsync(self, f): - if self.configuration.get("storage", "_filesystem_fsync"): - try: - pathutils.fsync(f.fileno()) - except OSError as e: - raise RuntimeError("Fsync'ing file %r failed: %s" % - (f.name, e)) from e - - def _sync_directory(self, path): - """Sync directory to disk. - - This only works on POSIX and does nothing on other systems. - - """ - if not self.configuration.get("storage", "_filesystem_fsync"): - return - if os.name == "posix": - try: - fd = os.open(path, 0) - try: - pathutils.fsync(fd) - finally: - os.close(fd) - except OSError as e: - raise RuntimeError("Fsync'ing directory %r failed: %s" % - (path, e)) from e - - def _makedirs_synced(self, filesystem_path): - """Recursively create a directory and its parents in a sync'ed way. - - This method acts silently when the folder already exists. - - """ - if os.path.isdir(filesystem_path): - return - parent_filesystem_path = os.path.dirname(filesystem_path) - # Prevent infinite loop - if filesystem_path != parent_filesystem_path: - # Create parent dirs recursively - self._makedirs_synced(parent_filesystem_path) - # Possible race! - os.makedirs(filesystem_path, exist_ok=True) - self._sync_directory(parent_filesystem_path) + self._makedirs_synced(self._filesystem_folder) diff --git a/radicale/storage/multifilesystem/base.py b/radicale/storage/multifilesystem/base.py new file mode 100644 index 00000000..5f2cdf93 --- /dev/null +++ b/radicale/storage/multifilesystem/base.py @@ -0,0 +1,121 @@ +# This file is part of Radicale Server - Calendar Server +# Copyright © 2014 Jean-Marc Martins +# Copyright © 2012-2017 Guillaume Ayoub +# Copyright © 2017-2019 Unrud +# +# This library is free software: you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation, either version 3 of the License, or +# (at your option) any later version. +# +# This library is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with Radicale. If not, see . + +import os +from tempfile import TemporaryDirectory +from typing import IO, AnyStr, Iterator, Optional, Type + +from radicale import config, pathutils, storage, types +from radicale.storage import multifilesystem # noqa:F401 + + +class CollectionBase(storage.BaseCollection): + + _storage: "multifilesystem.Storage" + _path: str + _encoding: str + _filesystem_path: str + + def __init__(self, storage_: "multifilesystem.Storage", path: str, + filesystem_path: Optional[str] = None) -> None: + super().__init__() + self._storage = storage_ + folder = storage_._get_collection_root_folder() + # Path should already be sanitized + self._path = pathutils.strip_path(path) + self._encoding = storage_.configuration.get("encoding", "stock") + if filesystem_path is None: + filesystem_path = pathutils.path_to_filesystem(folder, self.path) + self._filesystem_path = filesystem_path + + @types.contextmanager + def _atomic_write(self, path: str, mode: str = "w", + newline: Optional[str] = None) -> Iterator[IO[AnyStr]]: + # TODO: Overload with Literal when dropping support for Python < 3.8 + parent_dir, name = os.path.split(path) + # Do not use mkstemp because it creates with permissions 0o600 + with TemporaryDirectory( + prefix=".Radicale.tmp-", dir=parent_dir) as tmp_dir: + with open(os.path.join(tmp_dir, name), mode, newline=newline, + encoding=None if "b" in mode else self._encoding) as tmp: + yield tmp + tmp.flush() + self._storage._fsync(tmp) + os.replace(os.path.join(tmp_dir, name), path) + self._storage._sync_directory(parent_dir) + + +class StorageBase(storage.BaseStorage): + + _collection_class: Type["multifilesystem.Collection"] + _filesystem_folder: str + _filesystem_fsync: bool + + def __init__(self, configuration: config.Configuration) -> None: + super().__init__(configuration) + self._filesystem_folder = configuration.get( + "storage", "filesystem_folder") + self._filesystem_fsync = configuration.get( + "storage", "_filesystem_fsync") + + def _get_collection_root_folder(self) -> str: + return os.path.join(self._filesystem_folder, "collection-root") + + def _fsync(self, f: IO[AnyStr]) -> None: + if self._filesystem_fsync: + try: + pathutils.fsync(f.fileno()) + except OSError as e: + raise RuntimeError("Fsync'ing file %r failed: %s" % + (f.name, e)) from e + + def _sync_directory(self, path: str) -> None: + """Sync directory to disk. + + This only works on POSIX and does nothing on other systems. + + """ + if not self._filesystem_fsync: + return + if os.name == "posix": + try: + fd = os.open(path, 0) + try: + pathutils.fsync(fd) + finally: + os.close(fd) + except OSError as e: + raise RuntimeError("Fsync'ing directory %r failed: %s" % + (path, e)) from e + + def _makedirs_synced(self, filesystem_path: str) -> None: + """Recursively create a directory and its parents in a sync'ed way. + + This method acts silently when the folder already exists. + + """ + if os.path.isdir(filesystem_path): + return + parent_filesystem_path = os.path.dirname(filesystem_path) + # Prevent infinite loop + if filesystem_path != parent_filesystem_path: + # Create parent dirs recursively + self._makedirs_synced(parent_filesystem_path) + # Possible race! + os.makedirs(filesystem_path, exist_ok=True) + self._sync_directory(parent_filesystem_path) diff --git a/radicale/storage/multifilesystem/cache.py b/radicale/storage/multifilesystem/cache.py index 74327b32..119317dd 100644 --- a/radicale/storage/multifilesystem/cache.py +++ b/radicale/storage/multifilesystem/cache.py @@ -21,16 +21,27 @@ import os import pickle import time from hashlib import sha256 +from typing import BinaryIO, Iterable, NamedTuple, Optional, cast +import radicale.item as radicale_item from radicale import pathutils, storage from radicale.log import logger +from radicale.storage.multifilesystem.base import CollectionBase + +CacheContent = NamedTuple("CacheContent", [ + ("uid", str), ("etag", str), ("text", str), ("name", str), ("tag", str), + ("start", int), ("end", int)]) -class CollectionCacheMixin: - def _clean_cache(self, folder, names, max_age=None): +class CollectionPartCache(CollectionBase): + + def _clean_cache(self, folder: str, names: Iterable[str], + max_age: int = 0) -> None: """Delete all ``names`` in ``folder`` that are older than ``max_age``. """ - age_limit = time.time() - max_age if max_age is not None else None + age_limit: Optional[float] = None + if max_age is not None and max_age > 0: + age_limit = time.time() - max_age modified = False for name in names: if not pathutils.is_safe_filesystem_path_component(name): @@ -55,47 +66,49 @@ class CollectionCacheMixin: self._storage._sync_directory(folder) @staticmethod - def _item_cache_hash(raw_text): + def _item_cache_hash(raw_text: bytes) -> str: _hash = sha256() _hash.update(storage.CACHE_VERSION) _hash.update(raw_text) return _hash.hexdigest() - def _item_cache_content(self, item, cache_hash=None): - text = item.serialize() - if cache_hash is None: - cache_hash = self._item_cache_hash(text.encode(self._encoding)) - return (cache_hash, item.uid, item.etag, text, item.name, - item.component_name, *item.time_range) + def _item_cache_content(self, item: radicale_item.Item) -> CacheContent: + return CacheContent(item.uid, item.etag, item.serialize(), item.name, + item.component_name, *item.time_range) - def _store_item_cache(self, href, item, cache_hash=None): + def _store_item_cache(self, href: str, item: radicale_item.Item, + cache_hash: str = "") -> CacheContent: + if not cache_hash: + cache_hash = self._item_cache_hash( + item.serialize().encode(self._encoding)) cache_folder = os.path.join(self._filesystem_path, ".Radicale.cache", "item") - content = self._item_cache_content(item, cache_hash) + content = self._item_cache_content(item) self._storage._makedirs_synced(cache_folder) # Race: Other processes might have created and locked the file. with contextlib.suppress(PermissionError), self._atomic_write( - os.path.join(cache_folder, href), "wb") as f: - pickle.dump(content, f) + os.path.join(cache_folder, href), "wb") as fo: + fb = cast(BinaryIO, fo) + pickle.dump((cache_hash, *content), fb) return content - def _load_item_cache(self, href, input_hash): + def _load_item_cache(self, href: str, cache_hash: str + ) -> Optional[CacheContent]: cache_folder = os.path.join(self._filesystem_path, ".Radicale.cache", "item") - cache_hash = uid = etag = text = name = tag = start = end = None try: with open(os.path.join(cache_folder, href), "rb") as f: - cache_hash, *content = pickle.load(f) - if cache_hash == input_hash: - uid, etag, text, name, tag, start, end = content + hash_, *remainder = pickle.load(f) + if hash_ and hash_ == cache_hash: + return CacheContent(*remainder) except FileNotFoundError: pass except (pickle.UnpicklingError, ValueError) as e: logger.warning("Failed to load item cache entry %r in %r: %s", href, self.path, e, exc_info=True) - return cache_hash, uid, etag, text, name, tag, start, end + return None - def _clean_item_cache(self): + def _clean_item_cache(self) -> None: cache_folder = os.path.join(self._filesystem_path, ".Radicale.cache", "item") self._clean_cache(cache_folder, ( diff --git a/radicale/storage/multifilesystem/create_collection.py b/radicale/storage/multifilesystem/create_collection.py index fe0290e9..422c3c99 100644 --- a/radicale/storage/multifilesystem/create_collection.py +++ b/radicale/storage/multifilesystem/create_collection.py @@ -18,13 +18,19 @@ import os from tempfile import TemporaryDirectory +from typing import Iterable, Optional, cast +import radicale.item as radicale_item from radicale import pathutils +from radicale.storage import multifilesystem +from radicale.storage.multifilesystem.base import StorageBase -class StorageCreateCollectionMixin: +class StoragePartCreateCollection(StorageBase): - def create_collection(self, href, items=None, props=None): + def create_collection(self, href: str, + items: Optional[Iterable[radicale_item.Item]] = None, + props=None) -> "multifilesystem.Collection": folder = self._get_collection_root_folder() # Path should already be sanitized @@ -34,19 +40,21 @@ class StorageCreateCollectionMixin: if not props: self._makedirs_synced(filesystem_path) return self._collection_class( - self, pathutils.unstrip_path(sane_path, True)) + cast(multifilesystem.Storage, self), + pathutils.unstrip_path(sane_path, True)) parent_dir = os.path.dirname(filesystem_path) self._makedirs_synced(parent_dir) # Create a temporary directory with an unsafe name - with TemporaryDirectory( - prefix=".Radicale.tmp-", dir=parent_dir) as tmp_dir: + with TemporaryDirectory(prefix=".Radicale.tmp-", dir=parent_dir + ) as tmp_dir: # The temporary directory itself can't be renamed tmp_filesystem_path = os.path.join(tmp_dir, "collection") os.makedirs(tmp_filesystem_path) col = self._collection_class( - self, pathutils.unstrip_path(sane_path, True), + cast(multifilesystem.Storage, self), + pathutils.unstrip_path(sane_path, True), filesystem_path=tmp_filesystem_path) col.set_meta(props) if items is not None: @@ -62,4 +70,5 @@ class StorageCreateCollectionMixin: self._sync_directory(parent_dir) return self._collection_class( - self, pathutils.unstrip_path(sane_path, True)) + cast(multifilesystem.Storage, self), + pathutils.unstrip_path(sane_path, True)) diff --git a/radicale/storage/multifilesystem/delete.py b/radicale/storage/multifilesystem/delete.py index 264b608f..56a47325 100644 --- a/radicale/storage/multifilesystem/delete.py +++ b/radicale/storage/multifilesystem/delete.py @@ -18,20 +18,24 @@ import os from tempfile import TemporaryDirectory +from typing import Optional from radicale import pathutils, storage +from radicale.storage.multifilesystem.base import CollectionBase +from radicale.storage.multifilesystem.history import CollectionPartHistory -class CollectionDeleteMixin: - def delete(self, href=None): +class CollectionPartDelete(CollectionPartHistory, CollectionBase): + + def delete(self, href: Optional[str] = None) -> None: if href is None: # Delete the collection parent_dir = os.path.dirname(self._filesystem_path) try: os.rmdir(self._filesystem_path) except OSError: - with TemporaryDirectory( - prefix=".Radicale.tmp-", dir=parent_dir) as tmp: + with TemporaryDirectory(prefix=".Radicale.tmp-", dir=parent_dir + ) as tmp: os.rename(self._filesystem_path, os.path.join( tmp, os.path.basename(self._filesystem_path))) self._storage._sync_directory(parent_dir) diff --git a/radicale/storage/multifilesystem/discover.py b/radicale/storage/multifilesystem/discover.py index 68ec4e0a..211f2144 100644 --- a/radicale/storage/multifilesystem/discover.py +++ b/radicale/storage/multifilesystem/discover.py @@ -16,18 +16,31 @@ # You should have received a copy of the GNU General Public License # along with Radicale. If not, see . -import contextlib import os import posixpath +from typing import Callable, ContextManager, Iterator, Optional, cast -from radicale import pathutils +from radicale import pathutils, types from radicale.log import logger +from radicale.storage import multifilesystem +from radicale.storage.multifilesystem.base import StorageBase -class StorageDiscoverMixin: +@types.contextmanager +def _null_child_context_manager(path: str, + href: Optional[str]) -> Iterator[None]: + yield - def discover(self, path, depth="0", child_context_manager=( - lambda path, href=None: contextlib.ExitStack())): + +class StoragePartDiscover(StorageBase): + + def discover( + self, path: str, depth: str = "0", child_context_manager: Optional[ + Callable[[str, Optional[str]], ContextManager[None]]] = None + ) -> Iterator[types.CollectionOrItem]: + # assert isinstance(self, multifilesystem.Storage) + if child_context_manager is None: + child_context_manager = _null_child_context_manager # Path should already be sanitized sane_path = pathutils.strip_path(path) attributes = sane_path.split("/") if sane_path else [] @@ -44,6 +57,7 @@ class StorageDiscoverMixin: return # Check if the path exists and if it leads to a collection or an item + href: Optional[str] if not os.path.isdir(filesystem_path): if attributes and os.path.isfile(filesystem_path): href = attributes.pop() @@ -54,10 +68,13 @@ class StorageDiscoverMixin: sane_path = "/".join(attributes) collection = self._collection_class( - self, pathutils.unstrip_path(sane_path, True)) + cast(multifilesystem.Storage, self), + pathutils.unstrip_path(sane_path, True)) if href: - yield collection._get(href) + item = collection._get(href) + if item is not None: + yield item return yield collection @@ -67,7 +84,9 @@ class StorageDiscoverMixin: for href in collection._list(): with child_context_manager(sane_path, href): - yield collection._get(href) + item = collection._get(href) + if item is not None: + yield item for entry in os.scandir(filesystem_path): if not entry.is_dir(): @@ -80,5 +99,6 @@ class StorageDiscoverMixin: continue sane_child_path = posixpath.join(sane_path, href) child_path = pathutils.unstrip_path(sane_child_path, True) - with child_context_manager(sane_child_path): - yield self._collection_class(self, child_path) + with child_context_manager(sane_child_path, None): + yield self._collection_class( + cast(multifilesystem.Storage, self), child_path) diff --git a/radicale/storage/multifilesystem/get.py b/radicale/storage/multifilesystem/get.py index d1b63227..2f2f5923 100644 --- a/radicale/storage/multifilesystem/get.py +++ b/radicale/storage/multifilesystem/get.py @@ -19,20 +19,30 @@ import os import sys import time +from typing import Iterable, Iterator, Optional, Tuple import vobject import radicale.item as radicale_item from radicale import pathutils from radicale.log import logger +from radicale.storage import multifilesystem +from radicale.storage.multifilesystem.base import CollectionBase +from radicale.storage.multifilesystem.cache import CollectionPartCache +from radicale.storage.multifilesystem.lock import CollectionPartLock -class CollectionGetMixin: - def __init__(self): - super().__init__() +class CollectionPartGet(CollectionPartCache, CollectionPartLock, + CollectionBase): + + _item_cache_cleaned: bool + + def __init__(self, storage_: "multifilesystem.Storage", path: str, + filesystem_path: Optional[str] = None) -> None: + super().__init__(storage_, path, filesystem_path) self._item_cache_cleaned = False - def _list(self): + def _list(self) -> Iterator[str]: for entry in os.scandir(self._filesystem_path): if not entry.is_file(): continue @@ -43,13 +53,14 @@ class CollectionGetMixin: continue yield href - def _get(self, href, verify_href=True): + def _get(self, href: str, verify_href: bool = True + ) -> Optional[radicale_item.Item]: if verify_href: try: if not pathutils.is_safe_filesystem_path_component(href): raise pathutils.UnsafePathError(href) - path = pathutils.path_to_filesystem( - self._filesystem_path, href) + path = pathutils.path_to_filesystem(self._filesystem_path, + href) except ValueError as e: logger.debug( "Can't translate name %r safely to filesystem in %r: %s", @@ -70,19 +81,17 @@ class CollectionGetMixin: raise # The hash of the component in the file system. This is used to check, # if the entry in the cache is still valid. - input_hash = self._item_cache_hash(raw_text) - cache_hash, uid, etag, text, name, tag, start, end = \ - self._load_item_cache(href, input_hash) - if input_hash != cache_hash: + cache_hash = self._item_cache_hash(raw_text) + cache_content = self._load_item_cache(href, cache_hash) + if cache_content is None: with self._acquire_cache_lock("item"): # Lock the item cache to prevent multpile processes from # generating the same data in parallel. # This improves the performance for multiple requests. if self._storage._lock.locked == "r": # Check if another process created the file in the meantime - cache_hash, uid, etag, text, name, tag, start, end = \ - self._load_item_cache(href, input_hash) - if input_hash != cache_hash: + cache_content = self._load_item_cache(href, cache_hash) + if cache_content is None: try: vobject_items = list(vobject.readComponents( raw_text.decode(self._encoding))) @@ -91,9 +100,8 @@ class CollectionGetMixin: vobject_item, = vobject_items temp_item = radicale_item.Item( collection=self, vobject_item=vobject_item) - cache_hash, uid, etag, text, name, tag, start, end = \ - self._store_item_cache( - href, temp_item, input_hash) + cache_content = self._store_item_cache( + href, temp_item, cache_hash) except Exception as e: raise RuntimeError("Failed to load item %r in %r: %s" % (href, self.path, e)) from e @@ -108,11 +116,14 @@ class CollectionGetMixin: # Don't keep reference to ``vobject_item``, because it requires a lot # of memory. return radicale_item.Item( - collection=self, href=href, last_modified=last_modified, etag=etag, - text=text, uid=uid, name=name, component_name=tag, - time_range=(start, end)) + collection=self, href=href, last_modified=last_modified, + etag=cache_content.etag, text=cache_content.text, + uid=cache_content.uid, name=cache_content.name, + component_name=cache_content.tag, + time_range=(cache_content.start, cache_content.end)) - def get_multi(self, hrefs): + def get_multi(self, hrefs: Iterable[str] + ) -> Iterator[Tuple[str, Optional[radicale_item.Item]]]: # It's faster to check for file name collissions here, because # we only need to call os.listdir once. files = None @@ -124,13 +135,16 @@ class CollectionGetMixin: path = os.path.join(self._filesystem_path, href) if (not pathutils.is_safe_filesystem_path_component(href) or href not in files and os.path.lexists(path)): - logger.debug( - "Can't translate name safely to filesystem: %r", href) + logger.debug("Can't translate name safely to filesystem: %r", + href) yield (href, None) else: yield (href, self._get(href, verify_href=False)) - def get_all(self): - # We don't need to check for collissions, because the the file names - # are from os.listdir. - return (self._get(href, verify_href=False) for href in self._list()) + def get_all(self) -> Iterator[radicale_item.Item]: + for href in self._list(): + # We don't need to check for collissions, because the file names + # are from os.listdir. + item = self._get(href, verify_href=False) + if item is not None: + yield item diff --git a/radicale/storage/multifilesystem/history.py b/radicale/storage/multifilesystem/history.py index 56afd01c..767a8637 100644 --- a/radicale/storage/multifilesystem/history.py +++ b/radicale/storage/multifilesystem/history.py @@ -20,13 +20,25 @@ import binascii import contextlib import os import pickle +from typing import BinaryIO, Optional, cast import radicale.item as radicale_item from radicale import pathutils from radicale.log import logger +from radicale.storage import multifilesystem +from radicale.storage.multifilesystem.base import CollectionBase -class CollectionHistoryMixin: +class CollectionPartHistory(CollectionBase): + + _max_sync_token_age: int + + def __init__(self, storage_: "multifilesystem.Storage", path: str, + filesystem_path: Optional[str] = None) -> None: + super().__init__(storage_, path, filesystem_path) + self._max_sync_token_age = storage_.configuration.get( + "storage", "max_sync_token_age") + def _update_history_etag(self, href, item): """Updates and retrieves the history etag from the history cache. @@ -56,8 +68,9 @@ class CollectionHistoryMixin: history_etag + "/" + etag).strip("\"") # Race: Other processes might have created and locked the file. with contextlib.suppress(PermissionError), self._atomic_write( - os.path.join(history_folder, href), "wb") as f: - pickle.dump([etag, history_etag], f) + os.path.join(history_folder, href), "wb") as fo: + fb = cast(BinaryIO, fo) + pickle.dump([etag, history_etag], fb) return history_etag def _get_deleted_history_hrefs(self): @@ -79,5 +92,4 @@ class CollectionHistoryMixin: history_folder = os.path.join(self._filesystem_path, ".Radicale.cache", "history") self._clean_cache(history_folder, self._get_deleted_history_hrefs(), - max_age=self._storage.configuration.get( - "storage", "max_sync_token_age")) + max_age=self._max_sync_token_age) diff --git a/radicale/storage/multifilesystem/lock.py b/radicale/storage/multifilesystem/lock.py index 87b2edcb..164a9965 100644 --- a/radicale/storage/multifilesystem/lock.py +++ b/radicale/storage/multifilesystem/lock.py @@ -23,56 +23,65 @@ import shlex import signal import subprocess import sys +from typing import Iterator -from radicale import pathutils +from radicale import config, pathutils, types from radicale.log import logger +from radicale.storage.multifilesystem.base import CollectionBase, StorageBase -class CollectionLockMixin: - def _acquire_cache_lock(self, ns=""): +class CollectionPartLock(CollectionBase): + + @types.contextmanager + def _acquire_cache_lock(self, ns: str = "") -> Iterator[None]: if self._storage._lock.locked == "w": - return contextlib.ExitStack() + yield + return cache_folder = os.path.join(self._filesystem_path, ".Radicale.cache") self._storage._makedirs_synced(cache_folder) lock_path = os.path.join(cache_folder, ".Radicale.lock" + (".%s" % ns if ns else "")) lock = pathutils.RwLock(lock_path) - return lock.acquire("w") + with lock.acquire("w"): + yield -class StorageLockMixin: +class StoragePartLock(StorageBase): - def __init__(self, configuration): + _lock: pathutils.RwLock + _hook: str + + def __init__(self, configuration: config.Configuration) -> None: super().__init__(configuration) - folder = self.configuration.get("storage", "filesystem_folder") - lock_path = os.path.join(folder, ".Radicale.lock") + lock_path = os.path.join(self._filesystem_folder, ".Radicale.lock") self._lock = pathutils.RwLock(lock_path) + self._hook = configuration.get("storage", "hook") - @contextlib.contextmanager - def acquire_lock(self, mode, user=""): + @types.contextmanager + def acquire_lock(self, mode: str, user: str = "") -> Iterator[None]: with self._lock.acquire(mode): yield # execute hook - hook = self.configuration.get("storage", "hook") - if mode == "w" and hook: - folder = self.configuration.get("storage", "filesystem_folder") + if mode == "w" and self._hook: debug = logger.isEnabledFor(logging.DEBUG) - popen_kwargs = dict( - stdin=subprocess.DEVNULL, - stdout=subprocess.PIPE if debug else subprocess.DEVNULL, - stderr=subprocess.PIPE if debug else subprocess.DEVNULL, - shell=True, universal_newlines=True, cwd=folder) # Use new process group for child to prevent terminals # from sending SIGINT etc. + preexec_fn = None + creationflags = 0 if os.name == "posix": # Process group is also used to identify child processes - popen_kwargs["preexec_fn"] = os.setpgrp + preexec_fn = os.setpgrp elif sys.platform == "win32": - popen_kwargs["creationflags"] = ( - subprocess.CREATE_NEW_PROCESS_GROUP) - command = hook % {"user": shlex.quote(user or "Anonymous")} + creationflags |= subprocess.CREATE_NEW_PROCESS_GROUP + command = self._hook % { + "user": shlex.quote(user or "Anonymous")} logger.debug("Running storage hook") - p = subprocess.Popen(command, **popen_kwargs) + p = subprocess.Popen( + command, stdin=subprocess.DEVNULL, + stdout=subprocess.PIPE if debug else subprocess.DEVNULL, + stderr=subprocess.PIPE if debug else subprocess.DEVNULL, + shell=True, universal_newlines=True, preexec_fn=preexec_fn, + cwd=self._filesystem_folder, creationflags=creationflags) try: stdout_data, stderr_data = p.communicate() except BaseException: # e.g. KeyboardInterrupt or SystemExit diff --git a/radicale/storage/multifilesystem/meta.py b/radicale/storage/multifilesystem/meta.py index 7b196fad..6b932f7c 100644 --- a/radicale/storage/multifilesystem/meta.py +++ b/radicale/storage/multifilesystem/meta.py @@ -18,18 +18,33 @@ import json import os +from typing import Mapping, Optional, TextIO, Union, cast, overload import radicale.item as radicale_item +from radicale.storage import multifilesystem +from radicale.storage.multifilesystem.base import CollectionBase -class CollectionMetaMixin: - def __init__(self): - super().__init__() +class CollectionPartMeta(CollectionBase): + + _meta_cache: Optional[Mapping[str, str]] + _props_path: str + + def __init__(self, storage_: "multifilesystem.Storage", path: str, + filesystem_path: Optional[str] = None) -> None: + super().__init__(storage_, path, filesystem_path) self._meta_cache = None self._props_path = os.path.join( self._filesystem_path, ".Radicale.props") - def get_meta(self, key=None): + @overload + def get_meta(self, key: None = None) -> Mapping[str, str]: ... + + @overload + def get_meta(self, key: str) -> Optional[str]: ... + + def get_meta(self, key: Optional[str] = None) -> Union[Mapping[str, str], + Optional[str]]: # reuse cached value if the storage is read-only if self._storage._lock.locked == "w" or self._meta_cache is None: try: @@ -45,6 +60,7 @@ class CollectionMetaMixin: "%r: %s" % (self.path, e)) from e return self._meta_cache if key is None else self._meta_cache.get(key) - def set_meta(self, props): - with self._atomic_write(self._props_path, "w") as f: + def set_meta(self, props: Mapping[str, str]) -> None: + with self._atomic_write(self._props_path, "w") as fo: + f = cast(TextIO, fo) json.dump(props, f, sort_keys=True) diff --git a/radicale/storage/multifilesystem/move.py b/radicale/storage/multifilesystem/move.py index def8d2e4..a73894f4 100644 --- a/radicale/storage/multifilesystem/move.py +++ b/radicale/storage/multifilesystem/move.py @@ -18,19 +18,25 @@ import os -from radicale import pathutils +from radicale import item as radicale_item +from radicale import pathutils, storage +from radicale.storage import multifilesystem +from radicale.storage.multifilesystem.base import StorageBase -class StorageMoveMixin: +class StoragePartMove(StorageBase): - def move(self, item, to_collection, to_href): + def move(self, item: radicale_item.Item, + to_collection: storage.BaseCollection, to_href: str) -> None: if not pathutils.is_safe_filesystem_path_component(to_href): raise pathutils.UnsafePathError(to_href) - os.replace( - pathutils.path_to_filesystem( - item.collection._filesystem_path, item.href), - pathutils.path_to_filesystem( - to_collection._filesystem_path, to_href)) + assert isinstance(to_collection, multifilesystem.Collection) + assert isinstance(item.collection, multifilesystem.Collection) + assert item.href + os.replace(pathutils.path_to_filesystem( + item.collection._filesystem_path, item.href), + pathutils.path_to_filesystem( + to_collection._filesystem_path, to_href)) self._sync_directory(to_collection._filesystem_path) if item.collection._filesystem_path != to_collection._filesystem_path: self._sync_directory(item.collection._filesystem_path) diff --git a/radicale/storage/multifilesystem/sync.py b/radicale/storage/multifilesystem/sync.py index 03fe773e..6d73e24a 100644 --- a/radicale/storage/multifilesystem/sync.py +++ b/radicale/storage/multifilesystem/sync.py @@ -21,16 +21,22 @@ import itertools import os import pickle from hashlib import sha256 +from typing import BinaryIO, Iterable, Tuple, cast from radicale.log import logger +from radicale.storage.multifilesystem.base import CollectionBase +from radicale.storage.multifilesystem.cache import CollectionPartCache +from radicale.storage.multifilesystem.history import CollectionPartHistory -class CollectionSyncMixin: - def sync(self, old_token=""): +class CollectionPartSync(CollectionPartCache, CollectionPartHistory, + CollectionBase): + + def sync(self, old_token: str = "") -> Tuple[str, Iterable[str]]: # The sync token has the form http://radicale.org/ns/sync/TOKEN_NAME # where TOKEN_NAME is the sha256 hash of all history etags of present # and past items of the collection. - def check_token_name(token_name): + def check_token_name(token_name: str) -> bool: if len(token_name) != 64: return False for c in token_name: @@ -89,15 +95,15 @@ class CollectionSyncMixin: self._storage._makedirs_synced(token_folder) try: # Race: Other processes might have created and locked the file. - with self._atomic_write(token_path, "wb") as f: - pickle.dump(state, f) + with self._atomic_write(token_path, "wb") as fo: + fb = cast(BinaryIO, fo) + pickle.dump(state, fb) except PermissionError: pass else: # clean up old sync tokens and item cache self._clean_cache(token_folder, os.listdir(token_folder), - max_age=self._storage.configuration.get( - "storage", "max_sync_token_age")) + max_age=self._max_sync_token_age) self._clean_history() else: # Try to update the modification time diff --git a/radicale/storage/multifilesystem/upload.py b/radicale/storage/multifilesystem/upload.py index cf0f9983..4d2be5f1 100644 --- a/radicale/storage/multifilesystem/upload.py +++ b/radicale/storage/multifilesystem/upload.py @@ -19,13 +19,21 @@ import os import pickle import sys +from typing import Iterable, Set, TextIO, cast import radicale.item as radicale_item from radicale import pathutils +from radicale.storage.multifilesystem.base import CollectionBase +from radicale.storage.multifilesystem.cache import CollectionPartCache +from radicale.storage.multifilesystem.get import CollectionPartGet +from radicale.storage.multifilesystem.history import CollectionPartHistory -class CollectionUploadMixin: - def upload(self, href, item): +class CollectionPartUpload(CollectionPartGet, CollectionPartCache, + CollectionPartHistory, CollectionBase): + + def upload(self, href: str, item: radicale_item.Item + ) -> radicale_item.Item: if not pathutils.is_safe_filesystem_path_component(href): raise pathutils.UnsafePathError(href) try: @@ -34,17 +42,22 @@ class CollectionUploadMixin: raise ValueError("Failed to store item %r in collection %r: %s" % (href, self.path, e)) from e path = pathutils.path_to_filesystem(self._filesystem_path, href) - with self._atomic_write(path, newline="") as fd: - fd.write(item.serialize()) + with self._atomic_write(path, newline="") as fo: + f = cast(TextIO, fo) + f.write(item.serialize()) # Clean the cache after the actual item is stored, or the cache entry # will be removed again. self._clean_item_cache() # Track the change self._update_history_etag(href, item) self._clean_history() - return self._get(href, verify_href=False) + uploaded_item = self._get(href, verify_href=False) + if uploaded_item is None: + raise RuntimeError("Storage modified externally") + return uploaded_item - def _upload_all_nonatomic(self, items, suffix=""): + def _upload_all_nonatomic(self, items: Iterable[radicale_item.Item], + suffix: str = "") -> None: """Upload a new set of items. This takes a list of vobject items and @@ -54,7 +67,7 @@ class CollectionUploadMixin: cache_folder = os.path.join(self._filesystem_path, ".Radicale.cache", "item") self._storage._makedirs_synced(cache_folder) - hrefs = set() + hrefs: Set[str] = set() for item in items: uid = item.uid try: @@ -92,14 +105,15 @@ class CollectionUploadMixin: sys.platform == "win32" and e.errno == 123): continue raise + assert href is not None and f is not None with f: f.write(item.serialize()) f.flush() self._storage._fsync(f) hrefs.add(href) - with open(os.path.join(cache_folder, href), "wb") as f: - pickle.dump(cache_content, f) - f.flush() - self._storage._fsync(f) + with open(os.path.join(cache_folder, href), "wb") as fb: + pickle.dump(cache_content, fb) + fb.flush() + self._storage._fsync(fb) self._storage._sync_directory(cache_folder) self._storage._sync_directory(self._filesystem_path) diff --git a/radicale/storage/multifilesystem/verify.py b/radicale/storage/multifilesystem/verify.py index 93a05099..dfdf5957 100644 --- a/radicale/storage/multifilesystem/verify.py +++ b/radicale/storage/multifilesystem/verify.py @@ -16,23 +16,27 @@ # You should have received a copy of the GNU General Public License # along with Radicale. If not, see . -import contextlib +from typing import Iterator, Optional, Set -from radicale import pathutils, storage +from radicale import pathutils, storage, types from radicale.log import logger +from radicale.storage.multifilesystem.base import StorageBase +from radicale.storage.multifilesystem.discover import StoragePartDiscover -class StorageVerifyMixin: - def verify(self): +class StoragePartVerify(StoragePartDiscover, StorageBase): + + def verify(self) -> bool: item_errors = collection_errors = 0 - @contextlib.contextmanager - def exception_cm(sane_path, href=None): + @types.contextmanager + def exception_cm(sane_path: str, href: Optional[str] + ) -> Iterator[None]: nonlocal item_errors, collection_errors try: yield except Exception as e: - if href: + if href is not None: item_errors += 1 name = "item %r in %r" % (href, sane_path) else: @@ -45,13 +49,14 @@ class StorageVerifyMixin: sane_path = remaining_sane_paths.pop(0) path = pathutils.unstrip_path(sane_path, True) logger.debug("Verifying collection %r", sane_path) - with exception_cm(sane_path): + with exception_cm(sane_path, None): saved_item_errors = item_errors - collection = None - uids = set() + collection: Optional[storage.BaseCollection] = None + uids: Set[str] = set() has_child_collections = False for item in self.discover(path, "1", exception_cm): if not collection: + assert isinstance(item, storage.BaseCollection) collection = item collection.get_meta() continue @@ -65,6 +70,7 @@ class StorageVerifyMixin: uids.add(item.uid) logger.debug("Verified item %r in %r", item.href, sane_path) + assert collection if item_errors == saved_item_errors: collection.sync() if has_child_collections and collection.tag: From 60f25bf19a566181a54075f8ae0942a85c7f0d66 Mon Sep 17 00:00:00 2001 From: Unrud Date: Mon, 26 Jul 2021 20:56:47 +0200 Subject: [PATCH 055/238] Type hints for tests --- radicale/tests/__init__.py | 152 ++++--- radicale/tests/custom/auth.py | 3 +- radicale/tests/custom/rights.py | 3 +- radicale/tests/custom/storage_simple_sync.py | 2 + radicale/tests/custom/web.py | 9 +- radicale/tests/helpers.py | 14 +- radicale/tests/test_auth.py | 68 ++- radicale/tests/test_base.py | 415 +++++++++++-------- radicale/tests/test_config.py | 61 +-- radicale/tests/test_rights.py | 40 +- radicale/tests/test_server.py | 89 ++-- radicale/tests/test_web.py | 24 +- 12 files changed, 501 insertions(+), 379 deletions(-) diff --git a/radicale/tests/__init__.py b/radicale/tests/__init__.py index f8900b1b..00e2b15d 100644 --- a/radicale/tests/__init__.py +++ b/radicale/tests/__init__.py @@ -22,13 +22,19 @@ Tests for Radicale. import base64 import logging +import shutil import sys +import tempfile +import xml.etree.ElementTree as ET from io import BytesIO +from typing import Any, Dict, List, Optional, Tuple, Union import defusedxml.ElementTree as DefusedET import radicale -from radicale import xmlutils +from radicale import app, config, xmlutils + +RESPONSES = Dict[str, Union[int, Dict[str, Tuple[int, ET.Element]]]] # Enable debug output radicale.log.logger.setLevel(logging.DEBUG) @@ -37,40 +43,70 @@ radicale.log.logger.setLevel(logging.DEBUG) class BaseTest: """Base class for tests.""" - def request(self, method, path, data=None, login=None, **args): + colpath: str + configuration: config.Configuration + application: app.Application + + def setup(self) -> None: + self.configuration = config.load() + self.colpath = tempfile.mkdtemp() + self.configuration.update({ + "storage": {"filesystem_folder": self.colpath, + # Disable syncing to disk for better performance + "_filesystem_fsync": "False"}, + # Set incorrect authentication delay to a short duration + "auth": {"delay": "0.001"}}, "test", privileged=True) + self.application = app.Application(self.configuration) + + def teardown(self) -> None: + shutil.rmtree(self.colpath) + + def request(self, method: str, path: str, data: Optional[str] = None, + **kwargs) -> Tuple[int, Dict[str, str], str]: """Send a request.""" - for key in args: - args[key.upper()] = args[key] + login = kwargs.pop("login", None) + if login is not None and not isinstance(login, str): + raise TypeError("login argument must be %r, not %r" % + (str, type(login))) + environ: Dict[str, Any] = {k.upper(): v for k, v in kwargs.items()} + for k, v in environ.items(): + if not isinstance(v, str): + raise TypeError("type of %r is %r, expected %r" % + (k, type(v), str)) + encoding: str = self.configuration.get("encoding", "request") if login: - args["HTTP_AUTHORIZATION"] = "Basic " + base64.b64encode( - login.encode()).decode() - args["REQUEST_METHOD"] = method.upper() - args["PATH_INFO"] = path + environ["HTTP_AUTHORIZATION"] = "Basic " + base64.b64encode( + login.encode(encoding)).decode() + environ["REQUEST_METHOD"] = method.upper() + environ["PATH_INFO"] = path if data: - data = data.encode() - args["wsgi.input"] = BytesIO(data) - args["CONTENT_LENGTH"] = str(len(data)) - args["wsgi.errors"] = sys.stderr + data_bytes = data.encode(encoding) + environ["wsgi.input"] = BytesIO(data_bytes) + environ["CONTENT_LENGTH"] = str(len(data_bytes)) + environ["wsgi.errors"] = sys.stderr status = headers = None - def start_response(status_, headers_): + def start_response(status_: str, headers_: List[Tuple[str, str]] + ) -> None: nonlocal status, headers status = status_ headers = headers_ - answer = self.application(args, start_response) + answers = list(self.application(environ, start_response)) + assert status is not None and headers is not None return (int(status.split()[0]), dict(headers), - answer[0].decode() if answer else None) + answers[0].decode() if answers else "") @staticmethod - def parse_responses(text): + def parse_responses(text: str) -> RESPONSES: xml = DefusedET.fromstring(text) assert xml.tag == xmlutils.make_clark("D:multistatus") - path_responses = {} + path_responses: Dict[str, Union[ + int, Dict[str, Tuple[int, ET.Element]]]] = {} for response in xml.findall(xmlutils.make_clark("D:response")): href = response.find(xmlutils.make_clark("D:href")) assert href.text not in path_responses - prop_respones = {} + prop_respones: Dict[str, Tuple[int, ET.Element]] = {} for propstat in response.findall( xmlutils.make_clark("D:propstat")): status = propstat.find(xmlutils.make_clark("D:status")) @@ -92,70 +128,90 @@ class BaseTest: return path_responses @staticmethod - def _check_status(status, good_status, check=True): - if check is True: - assert status == good_status - elif check is not False: - assert status == check + def _check_status(status: int, good_status: int, + check: Union[bool, int] = True) -> bool: + if check is not False: + expected = good_status if check is True else check + assert status == expected, "%d != %d" % (status, expected) return status == good_status - def get(self, path, check=True, **args): - status, _, answer = self.request("GET", path, **args) + def get(self, path: str, check: Union[bool, int] = True, **kwargs + ) -> Tuple[int, str]: + assert "data" not in kwargs + status, _, answer = self.request("GET", path, **kwargs) self._check_status(status, 200, check) return status, answer - def post(self, path, data=None, check=True, **args): - status, _, answer = self.request("POST", path, data, **args) + def post(self, path: str, data: str = None, check: Union[bool, int] = True, + **kwargs) -> Tuple[int, str]: + status, _, answer = self.request("POST", path, data, **kwargs) self._check_status(status, 200, check) return status, answer - def put(self, path, data, check=True, **args): - status, _, answer = self.request("PUT", path, data, **args) + def put(self, path: str, data: str, check: Union[bool, int] = True, + **kwargs) -> Tuple[int, str]: + status, _, answer = self.request("PUT", path, data, **kwargs) self._check_status(status, 201, check) return status, answer - def propfind(self, path, data=None, check=True, **args): - status, _, answer = self.request("PROPFIND", path, data, **args) + def propfind(self, path: str, data: Optional[str] = None, + check: Union[bool, int] = True, **kwargs + ) -> Tuple[int, RESPONSES]: + status, _, answer = self.request("PROPFIND", path, data, **kwargs) if not self._check_status(status, 207, check): - return status, None + return status, {} + assert answer is not None responses = self.parse_responses(answer) - if args.get("HTTP_DEPTH", "0") == "0": + if kwargs.get("HTTP_DEPTH", "0") == "0": assert len(responses) == 1 and path in responses return status, responses - def proppatch(self, path, data=None, check=True, **args): - status, _, answer = self.request("PROPPATCH", path, data, **args) + def proppatch(self, path: str, data: Optional[str] = None, + check: Union[bool, int] = True, **kwargs + ) -> Tuple[int, RESPONSES]: + status, _, answer = self.request("PROPPATCH", path, data, **kwargs) if not self._check_status(status, 207, check): - return status, None + return status, {} + assert answer is not None responses = self.parse_responses(answer) assert len(responses) == 1 and path in responses return status, responses - def report(self, path, data, check=True, **args): - status, _, answer = self.request("REPORT", path, data, **args) + def report(self, path: str, data: str, check: Union[bool, int] = True, + **kwargs) -> Tuple[int, RESPONSES]: + status, _, answer = self.request("REPORT", path, data, **kwargs) if not self._check_status(status, 207, check): - return status, None + return status, {} + assert answer is not None return status, self.parse_responses(answer) - def delete(self, path, check=True, **args): - status, _, answer = self.request("DELETE", path, **args) + def delete(self, path: str, check: Union[bool, int] = True, **kwargs + ) -> Tuple[int, RESPONSES]: + assert "data" not in kwargs + status, _, answer = self.request("DELETE", path, **kwargs) if not self._check_status(status, 200, check): - return status, None + return status, {} + assert answer is not None responses = self.parse_responses(answer) assert len(responses) == 1 and path in responses return status, responses - def mkcalendar(self, path, data=None, check=True, **args): - status, _, answer = self.request("MKCALENDAR", path, data, **args) + def mkcalendar(self, path: str, data: Optional[str] = None, + check: Union[bool, int] = True, **kwargs + ) -> Tuple[int, str]: + status, _, answer = self.request("MKCALENDAR", path, data, **kwargs) self._check_status(status, 201, check) return status, answer - def mkcol(self, path, data=None, check=True, **args): - status, _, _ = self.request("MKCOL", path, data, **args) + def mkcol(self, path: str, data: Optional[str] = None, + check: Union[bool, int] = True, **kwargs) -> int: + status, _, _ = self.request("MKCOL", path, data, **kwargs) self._check_status(status, 201, check) return status - def create_addressbook(self, path, check=True, **args): + def create_addressbook(self, path: str, check: Union[bool, int] = True, + **kwargs) -> int: + assert "data" not in kwargs return self.mkcol(path, """\ @@ -167,4 +223,4 @@ class BaseTest: -""", check=check, **args) +""", check=check, **kwargs) diff --git a/radicale/tests/custom/auth.py b/radicale/tests/custom/auth.py index b0a11726..8e17adc1 100644 --- a/radicale/tests/custom/auth.py +++ b/radicale/tests/custom/auth.py @@ -28,7 +28,8 @@ from radicale import auth class Auth(auth.BaseAuth): - def login(self, login, password): + + def login(self, login: str, password: str) -> str: if login == "tmp": return login return "" diff --git a/radicale/tests/custom/rights.py b/radicale/tests/custom/rights.py index 5696ad53..8f145dd1 100644 --- a/radicale/tests/custom/rights.py +++ b/radicale/tests/custom/rights.py @@ -23,7 +23,8 @@ from radicale import pathutils, rights class Rights(rights.BaseRights): - def authorization(self, user, path): + + def authorization(self, user: str, path: str) -> str: sane_path = pathutils.strip_path(path) if sane_path not in ("tmp", "other"): return "" diff --git a/radicale/tests/custom/storage_simple_sync.py b/radicale/tests/custom/storage_simple_sync.py index 3046a829..7e023f02 100644 --- a/radicale/tests/custom/storage_simple_sync.py +++ b/radicale/tests/custom/storage_simple_sync.py @@ -27,8 +27,10 @@ from radicale.storage import BaseCollection, multifilesystem class Collection(multifilesystem.Collection): + sync = BaseCollection.sync class Storage(multifilesystem.Storage): + _collection_class = Collection diff --git a/radicale/tests/custom/web.py b/radicale/tests/custom/web.py index 784614f4..2626e051 100644 --- a/radicale/tests/custom/web.py +++ b/radicale/tests/custom/web.py @@ -21,13 +21,16 @@ Custom web plugin. from http import client -from radicale import httputils, web +from radicale import httputils, types, web class Web(web.BaseWeb): - def get(self, environ, base_prefix, path, user): + + def get(self, environ: types.WSGIEnviron, base_prefix: str, path: str, + user: str) -> types.WSGIResponse: return client.OK, {"Content-Type": "text/plain"}, "custom" - def post(self, environ, base_prefix, path, user): + def post(self, environ: types.WSGIEnviron, base_prefix: str, path: str, + user: str) -> types.WSGIResponse: content = httputils.read_request_body(self.configuration, environ) return client.OK, {"Content-Type": "text/plain"}, "echo:" + content diff --git a/radicale/tests/helpers.py b/radicale/tests/helpers.py index face22ba..3d2d13b4 100644 --- a/radicale/tests/helpers.py +++ b/radicale/tests/helpers.py @@ -26,19 +26,21 @@ This module offers helpers to use in tests. import os -EXAMPLES_FOLDER = os.path.join(os.path.dirname(__file__), "static") +from radicale import config, types + +EXAMPLES_FOLDER: str = os.path.join(os.path.dirname(__file__), "static") -def get_file_path(file_name): +def get_file_path(file_name: str) -> str: return os.path.join(EXAMPLES_FOLDER, file_name) -def get_file_content(file_name): - with open(get_file_path(file_name), encoding="utf-8") as fd: - return fd.read() +def get_file_content(file_name: str) -> str: + with open(get_file_path(file_name), encoding="utf-8") as f: + return f.read() -def configuration_to_dict(configuration): +def configuration_to_dict(configuration: config.Configuration) -> types.CONFIG: """Convert configuration to a dict with raw values.""" return {section: {option: configuration.get_raw(section, option) for option in configuration.options(section) diff --git a/radicale/tests/test_auth.py b/radicale/tests/test_auth.py index 5379be72..d2f52daa 100644 --- a/radicale/tests/test_auth.py +++ b/radicale/tests/test_auth.py @@ -22,13 +22,12 @@ Radicale tests with simple requests and authentication. """ import os -import shutil import sys -import tempfile +from typing import Iterable, Tuple, Union import pytest -from radicale import Application, config, xmlutils +from radicale import Application, xmlutils from radicale.tests import BaseTest @@ -38,21 +37,10 @@ class TestBaseAuthRequests(BaseTest): We should setup auth for each type before creating the Application object. """ - def setup(self): - self.configuration = config.load() - self.colpath = tempfile.mkdtemp() - self.configuration.update({ - "storage": {"filesystem_folder": self.colpath, - # Disable syncing to disk for better performance - "_filesystem_fsync": "False"}, - # Set incorrect authentication delay to a very low value - "auth": {"delay": "0.002"}}, "test", privileged=True) - def teardown(self): - shutil.rmtree(self.colpath) - - def _test_htpasswd(self, htpasswd_encryption, htpasswd_content, - test_matrix="ascii"): + def _test_htpasswd(self, htpasswd_encryption: str, htpasswd_content: str, + test_matrix: Union[str, Iterable[Tuple[str, str, bool]]] + = "ascii") -> None: """Test htpasswd authentication with user "tmp" and password "bepo" for ``test_matrix`` "ascii" or user "😀" and password "🔑" for ``test_matrix`` "unicode".""" @@ -67,7 +55,7 @@ class TestBaseAuthRequests(BaseTest): except MissingBackendError: pytest.skip("bcrypt backend for passlib is not installed") htpasswd_file_path = os.path.join(self.colpath, ".htpasswd") - encoding = self.configuration.get("encoding", "stock") + encoding: str = self.configuration.get("encoding", "stock") with open(htpasswd_file_path, "w", encoding=encoding) as f: f.write(htpasswd_content) self.configuration.update({ @@ -83,54 +71,56 @@ class TestBaseAuthRequests(BaseTest): test_matrix = (("😀", "🔑", True), ("😀", "🌹", False), ("😁", "🔑", False), ("😀", "", False), ("", "🔑", False), ("", "", False)) + elif isinstance(test_matrix, str): + raise ValueError("Unknown test matrix %r" % test_matrix) for user, password, valid in test_matrix: self.propfind("/", check=207 if valid else 401, login="%s:%s" % (user, password)) - def test_htpasswd_plain(self): + def test_htpasswd_plain(self) -> None: self._test_htpasswd("plain", "tmp:bepo") - def test_htpasswd_plain_password_split(self): + def test_htpasswd_plain_password_split(self) -> None: self._test_htpasswd("plain", "tmp:be:po", ( ("tmp", "be:po", True), ("tmp", "bepo", False))) - def test_htpasswd_plain_unicode(self): + def test_htpasswd_plain_unicode(self) -> None: self._test_htpasswd("plain", "😀:🔑", "unicode") - def test_htpasswd_md5(self): + def test_htpasswd_md5(self) -> None: self._test_htpasswd("md5", "tmp:$apr1$BI7VKCZh$GKW4vq2hqDINMr8uv7lDY/") def test_htpasswd_md5_unicode(self): self._test_htpasswd( "md5", "😀:$apr1$w4ev89r1$29xO8EvJmS2HEAadQ5qy11", "unicode") - def test_htpasswd_bcrypt(self): + def test_htpasswd_bcrypt(self) -> None: self._test_htpasswd("bcrypt", "tmp:$2y$05$oD7hbiQFQlvCM7zoalo/T.MssV3V" "NTRI3w5KDnj8NTUKJNWfVpvRq") - def test_htpasswd_bcrypt_unicode(self): + def test_htpasswd_bcrypt_unicode(self) -> None: self._test_htpasswd("bcrypt", "😀:$2y$10$Oyz5aHV4MD9eQJbk6GPemOs4T6edK" "6U9Sqlzr.W1mMVCS8wJUftnW", "unicode") - def test_htpasswd_multi(self): + def test_htpasswd_multi(self) -> None: self._test_htpasswd("plain", "ign:ign\ntmp:bepo") @pytest.mark.skipif(sys.platform == "win32", reason="leading and trailing " "whitespaces not allowed in file names") - def test_htpasswd_whitespace_user(self): + def test_htpasswd_whitespace_user(self) -> None: for user in (" tmp", "tmp ", " tmp "): self._test_htpasswd("plain", "%s:bepo" % user, ( (user, "bepo", True), ("tmp", "bepo", False))) - def test_htpasswd_whitespace_password(self): + def test_htpasswd_whitespace_password(self) -> None: for password in (" bepo", "bepo ", " bepo "): self._test_htpasswd("plain", "tmp:%s" % password, ( ("tmp", password, True), ("tmp", "bepo", False))) - def test_htpasswd_comment(self): + def test_htpasswd_comment(self) -> None: self._test_htpasswd("plain", "#comment\n #comment\n \ntmp:bepo\n\n") - def test_remote_user(self): + def test_remote_user(self) -> None: self.configuration.update({"auth": {"type": "remote_user"}}, "test") self.application = Application(self.configuration) _, responses = self.propfind("/", """\ @@ -140,11 +130,15 @@ class TestBaseAuthRequests(BaseTest): """, REMOTE_USER="test") - status, prop = responses["/"]["D:current-user-principal"] + assert responses is not None + response = responses["/"] + assert not isinstance(response, int) + status, prop = response["D:current-user-principal"] assert status == 200 - assert prop.find(xmlutils.make_clark("D:href")).text == "/test/" + href_element = prop.find(xmlutils.make_clark("D:href")) + assert href_element is not None and href_element.text == "/test/" - def test_http_x_remote_user(self): + def test_http_x_remote_user(self) -> None: self.configuration.update( {"auth": {"type": "http_x_remote_user"}}, "test") self.application = Application(self.configuration) @@ -155,11 +149,15 @@ class TestBaseAuthRequests(BaseTest): """, HTTP_X_REMOTE_USER="test") - status, prop = responses["/"]["D:current-user-principal"] + assert responses is not None + response = responses["/"] + assert not isinstance(response, int) + status, prop = response["D:current-user-principal"] assert status == 200 - assert prop.find(xmlutils.make_clark("D:href")).text == "/test/" + href_element = prop.find(xmlutils.make_clark("D:href")) + assert href_element is not None and href_element.text == "/test/" - def test_custom(self): + def test_custom(self) -> None: """Custom authentication.""" self.configuration.update( {"auth": {"type": "radicale.tests.custom.auth"}}, "test") diff --git a/radicale/tests/test_base.py b/radicale/tests/test_base.py index 5952615f..4e8cd113 100644 --- a/radicale/tests/test_base.py +++ b/radicale/tests/test_base.py @@ -24,37 +24,39 @@ import os import posixpath import shutil import sys -import tempfile -from typing import Any, ClassVar +from typing import (Any, Callable, ClassVar, Iterable, List, Optional, Tuple, + Union) import defusedxml.ElementTree as DefusedET import pytest import radicale.tests.custom.storage_simple_sync from radicale import Application, config, storage, xmlutils -from radicale.tests import BaseTest +from radicale.tests import RESPONSES, BaseTest from radicale.tests.helpers import get_file_content +StorageType = Union[str, Callable[[config.Configuration], storage.BaseStorage]] -class BaseRequestsMixIn: + +class BaseRequestsMixIn(BaseTest): """Tests with simple requests.""" # Allow skipping sync-token tests, when not fully supported by the backend - full_sync_token_support = True + full_sync_token_support: ClassVar[bool] = True - def test_root(self): + def test_root(self) -> None: """GET request at "/".""" _, answer = self.get("/", check=302) assert answer == "Redirected to .web" - def test_script_name(self): + def test_script_name(self) -> None: """GET request at "/" with SCRIPT_NAME.""" _, answer = self.get("/", check=302, SCRIPT_NAME="/radicale") assert answer == "Redirected to .web" _, answer = self.get("", check=302, SCRIPT_NAME="/radicale") assert answer == "Redirected to radicale/.web" - def test_add_event(self): + def test_add_event(self) -> None: """Add an event.""" self.mkcalendar("/calendar.ics/") event = get_file_content("event1.ics") @@ -68,7 +70,7 @@ class BaseRequestsMixIn: assert "Event" in answer assert "UID:event" in answer - def test_add_event_without_uid(self): + def test_add_event_without_uid(self) -> None: """Add an event without UID.""" self.mkcalendar("/calendar.ics/") event = get_file_content("event1.ics").replace("UID:event1\n", "") @@ -76,7 +78,7 @@ class BaseRequestsMixIn: path = "/calendar.ics/event.ics" self.put(path, event, check=400) - def test_add_event_duplicate_uid(self): + def test_add_event_duplicate_uid(self) -> None: """Add an event with an existing UID.""" self.mkcalendar("/calendar.ics/") event = get_file_content("event1.ics") @@ -88,7 +90,7 @@ class BaseRequestsMixIn: assert xml.tag == xmlutils.make_clark("D:error") assert xml.find(xmlutils.make_clark("C:no-uid-conflict")) is not None - def test_add_todo(self): + def test_add_todo(self) -> None: """Add a todo.""" self.mkcalendar("/calendar.ics/") todo = get_file_content("todo1.ics") @@ -102,7 +104,7 @@ class BaseRequestsMixIn: assert "Todo" in answer assert "UID:todo" in answer - def test_add_contact(self): + def test_add_contact(self) -> None: """Add a contact.""" self.create_addressbook("/contacts.vcf/") contact = get_file_content("contact1.vcf") @@ -117,7 +119,7 @@ class BaseRequestsMixIn: _, answer = self.get(path) assert "UID:contact1" in answer - def test_add_contact_without_uid(self): + def test_add_contact_without_uid(self) -> None: """Add a contact without UID.""" self.create_addressbook("/contacts.vcf/") contact = get_file_content("contact1.vcf").replace("UID:contact1\n", @@ -126,7 +128,7 @@ class BaseRequestsMixIn: path = "/contacts.vcf/contact.vcf" self.put(path, contact, check=400) - def test_update_event(self): + def test_update_event(self) -> None: """Update an event.""" self.mkcalendar("/calendar.ics/") event = get_file_content("event1.ics") @@ -139,7 +141,7 @@ class BaseRequestsMixIn: _, answer = self.get(path) assert "DTSTAMP:20130902T150159Z" in answer - def test_update_event_uid_event(self): + def test_update_event_uid_event(self) -> None: """Update an event with a different UID.""" self.mkcalendar("/calendar.ics/") event1 = get_file_content("event1.ics") @@ -152,7 +154,7 @@ class BaseRequestsMixIn: assert xml.tag == xmlutils.make_clark("D:error") assert xml.find(xmlutils.make_clark("C:no-uid-conflict")) is not None - def test_put_whole_calendar(self): + def test_put_whole_calendar(self) -> None: """Create and overwrite a whole calendar.""" self.put("/calendar.ics/", "BEGIN:VCALENDAR\r\nEND:VCALENDAR") event1 = get_file_content("event1.ics") @@ -165,7 +167,7 @@ class BaseRequestsMixIn: assert "\r\nUID:event\r\n" in answer and "\r\nUID:todo\r\n" in answer assert "\r\nUID:event1\r\n" not in answer - def test_put_whole_calendar_without_uids(self): + def test_put_whole_calendar_without_uids(self) -> None: """Create a whole calendar without UID.""" event = get_file_content("event_multiple.ics") event = event.replace("UID:event\n", "").replace("UID:todo\n", "") @@ -182,15 +184,16 @@ class BaseRequestsMixIn: for uid2 in uids[i + 1:]: assert uid1 != uid2 - def test_put_whole_addressbook(self): + def test_put_whole_addressbook(self) -> None: """Create and overwrite a whole addressbook.""" contacts = get_file_content("contact_multiple.vcf") self.put("/contacts.vcf/", contacts) _, answer = self.get("/contacts.vcf/") - assert ("\r\nUID:contact1\r\n" in answer and - "\r\nUID:contact2\r\n" in answer) + assert answer is not None + assert "\r\nUID:contact1\r\n" in answer + assert "\r\nUID:contact2\r\n" in answer - def test_put_whole_addressbook_without_uids(self): + def test_put_whole_addressbook_without_uids(self) -> None: """Create a whole addressbook without UID.""" contacts = get_file_content("contact_multiple.vcf") contacts = contacts.replace("UID:contact1\n", "").replace( @@ -208,7 +211,7 @@ class BaseRequestsMixIn: for uid2 in uids[i + 1:]: assert uid1 != uid2 - def test_verify(self): + def test_verify(self) -> None: """Verify the storage.""" contacts = get_file_content("contact_multiple.vcf") self.put("/contacts.vcf/", contacts) @@ -217,7 +220,7 @@ class BaseRequestsMixIn: s = storage.load(self.configuration) assert s.verify() - def test_delete(self): + def test_delete(self) -> None: """Delete an event.""" self.mkcalendar("/calendar.ics/") event = get_file_content("event1.ics") @@ -228,14 +231,14 @@ class BaseRequestsMixIn: _, answer = self.get("/calendar.ics/") assert "VEVENT" not in answer - def test_mkcalendar(self): + def test_mkcalendar(self) -> None: """Make a calendar.""" self.mkcalendar("/calendar.ics/") _, answer = self.get("/calendar.ics/") assert "BEGIN:VCALENDAR" in answer assert "END:VCALENDAR" in answer - def test_mkcalendar_overwrite(self): + def test_mkcalendar_overwrite(self) -> None: """Try to overwrite an existing calendar.""" self.mkcalendar("/calendar.ics/") status, answer = self.mkcalendar("/calendar.ics/", check=False) @@ -245,41 +248,43 @@ class BaseRequestsMixIn: assert xml.find(xmlutils.make_clark( "D:resource-must-be-null")) is not None - def test_mkcalendar_intermediate(self): + def test_mkcalendar_intermediate(self) -> None: """Try make a calendar in a unmapped collection.""" status, _ = self.mkcalendar("/unmapped/calendar.ics/", check=False) assert status == 409 - def test_mkcol(self): + def test_mkcol(self) -> None: """Make a collection.""" self.mkcol("/user/") - def test_mkcol_overwrite(self): + def test_mkcol_overwrite(self) -> None: """Try to overwrite an existing collection.""" self.mkcol("/user/") status = self.mkcol("/user/", check=False) assert status == 405 - def test_mkcol_intermediate(self): + def test_mkcol_intermediate(self) -> None: """Try make a collection in a unmapped collection.""" status = self.mkcol("/unmapped/user/", check=False) assert status == 409 - def test_mkcol_make_calendar(self): + def test_mkcol_make_calendar(self) -> None: """Make a calendar with additional props.""" mkcol_make_calendar = get_file_content("mkcol_make_calendar.xml") self.mkcol("/calendar.ics/", mkcol_make_calendar) _, answer = self.get("/calendar.ics/") + assert answer is not None assert "BEGIN:VCALENDAR" in answer assert "END:VCALENDAR" in answer # Read additional properties propfind = get_file_content("propfind_calendar_color.xml") _, responses = self.propfind("/calendar.ics/", propfind) - assert len(responses["/calendar.ics/"]) == 1 - status, prop = responses["/calendar.ics/"]["ICAL:calendar-color"] + response = responses["/calendar.ics/"] + assert not isinstance(response, int) and len(response) == 1 + status, prop = response["ICAL:calendar-color"] assert status == 200 and prop.text == "#BADA55" - def test_move(self): + def test_move(self) -> None: """Move a item.""" self.mkcalendar("/calendar.ics/") event = get_file_content("event1.ics") @@ -292,7 +297,7 @@ class BaseRequestsMixIn: self.get(path1, check=404) self.get(path2) - def test_move_between_colections(self): + def test_move_between_colections(self) -> None: """Move a item.""" self.mkcalendar("/calendar1.ics/") self.mkcalendar("/calendar2.ics/") @@ -306,7 +311,7 @@ class BaseRequestsMixIn: self.get(path1, check=404) self.get(path2) - def test_move_between_colections_duplicate_uid(self): + def test_move_between_colections_duplicate_uid(self) -> None: """Move a item to a collection which already contains the UID.""" self.mkcalendar("/calendar1.ics/") self.mkcalendar("/calendar2.ics/") @@ -322,7 +327,7 @@ class BaseRequestsMixIn: assert xml.tag == xmlutils.make_clark("D:error") assert xml.find(xmlutils.make_clark("C:no-uid-conflict")) is not None - def test_move_between_colections_overwrite(self): + def test_move_between_colections_overwrite(self) -> None: """Move a item to a collection which already contains the item.""" self.mkcalendar("/calendar1.ics/") self.mkcalendar("/calendar2.ics/") @@ -338,7 +343,7 @@ class BaseRequestsMixIn: HTTP_HOST="", HTTP_OVERWRITE="T") assert status == 204 - def test_move_between_colections_overwrite_uid_conflict(self): + def test_move_between_colections_overwrite_uid_conflict(self) -> None: """Move a item to a collection which already contains the item with a different UID.""" self.mkcalendar("/calendar1.ics/") @@ -356,16 +361,16 @@ class BaseRequestsMixIn: assert xml.tag == xmlutils.make_clark("D:error") assert xml.find(xmlutils.make_clark("C:no-uid-conflict")) is not None - def test_head(self): + def test_head(self) -> None: status, _, _ = self.request("HEAD", "/") assert status == 302 - def test_options(self): + def test_options(self) -> None: status, headers, _ = self.request("OPTIONS", "/") assert status == 200 assert "DAV" in headers - def test_delete_collection(self): + def test_delete_collection(self) -> None: """Delete a collection.""" self.mkcalendar("/calendar.ics/") event = get_file_content("event1.ics") @@ -374,7 +379,7 @@ class BaseRequestsMixIn: assert responses["/calendar.ics/"] == 200 self.get("/calendar.ics/", check=404) - def test_delete_root_collection(self): + def test_delete_root_collection(self) -> None: """Delete the root collection.""" self.mkcalendar("/calendar.ics/") event = get_file_content("event1.ics") @@ -385,7 +390,7 @@ class BaseRequestsMixIn: self.get("/calendar.ics/", check=404) self.get("/event1.ics", 404) - def test_propfind(self): + def test_propfind(self) -> None: calendar_path = "/calendar.ics/" self.mkcalendar("/calendar.ics/") event = get_file_content("event1.ics") @@ -398,139 +403,163 @@ class BaseRequestsMixIn: assert len(responses) == 2 assert calendar_path in responses and event_path in responses - def test_propfind_propname(self): + def test_propfind_propname(self) -> None: self.mkcalendar("/calendar.ics/") event = get_file_content("event1.ics") self.put("/calendar.ics/event.ics", event) propfind = get_file_content("propname.xml") _, responses = self.propfind("/calendar.ics/", propfind) - status, prop = responses["/calendar.ics/"]["D:sync-token"] + response = responses["/calendar.ics/"] + assert not isinstance(response, int) + status, prop = response["D:sync-token"] assert status == 200 and not prop.text _, responses = self.propfind("/calendar.ics/event.ics", propfind) - status, prop = responses["/calendar.ics/event.ics"]["D:getetag"] + response = responses["/calendar.ics/event.ics"] + assert not isinstance(response, int) + status, prop = response["D:getetag"] assert status == 200 and not prop.text - def test_propfind_allprop(self): + def test_propfind_allprop(self) -> None: self.mkcalendar("/calendar.ics/") event = get_file_content("event1.ics") self.put("/calendar.ics/event.ics", event) propfind = get_file_content("allprop.xml") _, responses = self.propfind("/calendar.ics/", propfind) - status, prop = responses["/calendar.ics/"]["D:sync-token"] + response = responses["/calendar.ics/"] + assert not isinstance(response, int) + status, prop = response["D:sync-token"] assert status == 200 and prop.text _, responses = self.propfind("/calendar.ics/event.ics", propfind) - status, prop = responses["/calendar.ics/event.ics"]["D:getetag"] + response = responses["/calendar.ics/event.ics"] + assert not isinstance(response, int) + status, prop = response["D:getetag"] assert status == 200 and prop.text - def test_propfind_nonexistent(self): + def test_propfind_nonexistent(self) -> None: """Read a property that does not exist.""" self.mkcalendar("/calendar.ics/") propfind = get_file_content("propfind_calendar_color.xml") _, responses = self.propfind("/calendar.ics/", propfind) - assert len(responses["/calendar.ics/"]) == 1 - status, prop = responses["/calendar.ics/"]["ICAL:calendar-color"] + response = responses["/calendar.ics/"] + assert not isinstance(response, int) and len(response) == 1 + status, prop = response["ICAL:calendar-color"] assert status == 404 and not prop.text - def test_proppatch(self): + def test_proppatch(self) -> None: """Set/Remove a property and read it back.""" self.mkcalendar("/calendar.ics/") proppatch = get_file_content("proppatch_set_calendar_color.xml") _, responses = self.proppatch("/calendar.ics/", proppatch) - assert len(responses["/calendar.ics/"]) == 1 - status, prop = responses["/calendar.ics/"]["ICAL:calendar-color"] + response = responses["/calendar.ics/"] + assert not isinstance(response, int) and len(response) == 1 + status, prop = response["ICAL:calendar-color"] assert status == 200 and not prop.text # Read property back propfind = get_file_content("propfind_calendar_color.xml") _, responses = self.propfind("/calendar.ics/", propfind) - assert len(responses["/calendar.ics/"]) == 1 - status, prop = responses["/calendar.ics/"]["ICAL:calendar-color"] + response = responses["/calendar.ics/"] + assert not isinstance(response, int) and len(response) == 1 + status, prop = response["ICAL:calendar-color"] assert status == 200 and prop.text == "#BADA55" propfind = get_file_content("allprop.xml") _, responses = self.propfind("/calendar.ics/", propfind) - status, prop = responses["/calendar.ics/"]["ICAL:calendar-color"] + response = responses["/calendar.ics/"] + assert not isinstance(response, int) + status, prop = response["ICAL:calendar-color"] assert status == 200 and prop.text == "#BADA55" # Remove property proppatch = get_file_content("proppatch_remove_calendar_color.xml") _, responses = self.proppatch("/calendar.ics/", proppatch) - assert len(responses["/calendar.ics/"]) == 1 - status, prop = responses["/calendar.ics/"]["ICAL:calendar-color"] + response = responses["/calendar.ics/"] + assert not isinstance(response, int) and len(response) == 1 + status, prop = response["ICAL:calendar-color"] assert status == 200 and not prop.text # Read property back propfind = get_file_content("propfind_calendar_color.xml") _, responses = self.propfind("/calendar.ics/", propfind) - assert len(responses["/calendar.ics/"]) == 1 - status, prop = responses["/calendar.ics/"]["ICAL:calendar-color"] + response = responses["/calendar.ics/"] + assert not isinstance(response, int) and len(response) == 1 + status, prop = response["ICAL:calendar-color"] assert status == 404 - def test_proppatch_multiple1(self): + def test_proppatch_multiple1(self) -> None: """Set/Remove a multiple properties and read them back.""" self.mkcalendar("/calendar.ics/") propfind = get_file_content("propfind_multiple.xml") proppatch = get_file_content("proppatch_set_multiple1.xml") _, responses = self.proppatch("/calendar.ics/", proppatch) - assert len(responses["/calendar.ics/"]) == 2 - status, prop = responses["/calendar.ics/"]["ICAL:calendar-color"] + response = responses["/calendar.ics/"] + assert not isinstance(response, int) and len(response) == 2 + status, prop = response["ICAL:calendar-color"] assert status == 200 and not prop.text - status, prop = responses["/calendar.ics/"]["C:calendar-description"] + status, prop = response["C:calendar-description"] assert status == 200 and not prop.text # Read properties back _, responses = self.propfind("/calendar.ics/", propfind) - assert len(responses["/calendar.ics/"]) == 2 - status, prop = responses["/calendar.ics/"]["ICAL:calendar-color"] + response = responses["/calendar.ics/"] + assert not isinstance(response, int) and len(response) == 2 + status, prop = response["ICAL:calendar-color"] assert status == 200 and prop.text == "#BADA55" - status, prop = responses["/calendar.ics/"]["C:calendar-description"] + status, prop = response["C:calendar-description"] assert status == 200 and prop.text == "test" # Remove properties proppatch = get_file_content("proppatch_remove_multiple1.xml") _, responses = self.proppatch("/calendar.ics/", proppatch) - assert len(responses["/calendar.ics/"]) == 2 - status, prop = responses["/calendar.ics/"]["ICAL:calendar-color"] + response = responses["/calendar.ics/"] + assert not isinstance(response, int) and len(response) == 2 + status, prop = response["ICAL:calendar-color"] assert status == 200 and not prop.text - status, prop = responses["/calendar.ics/"]["C:calendar-description"] + status, prop = response["C:calendar-description"] assert status == 200 and not prop.text # Read properties back _, responses = self.propfind("/calendar.ics/", propfind) - assert len(responses["/calendar.ics/"]) == 2 - status, prop = responses["/calendar.ics/"]["ICAL:calendar-color"] + response = responses["/calendar.ics/"] + assert not isinstance(response, int) and len(response) == 2 + status, prop = response["ICAL:calendar-color"] assert status == 404 - status, prop = responses["/calendar.ics/"]["C:calendar-description"] + status, prop = response["C:calendar-description"] assert status == 404 - def test_proppatch_multiple2(self): + def test_proppatch_multiple2(self) -> None: """Set/Remove a multiple properties and read them back.""" self.mkcalendar("/calendar.ics/") propfind = get_file_content("propfind_multiple.xml") proppatch = get_file_content("proppatch_set_multiple2.xml") _, responses = self.proppatch("/calendar.ics/", proppatch) - assert len(responses["/calendar.ics/"]) == 2 - status, prop = responses["/calendar.ics/"]["ICAL:calendar-color"] + response = responses["/calendar.ics/"] + assert not isinstance(response, int) and len(response) == 2 + status, prop = response["ICAL:calendar-color"] assert status == 200 and not prop.text - status, prop = responses["/calendar.ics/"]["C:calendar-description"] + status, prop = response["C:calendar-description"] assert status == 200 and not prop.text # Read properties back _, responses = self.propfind("/calendar.ics/", propfind) - assert len(responses["/calendar.ics/"]) == 2 - status, prop = responses["/calendar.ics/"]["ICAL:calendar-color"] + response = responses["/calendar.ics/"] + assert not isinstance(response, int) and len(response) == 2 + assert len(response) == 2 + status, prop = response["ICAL:calendar-color"] assert status == 200 and prop.text == "#BADA55" - status, prop = responses["/calendar.ics/"]["C:calendar-description"] + status, prop = response["C:calendar-description"] assert status == 200 and prop.text == "test" # Remove properties proppatch = get_file_content("proppatch_remove_multiple2.xml") _, responses = self.proppatch("/calendar.ics/", proppatch) - assert len(responses["/calendar.ics/"]) == 2 - status, prop = responses["/calendar.ics/"]["ICAL:calendar-color"] + response = responses["/calendar.ics/"] + assert not isinstance(response, int) and len(response) == 2 + status, prop = response["ICAL:calendar-color"] assert status == 200 and not prop.text - status, prop = responses["/calendar.ics/"]["C:calendar-description"] + status, prop = response["C:calendar-description"] assert status == 200 and not prop.text # Read properties back _, responses = self.propfind("/calendar.ics/", propfind) - assert len(responses["/calendar.ics/"]) == 2 - status, prop = responses["/calendar.ics/"]["ICAL:calendar-color"] + response = responses["/calendar.ics/"] + assert not isinstance(response, int) and len(response) == 2 + status, prop = response["ICAL:calendar-color"] assert status == 404 - status, prop = responses["/calendar.ics/"]["C:calendar-description"] + status, prop = response["C:calendar-description"] assert status == 404 - def test_proppatch_set_and_remove(self): + def test_proppatch_set_and_remove(self) -> None: """Set and remove multiple properties in single request.""" self.mkcalendar("/calendar.ics/") propfind = get_file_content("propfind_multiple.xml") @@ -540,20 +569,22 @@ class BaseRequestsMixIn: # Remove and set properties in single request proppatch = get_file_content("proppatch_set_and_remove.xml") _, responses = self.proppatch("/calendar.ics/", proppatch) - assert len(responses["/calendar.ics/"]) == 2 - status, prop = responses["/calendar.ics/"]["ICAL:calendar-color"] + response = responses["/calendar.ics/"] + assert not isinstance(response, int) and len(response) == 2 + status, prop = response["ICAL:calendar-color"] assert status == 200 and not prop.text - status, prop = responses["/calendar.ics/"]["C:calendar-description"] + status, prop = response["C:calendar-description"] assert status == 200 and not prop.text # Read properties back _, responses = self.propfind("/calendar.ics/", propfind) - assert len(responses["/calendar.ics/"]) == 2 - status, prop = responses["/calendar.ics/"]["ICAL:calendar-color"] + response = responses["/calendar.ics/"] + assert not isinstance(response, int) and len(response) == 2 + status, prop = response["ICAL:calendar-color"] assert status == 404 - status, prop = responses["/calendar.ics/"]["C:calendar-description"] + status, prop = response["C:calendar-description"] assert status == 200 and prop.text == "test2" - def test_put_whole_calendar_multiple_events_with_same_uid(self): + def test_put_whole_calendar_multiple_events_with_same_uid(self) -> None: """Add two events with the same UID.""" self.put("/calendar.ics/", get_file_content("event2.ics")) _, responses = self.report("/calendar.ics/", """\ @@ -564,13 +595,18 @@ class BaseRequestsMixIn: """) assert len(responses) == 1 - status, prop = responses["/calendar.ics/event2.ics"]["D:getetag"] + response = responses["/calendar.ics/event2.ics"] + assert not isinstance(response, int) + status, prop = response["D:getetag"] assert status == 200 and prop.text _, answer = self.get("/calendar.ics/") assert answer.count("BEGIN:VEVENT") == 2 - def _test_filter(self, filters, kind="event", test=None, items=(1,)): + def _test_filter(self, filters: Iterable[str], kind: str = "event", + test: Optional[str] = None, items: Iterable[int] = (1,) + ) -> List[str]: filter_template = "%s" + create_collection_fn: Callable[[str], Any] if kind in ("event", "journal", "todo"): create_collection_fn = self.mkcalendar path = "/calendar.ics/" @@ -603,18 +639,19 @@ class BaseRequestsMixIn: {2} """.format(namespace, report, filters_text)) + assert responses is not None paths = [] for path, props in responses.items(): - assert len(props) == 1 + assert not isinstance(props, int) and len(props) == 1 status, prop = props["D:getetag"] assert status == 200 and prop.text paths.append(path) return paths - def test_addressbook_empty_filter(self): + def test_addressbook_empty_filter(self) -> None: self._test_filter([""], kind="contact") - def test_addressbook_prop_filter(self): + def test_addressbook_prop_filter(self) -> None: assert "/contacts.vcf/contact1.vcf" in self._test_filter(["""\ tes """], "contact") - def test_addressbook_prop_filter_any(self): + def test_addressbook_prop_filter_any(self) -> None: assert "/contacts.vcf/contact1.vcf" in self._test_filter(["""\ test @@ -688,7 +725,7 @@ class BaseRequestsMixIn: test """], "contact") - def test_addressbook_prop_filter_all(self): + def test_addressbook_prop_filter_all(self) -> None: assert "/contacts.vcf/contact1.vcf" in self._test_filter(["""\ tes @@ -704,15 +741,15 @@ class BaseRequestsMixIn: test """], "contact", test="allof") - def test_calendar_empty_filter(self): + def test_calendar_empty_filter(self) -> None: self._test_filter([""]) - def test_calendar_tag_filter(self): + def test_calendar_tag_filter(self) -> None: """Report request with tag-based filter on calendar.""" assert "/calendar.ics/event1.ics" in self._test_filter(["""\ """]) - def test_item_tag_filter(self): + def test_item_tag_filter(self) -> None: """Report request with tag-based filter on an item.""" assert "/calendar.ics/event1.ics" in self._test_filter(["""\ @@ -723,7 +760,7 @@ class BaseRequestsMixIn: """]) - def test_item_not_tag_filter(self): + def test_item_not_tag_filter(self) -> None: """Report request with tag-based is-not filter on an item.""" assert "/calendar.ics/event1.ics" not in self._test_filter(["""\ @@ -738,7 +775,7 @@ class BaseRequestsMixIn: """]) - def test_item_prop_filter(self): + def test_item_prop_filter(self) -> None: """Report request with prop-based filter on an item.""" assert "/calendar.ics/event1.ics" in self._test_filter(["""\ @@ -753,7 +790,7 @@ class BaseRequestsMixIn: """]) - def test_item_not_prop_filter(self): + def test_item_not_prop_filter(self) -> None: """Report request with prop-based is-not filter on an item.""" assert "/calendar.ics/event1.ics" not in self._test_filter(["""\ @@ -772,7 +809,7 @@ class BaseRequestsMixIn: """]) - def test_mutiple_filters(self): + def test_mutiple_filters(self) -> None: """Report request with multiple filters on an item.""" assert "/calendar.ics/event1.ics" not in self._test_filter(["""\ @@ -812,7 +849,7 @@ class BaseRequestsMixIn: """]) - def test_text_match_filter(self): + def test_text_match_filter(self) -> None: """Report request with text-match filter on calendar.""" assert "/calendar.ics/event1.ics" in self._test_filter(["""\ @@ -847,7 +884,7 @@ class BaseRequestsMixIn: """]) - def test_param_filter(self): + def test_param_filter(self) -> None: """Report request with param-filter on calendar.""" assert "/calendar.ics/event1.ics" in self._test_filter(["""\ @@ -892,7 +929,7 @@ class BaseRequestsMixIn: """]) - def test_time_range_filter_events(self): + def test_time_range_filter_events(self) -> None: """Report request with time-range filter on events.""" answer = self._test_filter(["""\ @@ -1019,7 +1056,7 @@ class BaseRequestsMixIn: """], items=(9,)) assert "/calendar.ics/event9.ics" not in answer - def test_time_range_filter_events_rrule(self): + def test_time_range_filter_events_rrule(self) -> None: """Report request with time-range filter on events with rrules.""" answer = self._test_filter(["""\ @@ -1054,7 +1091,7 @@ class BaseRequestsMixIn: assert "/calendar.ics/event1.ics" not in answer assert "/calendar.ics/event2.ics" not in answer - def test_time_range_filter_todos(self): + def test_time_range_filter_todos(self) -> None: """Report request with time-range filter on todos.""" answer = self._test_filter(["""\ @@ -1113,7 +1150,7 @@ class BaseRequestsMixIn: """], "todo", items=range(1, 9)) assert "/calendar.ics/todo7.ics" in answer - def test_time_range_filter_todos_rrule(self): + def test_time_range_filter_todos_rrule(self) -> None: """Report request with time-range filter on todos with rrules.""" answer = self._test_filter(["""\ @@ -1157,7 +1194,7 @@ class BaseRequestsMixIn: """], "todo", items=(9,)) assert "/calendar.ics/todo9.ics" not in answer - def test_time_range_filter_journals(self): + def test_time_range_filter_journals(self) -> None: """Report request with time-range filter on journals.""" answer = self._test_filter(["""\ @@ -1205,7 +1242,7 @@ class BaseRequestsMixIn: assert "/calendar.ics/journal2.ics" in answer assert "/calendar.ics/journal3.ics" in answer - def test_time_range_filter_journals_rrule(self): + def test_time_range_filter_journals_rrule(self) -> None: """Report request with time-range filter on journals with rrules.""" answer = self._test_filter(["""\ @@ -1232,7 +1269,7 @@ class BaseRequestsMixIn: assert "/calendar.ics/journal1.ics" not in answer assert "/calendar.ics/journal2.ics" not in answer - def test_report_item(self): + def test_report_item(self) -> None: """Test report request on an item""" calendar_path = "/calendar.ics/" self.mkcalendar(calendar_path) @@ -1247,10 +1284,14 @@ class BaseRequestsMixIn: """) assert len(responses) == 1 - status, prop = responses[event_path]["D:getetag"] + response = responses[event_path] + assert not isinstance(response, int) + status, prop = response["D:getetag"] assert status == 200 and prop.text - def _report_sync_token(self, calendar_path, sync_token=None): + def _report_sync_token( + self, calendar_path: str, sync_token: Optional[str] = None + ) -> Tuple[str, RESPONSES]: sync_token_xml = ( "" % sync_token if sync_token else "") @@ -1267,7 +1308,7 @@ class BaseRequestsMixIn: assert xml.tag == xmlutils.make_clark("D:error") assert sync_token and xml.find( xmlutils.make_clark("D:valid-sync-token")) is not None - return None, None + return "", {} assert status == 207 assert xml.tag == xmlutils.make_clark("D:multistatus") sync_token = xml.find(xmlutils.make_clark("D:sync-token")).text.strip() @@ -1281,7 +1322,7 @@ class BaseRequestsMixIn: assert response in (200, 404) return sync_token, responses - def test_report_sync_collection_no_change(self): + def test_report_sync_collection_no_change(self) -> None: """Test sync-collection report without modifying the collection""" calendar_path = "/calendar.ics/" self.mkcalendar(calendar_path) @@ -1296,7 +1337,7 @@ class BaseRequestsMixIn: return assert sync_token == new_sync_token and len(responses) == 0 - def test_report_sync_collection_add(self): + def test_report_sync_collection_add(self) -> None: """Test sync-collection report with an added item""" calendar_path = "/calendar.ics/" self.mkcalendar(calendar_path) @@ -1311,7 +1352,7 @@ class BaseRequestsMixIn: return assert len(responses) == 1 and responses[event_path] == 200 - def test_report_sync_collection_delete(self): + def test_report_sync_collection_delete(self) -> None: """Test sync-collection report with a deleted item""" calendar_path = "/calendar.ics/" self.mkcalendar(calendar_path) @@ -1327,7 +1368,7 @@ class BaseRequestsMixIn: return assert len(responses) == 1 and responses[event_path] == 404 - def test_report_sync_collection_create_delete(self): + def test_report_sync_collection_create_delete(self) -> None: """Test sync-collection report with a created and deleted item""" calendar_path = "/calendar.ics/" self.mkcalendar(calendar_path) @@ -1343,7 +1384,7 @@ class BaseRequestsMixIn: return assert len(responses) == 1 and responses[event_path] == 404 - def test_report_sync_collection_modify_undo(self): + def test_report_sync_collection_modify_undo(self) -> None: """Test sync-collection report with a modified and changed back item""" calendar_path = "/calendar.ics/" self.mkcalendar(calendar_path) @@ -1361,7 +1402,7 @@ class BaseRequestsMixIn: return assert len(responses) == 1 and responses[event_path] == 200 - def test_report_sync_collection_move(self): + def test_report_sync_collection_move(self) -> None: """Test sync-collection report a moved item""" calendar_path = "/calendar.ics/" self.mkcalendar(calendar_path) @@ -1381,7 +1422,7 @@ class BaseRequestsMixIn: assert len(responses) == 2 and (responses[event1_path] == 404 and responses[event2_path] == 200) - def test_report_sync_collection_move_undo(self): + def test_report_sync_collection_move_undo(self) -> None: """Test sync-collection report with a moved and moved back item""" calendar_path = "/calendar.ics/" self.mkcalendar(calendar_path) @@ -1404,7 +1445,7 @@ class BaseRequestsMixIn: assert len(responses) == 2 and (responses[event1_path] == 200 and responses[event2_path] == 404) - def test_report_sync_collection_invalid_sync_token(self): + def test_report_sync_collection_invalid_sync_token(self) -> None: """Test sync-collection report with an invalid sync token""" calendar_path = "/calendar.ics/" self.mkcalendar(calendar_path) @@ -1412,34 +1453,40 @@ class BaseRequestsMixIn: calendar_path, "http://radicale.org/ns/sync/INVALID") assert not sync_token - def test_propfind_sync_token(self): + def test_propfind_sync_token(self) -> None: """Retrieve the sync-token with a propfind request""" calendar_path = "/calendar.ics/" self.mkcalendar(calendar_path) propfind = get_file_content("allprop.xml") _, responses = self.propfind(calendar_path, propfind) - status, sync_token = responses[calendar_path]["D:sync-token"] + response = responses[calendar_path] + assert not isinstance(response, int) + status, sync_token = response["D:sync-token"] assert status == 200 and sync_token.text event = get_file_content("event1.ics") event_path = posixpath.join(calendar_path, "event.ics") self.put(event_path, event) _, responses = self.propfind(calendar_path, propfind) - status, new_sync_token = responses[calendar_path]["D:sync-token"] + response = responses[calendar_path] + assert not isinstance(response, int) + status, new_sync_token = response["D:sync-token"] assert status == 200 and new_sync_token.text assert sync_token.text != new_sync_token.text - def test_propfind_same_as_sync_collection_sync_token(self): + def test_propfind_same_as_sync_collection_sync_token(self) -> None: """Compare sync-token property with sync-collection sync-token""" calendar_path = "/calendar.ics/" self.mkcalendar(calendar_path) propfind = get_file_content("allprop.xml") _, responses = self.propfind(calendar_path, propfind) - status, sync_token = responses[calendar_path]["D:sync-token"] + response = responses[calendar_path] + assert not isinstance(response, int) + status, sync_token = response["D:sync-token"] assert status == 200 and sync_token.text report_sync_token, _ = self._report_sync_token(calendar_path) assert sync_token.text == report_sync_token - def test_calendar_getcontenttype(self): + def test_calendar_getcontenttype(self) -> None: """Test report request on an item""" self.mkcalendar("/test/") for component in ("event", "todo", "journal"): @@ -1454,14 +1501,15 @@ class BaseRequestsMixIn: """) - assert len(responses) == 1 and len( - responses["/test/test.ics"]) == 1 - status, prop = responses["/test/test.ics"]["D:getcontenttype"] + assert len(responses) == 1 + response = responses["/test/test.ics"] + assert not isinstance(response, int) and len(response) == 1 + status, prop = response["D:getcontenttype"] assert status == 200 and prop.text == ( "text/calendar;charset=utf-8;component=V%s" % component.upper()) - def test_addressbook_getcontenttype(self): + def test_addressbook_getcontenttype(self) -> None: """Test report request on an item""" self.create_addressbook("/test/") contact = get_file_content("contact1.vcf") @@ -1473,11 +1521,13 @@ class BaseRequestsMixIn: """) - assert len(responses) == 1 and len(responses["/test/test.vcf"]) == 1 - status, prop = responses["/test/test.vcf"]["D:getcontenttype"] + assert len(responses) == 1 + response = responses["/test/test.vcf"] + assert not isinstance(response, int) and len(response) == 1 + status, prop = response["D:getcontenttype"] assert status == 200 and prop.text == "text/vcard;charset=utf-8" - def test_authorization(self): + def test_authorization(self) -> None: _, responses = self.propfind("/", """\ @@ -1485,12 +1535,14 @@ class BaseRequestsMixIn: """, login="user:") - assert len(responses["/"]) == 1 - status, prop = responses["/"]["D:current-user-principal"] + response = responses["/"] + assert not isinstance(response, int) and len(response) == 1 + status, prop = response["D:current-user-principal"] assert status == 200 and len(prop) == 1 - assert prop.find(xmlutils.make_clark("D:href")).text == "/user/" + element = prop.find(xmlutils.make_clark("D:href")) + assert element is not None and element.text == "/user/" - def test_authentication(self): + def test_authentication(self) -> None: """Test if server sends authentication request.""" self.configuration.update({ "auth": {"type": "htpasswd", @@ -1502,11 +1554,11 @@ class BaseRequestsMixIn: assert status in (401, 403) assert headers.get("WWW-Authenticate") - def test_principal_collection_creation(self): + def test_principal_collection_creation(self) -> None: """Verify existence of the principal collection.""" self.propfind("/user/", login="user:") - def test_authentication_current_user_principal_workaround(self): + def test_authentication_current_user_principal_hack(self) -> None: """Test if server sends authentication request when accessing current-user-principal prop (workaround for DAVx5).""" status, headers, _ = self.request("PROPFIND", "/", """\ @@ -1519,7 +1571,7 @@ class BaseRequestsMixIn: assert status in (401, 403) assert headers.get("WWW-Authenticate") - def test_existence_of_root_collections(self): + def test_existence_of_root_collections(self) -> None: """Verify that the root collection always exists.""" # Use PROPFIND because GET returns message self.propfind("/") @@ -1527,7 +1579,7 @@ class BaseRequestsMixIn: self.delete("/") self.propfind("/") - def test_custom_headers(self): + def test_custom_headers(self) -> None: self.configuration.update({"headers": {"test": "123"}}, "test") self.application = Application(self.configuration) # Test if header is set on success @@ -1541,7 +1593,7 @@ class BaseRequestsMixIn: @pytest.mark.skipif(sys.version_info < (3, 6), reason="Unsupported in Python < 3.6") - def test_timezone_seconds(self): + def test_timezone_seconds(self) -> None: """Verify that timezones with minutes and seconds work.""" self.mkcalendar("/calendar.ics/") event = get_file_content("event_timezone_seconds.ics") @@ -1551,11 +1603,10 @@ class BaseRequestsMixIn: class BaseFileSystemTest(BaseTest): """Base class for filesystem backend tests.""" - storage_type: ClassVar[Any] + storage_type: ClassVar[StorageType] - def setup(self): - self.configuration = config.load() - self.colpath = tempfile.mkdtemp() + def setup(self) -> None: + super().setup() # Allow access to anything for tests rights_file_path = os.path.join(self.colpath, "rights") with open(rights_file_path, "w") as f: @@ -1565,23 +1616,18 @@ user: .* collection: .* permissions: RrWw""") self.configuration.update({ - "storage": {"type": self.storage_type, - "filesystem_folder": self.colpath, - # Disable syncing to disk for better performance - "_filesystem_fsync": "False"}, + "storage": {"type": self.storage_type}, "rights": {"file": rights_file_path, "type": "from_file"}}, "test", privileged=True) self.application = Application(self.configuration) - def teardown(self): - shutil.rmtree(self.colpath) - class TestMultiFileSystem(BaseFileSystemTest, BaseRequestsMixIn): """Test BaseRequests on multifilesystem.""" - storage_type = "multifilesystem" - def test_folder_creation(self): + storage_type: ClassVar[StorageType] = "multifilesystem" + + def test_folder_creation(self) -> None: """Verify that the folder is created.""" folder = os.path.join(self.colpath, "subfolder") self.configuration.update( @@ -1589,14 +1635,14 @@ class TestMultiFileSystem(BaseFileSystemTest, BaseRequestsMixIn): self.application = Application(self.configuration) assert os.path.isdir(folder) - def test_fsync(self): + def test_fsync(self) -> None: """Create a directory and file with syncing enabled.""" self.configuration.update({"storage": {"_filesystem_fsync": "True"}}, "test", privileged=True) self.application = Application(self.configuration) self.mkcalendar("/calendar.ics/") - def test_hook(self): + def test_hook(self) -> None: """Run hook.""" self.configuration.update({"storage": { "hook": ("mkdir %s" % os.path.join( @@ -1605,7 +1651,7 @@ class TestMultiFileSystem(BaseFileSystemTest, BaseRequestsMixIn): self.mkcalendar("/calendar.ics/") self.propfind("/created_by_hook/") - def test_hook_read_access(self): + def test_hook_read_access(self) -> None: """Verify that hook is not run for read accesses.""" self.configuration.update({"storage": { "hook": ("mkdir %s" % os.path.join( @@ -1616,14 +1662,14 @@ class TestMultiFileSystem(BaseFileSystemTest, BaseRequestsMixIn): @pytest.mark.skipif(not shutil.which("flock"), reason="flock command not found") - def test_hook_storage_locked(self): + def test_hook_storage_locked(self) -> None: """Verify that the storage is locked when the hook runs.""" self.configuration.update({"storage": {"hook": ( "flock -n .Radicale.lock || exit 0; exit 1")}}, "test") self.application = Application(self.configuration) self.mkcalendar("/calendar.ics/") - def test_hook_principal_collection_creation(self): + def test_hook_principal_collection_creation(self) -> None: """Verify that the hooks runs when a new user is created.""" self.configuration.update({"storage": { "hook": ("mkdir %s" % os.path.join( @@ -1632,13 +1678,13 @@ class TestMultiFileSystem(BaseFileSystemTest, BaseRequestsMixIn): self.propfind("/", login="user:") self.propfind("/created_by_hook/") - def test_hook_fail(self): + def test_hook_fail(self) -> None: """Verify that a request fails if the hook fails.""" self.configuration.update({"storage": {"hook": "exit 1"}}, "test") self.application = Application(self.configuration) self.mkcalendar("/calendar.ics/", check=500) - def test_item_cache_rebuild(self): + def test_item_cache_rebuild(self) -> None: """Delete the item cache and verify that it is rebuild.""" self.mkcalendar("/calendar.ics/") event = get_file_content("event1.ics") @@ -1655,7 +1701,7 @@ class TestMultiFileSystem(BaseFileSystemTest, BaseRequestsMixIn): @pytest.mark.skipif(os.name != "posix" and sys.platform != "win32", reason="Only supported on 'posix' and 'win32'") - def test_put_whole_calendar_uids_used_as_file_names(self): + def test_put_whole_calendar_uids_used_as_file_names(self) -> None: """Test if UIDs are used as file names.""" BaseRequestsMixIn.test_put_whole_calendar(self) for uid in ("todo", "event"): @@ -1664,21 +1710,23 @@ class TestMultiFileSystem(BaseFileSystemTest, BaseRequestsMixIn): @pytest.mark.skipif(os.name != "posix" and sys.platform != "win32", reason="Only supported on 'posix' and 'win32'") - def test_put_whole_calendar_random_uids_used_as_file_names(self): + def test_put_whole_calendar_random_uids_used_as_file_names(self) -> None: """Test if UIDs are used as file names.""" BaseRequestsMixIn.test_put_whole_calendar_without_uids(self) _, answer = self.get("/calendar.ics") + assert answer is not None uids = [] for line in answer.split("\r\n"): if line.startswith("UID:"): uids.append(line[len("UID:"):]) for uid in uids: _, answer = self.get("/calendar.ics/%s.ics" % uid) + assert answer is not None assert "\r\nUID:%s\r\n" % uid in answer @pytest.mark.skipif(os.name != "posix" and sys.platform != "win32", reason="Only supported on 'posix' and 'win32'") - def test_put_whole_addressbook_uids_used_as_file_names(self): + def test_put_whole_addressbook_uids_used_as_file_names(self) -> None: """Test if UIDs are used as file names.""" BaseRequestsMixIn.test_put_whole_addressbook(self) for uid in ("contact1", "contact2"): @@ -1687,27 +1735,33 @@ class TestMultiFileSystem(BaseFileSystemTest, BaseRequestsMixIn): @pytest.mark.skipif(os.name != "posix" and sys.platform != "win32", reason="Only supported on 'posix' and 'win32'") - def test_put_whole_addressbook_random_uids_used_as_file_names(self): + def test_put_whole_addressbook_random_uids_used_as_file_names( + self) -> None: """Test if UIDs are used as file names.""" BaseRequestsMixIn.test_put_whole_addressbook_without_uids(self) _, answer = self.get("/contacts.vcf") + assert answer is not None uids = [] for line in answer.split("\r\n"): if line.startswith("UID:"): uids.append(line[len("UID:"):]) for uid in uids: _, answer = self.get("/contacts.vcf/%s.vcf" % uid) + assert answer is not None assert "\r\nUID:%s\r\n" % uid in answer class TestCustomStorageSystem(BaseFileSystemTest): """Test custom backend loading.""" - storage_type = "radicale.tests.custom.storage_simple_sync" - full_sync_token_support = False + + storage_type: ClassVar[StorageType] = ( + "radicale.tests.custom.storage_simple_sync") + full_sync_token_support: ClassVar[bool] = False + test_root = BaseRequestsMixIn.test_root _report_sync_token = BaseRequestsMixIn._report_sync_token # include tests related to sync token - s = None + s: str = "" for s in dir(BaseRequestsMixIn): if s.startswith("test_") and ("_sync_" in s or s.endswith("_sync")): locals()[s] = getattr(BaseRequestsMixIn, s) @@ -1716,5 +1770,8 @@ class TestCustomStorageSystem(BaseFileSystemTest): class TestCustomStorageSystemCallable(BaseFileSystemTest): """Test custom backend loading with ``callable``.""" - storage_type = radicale.tests.custom.storage_simple_sync.Storage + + storage_type: ClassVar[StorageType] = ( + radicale.tests.custom.storage_simple_sync.Storage) + test_add_event = BaseRequestsMixIn.test_add_event diff --git a/radicale/tests/test_config.py b/radicale/tests/test_config.py index e9177cb4..384cbca8 100644 --- a/radicale/tests/test_config.py +++ b/radicale/tests/test_config.py @@ -18,23 +18,26 @@ import os import shutil import tempfile from configparser import RawConfigParser +from typing import List, Tuple import pytest -from radicale import config +from radicale import config, types from radicale.tests.helpers import configuration_to_dict class TestConfig: """Test the configuration.""" - def setup(self): + colpath: str + + def setup(self) -> None: self.colpath = tempfile.mkdtemp() - def teardown(self): + def teardown(self) -> None: shutil.rmtree(self.colpath) - def _write_config(self, config_dict, name): + def _write_config(self, config_dict: types.CONFIG, name: str) -> str: parser = RawConfigParser() parser.read_dict(config_dict) config_path = os.path.join(self.colpath, name) @@ -42,7 +45,7 @@ class TestConfig: parser.write(f) return config_path - def test_parse_compound_paths(self): + def test_parse_compound_paths(self) -> None: assert len(config.parse_compound_paths()) == 0 assert len(config.parse_compound_paths("")) == 0 assert len(config.parse_compound_paths(None, "")) == 0 @@ -62,16 +65,16 @@ class TestConfig: assert os.path.basename(paths[i][0]) == name assert paths[i][1] is ignore_if_missing - def test_load_empty(self): + def test_load_empty(self) -> None: config_path = self._write_config({}, "config") config.load([(config_path, False)]) - def test_load_full(self): + def test_load_full(self) -> None: config_path = self._write_config( configuration_to_dict(config.load()), "config") config.load([(config_path, False)]) - def test_load_missing(self): + def test_load_missing(self) -> None: config_path = os.path.join(self.colpath, "does_not_exist") config.load([(config_path, True)]) with pytest.raises(Exception) as exc_info: @@ -79,18 +82,20 @@ class TestConfig: e = exc_info.value assert "Failed to load config file %r" % config_path in str(e) - def test_load_multiple(self): + def test_load_multiple(self) -> None: config_path1 = self._write_config({ "server": {"hosts": "192.0.2.1:1111"}}, "config1") config_path2 = self._write_config({ "server": {"max_connections": 1111}}, "config2") configuration = config.load([(config_path1, False), (config_path2, False)]) - assert len(configuration.get("server", "hosts")) == 1 - assert configuration.get("server", "hosts")[0] == ("192.0.2.1", 1111) + server_hosts: List[Tuple[str, int]] = configuration.get( + "server", "hosts") + assert len(server_hosts) == 1 + assert server_hosts[0] == ("192.0.2.1", 1111) assert configuration.get("server", "max_connections") == 1111 - def test_copy(self): + def test_copy(self) -> None: configuration1 = config.load() configuration1.update({"server": {"max_connections": "1111"}}, "test") configuration2 = configuration1.copy() @@ -98,14 +103,14 @@ class TestConfig: assert configuration1.get("server", "max_connections") == 1111 assert configuration2.get("server", "max_connections") == 1112 - def test_invalid_section(self): + def test_invalid_section(self) -> None: configuration = config.load() with pytest.raises(Exception) as exc_info: configuration.update({"does_not_exist": {"x": "x"}}, "test") e = exc_info.value assert "Invalid section 'does_not_exist'" in str(e) - def test_invalid_option(self): + def test_invalid_option(self) -> None: configuration = config.load() with pytest.raises(Exception) as exc_info: configuration.update({"server": {"x": "x"}}, "test") @@ -113,7 +118,7 @@ class TestConfig: assert "Invalid option 'x'" in str(e) assert "section 'server'" in str(e) - def test_invalid_option_plugin(self): + def test_invalid_option_plugin(self) -> None: configuration = config.load() with pytest.raises(Exception) as exc_info: configuration.update({"auth": {"x": "x"}}, "test") @@ -121,7 +126,7 @@ class TestConfig: assert "Invalid option 'x'" in str(e) assert "section 'auth'" in str(e) - def test_invalid_value(self): + def test_invalid_value(self) -> None: configuration = config.load() with pytest.raises(Exception) as exc_info: configuration.update({"server": {"max_connections": "x"}}, "test") @@ -131,7 +136,7 @@ class TestConfig: assert "section 'server" in str(e) assert "'x'" in str(e) - def test_privileged(self): + def test_privileged(self) -> None: configuration = config.load() configuration.update({"server": {"_internal_server": "True"}}, "test", privileged=True) @@ -141,9 +146,9 @@ class TestConfig: e = exc_info.value assert "Invalid option '_internal_server'" in str(e) - def test_plugin_schema(self): - plugin_schema = {"auth": {"new_option": {"value": "False", - "type": bool}}} + def test_plugin_schema(self) -> None: + plugin_schema: types.CONFIG_SCHEMA = { + "auth": {"new_option": {"value": "False", "type": bool}}} configuration = config.load() configuration.update({"auth": {"type": "new_plugin"}}, "test") plugin_configuration = configuration.copy(plugin_schema) @@ -152,26 +157,26 @@ class TestConfig: plugin_configuration = configuration.copy(plugin_schema) assert plugin_configuration.get("auth", "new_option") is True - def test_plugin_schema_duplicate_option(self): - plugin_schema = {"auth": {"type": {"value": "False", - "type": bool}}} + def test_plugin_schema_duplicate_option(self) -> None: + plugin_schema: types.CONFIG_SCHEMA = { + "auth": {"type": {"value": "False", "type": bool}}} configuration = config.load() with pytest.raises(Exception) as exc_info: configuration.copy(plugin_schema) e = exc_info.value assert "option already exists in 'auth': 'type'" in str(e) - def test_plugin_schema_invalid(self): - plugin_schema = {"server": {"new_option": {"value": "False", - "type": bool}}} + def test_plugin_schema_invalid(self) -> None: + plugin_schema: types.CONFIG_SCHEMA = { + "server": {"new_option": {"value": "False", "type": bool}}} configuration = config.load() with pytest.raises(Exception) as exc_info: configuration.copy(plugin_schema) e = exc_info.value assert "not a plugin section: 'server" in str(e) - def test_plugin_schema_option_invalid(self): - plugin_schema = {"auth": {}} + def test_plugin_schema_option_invalid(self) -> None: + plugin_schema: types.CONFIG_SCHEMA = {"auth": {}} configuration = config.load() configuration.update({"auth": {"type": "new_plugin", "new_option": False}}, "test") diff --git a/radicale/tests/test_rights.py b/radicale/tests/test_rights.py index 951cf55c..e9b92787 100644 --- a/radicale/tests/test_rights.py +++ b/radicale/tests/test_rights.py @@ -19,10 +19,8 @@ Radicale tests with simple requests and rights. """ import os -import shutil -import tempfile -from radicale import Application, config +from radicale import Application from radicale.tests import BaseTest from radicale.tests.helpers import get_file_content @@ -30,20 +28,8 @@ from radicale.tests.helpers import get_file_content class TestBaseRightsRequests(BaseTest): """Tests basic requests with rights.""" - def setup(self): - self.configuration = config.load() - self.colpath = tempfile.mkdtemp() - self.configuration.update({ - "storage": {"filesystem_folder": self.colpath, - # Disable syncing to disk for better performance - "_filesystem_fsync": "False"}}, - "test", privileged=True) - - def teardown(self): - shutil.rmtree(self.colpath) - - def _test_rights(self, rights_type, user, path, mode, expected_status, - with_auth=True): + def _test_rights(self, rights_type: str, user: str, path: str, mode: str, + expected_status: int, with_auth: bool = True) -> None: assert mode in ("r", "w") assert user in ("", "tmp") htpasswd_file_path = os.path.join(self.colpath, ".htpasswd") @@ -61,7 +47,7 @@ class TestBaseRightsRequests(BaseTest): (self.propfind if mode == "r" else self.proppatch)( path, check=expected_status, login="tmp:bepo" if user else None) - def test_owner_only(self): + def test_owner_only(self) -> None: self._test_rights("owner_only", "", "/", "r", 401) self._test_rights("owner_only", "", "/", "w", 401) self._test_rights("owner_only", "", "/tmp/", "r", 401) @@ -73,13 +59,13 @@ class TestBaseRightsRequests(BaseTest): self._test_rights("owner_only", "tmp", "/other/", "r", 403) self._test_rights("owner_only", "tmp", "/other/", "w", 403) - def test_owner_only_without_auth(self): + def test_owner_only_without_auth(self) -> None: self._test_rights("owner_only", "", "/", "r", 207, False) self._test_rights("owner_only", "", "/", "w", 401, False) self._test_rights("owner_only", "", "/tmp/", "r", 207, False) self._test_rights("owner_only", "", "/tmp/", "w", 207, False) - def test_owner_write(self): + def test_owner_write(self) -> None: self._test_rights("owner_write", "", "/", "r", 401) self._test_rights("owner_write", "", "/", "w", 401) self._test_rights("owner_write", "", "/tmp/", "r", 401) @@ -91,13 +77,13 @@ class TestBaseRightsRequests(BaseTest): self._test_rights("owner_write", "tmp", "/other/", "r", 207) self._test_rights("owner_write", "tmp", "/other/", "w", 403) - def test_owner_write_without_auth(self): + def test_owner_write_without_auth(self) -> None: self._test_rights("owner_write", "", "/", "r", 207, False) self._test_rights("owner_write", "", "/", "w", 401, False) self._test_rights("owner_write", "", "/tmp/", "r", 207, False) self._test_rights("owner_write", "", "/tmp/", "w", 207, False) - def test_authenticated(self): + def test_authenticated(self) -> None: self._test_rights("authenticated", "", "/", "r", 401) self._test_rights("authenticated", "", "/", "w", 401) self._test_rights("authenticated", "", "/tmp/", "r", 401) @@ -109,13 +95,13 @@ class TestBaseRightsRequests(BaseTest): self._test_rights("authenticated", "tmp", "/other/", "r", 207) self._test_rights("authenticated", "tmp", "/other/", "w", 207) - def test_authenticated_without_auth(self): + def test_authenticated_without_auth(self) -> None: self._test_rights("authenticated", "", "/", "r", 207, False) self._test_rights("authenticated", "", "/", "w", 207, False) self._test_rights("authenticated", "", "/tmp/", "r", 207, False) self._test_rights("authenticated", "", "/tmp/", "w", 207, False) - def test_from_file(self): + def test_from_file(self) -> None: rights_file_path = os.path.join(self.colpath, "rights") with open(rights_file_path, "w") as f: f.write("""\ @@ -160,13 +146,13 @@ permissions: i""") self.get("/public/calendar") self.get("/public/calendar/1.ics", check=401) - def test_custom(self): + def test_custom(self) -> None: """Custom rights management.""" self._test_rights("radicale.tests.custom.rights", "", "/", "r", 401) self._test_rights( "radicale.tests.custom.rights", "", "/tmp/", "r", 207) - def test_collections_and_items(self): + def test_collections_and_items(self) -> None: """Test rights for creation of collections, calendars and items. Collections are allowed at "/" and "/.../". @@ -183,7 +169,7 @@ permissions: i""") self.mkcol("/user/calendar/item", check=401) self.mkcalendar("/user/calendar/item", check=401) - def test_put_collections_and_items(self): + def test_put_collections_and_items(self) -> None: """Test rights for creation of calendars and items with PUT.""" self.application = Application(self.configuration) self.put("/user/", "BEGIN:VCALENDAR\r\nEND:VCALENDAR", check=401) diff --git a/radicale/tests/test_server.py b/radicale/tests/test_server.py index 72ff52be..956bc85b 100644 --- a/radicale/tests/test_server.py +++ b/radicale/tests/test_server.py @@ -21,15 +21,14 @@ Test the internal server. import errno import os -import shutil import socket import ssl import subprocess import sys -import tempfile import threading import time from configparser import RawConfigParser +from typing import Callable, Dict, NoReturn, Optional, Tuple, cast from urllib import request from urllib.error import HTTPError, URLError @@ -41,34 +40,43 @@ from radicale.tests.helpers import configuration_to_dict, get_file_path class DisabledRedirectHandler(request.HTTPRedirectHandler): - def http_error_301(self, req, fp, code, msg, headers): + + # HACK: typeshed annotation are wrong for `fp` and `msg` + # (https://github.com/python/typeshed/pull/5728) + # `headers` is incompatible with `http.client.HTTPMessage` + # (https://github.com/python/typeshed/issues/5729) + def http_error_301(self, req: request.Request, fp, code: int, + msg, headers) -> NoReturn: raise HTTPError(req.full_url, code, msg, headers, fp) - def http_error_302(self, req, fp, code, msg, headers): + def http_error_302(self, req: request.Request, fp, code: int, + msg, headers) -> NoReturn: raise HTTPError(req.full_url, code, msg, headers, fp) - def http_error_303(self, req, fp, code, msg, headers): + def http_error_303(self, req: request.Request, fp, code: int, + msg, headers) -> NoReturn: raise HTTPError(req.full_url, code, msg, headers, fp) - def http_error_307(self, req, fp, code, msg, headers): + def http_error_307(self, req: request.Request, fp, code: int, + msg, headers) -> NoReturn: raise HTTPError(req.full_url, code, msg, headers, fp) class TestBaseServerRequests(BaseTest): """Test the internal server.""" - def setup(self): - self.configuration = config.load() - self.colpath = tempfile.mkdtemp() + shutdown_socket: socket.socket + thread: threading.Thread + opener: request.OpenerDirector + + def setup(self) -> None: + super().setup() self.shutdown_socket, shutdown_socket_out = socket.socketpair() with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as sock: # Find available port sock.bind(("127.0.0.1", 0)) self.sockname = sock.getsockname() self.configuration.update({ - "storage": {"filesystem_folder": self.colpath, - # Disable syncing to disk for better performance - "_filesystem_fsync": "False"}, "server": {"hosts": "[%s]:%d" % self.sockname}, # Enable debugging for new processes "logging": {"level": "debug"}}, @@ -82,40 +90,57 @@ class TestBaseServerRequests(BaseTest): request.HTTPSHandler(context=ssl_context), DisabledRedirectHandler) - def teardown(self): + def teardown(self) -> None: self.shutdown_socket.close() try: self.thread.join() except RuntimeError: # Thread never started pass - shutil.rmtree(self.colpath) + super().teardown() - def request(self, method, path, data=None, is_alive_fn=None, **headers): + def request(self, method: str, path: str, data: Optional[str] = None, + **kwargs) -> Tuple[int, Dict[str, str], str]: """Send a request.""" + login = kwargs.pop("login", None) + if login is not None and not isinstance(login, str): + raise TypeError("login argument must be %r, not %r" % + (str, type(login))) + if login: + raise NotImplementedError + is_alive_fn: Optional[Callable[[], bool]] = kwargs.pop( + "is_alive_fn", None) + headers: Dict[str, str] = kwargs + for k, v in headers.items(): + if not isinstance(v, str): + raise TypeError("type of %r is %r, expected %r" % + (k, type(v), str)) if is_alive_fn is None: is_alive_fn = self.thread.is_alive - scheme = ("https" if self.configuration.get("server", "ssl") else - "http") + encoding: str = self.configuration.get("encoding", "request") + scheme = "https" if self.configuration.get("server", "ssl") else "http" + data_bytes = None + if data: + data_bytes = data.encode(encoding) req = request.Request( "%s://[%s]:%d%s" % (scheme, *self.sockname, path), - data=data, headers=headers, method=method) + data=data_bytes, headers=headers, method=method) while True: assert is_alive_fn() try: with self.opener.open(req) as f: - return f.getcode(), f.info(), f.read().decode() + return f.getcode(), dict(f.info()), f.read().decode() except HTTPError as e: - return e.code, e.headers, e.read().decode() + return e.code, dict(e.headers), e.read().decode() except URLError as e: if not isinstance(e.reason, ConnectionRefusedError): raise time.sleep(0.1) - def test_root(self): + def test_root(self) -> None: self.thread.start() self.get("/", check=302) - def test_ssl(self): + def test_ssl(self) -> None: self.configuration.update({ "server": {"ssl": "True", "certificate": get_file_path("cert.pem"), @@ -123,7 +148,7 @@ class TestBaseServerRequests(BaseTest): self.thread.start() self.get("/", check=302) - def test_bind_fail(self): + def test_bind_fail(self) -> None: for address_family, address in [(socket.AF_INET, "::1"), (socket.AF_INET6, "127.0.0.1")]: with socket.socket(address_family, socket.SOCK_STREAM) as sock: @@ -143,7 +168,7 @@ class TestBaseServerRequests(BaseTest): errno.EADDRNOTAVAIL, errno.EAFNOSUPPORT, errno.EPROTONOSUPPORT)) - def test_ipv6(self): + def test_ipv6(self) -> None: try: with socket.socket(socket.AF_INET6, socket.SOCK_STREAM) as sock: # Only allow IPv6 connections to the IPv6 socket @@ -162,7 +187,7 @@ class TestBaseServerRequests(BaseTest): self.thread.start() self.get("/", check=302) - def test_command_line_interface(self): + def test_command_line_interface(self) -> None: config_args = [] for section, values in config.DEFAULT_CONFIG_SCHEMA.items(): if section.startswith("_"): @@ -172,13 +197,14 @@ class TestBaseServerRequests(BaseTest): continue long_name = "--%s-%s" % (section, option.replace("_", "-")) if data["type"] == bool: - if not self.configuration.get(section, option): + if not cast(bool, self.configuration.get(section, option)): long_name = "--no%s" % long_name[1:] config_args.append(long_name) else: config_args.append(long_name) - config_args.append( - self.configuration.get_raw(section, option)) + raw_value = self.configuration.get_raw(section, option) + assert isinstance(raw_value, str) + config_args.append(raw_value) p = subprocess.Popen( [sys.executable, "-m", "radicale"] + config_args, env={**os.environ, "PYTHONPATH": os.pathsep.join(sys.path)}) @@ -190,7 +216,7 @@ class TestBaseServerRequests(BaseTest): if os.name == "posix": assert p.returncode == 0 - def test_wsgi_server(self): + def test_wsgi_server(self) -> None: config_path = os.path.join(self.colpath, "config") parser = RawConfigParser() parser.read_dict(configuration_to_dict(self.configuration)) @@ -199,9 +225,10 @@ class TestBaseServerRequests(BaseTest): env = os.environ.copy() env["PYTHONPATH"] = os.pathsep.join(sys.path) env["RADICALE_CONFIG"] = config_path + raw_server_hosts = self.configuration.get_raw("server", "hosts") + assert isinstance(raw_server_hosts, str) p = subprocess.Popen([ - sys.executable, "-m", "waitress", - "--listen", self.configuration.get_raw("server", "hosts"), + sys.executable, "-m", "waitress", "--listen", raw_server_hosts, "radicale:application"], env=env) try: self.get("/", is_alive_fn=lambda: p.poll() is None, check=302) diff --git a/radicale/tests/test_web.py b/radicale/tests/test_web.py index 5d2b7925..2dc599e3 100644 --- a/radicale/tests/test_web.py +++ b/radicale/tests/test_web.py @@ -19,30 +19,14 @@ Test web plugin. """ -import shutil -import tempfile - -from radicale import Application, config +from radicale import Application from radicale.tests import BaseTest class TestBaseWebRequests(BaseTest): """Test web plugin.""" - def setup(self): - self.configuration = config.load() - self.colpath = tempfile.mkdtemp() - self.configuration.update({ - "storage": {"filesystem_folder": self.colpath, - # Disable syncing to disk for better performance - "_filesystem_fsync": "False"}}, - "test", privileged=True) - self.application = Application(self.configuration) - - def teardown(self): - shutil.rmtree(self.colpath) - - def test_internal(self): + def test_internal(self) -> None: status, headers, _ = self.request("GET", "/.web") assert status == 302 assert headers.get("Location") == ".web/" @@ -50,7 +34,7 @@ class TestBaseWebRequests(BaseTest): assert answer self.post("/.web", check=405) - def test_none(self): + def test_none(self) -> None: self.configuration.update({"web": {"type": "none"}}, "test") self.application = Application(self.configuration) _, answer = self.get("/.web") @@ -58,7 +42,7 @@ class TestBaseWebRequests(BaseTest): self.get("/.web/", check=404) self.post("/.web", check=405) - def test_custom(self): + def test_custom(self) -> None: """Custom web plugin.""" self.configuration.update({ "web": {"type": "radicale.tests.custom.web"}}, "test") From 574e6f8c7bb250a74f37d46612a35084088b441a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Tom=C3=A1=C5=A1=20Hrn=C4=8Diar?= Date: Wed, 28 Apr 2021 08:56:46 +0200 Subject: [PATCH 056/238] Require setuptools, radicale/__init__.py, radicale/web/internal.py, radicale/storage/__init__.py, radicale/app/__init__.py import pkg_resources --- setup.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/setup.py b/setup.py index a118cc12..5834c013 100644 --- a/setup.py +++ b/setup.py @@ -76,7 +76,7 @@ setup( package_data={"radicale": WEB_FILES}, entry_points={"console_scripts": ["radicale = radicale.__main__:run"]}, install_requires=["defusedxml", "passlib", "vobject>=0.9.6", - "python-dateutil>=2.7.3"], + "python-dateutil>=2.7.3", "setuptools"], setup_requires=pytest_runner, tests_require=tests_require, extras_require={"test": tests_require, From 111a79f0828f0c57477f23342c64d40f32756ab2 Mon Sep 17 00:00:00 2001 From: jorge Date: Fri, 24 Sep 2021 12:02:57 +0200 Subject: [PATCH 057/238] Fix documentation arguments --- DOCUMENTATION.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/DOCUMENTATION.md b/DOCUMENTATION.md index 95c5f649..35f9bf3c 100644 --- a/DOCUMENTATION.md +++ b/DOCUMENTATION.md @@ -552,7 +552,7 @@ Paths that start with `?` are optional. The same example configuration via command line arguments looks like: ```bash -python3 -m radicale --server-hosts 0.0.0.0:5232,[::]:5232 --auth-type htpasswd --htpasswd-filename ~/.config/radicale/users --htpasswd-encryption md5 +python3 -m radicale --server-hosts 0.0.0.0:5232,[::]:5232 --auth-type htpasswd --auth-htpasswd-filename ~/.config/radicale/users --auth-htpasswd-encryption md5 ``` Add the argument `--config ""` to stop Radicale from loading the default From f921e48648b1bae14bbd1a28c738faa98a563277 Mon Sep 17 00:00:00 2001 From: Unrud Date: Mon, 27 Sep 2021 17:22:37 +0200 Subject: [PATCH 058/238] Remove unused variable --- radicale/app/__init__.py | 4 ---- 1 file changed, 4 deletions(-) diff --git a/radicale/app/__init__.py b/radicale/app/__init__.py index c1bd0905..6bebf81c 100644 --- a/radicale/app/__init__.py +++ b/radicale/app/__init__.py @@ -34,8 +34,6 @@ import zlib from http import client from typing import Iterable, List, Mapping, Tuple, Union -import pkg_resources - from radicale import config, httputils, log, pathutils, types from radicale.app.base import ApplicationBase from radicale.app.delete import ApplicationPartDelete @@ -52,8 +50,6 @@ from radicale.app.put import ApplicationPartPut from radicale.app.report import ApplicationPartReport from radicale.log import logger -VERSION: str = pkg_resources.get_distribution("radicale").version - # Combination of types.WSGIStartResponse and WSGI application return value _IntermediateResponse = Tuple[str, List[Tuple[str, str]], Iterable[bytes]] From cd3f834a27e532c180420e5ec802893502705cb8 Mon Sep 17 00:00:00 2001 From: Unrud Date: Mon, 27 Sep 2021 17:22:42 +0200 Subject: [PATCH 059/238] Rename variable --- setup.py | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/setup.py b/setup.py index 5834c013..d22a4a60 100644 --- a/setup.py +++ b/setup.py @@ -49,8 +49,9 @@ WEB_FILES = ["web/internal_data/css/icon.png", "web/internal_data/fn.js", "web/internal_data/index.html"] -needs_pytest = {"pytest", "test", "ptr"}.intersection(sys.argv) -pytest_runner = ["pytest-runner"] if needs_pytest else [] +setup_requires = [] +if {"pytest", "test", "ptr"}.intersection(sys.argv): + setup_requires.append("pytest-runner") tests_require = ["pytest-runner", "pytest", "pytest-cov", "pytest-flake8", "pytest-isort", "typeguard", "waitress"] os.environ["PYTEST_ADDOPTS"] = os.environ.get("PYTEST_ADDOPTS", "") @@ -77,7 +78,7 @@ setup( entry_points={"console_scripts": ["radicale = radicale.__main__:run"]}, install_requires=["defusedxml", "passlib", "vobject>=0.9.6", "python-dateutil>=2.7.3", "setuptools"], - setup_requires=pytest_runner, + setup_requires=setup_requires, tests_require=tests_require, extras_require={"test": tests_require, "bcrypt": ["passlib[bcrypt]", "bcrypt"]}, From 056ce5b69fe6a8f3e3b94b3d182a4502342a1abc Mon Sep 17 00:00:00 2001 From: Unrud Date: Mon, 27 Sep 2021 17:22:51 +0200 Subject: [PATCH 060/238] Flake8: Only enable default tests --- setup.cfg | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/setup.cfg b/setup.cfg index 8ed34d51..44ba71ed 100644 --- a/setup.cfg +++ b/setup.cfg @@ -14,7 +14,8 @@ known_standard_library = _dummy_thread,_thread,abc,aifc,argparse,array,ast,async known_third_party = defusedxml,passlib,pkg_resources,pytest,vobject [flake8] -extend-ignore = H +# Only enable default tests (https://github.com/PyCQA/flake8/issues/790#issuecomment-812823398) +select = E,F,W,C90,DOES-NOT-EXIST [mypy] ignore_missing_imports = True From 35e7ee5a08671eeb764e070acecee6c25356e81e Mon Sep 17 00:00:00 2001 From: Unrud Date: Mon, 27 Sep 2021 19:19:18 +0200 Subject: [PATCH 061/238] Fix flake8 tests --- setup.cfg | 1 + 1 file changed, 1 insertion(+) diff --git a/setup.cfg b/setup.cfg index 44ba71ed..35c2c8ea 100644 --- a/setup.cfg +++ b/setup.cfg @@ -16,6 +16,7 @@ known_third_party = defusedxml,passlib,pkg_resources,pytest,vobject [flake8] # Only enable default tests (https://github.com/PyCQA/flake8/issues/790#issuecomment-812823398) select = E,F,W,C90,DOES-NOT-EXIST +ignore = E121,E123,E126,E226,E24,E704,W503,W504,DOES-NOT-EXIST [mypy] ignore_missing_imports = True From f72b3449818600962268bc96a2a12e8e022a0c42 Mon Sep 17 00:00:00 2001 From: Jochen Sprickerhof Date: Thu, 14 Oct 2021 11:30:46 +0200 Subject: [PATCH 062/238] Add py.typed to mark as having typing information According to PEP 561. --- radicale/py.typed | 0 setup.py | 2 +- 2 files changed, 1 insertion(+), 1 deletion(-) create mode 100644 radicale/py.typed diff --git a/radicale/py.typed b/radicale/py.typed new file mode 100644 index 00000000..e69de29b diff --git a/setup.py b/setup.py index d22a4a60..34af83e9 100644 --- a/setup.py +++ b/setup.py @@ -74,7 +74,7 @@ setup( platforms="Any", packages=find_packages( exclude=["*.tests", "*.tests.*", "tests.*", "tests"]), - package_data={"radicale": WEB_FILES}, + package_data={"radicale": WEB_FILES + ['py.typed']}, entry_points={"console_scripts": ["radicale = radicale.__main__:run"]}, install_requires=["defusedxml", "passlib", "vobject>=0.9.6", "python-dateutil>=2.7.3", "setuptools"], From 7c9c873b1331afc95a6be5fb92db5b012848eb78 Mon Sep 17 00:00:00 2001 From: Unrud Date: Wed, 10 Nov 2021 22:14:51 +0100 Subject: [PATCH 063/238] Don't modify DEFAULT_CONFIG_SCHEMA --- radicale/__main__.py | 2 +- radicale/config.py | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/radicale/__main__.py b/radicale/__main__.py index d88aeeb1..8f21ece8 100644 --- a/radicale/__main__.py +++ b/radicale/__main__.py @@ -91,7 +91,7 @@ def run() -> None: del kwargs["type"] kwargs["action"] = "store_const" kwargs["const"] = "True" - opposite_args = kwargs.pop("opposite", []) + opposite_args = list(kwargs.pop("opposite", ())) opposite_args.append("--no%s" % long_name[1:]) group.add_argument(*args, **kwargs) diff --git a/radicale/config.py b/radicale/config.py index c0947112..ec94ada2 100644 --- a/radicale/config.py +++ b/radicale/config.py @@ -126,7 +126,7 @@ DEFAULT_CONFIG_SCHEMA: types.CONFIG_SCHEMA = OrderedDict([ "value": "False", "help": "use SSL connection", "aliases": ("-s", "--ssl",), - "opposite": ["-S", "--no-ssl"], + "opposite": ("-S", "--no-ssl",), "type": bool}), ("certificate", { "value": "/etc/ssl/radicale.cert.pem", From dba6338968b17156354c7b74afaec0b0f2c39e0b Mon Sep 17 00:00:00 2001 From: Unrud Date: Wed, 10 Nov 2021 22:16:30 +0100 Subject: [PATCH 064/238] Rename opposite to opposite_aliases --- radicale/__main__.py | 2 +- radicale/config.py | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/radicale/__main__.py b/radicale/__main__.py index 8f21ece8..cd6e5d72 100644 --- a/radicale/__main__.py +++ b/radicale/__main__.py @@ -91,7 +91,7 @@ def run() -> None: del kwargs["type"] kwargs["action"] = "store_const" kwargs["const"] = "True" - opposite_args = list(kwargs.pop("opposite", ())) + opposite_args = list(kwargs.pop("opposite_aliases", ())) opposite_args.append("--no%s" % long_name[1:]) group.add_argument(*args, **kwargs) diff --git a/radicale/config.py b/radicale/config.py index ec94ada2..17e4a25d 100644 --- a/radicale/config.py +++ b/radicale/config.py @@ -126,7 +126,7 @@ DEFAULT_CONFIG_SCHEMA: types.CONFIG_SCHEMA = OrderedDict([ "value": "False", "help": "use SSL connection", "aliases": ("-s", "--ssl",), - "opposite": ("-S", "--no-ssl",), + "opposite_aliases": ("-S", "--no-ssl",), "type": bool}), ("certificate", { "value": "/etc/ssl/radicale.cert.pem", From b23aa4629c2a7e28e54f4c42ba7b830a61af70f9 Mon Sep 17 00:00:00 2001 From: Unrud Date: Sun, 14 Nov 2021 23:30:58 +0100 Subject: [PATCH 065/238] Refactor command line argument parser --- radicale/__main__.py | 47 +++++++++++++++++++++----------------------- 1 file changed, 22 insertions(+), 25 deletions(-) diff --git a/radicale/__main__.py b/radicale/__main__.py index cd6e5d72..f7aa48dc 100644 --- a/radicale/__main__.py +++ b/radicale/__main__.py @@ -30,9 +30,9 @@ import signal import socket import sys from types import FrameType -from typing import Dict, List, cast +from typing import List, cast -from radicale import VERSION, config, log, server, storage +from radicale import VERSION, config, log, server, storage, types from radicale.log import logger @@ -57,6 +57,7 @@ def run() -> None: log.setup() # Get command-line arguments + # Configuration options are stored in dest with format "c:SECTION:OPTION" parser = argparse.ArgumentParser( prog="radicale", usage="%(prog)s [OPTIONS]", allow_abbrev=False) @@ -65,36 +66,38 @@ def run() -> None: help="check the storage for errors and exit") parser.add_argument("-C", "--config", help="use specific configuration files", nargs="*") - parser.add_argument("-D", "--debug", action="store_true", + parser.add_argument("-D", "--debug", action="store_const", const="debug", + dest="c:logging:level", default=argparse.SUPPRESS, help="print debug information") - groups: Dict["argparse._ArgumentGroup", List[str]] = {} - for section, values in config.DEFAULT_CONFIG_SCHEMA.items(): + for section, section_data in config.DEFAULT_CONFIG_SCHEMA.items(): if section.startswith("_"): continue + assert ":" not in section # check field separator + assert "-" not in section and "_" not in section # not implemented group = parser.add_argument_group(section) - groups[group] = [] - for option, data in values.items(): + for option, data in section_data.items(): if option.startswith("_"): continue kwargs = data.copy() long_name = "--%s-%s" % (section, option.replace("_", "-")) args: List[str] = list(kwargs.pop("aliases", ())) args.append(long_name) - kwargs["dest"] = "%s_%s" % (section, option) - groups[group].append(kwargs["dest"]) + kwargs["dest"] = "c:%s:%s" % (section, option) + kwargs["metavar"] = "VALUE" + kwargs["default"] = argparse.SUPPRESS del kwargs["value"] with contextlib.suppress(KeyError): del kwargs["internal"] if kwargs["type"] == bool: del kwargs["type"] - kwargs["action"] = "store_const" - kwargs["const"] = "True" opposite_args = list(kwargs.pop("opposite_aliases", ())) opposite_args.append("--no%s" % long_name[1:]) + kwargs["action"] = "store_const" + kwargs["const"] = "True" group.add_argument(*args, **kwargs) - + # Opposite argument kwargs["const"] = "False" kwargs["help"] = "do not %s (opposite of %s)" % ( kwargs["help"], long_name) @@ -106,23 +109,17 @@ def run() -> None: args_ns = parser.parse_args() # Preliminary configure logging - if args_ns.debug: - args_ns.logging_level = "debug" with contextlib.suppress(ValueError): log.set_level(config.DEFAULT_CONFIG_SCHEMA["logging"]["level"]["type"]( - args_ns.logging_level)) + vars(args_ns).get("c:logging:level", ""))) # Update Radicale configuration according to arguments - arguments_config = {} - for group, actions in groups.items(): - section = group.title or "" - section_config = {} - for action in actions: - value = getattr(args_ns, action) - if value is not None: - section_config[action.split('_', 1)[1]] = value - if section_config: - arguments_config[section] = section_config + arguments_config: types.MUTABLE_CONFIG = {} + for key, value in vars(args_ns).items(): + if key.startswith("c:"): + _, section, option = key.split(":", maxsplit=2) + arguments_config[section] = arguments_config.get(section, {}) + arguments_config[section][option] = value try: configuration = config.load(config.parse_compound_paths( From 08e789d993a3297baaee6c2117c40eb278047c79 Mon Sep 17 00:00:00 2001 From: Unrud Date: Sun, 14 Nov 2021 23:30:59 +0100 Subject: [PATCH 066/238] Support backend specific options and HTTP headers via command-line --- radicale/__main__.py | 36 +++++++++++++++++++++++++++++++++-- radicale/tests/test_server.py | 16 ++++++++++++---- 2 files changed, 46 insertions(+), 6 deletions(-) diff --git a/radicale/__main__.py b/radicale/__main__.py index f7aa48dc..67da92b8 100644 --- a/radicale/__main__.py +++ b/radicale/__main__.py @@ -75,7 +75,14 @@ def run() -> None: continue assert ":" not in section # check field separator assert "-" not in section and "_" not in section # not implemented - group = parser.add_argument_group(section) + group_description = None + if section_data.get("_allow_extra"): + group_description = "additional options allowed" + if section == "headers": + group_description += " (e.g. --headers-Pragma=no-cache)" + elif "type" in section_data: + group_description = "backend specific options omitted" + group = parser.add_argument_group(section, group_description) for option, data in section_data.items(): if option.startswith("_"): continue @@ -106,7 +113,32 @@ def run() -> None: del kwargs["type"] group.add_argument(*args, **kwargs) - args_ns = parser.parse_args() + args_ns, remaining_args = parser.parse_known_args() + unrecognized_args = [] + while remaining_args: + arg = remaining_args.pop(0) + for section, data in config.DEFAULT_CONFIG_SCHEMA.items(): + if "type" not in data and not data.get("_allow_extra"): + continue + prefix = "--%s-" % section + if arg.startswith(prefix): + arg = arg[len(prefix):] + break + else: + unrecognized_args.append(arg) + continue + value = "" + if "=" in arg: + arg, value = arg.split("=", maxsplit=1) + elif remaining_args and not remaining_args[0].startswith("-"): + value = remaining_args.pop(0) + option = arg + if not data.get("_allow_extra"): # preserve dash in HTTP header names + option = option.replace("-", "_") + vars(args_ns)["c:%s:%s" % (section, option)] = value + if unrecognized_args: + parser.error("unrecognized arguments: %s" % + " ".join(unrecognized_args)) # Preliminary configure logging with contextlib.suppress(ValueError): diff --git a/radicale/tests/test_server.py b/radicale/tests/test_server.py index 956bc85b..d2b0243a 100644 --- a/radicale/tests/test_server.py +++ b/radicale/tests/test_server.py @@ -188,15 +188,17 @@ class TestBaseServerRequests(BaseTest): self.get("/", check=302) def test_command_line_interface(self) -> None: + self.configuration.update({"headers": {"Test-Server": "test"}}) config_args = [] - for section, values in config.DEFAULT_CONFIG_SCHEMA.items(): + for section in self.configuration.sections(): if section.startswith("_"): continue - for option, data in values.items(): + for option in self.configuration.options(section): if option.startswith("_"): continue long_name = "--%s-%s" % (section, option.replace("_", "-")) - if data["type"] == bool: + if config.DEFAULT_CONFIG_SCHEMA.get( + section, {}).get(option, {}).get("type") == bool: if not cast(bool, self.configuration.get(section, option)): long_name = "--no%s" % long_name[1:] config_args.append(long_name) @@ -205,11 +207,17 @@ class TestBaseServerRequests(BaseTest): raw_value = self.configuration.get_raw(section, option) assert isinstance(raw_value, str) config_args.append(raw_value) + config_args.append("--headers-Test-Header=test") p = subprocess.Popen( [sys.executable, "-m", "radicale"] + config_args, env={**os.environ, "PYTHONPATH": os.pathsep.join(sys.path)}) try: - self.get("/", is_alive_fn=lambda: p.poll() is None, check=302) + status, headers, _ = self.request( + "GET", "/", is_alive_fn=lambda: p.poll() is None) + self._check_status(status, 302) + for key in self.configuration.options("headers"): + assert headers.get(key) == self.configuration.get( + "headers", key) finally: p.terminate() p.wait() From 98b49ac2b6ad7325e3e0104084968b0c541f4dfe Mon Sep 17 00:00:00 2001 From: Unrud Date: Sun, 14 Nov 2021 23:30:59 +0100 Subject: [PATCH 067/238] Optional argument for boolean command-line options --- radicale/__main__.py | 8 +++----- radicale/tests/test_server.py | 7 +++++-- 2 files changed, 8 insertions(+), 7 deletions(-) diff --git a/radicale/__main__.py b/radicale/__main__.py index 67da92b8..2ad9fa17 100644 --- a/radicale/__main__.py +++ b/radicale/__main__.py @@ -101,14 +101,12 @@ def run() -> None: del kwargs["type"] opposite_args = list(kwargs.pop("opposite_aliases", ())) opposite_args.append("--no%s" % long_name[1:]) - kwargs["action"] = "store_const" - kwargs["const"] = "True" - group.add_argument(*args, **kwargs) + group.add_argument(*args, nargs="?", const="True", **kwargs) # Opposite argument - kwargs["const"] = "False" kwargs["help"] = "do not %s (opposite of %s)" % ( kwargs["help"], long_name) - group.add_argument(*opposite_args, **kwargs) + group.add_argument(*opposite_args, action="store_const", + const="False", **kwargs) else: del kwargs["type"] group.add_argument(*args, **kwargs) diff --git a/radicale/tests/test_server.py b/radicale/tests/test_server.py index d2b0243a..7420e1cd 100644 --- a/radicale/tests/test_server.py +++ b/radicale/tests/test_server.py @@ -187,7 +187,7 @@ class TestBaseServerRequests(BaseTest): self.thread.start() self.get("/", check=302) - def test_command_line_interface(self) -> None: + def test_command_line_interface(self, with_bool_options=False) -> None: self.configuration.update({"headers": {"Test-Server": "test"}}) config_args = [] for section in self.configuration.sections(): @@ -197,7 +197,7 @@ class TestBaseServerRequests(BaseTest): if option.startswith("_"): continue long_name = "--%s-%s" % (section, option.replace("_", "-")) - if config.DEFAULT_CONFIG_SCHEMA.get( + if with_bool_options and config.DEFAULT_CONFIG_SCHEMA.get( section, {}).get(option, {}).get("type") == bool: if not cast(bool, self.configuration.get(section, option)): long_name = "--no%s" % long_name[1:] @@ -224,6 +224,9 @@ class TestBaseServerRequests(BaseTest): if os.name == "posix": assert p.returncode == 0 + def test_command_line_interface_with_bool_options(self) -> None: + self.test_command_line_interface(with_bool_options=True) + def test_wsgi_server(self) -> None: config_path = os.path.join(self.colpath, "config") parser = RawConfigParser() From e629e9a2e17b7f2461c0b7fab520d6171b7d2b1c Mon Sep 17 00:00:00 2001 From: Unrud Date: Sun, 14 Nov 2021 23:31:00 +0100 Subject: [PATCH 068/238] Require argument for --config command-line option --- radicale/__main__.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/radicale/__main__.py b/radicale/__main__.py index 2ad9fa17..f1828123 100644 --- a/radicale/__main__.py +++ b/radicale/__main__.py @@ -65,7 +65,7 @@ def run() -> None: parser.add_argument("--verify-storage", action="store_true", help="check the storage for errors and exit") parser.add_argument("-C", "--config", - help="use specific configuration files", nargs="*") + help="use specific configuration files", nargs="+") parser.add_argument("-D", "--debug", action="store_const", const="debug", dest="c:logging:level", default=argparse.SUPPRESS, help="print debug information") From f14e1de071c10b2c2b7803a50ea8779a6b05ce89 Mon Sep 17 00:00:00 2001 From: Unrud Date: Wed, 8 Dec 2021 21:41:12 +0100 Subject: [PATCH 069/238] Add multifilesystem_nolock storage --- DOCUMENTATION.md | 3 + config | 2 +- radicale/storage/__init__.py | 2 +- radicale/storage/multifilesystem_nolock.py | 103 +++++++++++++++++++++ radicale/tests/test_base.py | 9 ++ 5 files changed, 117 insertions(+), 2 deletions(-) create mode 100644 radicale/storage/multifilesystem_nolock.py diff --git a/DOCUMENTATION.md b/DOCUMENTATION.md index 35f9bf3c..1de8ebca 100644 --- a/DOCUMENTATION.md +++ b/DOCUMENTATION.md @@ -743,6 +743,9 @@ Available backends: `multifilesystem` : Stores the data in the filesystem. +`multifilesystem_nolock` +: The `multifilesystem` backend without file-based locking. Must only be used with a single process. + Default: `multifilesystem` #### filesystem_folder diff --git a/config b/config index 1d0ee557..7c77f5f9 100644 --- a/config +++ b/config @@ -83,7 +83,7 @@ [storage] # Storage backend -# Value: multifilesystem +# Value: multifilesystem | multifilesystem_nolock #type = multifilesystem # Folder for storing local collections, created if not present diff --git a/radicale/storage/__init__.py b/radicale/storage/__init__.py index 0163c7ca..c36a070d 100644 --- a/radicale/storage/__init__.py +++ b/radicale/storage/__init__.py @@ -37,7 +37,7 @@ from radicale import item as radicale_item from radicale import types, utils from radicale.item import filter as radicale_filter -INTERNAL_TYPES: Sequence[str] = ("multifilesystem",) +INTERNAL_TYPES: Sequence[str] = ("multifilesystem", "multifilesystem_nolock",) CACHE_DEPS: Sequence[str] = ("radicale", "vobject", "python-dateutil",) CACHE_VERSION: bytes = "".join( diff --git a/radicale/storage/multifilesystem_nolock.py b/radicale/storage/multifilesystem_nolock.py new file mode 100644 index 00000000..6bb63a22 --- /dev/null +++ b/radicale/storage/multifilesystem_nolock.py @@ -0,0 +1,103 @@ +# This file is part of Radicale Server - Calendar Server +# Copyright © 2021 Unrud +# +# This library is free software: you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation, either version 3 of the License, or +# (at your option) any later version. +# +# This library is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with Radicale. If not, see . + +""" +The multifilesystem backend without file-based locking. +""" + +import threading +from collections import deque +from typing import Deque, Dict, Iterator, Tuple + +from radicale import config, pathutils, types +from radicale.storage import multifilesystem + + +class RwLock(pathutils.RwLock): + + _cond: threading.Condition + + def __init__(self) -> None: + super().__init__("") + self._cond = threading.Condition(self._lock) + + @types.contextmanager + def acquire(self, mode: str, user: str = "") -> Iterator[None]: + if mode not in "rw": + raise ValueError("Invalid mode: %r" % mode) + with self._cond: + self._cond.wait_for(lambda: not self._writer and ( + mode == "r" or self._readers == 0)) + if mode == "r": + self._readers += 1 + self._cond.notify() + else: + self._writer = True + try: + yield + finally: + with self._cond: + if mode == "r": + self._readers -= 1 + self._writer = False + self._cond.notify() + + +class Collection(multifilesystem.Collection): + + _storage: "Storage" + + @types.contextmanager + def _acquire_cache_lock(self, ns: str = "") -> Iterator[None]: + if self._storage._lock.locked == "w": + yield + return + key = (self.path, ns) + with self._storage._cache_lock: + waiters = self._storage._cache_locks.get(key) + if waiters is None: + self._storage._cache_locks[key] = waiters = deque() + wait = bool(waiters) + waiter = threading.Lock() + waiter.acquire() + waiters.append(waiter) + if wait: + waiter.acquire() + try: + yield + finally: + with self._storage._cache_lock: + removedWaiter = waiters.popleft() + assert removedWaiter is waiter + if waiters: + waiters[0].release() + else: + removedWaiters = self._storage._cache_locks.pop(key) + assert removedWaiters is waiters + + +class Storage(multifilesystem.Storage): + + _collection_class = Collection + + _cache_lock: threading.Lock + _cache_locks: Dict[Tuple[str, str], Deque[threading.Lock]] + + def __init__(self, configuration: config.Configuration) -> None: + super().__init__(configuration) + self._lock = RwLock() + self._cache_lock = threading.Lock() + self._cache_locks = {} diff --git a/radicale/tests/test_base.py b/radicale/tests/test_base.py index 4e8cd113..0c33d539 100644 --- a/radicale/tests/test_base.py +++ b/radicale/tests/test_base.py @@ -1751,6 +1751,15 @@ class TestMultiFileSystem(BaseFileSystemTest, BaseRequestsMixIn): assert "\r\nUID:%s\r\n" % uid in answer +class TestMultiFileSystemNoLock(BaseFileSystemTest): + """Test BaseRequests on multifilesystem_nolock.""" + + storage_type: ClassVar[StorageType] = "multifilesystem_nolock" + + test_add_event = BaseRequestsMixIn.test_add_event + test_item_cache_rebuild = TestMultiFileSystem.test_item_cache_rebuild + + class TestCustomStorageSystem(BaseFileSystemTest): """Test custom backend loading.""" From bbaf0ebd8cd85efe6bca2ce1a5b648c908c89d43 Mon Sep 17 00:00:00 2001 From: Unrud Date: Wed, 8 Dec 2021 21:45:42 +0100 Subject: [PATCH 070/238] Change name in file header --- radicale/__init__.py | 2 +- radicale/__main__.py | 2 +- radicale/app/__init__.py | 2 +- radicale/app/base.py | 2 +- radicale/app/delete.py | 2 +- radicale/app/get.py | 2 +- radicale/app/head.py | 2 +- radicale/app/mkcalendar.py | 2 +- radicale/app/mkcol.py | 2 +- radicale/app/move.py | 2 +- radicale/app/options.py | 2 +- radicale/app/post.py | 2 +- radicale/app/propfind.py | 2 +- radicale/app/proppatch.py | 2 +- radicale/app/put.py | 2 +- radicale/app/report.py | 2 +- radicale/auth/__init__.py | 2 +- radicale/auth/htpasswd.py | 2 +- radicale/auth/http_x_remote_user.py | 2 +- radicale/auth/none.py | 2 +- radicale/auth/remote_user.py | 2 +- radicale/config.py | 2 +- radicale/httputils.py | 2 +- radicale/item/__init__.py | 2 +- radicale/item/filter.py | 2 +- radicale/log.py | 2 +- radicale/pathutils.py | 2 +- radicale/rights/__init__.py | 2 +- radicale/rights/authenticated.py | 2 +- radicale/rights/from_file.py | 2 +- radicale/rights/owner_only.py | 2 +- radicale/rights/owner_write.py | 2 +- radicale/server.py | 2 +- radicale/storage/__init__.py | 2 +- radicale/storage/multifilesystem/__init__.py | 2 +- radicale/storage/multifilesystem/base.py | 2 +- radicale/storage/multifilesystem/cache.py | 2 +- radicale/storage/multifilesystem/create_collection.py | 2 +- radicale/storage/multifilesystem/delete.py | 2 +- radicale/storage/multifilesystem/discover.py | 2 +- radicale/storage/multifilesystem/get.py | 2 +- radicale/storage/multifilesystem/history.py | 2 +- radicale/storage/multifilesystem/lock.py | 2 +- radicale/storage/multifilesystem/meta.py | 2 +- radicale/storage/multifilesystem/move.py | 2 +- radicale/storage/multifilesystem/sync.py | 2 +- radicale/storage/multifilesystem/upload.py | 2 +- radicale/storage/multifilesystem/verify.py | 2 +- radicale/storage/multifilesystem_nolock.py | 2 +- radicale/tests/__init__.py | 2 +- radicale/tests/custom/auth.py | 2 +- radicale/tests/custom/rights.py | 2 +- radicale/tests/custom/storage_simple_sync.py | 2 +- radicale/tests/custom/web.py | 2 +- radicale/tests/helpers.py | 2 +- radicale/tests/test_auth.py | 2 +- radicale/tests/test_base.py | 2 +- radicale/tests/test_config.py | 2 +- radicale/tests/test_rights.py | 2 +- radicale/tests/test_server.py | 2 +- radicale/tests/test_web.py | 2 +- radicale/types.py | 2 +- radicale/utils.py | 2 +- radicale/web/__init__.py | 2 +- radicale/web/internal.py | 2 +- radicale/web/none.py | 2 +- radicale/xmlutils.py | 2 +- setup.py | 2 +- 68 files changed, 68 insertions(+), 68 deletions(-) diff --git a/radicale/__init__.py b/radicale/__init__.py index ef98635d..1f107739 100644 --- a/radicale/__init__.py +++ b/radicale/__init__.py @@ -1,4 +1,4 @@ -# This file is part of Radicale Server - Calendar Server +# This file is part of Radicale - CalDAV and CardDAV server # Copyright © 2008 Nicolas Kandel # Copyright © 2008 Pascal Halter # Copyright © 2008-2017 Guillaume Ayoub diff --git a/radicale/__main__.py b/radicale/__main__.py index f1828123..d0bfe7bb 100644 --- a/radicale/__main__.py +++ b/radicale/__main__.py @@ -1,4 +1,4 @@ -# This file is part of Radicale Server - Calendar Server +# This file is part of Radicale - CalDAV and CardDAV server # Copyright © 2011-2017 Guillaume Ayoub # Copyright © 2017-2019 Unrud # diff --git a/radicale/app/__init__.py b/radicale/app/__init__.py index 6bebf81c..ffb9e267 100644 --- a/radicale/app/__init__.py +++ b/radicale/app/__init__.py @@ -1,4 +1,4 @@ -# This file is part of Radicale Server - Calendar Server +# This file is part of Radicale - CalDAV and CardDAV server # Copyright © 2008 Nicolas Kandel # Copyright © 2008 Pascal Halter # Copyright © 2008-2017 Guillaume Ayoub diff --git a/radicale/app/base.py b/radicale/app/base.py index 7b139a26..4316117d 100644 --- a/radicale/app/base.py +++ b/radicale/app/base.py @@ -1,4 +1,4 @@ -# This file is part of Radicale Server - Calendar Server +# This file is part of Radicale - CalDAV and CardDAV server # Copyright © 2020 Unrud # # This library is free software: you can redistribute it and/or modify diff --git a/radicale/app/delete.py b/radicale/app/delete.py index c47fea3f..69ae5ab4 100644 --- a/radicale/app/delete.py +++ b/radicale/app/delete.py @@ -1,4 +1,4 @@ -# This file is part of Radicale Server - Calendar Server +# This file is part of Radicale - CalDAV and CardDAV server # Copyright © 2008 Nicolas Kandel # Copyright © 2008 Pascal Halter # Copyright © 2008-2017 Guillaume Ayoub diff --git a/radicale/app/get.py b/radicale/app/get.py index 7e990027..255a3f10 100644 --- a/radicale/app/get.py +++ b/radicale/app/get.py @@ -1,4 +1,4 @@ -# This file is part of Radicale Server - Calendar Server +# This file is part of Radicale - CalDAV and CardDAV server # Copyright © 2008 Nicolas Kandel # Copyright © 2008 Pascal Halter # Copyright © 2008-2017 Guillaume Ayoub diff --git a/radicale/app/head.py b/radicale/app/head.py index 357682d2..af39873b 100644 --- a/radicale/app/head.py +++ b/radicale/app/head.py @@ -1,4 +1,4 @@ -# This file is part of Radicale Server - Calendar Server +# This file is part of Radicale - CalDAV and CardDAV server # Copyright © 2008 Nicolas Kandel # Copyright © 2008 Pascal Halter # Copyright © 2008-2017 Guillaume Ayoub diff --git a/radicale/app/mkcalendar.py b/radicale/app/mkcalendar.py index 67b6c3fc..c507ae44 100644 --- a/radicale/app/mkcalendar.py +++ b/radicale/app/mkcalendar.py @@ -1,4 +1,4 @@ -# This file is part of Radicale Server - Calendar Server +# This file is part of Radicale - CalDAV and CardDAV server # Copyright © 2008 Nicolas Kandel # Copyright © 2008 Pascal Halter # Copyright © 2008-2017 Guillaume Ayoub diff --git a/radicale/app/mkcol.py b/radicale/app/mkcol.py index 5d871697..94207e32 100644 --- a/radicale/app/mkcol.py +++ b/radicale/app/mkcol.py @@ -1,4 +1,4 @@ -# This file is part of Radicale Server - Calendar Server +# This file is part of Radicale - CalDAV and CardDAV server # Copyright © 2008 Nicolas Kandel # Copyright © 2008 Pascal Halter # Copyright © 2008-2017 Guillaume Ayoub diff --git a/radicale/app/move.py b/radicale/app/move.py index 37a72946..fda85257 100644 --- a/radicale/app/move.py +++ b/radicale/app/move.py @@ -1,4 +1,4 @@ -# This file is part of Radicale Server - Calendar Server +# This file is part of Radicale - CalDAV and CardDAV server # Copyright © 2008 Nicolas Kandel # Copyright © 2008 Pascal Halter # Copyright © 2008-2017 Guillaume Ayoub diff --git a/radicale/app/options.py b/radicale/app/options.py index 19f00f07..6e9053a3 100644 --- a/radicale/app/options.py +++ b/radicale/app/options.py @@ -1,4 +1,4 @@ -# This file is part of Radicale Server - Calendar Server +# This file is part of Radicale - CalDAV and CardDAV server # Copyright © 2008 Nicolas Kandel # Copyright © 2008 Pascal Halter # Copyright © 2008-2017 Guillaume Ayoub diff --git a/radicale/app/post.py b/radicale/app/post.py index e350a103..f5367b86 100644 --- a/radicale/app/post.py +++ b/radicale/app/post.py @@ -1,4 +1,4 @@ -# This file is part of Radicale Server - Calendar Server +# This file is part of Radicale - CalDAV and CardDAV server # Copyright © 2008 Nicolas Kandel # Copyright © 2008 Pascal Halter # Copyright © 2008-2017 Guillaume Ayoub diff --git a/radicale/app/propfind.py b/radicale/app/propfind.py index e4f674e9..52d0b00b 100644 --- a/radicale/app/propfind.py +++ b/radicale/app/propfind.py @@ -1,4 +1,4 @@ -# This file is part of Radicale Server - Calendar Server +# This file is part of Radicale - CalDAV and CardDAV server # Copyright © 2008 Nicolas Kandel # Copyright © 2008 Pascal Halter # Copyright © 2008-2017 Guillaume Ayoub diff --git a/radicale/app/proppatch.py b/radicale/app/proppatch.py index 7170266f..934f53b7 100644 --- a/radicale/app/proppatch.py +++ b/radicale/app/proppatch.py @@ -1,4 +1,4 @@ -# This file is part of Radicale Server - Calendar Server +# This file is part of Radicale - CalDAV and CardDAV server # Copyright © 2008 Nicolas Kandel # Copyright © 2008 Pascal Halter # Copyright © 2008-2017 Guillaume Ayoub diff --git a/radicale/app/put.py b/radicale/app/put.py index bdb9faee..ac07bf45 100644 --- a/radicale/app/put.py +++ b/radicale/app/put.py @@ -1,4 +1,4 @@ -# This file is part of Radicale Server - Calendar Server +# This file is part of Radicale - CalDAV and CardDAV server # Copyright © 2008 Nicolas Kandel # Copyright © 2008 Pascal Halter # Copyright © 2008-2017 Guillaume Ayoub diff --git a/radicale/app/report.py b/radicale/app/report.py index b2e6335a..5807f6e6 100644 --- a/radicale/app/report.py +++ b/radicale/app/report.py @@ -1,4 +1,4 @@ -# This file is part of Radicale Server - Calendar Server +# This file is part of Radicale - CalDAV and CardDAV server # Copyright © 2008 Nicolas Kandel # Copyright © 2008 Pascal Halter # Copyright © 2008-2017 Guillaume Ayoub diff --git a/radicale/auth/__init__.py b/radicale/auth/__init__.py index 8de6c5f0..a7776bdf 100644 --- a/radicale/auth/__init__.py +++ b/radicale/auth/__init__.py @@ -1,4 +1,4 @@ -# This file is part of Radicale Server - Calendar Server +# This file is part of Radicale - CalDAV and CardDAV server # Copyright © 2008 Nicolas Kandel # Copyright © 2008 Pascal Halter # Copyright © 2008-2017 Guillaume Ayoub diff --git a/radicale/auth/htpasswd.py b/radicale/auth/htpasswd.py index 35e30f9f..872f7277 100644 --- a/radicale/auth/htpasswd.py +++ b/radicale/auth/htpasswd.py @@ -1,4 +1,4 @@ -# This file is part of Radicale Server - Calendar Server +# This file is part of Radicale - CalDAV and CardDAV server # Copyright © 2008 Nicolas Kandel # Copyright © 2008 Pascal Halter # Copyright © 2008-2017 Guillaume Ayoub diff --git a/radicale/auth/http_x_remote_user.py b/radicale/auth/http_x_remote_user.py index 8c0f236d..120342ab 100644 --- a/radicale/auth/http_x_remote_user.py +++ b/radicale/auth/http_x_remote_user.py @@ -1,4 +1,4 @@ -# This file is part of Radicale Server - Calendar Server +# This file is part of Radicale - CalDAV and CardDAV server # Copyright © 2008 Nicolas Kandel # Copyright © 2008 Pascal Halter # Copyright © 2008-2017 Guillaume Ayoub diff --git a/radicale/auth/none.py b/radicale/auth/none.py index b75a33c1..ce2b1c86 100644 --- a/radicale/auth/none.py +++ b/radicale/auth/none.py @@ -1,4 +1,4 @@ -# This file is part of Radicale Server - Calendar Server +# This file is part of Radicale - CalDAV and CardDAV server # Copyright © 2008 Nicolas Kandel # Copyright © 2008 Pascal Halter # Copyright © 2008-2017 Guillaume Ayoub diff --git a/radicale/auth/remote_user.py b/radicale/auth/remote_user.py index 81175913..98e255a0 100644 --- a/radicale/auth/remote_user.py +++ b/radicale/auth/remote_user.py @@ -1,4 +1,4 @@ -# This file is part of Radicale Server - Calendar Server +# This file is part of Radicale - CalDAV and CardDAV server # Copyright © 2008 Nicolas Kandel # Copyright © 2008 Pascal Halter # Copyright © 2008-2017 Guillaume Ayoub diff --git a/radicale/config.py b/radicale/config.py index 17e4a25d..0e119109 100644 --- a/radicale/config.py +++ b/radicale/config.py @@ -1,4 +1,4 @@ -# This file is part of Radicale Server - Calendar Server +# This file is part of Radicale - CalDAV and CardDAV server # Copyright © 2008-2017 Guillaume Ayoub # Copyright © 2008 Nicolas Kandel # Copyright © 2008 Pascal Halter diff --git a/radicale/httputils.py b/radicale/httputils.py index d8a31b61..000bee78 100644 --- a/radicale/httputils.py +++ b/radicale/httputils.py @@ -1,4 +1,4 @@ -# This file is part of Radicale Server - Calendar Server +# This file is part of Radicale - CalDAV and CardDAV server # Copyright © 2008 Nicolas Kandel # Copyright © 2008 Pascal Halter # Copyright © 2008-2017 Guillaume Ayoub diff --git a/radicale/item/__init__.py b/radicale/item/__init__.py index 3c9c59d3..e715e2c0 100644 --- a/radicale/item/__init__.py +++ b/radicale/item/__init__.py @@ -1,4 +1,4 @@ -# This file is part of Radicale Server - Calendar Server +# This file is part of Radicale - CalDAV and CardDAV server # Copyright © 2008 Nicolas Kandel # Copyright © 2008 Pascal Halter # Copyright © 2014 Jean-Marc Martins diff --git a/radicale/item/filter.py b/radicale/item/filter.py index 973f4ddb..4db14658 100644 --- a/radicale/item/filter.py +++ b/radicale/item/filter.py @@ -1,4 +1,4 @@ -# This file is part of Radicale Server - Calendar Server +# This file is part of Radicale - CalDAV and CardDAV server # Copyright © 2008 Nicolas Kandel # Copyright © 2008 Pascal Halter # Copyright © 2008-2015 Guillaume Ayoub diff --git a/radicale/log.py b/radicale/log.py index 708a36f5..eaa842bf 100644 --- a/radicale/log.py +++ b/radicale/log.py @@ -1,4 +1,4 @@ -# This file is part of Radicale Server - Calendar Server +# This file is part of Radicale - CalDAV and CardDAV server # Copyright © 2011-2017 Guillaume Ayoub # Copyright © 2017-2019 Unrud # diff --git a/radicale/pathutils.py b/radicale/pathutils.py index fdbff5d3..df039418 100644 --- a/radicale/pathutils.py +++ b/radicale/pathutils.py @@ -1,4 +1,4 @@ -# This file is part of Radicale Server - Calendar Server +# This file is part of Radicale - CalDAV and CardDAV server # Copyright © 2014 Jean-Marc Martins # Copyright © 2012-2017 Guillaume Ayoub # Copyright © 2017-2018 Unrud diff --git a/radicale/rights/__init__.py b/radicale/rights/__init__.py index 62a79cb0..1b898659 100644 --- a/radicale/rights/__init__.py +++ b/radicale/rights/__init__.py @@ -1,4 +1,4 @@ -# This file is part of Radicale Server - Calendar Server +# This file is part of Radicale - CalDAV and CardDAV server # Copyright © 2012-2017 Guillaume Ayoub # Copyright © 2017-2018 Unrud # diff --git a/radicale/rights/authenticated.py b/radicale/rights/authenticated.py index fc669b4f..a72cae08 100644 --- a/radicale/rights/authenticated.py +++ b/radicale/rights/authenticated.py @@ -1,4 +1,4 @@ -# This file is part of Radicale Server - Calendar Server +# This file is part of Radicale - CalDAV and CardDAV server # Copyright © 2012-2017 Guillaume Ayoub # Copyright © 2017-2018 Unrud # diff --git a/radicale/rights/from_file.py b/radicale/rights/from_file.py index 5ec90cea..c7e9c0cd 100644 --- a/radicale/rights/from_file.py +++ b/radicale/rights/from_file.py @@ -1,4 +1,4 @@ -# This file is part of Radicale Server - Calendar Server +# This file is part of Radicale - CalDAV and CardDAV server # Copyright © 2012-2017 Guillaume Ayoub # Copyright © 2017-2019 Unrud # diff --git a/radicale/rights/owner_only.py b/radicale/rights/owner_only.py index bfcad8ee..36b25d9c 100644 --- a/radicale/rights/owner_only.py +++ b/radicale/rights/owner_only.py @@ -1,4 +1,4 @@ -# This file is part of Radicale Server - Calendar Server +# This file is part of Radicale - CalDAV and CardDAV server # Copyright © 2012-2017 Guillaume Ayoub # Copyright © 2017-2018 Unrud # diff --git a/radicale/rights/owner_write.py b/radicale/rights/owner_write.py index be4c92db..e28790ad 100644 --- a/radicale/rights/owner_write.py +++ b/radicale/rights/owner_write.py @@ -1,4 +1,4 @@ -# This file is part of Radicale Server - Calendar Server +# This file is part of Radicale - CalDAV and CardDAV server # Copyright © 2012-2017 Guillaume Ayoub # Copyright © 2017-2018 Unrud # diff --git a/radicale/server.py b/radicale/server.py index 7ec5b3c4..459c3385 100644 --- a/radicale/server.py +++ b/radicale/server.py @@ -1,4 +1,4 @@ -# This file is part of Radicale Server - Calendar Server +# This file is part of Radicale - CalDAV and CardDAV server # Copyright © 2008 Nicolas Kandel # Copyright © 2008 Pascal Halter # Copyright © 2008-2017 Guillaume Ayoub diff --git a/radicale/storage/__init__.py b/radicale/storage/__init__.py index c36a070d..db6a8718 100644 --- a/radicale/storage/__init__.py +++ b/radicale/storage/__init__.py @@ -1,4 +1,4 @@ -# This file is part of Radicale Server - Calendar Server +# This file is part of Radicale - CalDAV and CardDAV server # Copyright © 2014 Jean-Marc Martins # Copyright © 2012-2017 Guillaume Ayoub # Copyright © 2017-2018 Unrud diff --git a/radicale/storage/multifilesystem/__init__.py b/radicale/storage/multifilesystem/__init__.py index e044fb17..b5b24b1b 100644 --- a/radicale/storage/multifilesystem/__init__.py +++ b/radicale/storage/multifilesystem/__init__.py @@ -1,4 +1,4 @@ -# This file is part of Radicale Server - Calendar Server +# This file is part of Radicale - CalDAV and CardDAV server # Copyright © 2014 Jean-Marc Martins # Copyright © 2012-2017 Guillaume Ayoub # Copyright © 2017-2019 Unrud diff --git a/radicale/storage/multifilesystem/base.py b/radicale/storage/multifilesystem/base.py index 5f2cdf93..241458c3 100644 --- a/radicale/storage/multifilesystem/base.py +++ b/radicale/storage/multifilesystem/base.py @@ -1,4 +1,4 @@ -# This file is part of Radicale Server - Calendar Server +# This file is part of Radicale - CalDAV and CardDAV server # Copyright © 2014 Jean-Marc Martins # Copyright © 2012-2017 Guillaume Ayoub # Copyright © 2017-2019 Unrud diff --git a/radicale/storage/multifilesystem/cache.py b/radicale/storage/multifilesystem/cache.py index 119317dd..9cb4dda6 100644 --- a/radicale/storage/multifilesystem/cache.py +++ b/radicale/storage/multifilesystem/cache.py @@ -1,4 +1,4 @@ -# This file is part of Radicale Server - Calendar Server +# This file is part of Radicale - CalDAV and CardDAV server # Copyright © 2014 Jean-Marc Martins # Copyright © 2012-2017 Guillaume Ayoub # Copyright © 2017-2018 Unrud diff --git a/radicale/storage/multifilesystem/create_collection.py b/radicale/storage/multifilesystem/create_collection.py index 422c3c99..75d3a387 100644 --- a/radicale/storage/multifilesystem/create_collection.py +++ b/radicale/storage/multifilesystem/create_collection.py @@ -1,4 +1,4 @@ -# This file is part of Radicale Server - Calendar Server +# This file is part of Radicale - CalDAV and CardDAV server # Copyright © 2014 Jean-Marc Martins # Copyright © 2012-2017 Guillaume Ayoub # Copyright © 2017-2018 Unrud diff --git a/radicale/storage/multifilesystem/delete.py b/radicale/storage/multifilesystem/delete.py index 56a47325..dd7a26e2 100644 --- a/radicale/storage/multifilesystem/delete.py +++ b/radicale/storage/multifilesystem/delete.py @@ -1,4 +1,4 @@ -# This file is part of Radicale Server - Calendar Server +# This file is part of Radicale - CalDAV and CardDAV server # Copyright © 2014 Jean-Marc Martins # Copyright © 2012-2017 Guillaume Ayoub # Copyright © 2017-2018 Unrud diff --git a/radicale/storage/multifilesystem/discover.py b/radicale/storage/multifilesystem/discover.py index 211f2144..00316141 100644 --- a/radicale/storage/multifilesystem/discover.py +++ b/radicale/storage/multifilesystem/discover.py @@ -1,4 +1,4 @@ -# This file is part of Radicale Server - Calendar Server +# This file is part of Radicale - CalDAV and CardDAV server # Copyright © 2014 Jean-Marc Martins # Copyright © 2012-2017 Guillaume Ayoub # Copyright © 2017-2018 Unrud diff --git a/radicale/storage/multifilesystem/get.py b/radicale/storage/multifilesystem/get.py index 2f2f5923..e4f184e0 100644 --- a/radicale/storage/multifilesystem/get.py +++ b/radicale/storage/multifilesystem/get.py @@ -1,4 +1,4 @@ -# This file is part of Radicale Server - Calendar Server +# This file is part of Radicale - CalDAV and CardDAV server # Copyright © 2014 Jean-Marc Martins # Copyright © 2012-2017 Guillaume Ayoub # Copyright © 2017-2018 Unrud diff --git a/radicale/storage/multifilesystem/history.py b/radicale/storage/multifilesystem/history.py index 767a8637..c385c32a 100644 --- a/radicale/storage/multifilesystem/history.py +++ b/radicale/storage/multifilesystem/history.py @@ -1,4 +1,4 @@ -# This file is part of Radicale Server - Calendar Server +# This file is part of Radicale - CalDAV and CardDAV server # Copyright © 2014 Jean-Marc Martins # Copyright © 2012-2017 Guillaume Ayoub # Copyright © 2017-2019 Unrud diff --git a/radicale/storage/multifilesystem/lock.py b/radicale/storage/multifilesystem/lock.py index 164a9965..803b72f6 100644 --- a/radicale/storage/multifilesystem/lock.py +++ b/radicale/storage/multifilesystem/lock.py @@ -1,4 +1,4 @@ -# This file is part of Radicale Server - Calendar Server +# This file is part of Radicale - CalDAV and CardDAV server # Copyright © 2014 Jean-Marc Martins # Copyright © 2012-2017 Guillaume Ayoub # Copyright © 2017-2019 Unrud diff --git a/radicale/storage/multifilesystem/meta.py b/radicale/storage/multifilesystem/meta.py index 6b932f7c..edce6513 100644 --- a/radicale/storage/multifilesystem/meta.py +++ b/radicale/storage/multifilesystem/meta.py @@ -1,4 +1,4 @@ -# This file is part of Radicale Server - Calendar Server +# This file is part of Radicale - CalDAV and CardDAV server # Copyright © 2014 Jean-Marc Martins # Copyright © 2012-2017 Guillaume Ayoub # Copyright © 2017-2018 Unrud diff --git a/radicale/storage/multifilesystem/move.py b/radicale/storage/multifilesystem/move.py index a73894f4..30995c4f 100644 --- a/radicale/storage/multifilesystem/move.py +++ b/radicale/storage/multifilesystem/move.py @@ -1,4 +1,4 @@ -# This file is part of Radicale Server - Calendar Server +# This file is part of Radicale - CalDAV and CardDAV server # Copyright © 2014 Jean-Marc Martins # Copyright © 2012-2017 Guillaume Ayoub # Copyright © 2017-2018 Unrud diff --git a/radicale/storage/multifilesystem/sync.py b/radicale/storage/multifilesystem/sync.py index 6d73e24a..83cbe2a0 100644 --- a/radicale/storage/multifilesystem/sync.py +++ b/radicale/storage/multifilesystem/sync.py @@ -1,4 +1,4 @@ -# This file is part of Radicale Server - Calendar Server +# This file is part of Radicale - CalDAV and CardDAV server # Copyright © 2014 Jean-Marc Martins # Copyright © 2012-2017 Guillaume Ayoub # Copyright © 2017-2019 Unrud diff --git a/radicale/storage/multifilesystem/upload.py b/radicale/storage/multifilesystem/upload.py index 4d2be5f1..edabeb5d 100644 --- a/radicale/storage/multifilesystem/upload.py +++ b/radicale/storage/multifilesystem/upload.py @@ -1,4 +1,4 @@ -# This file is part of Radicale Server - Calendar Server +# This file is part of Radicale - CalDAV and CardDAV server # Copyright © 2014 Jean-Marc Martins # Copyright © 2012-2017 Guillaume Ayoub # Copyright © 2017-2018 Unrud diff --git a/radicale/storage/multifilesystem/verify.py b/radicale/storage/multifilesystem/verify.py index dfdf5957..d25d4fe7 100644 --- a/radicale/storage/multifilesystem/verify.py +++ b/radicale/storage/multifilesystem/verify.py @@ -1,4 +1,4 @@ -# This file is part of Radicale Server - Calendar Server +# This file is part of Radicale - CalDAV and CardDAV server # Copyright © 2014 Jean-Marc Martins # Copyright © 2012-2017 Guillaume Ayoub # Copyright © 2017-2018 Unrud diff --git a/radicale/storage/multifilesystem_nolock.py b/radicale/storage/multifilesystem_nolock.py index 6bb63a22..f9b2d574 100644 --- a/radicale/storage/multifilesystem_nolock.py +++ b/radicale/storage/multifilesystem_nolock.py @@ -1,4 +1,4 @@ -# This file is part of Radicale Server - Calendar Server +# This file is part of Radicale - CalDAV and CardDAV server # Copyright © 2021 Unrud # # This library is free software: you can redistribute it and/or modify diff --git a/radicale/tests/__init__.py b/radicale/tests/__init__.py index 00e2b15d..2a12a117 100644 --- a/radicale/tests/__init__.py +++ b/radicale/tests/__init__.py @@ -1,4 +1,4 @@ -# This file is part of Radicale Server - Calendar Server +# This file is part of Radicale - CalDAV and CardDAV server # Copyright © 2012-2017 Guillaume Ayoub # Copyright © 2017-2018 Unrud # diff --git a/radicale/tests/custom/auth.py b/radicale/tests/custom/auth.py index 8e17adc1..490ec313 100644 --- a/radicale/tests/custom/auth.py +++ b/radicale/tests/custom/auth.py @@ -1,4 +1,4 @@ -# This file is part of Radicale Server - Calendar Server +# This file is part of Radicale - CalDAV and CardDAV server # Copyright © 2008 Nicolas Kandel # Copyright © 2008 Pascal Halter # Copyright © 2008-2017 Guillaume Ayoub diff --git a/radicale/tests/custom/rights.py b/radicale/tests/custom/rights.py index 8f145dd1..507a4491 100644 --- a/radicale/tests/custom/rights.py +++ b/radicale/tests/custom/rights.py @@ -1,4 +1,4 @@ -# This file is part of Radicale Server - Calendar Server +# This file is part of Radicale - CalDAV and CardDAV server # Copyright © 2017-2018 Unrud # # This library is free software: you can redistribute it and/or modify diff --git a/radicale/tests/custom/storage_simple_sync.py b/radicale/tests/custom/storage_simple_sync.py index 7e023f02..2e32871e 100644 --- a/radicale/tests/custom/storage_simple_sync.py +++ b/radicale/tests/custom/storage_simple_sync.py @@ -1,4 +1,4 @@ -# This file is part of Radicale Server - Calendar Server +# This file is part of Radicale - CalDAV and CardDAV server # Copyright © 2012-2017 Guillaume Ayoub # Copyright © 2017-2018 Unrud # diff --git a/radicale/tests/custom/web.py b/radicale/tests/custom/web.py index 2626e051..695bbe81 100644 --- a/radicale/tests/custom/web.py +++ b/radicale/tests/custom/web.py @@ -1,4 +1,4 @@ -# This file is part of Radicale Server - Calendar Server +# This file is part of Radicale - CalDAV and CardDAV server # Copyright © 2017-2018 Unrud # # This library is free software: you can redistribute it and/or modify diff --git a/radicale/tests/helpers.py b/radicale/tests/helpers.py index 3d2d13b4..11f9a8d4 100644 --- a/radicale/tests/helpers.py +++ b/radicale/tests/helpers.py @@ -1,4 +1,4 @@ -# This file is part of Radicale Server - Calendar Server +# This file is part of Radicale - CalDAV and CardDAV server # Copyright © 2008 Nicolas Kandel # Copyright © 2008 Pascal Halter # Copyright © 2008-2017 Guillaume Ayoub diff --git a/radicale/tests/test_auth.py b/radicale/tests/test_auth.py index d2f52daa..12829704 100644 --- a/radicale/tests/test_auth.py +++ b/radicale/tests/test_auth.py @@ -1,4 +1,4 @@ -# This file is part of Radicale Server - Calendar Server +# This file is part of Radicale - CalDAV and CardDAV server # Copyright © 2012-2016 Jean-Marc Martins # Copyright © 2012-2017 Guillaume Ayoub # Copyright © 2017-2019 Unrud diff --git a/radicale/tests/test_base.py b/radicale/tests/test_base.py index 0c33d539..7376162e 100644 --- a/radicale/tests/test_base.py +++ b/radicale/tests/test_base.py @@ -1,4 +1,4 @@ -# This file is part of Radicale Server - Calendar Server +# This file is part of Radicale - CalDAV and CardDAV server # Copyright © 2012-2017 Guillaume Ayoub # Copyright © 2017-2019 Unrud # diff --git a/radicale/tests/test_config.py b/radicale/tests/test_config.py index 384cbca8..32a87ec2 100644 --- a/radicale/tests/test_config.py +++ b/radicale/tests/test_config.py @@ -1,4 +1,4 @@ -# This file is part of Radicale Server - Calendar Server +# This file is part of Radicale - CalDAV and CardDAV server # Copyright © 2019 Unrud # # This library is free software: you can redistribute it and/or modify diff --git a/radicale/tests/test_rights.py b/radicale/tests/test_rights.py index e9b92787..c1a4d430 100644 --- a/radicale/tests/test_rights.py +++ b/radicale/tests/test_rights.py @@ -1,4 +1,4 @@ -# This file is part of Radicale Server - Calendar Server +# This file is part of Radicale - CalDAV and CardDAV server # Copyright © 2017-2019 Unrud # # This library is free software: you can redistribute it and/or modify diff --git a/radicale/tests/test_server.py b/radicale/tests/test_server.py index 7420e1cd..c6555f1f 100644 --- a/radicale/tests/test_server.py +++ b/radicale/tests/test_server.py @@ -1,4 +1,4 @@ -# This file is part of Radicale Server - Calendar Server +# This file is part of Radicale - CalDAV and CardDAV server # Copyright © 2018-2019 Unrud # # This library is free software: you can redistribute it and/or modify diff --git a/radicale/tests/test_web.py b/radicale/tests/test_web.py index 2dc599e3..bfa2c72b 100644 --- a/radicale/tests/test_web.py +++ b/radicale/tests/test_web.py @@ -1,4 +1,4 @@ -# This file is part of Radicale Server - Calendar Server +# This file is part of Radicale - CalDAV and CardDAV server # Copyright © 2018-2019 Unrud # # This library is free software: you can redistribute it and/or modify diff --git a/radicale/types.py b/radicale/types.py index f0393e3a..0eb3fd6a 100644 --- a/radicale/types.py +++ b/radicale/types.py @@ -1,4 +1,4 @@ -# This file is part of Radicale Server - Calendar Server +# This file is part of Radicale - CalDAV and CardDAV server # Copyright © 2020 Unrud # # This library is free software: you can redistribute it and/or modify diff --git a/radicale/utils.py b/radicale/utils.py index 8163ea7e..33c77354 100644 --- a/radicale/utils.py +++ b/radicale/utils.py @@ -1,4 +1,4 @@ -# This file is part of Radicale Server - Calendar Server +# This file is part of Radicale - CalDAV and CardDAV server # Copyright © 2014 Jean-Marc Martins # Copyright © 2012-2017 Guillaume Ayoub # Copyright © 2017-2018 Unrud diff --git a/radicale/web/__init__.py b/radicale/web/__init__.py index efcbf618..a8f2b731 100644 --- a/radicale/web/__init__.py +++ b/radicale/web/__init__.py @@ -1,4 +1,4 @@ -# This file is part of Radicale Server - Calendar Server +# This file is part of Radicale - CalDAV and CardDAV server # Copyright © 2017-2018 Unrud # # This library is free software: you can redistribute it and/or modify diff --git a/radicale/web/internal.py b/radicale/web/internal.py index 0a3b3b77..7bed5e99 100644 --- a/radicale/web/internal.py +++ b/radicale/web/internal.py @@ -1,4 +1,4 @@ -# This file is part of Radicale Server - Calendar Server +# This file is part of Radicale - CalDAV and CardDAV server # Copyright © 2017-2018 Unrud # # This library is free software: you can redistribute it and/or modify diff --git a/radicale/web/none.py b/radicale/web/none.py index 423579e4..4f114a09 100644 --- a/radicale/web/none.py +++ b/radicale/web/none.py @@ -1,4 +1,4 @@ -# This file is part of Radicale Server - Calendar Server +# This file is part of Radicale - CalDAV and CardDAV server # Copyright © 2017-2018 Unrud # # This library is free software: you can redistribute it and/or modify diff --git a/radicale/xmlutils.py b/radicale/xmlutils.py index 5fb86283..09508d9c 100644 --- a/radicale/xmlutils.py +++ b/radicale/xmlutils.py @@ -1,4 +1,4 @@ -# This file is part of Radicale Server - Calendar Server +# This file is part of Radicale - CalDAV and CardDAV server # Copyright © 2008 Nicolas Kandel # Copyright © 2008 Pascal Halter # Copyright © 2008-2015 Guillaume Ayoub diff --git a/setup.py b/setup.py index 34af83e9..58a31389 100644 --- a/setup.py +++ b/setup.py @@ -1,6 +1,6 @@ #!/usr/bin/env python3 -# This file is part of Radicale Server - Calendar Server +# This file is part of Radicale - CalDAV and CardDAV server # Copyright © 2009-2017 Guillaume Ayoub # Copyright © 2017-2018 Unrud # From e38ae96227dd4400760c7d30f9a3579f0c651667 Mon Sep 17 00:00:00 2001 From: Unrud Date: Thu, 9 Dec 2021 19:15:23 +0100 Subject: [PATCH 071/238] Cosmetics --- radicale/tests/test_base.py | 2 +- setup.py | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/radicale/tests/test_base.py b/radicale/tests/test_base.py index 7376162e..af0c759f 100644 --- a/radicale/tests/test_base.py +++ b/radicale/tests/test_base.py @@ -1772,7 +1772,7 @@ class TestCustomStorageSystem(BaseFileSystemTest): # include tests related to sync token s: str = "" for s in dir(BaseRequestsMixIn): - if s.startswith("test_") and ("_sync_" in s or s.endswith("_sync")): + if s.startswith("test_") and "sync" in s.split("_"): locals()[s] = getattr(BaseRequestsMixIn, s) del s diff --git a/setup.py b/setup.py index 58a31389..e647ddc1 100644 --- a/setup.py +++ b/setup.py @@ -74,7 +74,7 @@ setup( platforms="Any", packages=find_packages( exclude=["*.tests", "*.tests.*", "tests.*", "tests"]), - package_data={"radicale": WEB_FILES + ['py.typed']}, + package_data={"radicale": [*WEB_FILES, 'py.typed']}, entry_points={"console_scripts": ["radicale = radicale.__main__:run"]}, install_requires=["defusedxml", "passlib", "vobject>=0.9.6", "python-dateutil>=2.7.3", "setuptools"], From e176567ad0a3839f66345fe8bd3ffbc817bfbb2e Mon Sep 17 00:00:00 2001 From: Unrud Date: Thu, 9 Dec 2021 19:15:44 +0100 Subject: [PATCH 072/238] Add Python 3.10 classifier --- setup.py | 1 + 1 file changed, 1 insertion(+) diff --git a/setup.py b/setup.py index e647ddc1..02891cc3 100644 --- a/setup.py +++ b/setup.py @@ -97,6 +97,7 @@ setup( "Programming Language :: Python :: 3.7", "Programming Language :: Python :: 3.8", "Programming Language :: Python :: 3.9", + "Programming Language :: Python :: 3.10", "Programming Language :: Python :: Implementation :: CPython", "Programming Language :: Python :: Implementation :: PyPy", "Topic :: Office/Business :: Groupware"]) From 1234802f513acd08a534214a35c96a60f943ecc5 Mon Sep 17 00:00:00 2001 From: Unrud Date: Thu, 9 Dec 2021 19:32:47 +0100 Subject: [PATCH 073/238] Use " instead of ' --- setup.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/setup.py b/setup.py index 02891cc3..114da3a9 100644 --- a/setup.py +++ b/setup.py @@ -74,7 +74,7 @@ setup( platforms="Any", packages=find_packages( exclude=["*.tests", "*.tests.*", "tests.*", "tests"]), - package_data={"radicale": [*WEB_FILES, 'py.typed']}, + package_data={"radicale": [*WEB_FILES, "py.typed"]}, entry_points={"console_scripts": ["radicale = radicale.__main__:run"]}, install_requires=["defusedxml", "passlib", "vobject>=0.9.6", "python-dateutil>=2.7.3", "setuptools"], From 208ae116832ff2a90d1916a7b491e8d4d8c54bdd Mon Sep 17 00:00:00 2001 From: Unrud Date: Fri, 10 Dec 2021 16:03:06 +0100 Subject: [PATCH 074/238] Rename BaseFileSystemTest to BaseStorageTest --- radicale/tests/test_base.py | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/radicale/tests/test_base.py b/radicale/tests/test_base.py index af0c759f..d317d7ca 100644 --- a/radicale/tests/test_base.py +++ b/radicale/tests/test_base.py @@ -1600,7 +1600,7 @@ class BaseRequestsMixIn(BaseTest): self.put("/calendar.ics/event.ics", event) -class BaseFileSystemTest(BaseTest): +class BaseStorageTest(BaseTest): """Base class for filesystem backend tests.""" storage_type: ClassVar[StorageType] @@ -1622,7 +1622,7 @@ permissions: RrWw""") self.application = Application(self.configuration) -class TestMultiFileSystem(BaseFileSystemTest, BaseRequestsMixIn): +class TestMultiFileSystem(BaseStorageTest, BaseRequestsMixIn): """Test BaseRequests on multifilesystem.""" storage_type: ClassVar[StorageType] = "multifilesystem" @@ -1751,7 +1751,7 @@ class TestMultiFileSystem(BaseFileSystemTest, BaseRequestsMixIn): assert "\r\nUID:%s\r\n" % uid in answer -class TestMultiFileSystemNoLock(BaseFileSystemTest): +class TestMultiFileSystemNoLock(BaseStorageTest): """Test BaseRequests on multifilesystem_nolock.""" storage_type: ClassVar[StorageType] = "multifilesystem_nolock" @@ -1760,7 +1760,7 @@ class TestMultiFileSystemNoLock(BaseFileSystemTest): test_item_cache_rebuild = TestMultiFileSystem.test_item_cache_rebuild -class TestCustomStorageSystem(BaseFileSystemTest): +class TestCustomStorageSystem(BaseStorageTest): """Test custom backend loading.""" storage_type: ClassVar[StorageType] = ( @@ -1777,7 +1777,7 @@ class TestCustomStorageSystem(BaseFileSystemTest): del s -class TestCustomStorageSystemCallable(BaseFileSystemTest): +class TestCustomStorageSystemCallable(BaseStorageTest): """Test custom backend loading with ``callable``.""" storage_type: ClassVar[StorageType] = ( From 4b5165dc42f6595f9d9f13f32c5c7d21b406eefb Mon Sep 17 00:00:00 2001 From: Unrud Date: Fri, 10 Dec 2021 20:54:04 +0100 Subject: [PATCH 075/238] Extract method configure --- radicale/tests/__init__.py | 9 ++++-- radicale/tests/test_auth.py | 21 +++++-------- radicale/tests/test_base.py | 57 ++++++++++++----------------------- radicale/tests/test_rights.py | 17 +++-------- radicale/tests/test_server.py | 20 +++++------- radicale/tests/test_web.py | 8 ++--- 6 files changed, 48 insertions(+), 84 deletions(-) diff --git a/radicale/tests/__init__.py b/radicale/tests/__init__.py index 2a12a117..0833fc4f 100644 --- a/radicale/tests/__init__.py +++ b/radicale/tests/__init__.py @@ -32,7 +32,7 @@ from typing import Any, Dict, List, Optional, Tuple, Union import defusedxml.ElementTree as DefusedET import radicale -from radicale import app, config, xmlutils +from radicale import app, config, types, xmlutils RESPONSES = Dict[str, Union[int, Dict[str, Tuple[int, ET.Element]]]] @@ -50,12 +50,15 @@ class BaseTest: def setup(self) -> None: self.configuration = config.load() self.colpath = tempfile.mkdtemp() - self.configuration.update({ + self.configure({ "storage": {"filesystem_folder": self.colpath, # Disable syncing to disk for better performance "_filesystem_fsync": "False"}, # Set incorrect authentication delay to a short duration - "auth": {"delay": "0.001"}}, "test", privileged=True) + "auth": {"delay": "0.001"}}) + + def configure(self, config_: types.CONFIG) -> None: + self.configuration.update(config_, "test", privileged=True) self.application = app.Application(self.configuration) def teardown(self) -> None: diff --git a/radicale/tests/test_auth.py b/radicale/tests/test_auth.py index 12829704..516a6f8e 100644 --- a/radicale/tests/test_auth.py +++ b/radicale/tests/test_auth.py @@ -27,7 +27,7 @@ from typing import Iterable, Tuple, Union import pytest -from radicale import Application, xmlutils +from radicale import xmlutils from radicale.tests import BaseTest @@ -58,11 +58,9 @@ class TestBaseAuthRequests(BaseTest): encoding: str = self.configuration.get("encoding", "stock") with open(htpasswd_file_path, "w", encoding=encoding) as f: f.write(htpasswd_content) - self.configuration.update({ - "auth": {"type": "htpasswd", - "htpasswd_filename": htpasswd_file_path, - "htpasswd_encryption": htpasswd_encryption}}, "test") - self.application = Application(self.configuration) + self.configure({"auth": {"type": "htpasswd", + "htpasswd_filename": htpasswd_file_path, + "htpasswd_encryption": htpasswd_encryption}}) if test_matrix == "ascii": test_matrix = (("tmp", "bepo", True), ("tmp", "tmp", False), ("tmp", "", False), ("unk", "unk", False), @@ -121,8 +119,7 @@ class TestBaseAuthRequests(BaseTest): self._test_htpasswd("plain", "#comment\n #comment\n \ntmp:bepo\n\n") def test_remote_user(self) -> None: - self.configuration.update({"auth": {"type": "remote_user"}}, "test") - self.application = Application(self.configuration) + self.configure({"auth": {"type": "remote_user"}}) _, responses = self.propfind("/", """\ @@ -139,9 +136,7 @@ class TestBaseAuthRequests(BaseTest): assert href_element is not None and href_element.text == "/test/" def test_http_x_remote_user(self) -> None: - self.configuration.update( - {"auth": {"type": "http_x_remote_user"}}, "test") - self.application = Application(self.configuration) + self.configure({"auth": {"type": "http_x_remote_user"}}) _, responses = self.propfind("/", """\ @@ -159,7 +154,5 @@ class TestBaseAuthRequests(BaseTest): def test_custom(self) -> None: """Custom authentication.""" - self.configuration.update( - {"auth": {"type": "radicale.tests.custom.auth"}}, "test") - self.application = Application(self.configuration) + self.configure({"auth": {"type": "radicale.tests.custom.auth"}}) self.propfind("/tmp/", login="tmp:") diff --git a/radicale/tests/test_base.py b/radicale/tests/test_base.py index d317d7ca..bf851308 100644 --- a/radicale/tests/test_base.py +++ b/radicale/tests/test_base.py @@ -31,7 +31,7 @@ import defusedxml.ElementTree as DefusedET import pytest import radicale.tests.custom.storage_simple_sync -from radicale import Application, config, storage, xmlutils +from radicale import config, storage, xmlutils from radicale.tests import RESPONSES, BaseTest from radicale.tests.helpers import get_file_content @@ -1544,12 +1544,10 @@ class BaseRequestsMixIn(BaseTest): def test_authentication(self) -> None: """Test if server sends authentication request.""" - self.configuration.update({ - "auth": {"type": "htpasswd", - "htpasswd_filename": os.devnull, - "htpasswd_encryption": "plain"}, - "rights": {"type": "owner_only"}}, "test") - self.application = Application(self.configuration) + self.configure({"auth": {"type": "htpasswd", + "htpasswd_filename": os.devnull, + "htpasswd_encryption": "plain"}, + "rights": {"type": "owner_only"}}) status, headers, _ = self.request("MKCOL", "/user/") assert status in (401, 403) assert headers.get("WWW-Authenticate") @@ -1580,8 +1578,7 @@ class BaseRequestsMixIn(BaseTest): self.propfind("/") def test_custom_headers(self) -> None: - self.configuration.update({"headers": {"test": "123"}}, "test") - self.application = Application(self.configuration) + self.configure({"headers": {"test": "123"}}) # Test if header is set on success status, headers, _ = self.request("OPTIONS", "/") assert status == 200 @@ -1615,11 +1612,9 @@ class BaseStorageTest(BaseTest): user: .* collection: .* permissions: RrWw""") - self.configuration.update({ - "storage": {"type": self.storage_type}, - "rights": {"file": rights_file_path, - "type": "from_file"}}, "test", privileged=True) - self.application = Application(self.configuration) + self.configure({"storage": {"type": self.storage_type}, + "rights": {"file": rights_file_path, + "type": "from_file"}}) class TestMultiFileSystem(BaseStorageTest, BaseRequestsMixIn): @@ -1630,33 +1625,25 @@ class TestMultiFileSystem(BaseStorageTest, BaseRequestsMixIn): def test_folder_creation(self) -> None: """Verify that the folder is created.""" folder = os.path.join(self.colpath, "subfolder") - self.configuration.update( - {"storage": {"filesystem_folder": folder}}, "test") - self.application = Application(self.configuration) + self.configure({"storage": {"filesystem_folder": folder}}) assert os.path.isdir(folder) def test_fsync(self) -> None: """Create a directory and file with syncing enabled.""" - self.configuration.update({"storage": {"_filesystem_fsync": "True"}}, - "test", privileged=True) - self.application = Application(self.configuration) + self.configure({"storage": {"_filesystem_fsync": "True"}}) self.mkcalendar("/calendar.ics/") def test_hook(self) -> None: """Run hook.""" - self.configuration.update({"storage": { - "hook": ("mkdir %s" % os.path.join( - "collection-root", "created_by_hook"))}}, "test") - self.application = Application(self.configuration) + self.configure({"storage": {"hook": "mkdir %s" % os.path.join( + "collection-root", "created_by_hook")}}) self.mkcalendar("/calendar.ics/") self.propfind("/created_by_hook/") def test_hook_read_access(self) -> None: """Verify that hook is not run for read accesses.""" - self.configuration.update({"storage": { - "hook": ("mkdir %s" % os.path.join( - "collection-root", "created_by_hook"))}}, "test") - self.application = Application(self.configuration) + self.configure({"storage": {"hook": "mkdir %s" % os.path.join( + "collection-root", "created_by_hook")}}) self.propfind("/") self.propfind("/created_by_hook/", check=404) @@ -1664,24 +1651,20 @@ class TestMultiFileSystem(BaseStorageTest, BaseRequestsMixIn): reason="flock command not found") def test_hook_storage_locked(self) -> None: """Verify that the storage is locked when the hook runs.""" - self.configuration.update({"storage": {"hook": ( - "flock -n .Radicale.lock || exit 0; exit 1")}}, "test") - self.application = Application(self.configuration) + self.configure({"storage": {"hook": ( + "flock -n .Radicale.lock || exit 0; exit 1")}}) self.mkcalendar("/calendar.ics/") def test_hook_principal_collection_creation(self) -> None: """Verify that the hooks runs when a new user is created.""" - self.configuration.update({"storage": { - "hook": ("mkdir %s" % os.path.join( - "collection-root", "created_by_hook"))}}, "test") - self.application = Application(self.configuration) + self.configure({"storage": {"hook": "mkdir %s" % os.path.join( + "collection-root", "created_by_hook")}}) self.propfind("/", login="user:") self.propfind("/created_by_hook/") def test_hook_fail(self) -> None: """Verify that a request fails if the hook fails.""" - self.configuration.update({"storage": {"hook": "exit 1"}}, "test") - self.application = Application(self.configuration) + self.configure({"storage": {"hook": "exit 1"}}) self.mkcalendar("/calendar.ics/", check=500) def test_item_cache_rebuild(self) -> None: diff --git a/radicale/tests/test_rights.py b/radicale/tests/test_rights.py index c1a4d430..c8efa4b5 100644 --- a/radicale/tests/test_rights.py +++ b/radicale/tests/test_rights.py @@ -20,7 +20,6 @@ Radicale tests with simple requests and rights. import os -from radicale import Application from radicale.tests import BaseTest from radicale.tests.helpers import get_file_content @@ -35,12 +34,11 @@ class TestBaseRightsRequests(BaseTest): htpasswd_file_path = os.path.join(self.colpath, ".htpasswd") with open(htpasswd_file_path, "w") as f: f.write("tmp:bepo\nother:bepo") - self.configuration.update({ + self.configure({ "rights": {"type": rights_type}, "auth": {"type": "htpasswd" if with_auth else "none", "htpasswd_filename": htpasswd_file_path, - "htpasswd_encryption": "plain"}}, "test") - self.application = Application(self.configuration) + "htpasswd_encryption": "plain"}}) for u in ("tmp", "other"): # Indirect creation of principal collection self.propfind("/%s/" % u, login="%s:bepo" % u) @@ -113,8 +111,7 @@ permissions: RrWw user: .* collection: custom(/.*)? permissions: Rr""") - self.configuration.update( - {"rights": {"file": rights_file_path}}, "test") + self.configure({"rights": {"file": rights_file_path}}) self._test_rights("from_file", "", "/other/", "r", 401) self._test_rights("from_file", "tmp", "/other/", "r", 403) self._test_rights("from_file", "", "/custom/sub", "r", 404) @@ -134,10 +131,8 @@ permissions: RrWw user: .* collection: public/[^/]* permissions: i""") - self.configuration.update( - {"rights": {"type": "from_file", - "file": rights_file_path}}, "test") - self.application = Application(self.configuration) + self.configure({"rights": {"type": "from_file", + "file": rights_file_path}}) self.mkcalendar("/tmp/calendar", login="tmp:bepo") self.mkcol("/public", login="tmp:bepo") self.mkcalendar("/public/calendar", login="tmp:bepo") @@ -160,7 +155,6 @@ permissions: i""") Items are allowed at "/.../.../...". """ - self.application = Application(self.configuration) self.mkcalendar("/", check=401) self.mkcalendar("/user/", check=401) self.mkcol("/user/") @@ -171,7 +165,6 @@ permissions: i""") def test_put_collections_and_items(self) -> None: """Test rights for creation of calendars and items with PUT.""" - self.application = Application(self.configuration) self.put("/user/", "BEGIN:VCALENDAR\r\nEND:VCALENDAR", check=401) self.mkcol("/user/") self.put("/user/calendar/", "BEGIN:VCALENDAR\r\nEND:VCALENDAR") diff --git a/radicale/tests/test_server.py b/radicale/tests/test_server.py index c6555f1f..e2f3b138 100644 --- a/radicale/tests/test_server.py +++ b/radicale/tests/test_server.py @@ -76,11 +76,9 @@ class TestBaseServerRequests(BaseTest): # Find available port sock.bind(("127.0.0.1", 0)) self.sockname = sock.getsockname() - self.configuration.update({ - "server": {"hosts": "[%s]:%d" % self.sockname}, - # Enable debugging for new processes - "logging": {"level": "debug"}}, - "test", privileged=True) + self.configure({"server": {"hosts": "[%s]:%d" % self.sockname}, + # Enable debugging for new processes + "logging": {"level": "debug"}}) self.thread = threading.Thread(target=server.serve, args=( self.configuration, shutdown_socket_out)) ssl_context = ssl.create_default_context() @@ -141,10 +139,9 @@ class TestBaseServerRequests(BaseTest): self.get("/", check=302) def test_ssl(self) -> None: - self.configuration.update({ - "server": {"ssl": "True", - "certificate": get_file_path("cert.pem"), - "key": get_file_path("key.pem")}}, "test") + self.configure({"server": {"ssl": "True", + "certificate": get_file_path("cert.pem"), + "key": get_file_path("key.pem")}}) self.thread.start() self.get("/", check=302) @@ -182,13 +179,12 @@ class TestBaseServerRequests(BaseTest): errno.EPROTONOSUPPORT): pytest.skip("IPv6 not supported") raise - self.configuration.update({ - "server": {"hosts": "[%s]:%d" % self.sockname}}, "test") + self.configure({"server": {"hosts": "[%s]:%d" % self.sockname}}) self.thread.start() self.get("/", check=302) def test_command_line_interface(self, with_bool_options=False) -> None: - self.configuration.update({"headers": {"Test-Server": "test"}}) + self.configure({"headers": {"Test-Server": "test"}}) config_args = [] for section in self.configuration.sections(): if section.startswith("_"): diff --git a/radicale/tests/test_web.py b/radicale/tests/test_web.py index bfa2c72b..9432166f 100644 --- a/radicale/tests/test_web.py +++ b/radicale/tests/test_web.py @@ -19,7 +19,6 @@ Test web plugin. """ -from radicale import Application from radicale.tests import BaseTest @@ -35,8 +34,7 @@ class TestBaseWebRequests(BaseTest): self.post("/.web", check=405) def test_none(self) -> None: - self.configuration.update({"web": {"type": "none"}}, "test") - self.application = Application(self.configuration) + self.configure({"web": {"type": "none"}}) _, answer = self.get("/.web") assert answer self.get("/.web/", check=404) @@ -44,9 +42,7 @@ class TestBaseWebRequests(BaseTest): def test_custom(self) -> None: """Custom web plugin.""" - self.configuration.update({ - "web": {"type": "radicale.tests.custom.web"}}, "test") - self.application = Application(self.configuration) + self.configure({"web": {"type": "radicale.tests.custom.web"}}) _, answer = self.get("/.web") assert answer == "custom" _, answer = self.post("/.web", "body content") From 91c06041f83c4c16ec7bb72416a79624ac820346 Mon Sep 17 00:00:00 2001 From: Unrud Date: Sat, 11 Dec 2021 12:59:02 +0100 Subject: [PATCH 076/238] Split storage from base tests --- radicale/tests/test_base.py | 195 +++----------------------------- radicale/tests/test_storage.py | 197 +++++++++++++++++++++++++++++++++ 2 files changed, 212 insertions(+), 180 deletions(-) create mode 100644 radicale/tests/test_storage.py diff --git a/radicale/tests/test_base.py b/radicale/tests/test_base.py index bf851308..d0557e5b 100644 --- a/radicale/tests/test_base.py +++ b/radicale/tests/test_base.py @@ -22,28 +22,35 @@ Radicale tests with simple requests. import os import posixpath -import shutil import sys -from typing import (Any, Callable, ClassVar, Iterable, List, Optional, Tuple, - Union) +from typing import Any, Callable, ClassVar, Iterable, List, Optional, Tuple import defusedxml.ElementTree as DefusedET import pytest -import radicale.tests.custom.storage_simple_sync -from radicale import config, storage, xmlutils +from radicale import storage, xmlutils from radicale.tests import RESPONSES, BaseTest from radicale.tests.helpers import get_file_content -StorageType = Union[str, Callable[[config.Configuration], storage.BaseStorage]] - -class BaseRequestsMixIn(BaseTest): +class TestBaseRequests(BaseTest): """Tests with simple requests.""" # Allow skipping sync-token tests, when not fully supported by the backend full_sync_token_support: ClassVar[bool] = True + def setup(self) -> None: + BaseTest.setup(self) + rights_file_path = os.path.join(self.colpath, "rights") + with open(rights_file_path, "w") as f: + f.write("""\ +[allow all] +user: .* +collection: .* +permissions: RrWw""") + self.configure({"rights": {"file": rights_file_path, + "type": "from_file"}}) + def test_root(self) -> None: """GET request at "/".""" _, answer = self.get("/", check=302) @@ -1595,175 +1602,3 @@ class BaseRequestsMixIn(BaseTest): self.mkcalendar("/calendar.ics/") event = get_file_content("event_timezone_seconds.ics") self.put("/calendar.ics/event.ics", event) - - -class BaseStorageTest(BaseTest): - """Base class for filesystem backend tests.""" - - storage_type: ClassVar[StorageType] - - def setup(self) -> None: - super().setup() - # Allow access to anything for tests - rights_file_path = os.path.join(self.colpath, "rights") - with open(rights_file_path, "w") as f: - f.write("""\ -[allow all] -user: .* -collection: .* -permissions: RrWw""") - self.configure({"storage": {"type": self.storage_type}, - "rights": {"file": rights_file_path, - "type": "from_file"}}) - - -class TestMultiFileSystem(BaseStorageTest, BaseRequestsMixIn): - """Test BaseRequests on multifilesystem.""" - - storage_type: ClassVar[StorageType] = "multifilesystem" - - def test_folder_creation(self) -> None: - """Verify that the folder is created.""" - folder = os.path.join(self.colpath, "subfolder") - self.configure({"storage": {"filesystem_folder": folder}}) - assert os.path.isdir(folder) - - def test_fsync(self) -> None: - """Create a directory and file with syncing enabled.""" - self.configure({"storage": {"_filesystem_fsync": "True"}}) - self.mkcalendar("/calendar.ics/") - - def test_hook(self) -> None: - """Run hook.""" - self.configure({"storage": {"hook": "mkdir %s" % os.path.join( - "collection-root", "created_by_hook")}}) - self.mkcalendar("/calendar.ics/") - self.propfind("/created_by_hook/") - - def test_hook_read_access(self) -> None: - """Verify that hook is not run for read accesses.""" - self.configure({"storage": {"hook": "mkdir %s" % os.path.join( - "collection-root", "created_by_hook")}}) - self.propfind("/") - self.propfind("/created_by_hook/", check=404) - - @pytest.mark.skipif(not shutil.which("flock"), - reason="flock command not found") - def test_hook_storage_locked(self) -> None: - """Verify that the storage is locked when the hook runs.""" - self.configure({"storage": {"hook": ( - "flock -n .Radicale.lock || exit 0; exit 1")}}) - self.mkcalendar("/calendar.ics/") - - def test_hook_principal_collection_creation(self) -> None: - """Verify that the hooks runs when a new user is created.""" - self.configure({"storage": {"hook": "mkdir %s" % os.path.join( - "collection-root", "created_by_hook")}}) - self.propfind("/", login="user:") - self.propfind("/created_by_hook/") - - def test_hook_fail(self) -> None: - """Verify that a request fails if the hook fails.""" - self.configure({"storage": {"hook": "exit 1"}}) - self.mkcalendar("/calendar.ics/", check=500) - - def test_item_cache_rebuild(self) -> None: - """Delete the item cache and verify that it is rebuild.""" - self.mkcalendar("/calendar.ics/") - event = get_file_content("event1.ics") - path = "/calendar.ics/event1.ics" - self.put(path, event) - _, answer1 = self.get(path) - cache_folder = os.path.join(self.colpath, "collection-root", - "calendar.ics", ".Radicale.cache", "item") - assert os.path.exists(os.path.join(cache_folder, "event1.ics")) - shutil.rmtree(cache_folder) - _, answer2 = self.get(path) - assert answer1 == answer2 - assert os.path.exists(os.path.join(cache_folder, "event1.ics")) - - @pytest.mark.skipif(os.name != "posix" and sys.platform != "win32", - reason="Only supported on 'posix' and 'win32'") - def test_put_whole_calendar_uids_used_as_file_names(self) -> None: - """Test if UIDs are used as file names.""" - BaseRequestsMixIn.test_put_whole_calendar(self) - for uid in ("todo", "event"): - _, answer = self.get("/calendar.ics/%s.ics" % uid) - assert "\r\nUID:%s\r\n" % uid in answer - - @pytest.mark.skipif(os.name != "posix" and sys.platform != "win32", - reason="Only supported on 'posix' and 'win32'") - def test_put_whole_calendar_random_uids_used_as_file_names(self) -> None: - """Test if UIDs are used as file names.""" - BaseRequestsMixIn.test_put_whole_calendar_without_uids(self) - _, answer = self.get("/calendar.ics") - assert answer is not None - uids = [] - for line in answer.split("\r\n"): - if line.startswith("UID:"): - uids.append(line[len("UID:"):]) - for uid in uids: - _, answer = self.get("/calendar.ics/%s.ics" % uid) - assert answer is not None - assert "\r\nUID:%s\r\n" % uid in answer - - @pytest.mark.skipif(os.name != "posix" and sys.platform != "win32", - reason="Only supported on 'posix' and 'win32'") - def test_put_whole_addressbook_uids_used_as_file_names(self) -> None: - """Test if UIDs are used as file names.""" - BaseRequestsMixIn.test_put_whole_addressbook(self) - for uid in ("contact1", "contact2"): - _, answer = self.get("/contacts.vcf/%s.vcf" % uid) - assert "\r\nUID:%s\r\n" % uid in answer - - @pytest.mark.skipif(os.name != "posix" and sys.platform != "win32", - reason="Only supported on 'posix' and 'win32'") - def test_put_whole_addressbook_random_uids_used_as_file_names( - self) -> None: - """Test if UIDs are used as file names.""" - BaseRequestsMixIn.test_put_whole_addressbook_without_uids(self) - _, answer = self.get("/contacts.vcf") - assert answer is not None - uids = [] - for line in answer.split("\r\n"): - if line.startswith("UID:"): - uids.append(line[len("UID:"):]) - for uid in uids: - _, answer = self.get("/contacts.vcf/%s.vcf" % uid) - assert answer is not None - assert "\r\nUID:%s\r\n" % uid in answer - - -class TestMultiFileSystemNoLock(BaseStorageTest): - """Test BaseRequests on multifilesystem_nolock.""" - - storage_type: ClassVar[StorageType] = "multifilesystem_nolock" - - test_add_event = BaseRequestsMixIn.test_add_event - test_item_cache_rebuild = TestMultiFileSystem.test_item_cache_rebuild - - -class TestCustomStorageSystem(BaseStorageTest): - """Test custom backend loading.""" - - storage_type: ClassVar[StorageType] = ( - "radicale.tests.custom.storage_simple_sync") - full_sync_token_support: ClassVar[bool] = False - - test_root = BaseRequestsMixIn.test_root - _report_sync_token = BaseRequestsMixIn._report_sync_token - # include tests related to sync token - s: str = "" - for s in dir(BaseRequestsMixIn): - if s.startswith("test_") and "sync" in s.split("_"): - locals()[s] = getattr(BaseRequestsMixIn, s) - del s - - -class TestCustomStorageSystemCallable(BaseStorageTest): - """Test custom backend loading with ``callable``.""" - - storage_type: ClassVar[StorageType] = ( - radicale.tests.custom.storage_simple_sync.Storage) - - test_add_event = BaseRequestsMixIn.test_add_event diff --git a/radicale/tests/test_storage.py b/radicale/tests/test_storage.py new file mode 100644 index 00000000..7dd335ca --- /dev/null +++ b/radicale/tests/test_storage.py @@ -0,0 +1,197 @@ +# This file is part of Radicale - CalDAV and CardDAV server +# Copyright © 2012-2017 Guillaume Ayoub +# Copyright © 2017-2019 Unrud +# +# This library is free software: you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation, either version 3 of the License, or +# (at your option) any later version. +# +# This library is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with Radicale. If not, see . + +""" +Tests for storage backends. + +""" + +import os +import shutil +import sys +from typing import ClassVar, cast + +import pytest + +import radicale.tests.custom.storage_simple_sync +from radicale.tests import BaseTest +from radicale.tests.helpers import get_file_content +from radicale.tests.test_base import TestBaseRequests + + +class TestMultiFileSystem(BaseTest): + """Tests for multifilesystem.""" + + def setup(self) -> None: + TestBaseRequests.setup(cast(TestBaseRequests, self)) + self.configure({"storage": {"type": "multifilesystem"}}) + + def test_folder_creation(self) -> None: + """Verify that the folder is created.""" + folder = os.path.join(self.colpath, "subfolder") + self.configure({"storage": {"filesystem_folder": folder}}) + assert os.path.isdir(folder) + + def test_fsync(self) -> None: + """Create a directory and file with syncing enabled.""" + self.configure({"storage": {"_filesystem_fsync": "True"}}) + self.mkcalendar("/calendar.ics/") + + def test_hook(self) -> None: + """Run hook.""" + self.configure({"storage": {"hook": "mkdir %s" % os.path.join( + "collection-root", "created_by_hook")}}) + self.mkcalendar("/calendar.ics/") + self.propfind("/created_by_hook/") + + def test_hook_read_access(self) -> None: + """Verify that hook is not run for read accesses.""" + self.configure({"storage": {"hook": "mkdir %s" % os.path.join( + "collection-root", "created_by_hook")}}) + self.propfind("/") + self.propfind("/created_by_hook/", check=404) + + @pytest.mark.skipif(not shutil.which("flock"), + reason="flock command not found") + def test_hook_storage_locked(self) -> None: + """Verify that the storage is locked when the hook runs.""" + self.configure({"storage": {"hook": ( + "flock -n .Radicale.lock || exit 0; exit 1")}}) + self.mkcalendar("/calendar.ics/") + + def test_hook_principal_collection_creation(self) -> None: + """Verify that the hooks runs when a new user is created.""" + self.configure({"storage": {"hook": "mkdir %s" % os.path.join( + "collection-root", "created_by_hook")}}) + self.propfind("/", login="user:") + self.propfind("/created_by_hook/") + + def test_hook_fail(self) -> None: + """Verify that a request fails if the hook fails.""" + self.configure({"storage": {"hook": "exit 1"}}) + self.mkcalendar("/calendar.ics/", check=500) + + def test_item_cache_rebuild(self) -> None: + """Delete the item cache and verify that it is rebuild.""" + self.mkcalendar("/calendar.ics/") + event = get_file_content("event1.ics") + path = "/calendar.ics/event1.ics" + self.put(path, event) + _, answer1 = self.get(path) + cache_folder = os.path.join(self.colpath, "collection-root", + "calendar.ics", ".Radicale.cache", "item") + assert os.path.exists(os.path.join(cache_folder, "event1.ics")) + shutil.rmtree(cache_folder) + _, answer2 = self.get(path) + assert answer1 == answer2 + assert os.path.exists(os.path.join(cache_folder, "event1.ics")) + + @pytest.mark.skipif(os.name != "posix" and sys.platform != "win32", + reason="Only supported on 'posix' and 'win32'") + def test_put_whole_calendar_uids_used_as_file_names(self) -> None: + """Test if UIDs are used as file names.""" + TestBaseRequests.test_put_whole_calendar(cast(TestBaseRequests, self)) + for uid in ("todo", "event"): + _, answer = self.get("/calendar.ics/%s.ics" % uid) + assert "\r\nUID:%s\r\n" % uid in answer + + @pytest.mark.skipif(os.name != "posix" and sys.platform != "win32", + reason="Only supported on 'posix' and 'win32'") + def test_put_whole_calendar_random_uids_used_as_file_names(self) -> None: + """Test if UIDs are used as file names.""" + TestBaseRequests.test_put_whole_calendar_without_uids( + cast(TestBaseRequests, self)) + _, answer = self.get("/calendar.ics") + assert answer is not None + uids = [] + for line in answer.split("\r\n"): + if line.startswith("UID:"): + uids.append(line[len("UID:"):]) + for uid in uids: + _, answer = self.get("/calendar.ics/%s.ics" % uid) + assert answer is not None + assert "\r\nUID:%s\r\n" % uid in answer + + @pytest.mark.skipif(os.name != "posix" and sys.platform != "win32", + reason="Only supported on 'posix' and 'win32'") + def test_put_whole_addressbook_uids_used_as_file_names(self) -> None: + """Test if UIDs are used as file names.""" + TestBaseRequests.test_put_whole_addressbook( + cast(TestBaseRequests, self)) + for uid in ("contact1", "contact2"): + _, answer = self.get("/contacts.vcf/%s.vcf" % uid) + assert "\r\nUID:%s\r\n" % uid in answer + + @pytest.mark.skipif(os.name != "posix" and sys.platform != "win32", + reason="Only supported on 'posix' and 'win32'") + def test_put_whole_addressbook_random_uids_used_as_file_names( + self) -> None: + """Test if UIDs are used as file names.""" + TestBaseRequests.test_put_whole_addressbook_without_uids( + cast(TestBaseRequests, self)) + _, answer = self.get("/contacts.vcf") + assert answer is not None + uids = [] + for line in answer.split("\r\n"): + if line.startswith("UID:"): + uids.append(line[len("UID:"):]) + for uid in uids: + _, answer = self.get("/contacts.vcf/%s.vcf" % uid) + assert answer is not None + assert "\r\nUID:%s\r\n" % uid in answer + + +class TestMultiFileSystemNoLock(BaseTest): + """Tests for multifilesystem_nolock.""" + + def setup(self) -> None: + TestBaseRequests.setup(cast(TestBaseRequests, self)) + self.configure({"storage": {"type": "multifilesystem_nolock"}}) + + test_add_event = TestBaseRequests.test_add_event + test_item_cache_rebuild = TestMultiFileSystem.test_item_cache_rebuild + + +class TestCustomStorageSystem(BaseTest): + """Test custom backend loading.""" + + def setup(self) -> None: + TestBaseRequests.setup(cast(TestBaseRequests, self)) + self.configure({"storage": { + "type": "radicale.tests.custom.storage_simple_sync"}}) + + full_sync_token_support: ClassVar[bool] = False + + test_add_event = TestBaseRequests.test_add_event + _report_sync_token = TestBaseRequests._report_sync_token + # include tests related to sync token + s: str = "" + for s in dir(TestBaseRequests): + if s.startswith("test_") and "sync" in s.split("_"): + locals()[s] = getattr(TestBaseRequests, s) + del s + + +class TestCustomStorageSystemCallable(BaseTest): + """Test custom backend loading with ``callable``.""" + + def setup(self) -> None: + TestBaseRequests.setup(cast(TestBaseRequests, self)) + self.configure({"storage": { + "type": radicale.tests.custom.storage_simple_sync.Storage}}) + + test_add_event = TestBaseRequests.test_add_event From 90bd33f466c91d88df02438c09a222c499a9ac5b Mon Sep 17 00:00:00 2001 From: Unrud Date: Sun, 12 Dec 2021 19:36:19 +0100 Subject: [PATCH 077/238] Extract LockDict class --- radicale/storage/multifilesystem_nolock.py | 50 +++++++++++++--------- 1 file changed, 30 insertions(+), 20 deletions(-) diff --git a/radicale/storage/multifilesystem_nolock.py b/radicale/storage/multifilesystem_nolock.py index f9b2d574..759af072 100644 --- a/radicale/storage/multifilesystem_nolock.py +++ b/radicale/storage/multifilesystem_nolock.py @@ -20,7 +20,7 @@ The multifilesystem backend without file-based locking. import threading from collections import deque -from typing import Deque, Dict, Iterator, Tuple +from typing import Deque, Dict, Hashable, Iterator from radicale import config, pathutils, types from radicale.storage import multifilesystem @@ -56,20 +56,21 @@ class RwLock(pathutils.RwLock): self._cond.notify() -class Collection(multifilesystem.Collection): +class LockDict: - _storage: "Storage" + _lock: threading.Lock + _dict: Dict[Hashable, Deque[threading.Lock]] + + def __init__(self) -> None: + self._lock = threading.Lock() + self._dict = {} @types.contextmanager - def _acquire_cache_lock(self, ns: str = "") -> Iterator[None]: - if self._storage._lock.locked == "w": - yield - return - key = (self.path, ns) - with self._storage._cache_lock: - waiters = self._storage._cache_locks.get(key) + def acquire(self, key: Hashable) -> Iterator[None]: + with self._lock: + waiters = self._dict.get(key) if waiters is None: - self._storage._cache_locks[key] = waiters = deque() + self._dict[key] = waiters = deque() wait = bool(waiters) waiter = threading.Lock() waiter.acquire() @@ -79,25 +80,34 @@ class Collection(multifilesystem.Collection): try: yield finally: - with self._storage._cache_lock: - removedWaiter = waiters.popleft() - assert removedWaiter is waiter + with self._lock: + del waiters[0] if waiters: waiters[0].release() else: - removedWaiters = self._storage._cache_locks.pop(key) - assert removedWaiters is waiters + del self._dict[key] + + +class Collection(multifilesystem.Collection): + + _storage: "Storage" + + @types.contextmanager + def _acquire_cache_lock(self, ns: str = "") -> Iterator[None]: + if self._storage._lock.locked == "w": + yield + return + with self._storage._cache_lock.acquire((self.path, ns)): + yield class Storage(multifilesystem.Storage): _collection_class = Collection - _cache_lock: threading.Lock - _cache_locks: Dict[Tuple[str, str], Deque[threading.Lock]] + _cache_lock: LockDict def __init__(self, configuration: config.Configuration) -> None: super().__init__(configuration) self._lock = RwLock() - self._cache_lock = threading.Lock() - self._cache_locks = {} + self._cache_lock = LockDict() From e0f7fe65261163fa3740678de8ffe4623b883a4f Mon Sep 17 00:00:00 2001 From: Unrud Date: Sun, 12 Dec 2021 19:36:23 +0100 Subject: [PATCH 078/238] Instant notification of all waiting readers --- radicale/storage/multifilesystem_nolock.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/radicale/storage/multifilesystem_nolock.py b/radicale/storage/multifilesystem_nolock.py index 759af072..0ca087df 100644 --- a/radicale/storage/multifilesystem_nolock.py +++ b/radicale/storage/multifilesystem_nolock.py @@ -43,7 +43,6 @@ class RwLock(pathutils.RwLock): mode == "r" or self._readers == 0)) if mode == "r": self._readers += 1 - self._cond.notify() else: self._writer = True try: @@ -53,7 +52,8 @@ class RwLock(pathutils.RwLock): if mode == "r": self._readers -= 1 self._writer = False - self._cond.notify() + if self._readers == 0: + self._cond.notify_all() class LockDict: From f25d7eebb81f3d5d7884f7415268f4d2bd407a74 Mon Sep 17 00:00:00 2001 From: Unrud Date: Sun, 12 Dec 2021 20:05:11 +0100 Subject: [PATCH 079/238] Change _collection_class to ClassVar --- radicale/storage/multifilesystem/__init__.py | 4 ++-- radicale/storage/multifilesystem/base.py | 5 +++-- radicale/storage/multifilesystem_nolock.py | 4 ++-- 3 files changed, 7 insertions(+), 6 deletions(-) diff --git a/radicale/storage/multifilesystem/__init__.py b/radicale/storage/multifilesystem/__init__.py index b5b24b1b..67aa6a52 100644 --- a/radicale/storage/multifilesystem/__init__.py +++ b/radicale/storage/multifilesystem/__init__.py @@ -25,7 +25,7 @@ Uses one folder per collection and one file per collection entry. import os import time -from typing import Iterator, Optional +from typing import ClassVar, Iterator, Optional, Type from radicale import config from radicale.storage.multifilesystem.base import CollectionBase, StorageBase @@ -84,7 +84,7 @@ class Storage( StoragePartCreateCollection, StoragePartLock, StoragePartMove, StoragePartVerify, StoragePartDiscover, StorageBase): - _collection_class = Collection + _collection_class: ClassVar[Type[Collection]] = Collection def __init__(self, configuration: config.Configuration) -> None: super().__init__(configuration) diff --git a/radicale/storage/multifilesystem/base.py b/radicale/storage/multifilesystem/base.py index 241458c3..4b1fb5de 100644 --- a/radicale/storage/multifilesystem/base.py +++ b/radicale/storage/multifilesystem/base.py @@ -18,7 +18,7 @@ import os from tempfile import TemporaryDirectory -from typing import IO, AnyStr, Iterator, Optional, Type +from typing import IO, AnyStr, ClassVar, Iterator, Optional, Type from radicale import config, pathutils, storage, types from radicale.storage import multifilesystem # noqa:F401 @@ -62,7 +62,8 @@ class CollectionBase(storage.BaseCollection): class StorageBase(storage.BaseStorage): - _collection_class: Type["multifilesystem.Collection"] + _collection_class: ClassVar[Type["multifilesystem.Collection"]] + _filesystem_folder: str _filesystem_fsync: bool diff --git a/radicale/storage/multifilesystem_nolock.py b/radicale/storage/multifilesystem_nolock.py index 0ca087df..3653de85 100644 --- a/radicale/storage/multifilesystem_nolock.py +++ b/radicale/storage/multifilesystem_nolock.py @@ -20,7 +20,7 @@ The multifilesystem backend without file-based locking. import threading from collections import deque -from typing import Deque, Dict, Hashable, Iterator +from typing import ClassVar, Deque, Dict, Hashable, Iterator, Type from radicale import config, pathutils, types from radicale.storage import multifilesystem @@ -103,7 +103,7 @@ class Collection(multifilesystem.Collection): class Storage(multifilesystem.Storage): - _collection_class = Collection + _collection_class: ClassVar[Type[Collection]] = Collection _cache_lock: LockDict From e1e563cc281bbca9019d76b1be8ed9f8f87134b9 Mon Sep 17 00:00:00 2001 From: Unrud Date: Tue, 14 Dec 2021 00:25:31 +0100 Subject: [PATCH 080/238] Lint markdown --- .mdl.style | 4 + .mdlrc | 1 + DOCUMENTATION.md | 416 ++++++++++++++++--------------- NEWS.md | 621 +++++++++++++++++++++++------------------------ 4 files changed, 511 insertions(+), 531 deletions(-) create mode 100644 .mdl.style create mode 100644 .mdlrc diff --git a/.mdl.style b/.mdl.style new file mode 100644 index 00000000..f578f3c8 --- /dev/null +++ b/.mdl.style @@ -0,0 +1,4 @@ +all +rule 'MD026', :punctuation => '.,;:!' +exclude_rule 'MD001' +exclude_rule 'MD024' diff --git a/.mdlrc b/.mdlrc new file mode 100644 index 00000000..46c2ec93 --- /dev/null +++ b/.mdlrc @@ -0,0 +1 @@ +style File.join(File.dirname(__FILE__), '.mdl.style') diff --git a/DOCUMENTATION.md b/DOCUMENTATION.md index 1de8ebca..6e3f4b43 100644 --- a/DOCUMENTATION.md +++ b/DOCUMENTATION.md @@ -1,42 +1,46 @@ -# Getting started -### About Radicale +# Documentation + +## Getting started + +#### About Radicale Radicale is a small but powerful CalDAV (calendars, to-do lists) and CardDAV (contacts) server, that: - * Shares calendars and contact lists through CalDAV, CardDAV and HTTP. - * Supports events, todos, journal entries and business cards. - * Works out-of-the-box, no complicated setup or configuration required. - * Can limit access by authentication. - * Can secure connections with TLS. - * Works with many - [CalDAV and CardDAV clients](#documentation/supported-clients). - * Stores all data on the file system in a simple folder structure. - * Can be extended with plugins. - * Is GPLv3-licensed free software. +* Shares calendars and contact lists through CalDAV, CardDAV and HTTP. +* Supports events, todos, journal entries and business cards. +* Works out-of-the-box, no complicated setup or configuration required. +* Can limit access by authentication. +* Can secure connections with TLS. +* Works with many + [CalDAV and CardDAV clients](#documentation/supported-clients). +* Stores all data on the file system in a simple folder structure. +* Can be extended with plugins. +* Is GPLv3-licensed free software. -### Installation +#### Installation Radicale is really easy to install and works out-of-the-box. ```bash -$ python3 -m pip install --upgrade https://github.com/Kozea/Radicale/archive/master.tar.gz -$ python3 -m radicale --storage-filesystem-folder=~/.var/lib/radicale/collections +python3 -m pip install --upgrade https://github.com/Kozea/Radicale/archive/master.tar.gz +python3 -m radicale --storage-filesystem-folder=~/.var/lib/radicale/collections ``` -When the server is launched, open http://localhost:5232/ in your browser! +When the server is launched, open in your browser! You can login with any username and password. Want more? Check the [tutorials](#tutorials) and the [documentation](#documentation). -### What's New? +#### What's New? Read the [changelog on GitHub.](https://github.com/Kozea/Radicale/blob/master/NEWS.md) -# Tutorials -## Simple 5-minute setup +## Tutorials + +### Simple 5-minute setup You want to try Radicale but only have 5 minutes free in your calendar? Let's go right now and play a bit with Radicale! @@ -49,7 +53,7 @@ user name and password. If Radicale fits your needs, it may be time for Follow one of the chapters below depending on your operating system. -### Linux / \*BSD +#### Linux / \*BSD First, make sure that **python** 3.5 or later (**python** ≥ 3.6 is recommended) and **pip** are installed. On most distributions it should be @@ -64,10 +68,10 @@ $ python3 -m pip install --upgrade https://github.com/Kozea/Radicale/archive/mas $ python3 -m radicale --storage-filesystem-folder=~/.var/lib/radicale/collections ``` -Victory! Open http://localhost:5232/ in your browser! +Victory! Open in your browser! You can log in with any username and password. -### Windows +#### Windows The first step is to install Python. Go to [python.org](https://python.org) and download the latest version of Python 3. @@ -82,10 +86,10 @@ C:\Users\User> python -m pip install --upgrade https://github.com/Kozea/Radicale C:\Users\User> python -m radicale --storage-filesystem-folder=~/radicale/collections ``` -Victory! Open http://localhost:5232/ in your browser! +Victory! Open in your browser! You can log in with any username and password. -## Basic Configuration +### Basic Configuration Installation instructions can be found in the [simple 5-minute setup](#tutorials/simple-5-minute-setup) tutorial. @@ -104,7 +108,7 @@ passed via command line arguments.) All configuration options are described in detail in the [Configuration](#documentation/configuration) section. -### Authentication +#### Authentication In its default configuration Radicale doesn't check user names or passwords. If the server is reachable over a network, you should change this. @@ -112,7 +116,7 @@ If the server is reachable over a network, you should change this. First a `users` file with all user names and passwords must be created. It can be stored in the same directory as the configuration file. -#### The secure way +##### The secure way The `users` file can be created and managed with [htpasswd](https://httpd.apache.org/docs/current/programs/htpasswd.html): @@ -138,7 +142,7 @@ htpasswd_filename = /path/to/users htpasswd_encryption = md5 ``` -#### The simple but insecure way +##### The simple but insecure way Create the `users` file by hand with lines containing the user name and password separated by `:`. Example: @@ -158,7 +162,7 @@ htpasswd_filename = /path/to/users htpasswd_encryption = plain ``` -### Addresses +#### Addresses The default configuration binds the server to localhost. It can't be reached from other computers. This can be changed with the following configuration @@ -169,7 +173,7 @@ options (IPv4 and IPv6): hosts = 0.0.0.0:5232, [::]:5232 ``` -### Storage +#### Storage Data is stored in the folder `/var/lib/radicale/collections`. The path can be changed with the following configuration: @@ -184,7 +188,7 @@ filesystem_folder = /path/to/storage > You can find OS dependent instructions in the > [Running as a service](#tutorials/running-as-a-service) section. -### Limits +#### Limits Radicale enforces limits on the maximum number of parallel connections, the maximum file size (important for contacts with big photos) and the rate of @@ -204,16 +208,16 @@ timeout = 30 delay = 1 ``` -## Running as a service +### Running as a service The method to run Radicale as a service depends on your host operating system. Follow one of the chapters below depending on your operating system and requirements. -### Linux with systemd system-wide +#### Linux with systemd system-wide -Create the **radicale** user and group for the Radicale service. -(Run `useradd --system --user-group --home-dir / --shell /sbin/nologin radicale` as root.) +Create the **radicale** user and group for the Radicale service. (Run +`useradd --system --user-group --home-dir / --shell /sbin/nologin radicale` as root.) The storage folder must be writable by **radicale**. (Run `mkdir -p /var/lib/radicale/collections && chown -R radicale:radicale /var/lib/radicale/collections` as root.) @@ -249,6 +253,7 @@ ReadWritePaths=/var/lib/radicale/collections [Install] WantedBy=multi-user.target ``` + Radicale will load the configuration file from `/etc/radicale/config`. To enable and manage the service run: @@ -264,7 +269,7 @@ $ systemctl status radicale $ journalctl --unit radicale.service ``` -### Linux with systemd as a user +#### Linux with systemd as a user Create the file `~/.config/systemd/user/radicale.service`: @@ -297,17 +302,17 @@ $ systemctl --user status radicale $ journalctl --user --unit radicale.service ``` -### Windows with "NSSM - the Non-Sucking Service Manager" +#### Windows with "NSSM - the Non-Sucking Service Manager" First install [NSSM](https://nssm.cc/) and start `nssm install` in a command prompt. Apply the following configuration: - * Service name: `Radicale` - * Application - * Path: `C:\Path\To\Python\python.exe` - * Arguments: `-m radicale --config C:\Path\To\Config` - * I/O redirection - * Error: `C:\Path\To\Radicale.log` +* Service name: `Radicale` +* Application + * Path: `C:\Path\To\Python\python.exe` + * Arguments: `-m radicale --config C:\Path\To\Config` +* I/O redirection + * Error: `C:\Path\To\Radicale.log` > **Security:** Be aware that the service runs in the local system account, > you might want to change this. Managing user accounts is beyond the scope of @@ -321,7 +326,7 @@ The service is configured to start automatically when the computer starts. To start the service manually open **Services** in **Computer Management** and start the **Radicale** service. -## Reverse Proxy +### Reverse Proxy When a reverse proxy is used, the path at which Radicale is available must be provided via the `X-Script-Name` header. The proxy must remove the location @@ -367,7 +372,7 @@ Be reminded that Radicale's default configuration enforces limits on the maximum number of parallel connections, the maximum file size and the rate of incorrect authentication attempts. Connections are terminated after a timeout. -### Manage user accounts with the reverse proxy +#### Manage user accounts with the reverse proxy Set the configuration option `type` in the `auth` section to `http_x_remote_user`. @@ -427,7 +432,7 @@ RequestHeader set X-Remote-User expr=%{REMOTE_USER} > **Security:** Untrusted clients should not be able to access the Radicale > server directly. Otherwise, they can authenticate as any user. -### Secure connection between Radicale and the reverse proxy +#### Secure connection between Radicale and the reverse proxy SSL certificates can be used to encrypt and authenticate the connection between Radicale and the reverse proxy. First you have to generate a certificate for @@ -437,8 +442,10 @@ information about the certificate, the values don't matter and you can keep the defaults. ```bash -$ openssl req -x509 -newkey rsa:4096 -keyout server_key.pem -out server_cert.pem -nodes -days 9999 -$ openssl req -x509 -newkey rsa:4096 -keyout client_key.pem -out client_cert.pem -nodes -days 9999 +openssl req -x509 -newkey rsa:4096 -keyout server_key.pem -out server_cert.pem \ + -nodes -days 9999 +openssl req -x509 -newkey rsa:4096 -keyout client_key.pem -out client_cert.pem \ + -nodes -days 9999 ``` Use the following configuration for Radicale: @@ -464,7 +471,7 @@ location /radicale/ { } ``` -## WSGI Server +### WSGI Server Radicale is compatible with the WSGI specification. @@ -486,16 +493,17 @@ env = RADICALE_CONFIG=/etc/radicale/config Example **Gunicorn** configuration: ```bash -gunicorn --bind '127.0.0.1:5232' --workers 8 --env 'RADICALE_CONFIG=/etc/radicale/config' radicale +gunicorn --bind '127.0.0.1:5232' --env 'RADICALE_CONFIG=/etc/radicale/config' \ + --workers 8 radicale ``` -### Manage user accounts with the WSGI server +#### Manage user accounts with the WSGI server Set the configuration option `type` in the `auth` section to `remote_user`. Radicale uses the user name provided by the WSGI server and disables authentication over HTTP. -## Versioning with Git +### Versioning with Git This tutorial describes how to keep track of all changes to calendars and address books with **git** (or any other version control system). @@ -504,7 +512,7 @@ The repository must be initialized by running `git init` in the file system folder. Internal files of Radicale can be excluded by creating the file `.gitignore` with the following content: -``` +```gitignore .Radicale.cache .Radicale.lock .Radicale.tmp-* @@ -520,8 +528,9 @@ git add -A && (git diff --cached --quiet || git commit -m "Changes by "%(user)s) The command gets executed after every change to the storage and commits the changes into the **git** repository. -# Documentation -## Configuration +## Documentation + +### Configuration Radicale can be configured with a configuration file or with command line arguments. @@ -552,7 +561,9 @@ Paths that start with `?` are optional. The same example configuration via command line arguments looks like: ```bash -python3 -m radicale --server-hosts 0.0.0.0:5232,[::]:5232 --auth-type htpasswd --auth-htpasswd-filename ~/.config/radicale/users --auth-htpasswd-encryption md5 +python3 -m radicale --server-hosts 0.0.0.0:5232,[::]:5232 \ + --auth-type htpasswd --auth-htpasswd-filename ~/.config/radicale/users \ + --auth-htpasswd-encryption md5 ``` Add the argument `--config ""` to stop Radicale from loading the default @@ -560,54 +571,54 @@ configuration files. Run `python3 -m radicale --help` for more information. In the following, all configuration categories and options are described. -### server +#### server The configuration options in this category are only relevant in standalone mode. All options are ignored, when Radicale runs via WSGI. -#### hosts +##### hosts A comma separated list of addresses that the server will bind to. Default: `localhost:5232` -#### max_connections +##### max_connections The maximum number of parallel connections. Set to `0` to disable the limit. Default: `8` -#### max_content_length +##### max_content_length The maximum size of the request body. (bytes) Default: `100000000` -#### timeout +##### timeout Socket timeout. (seconds) Default: `30` -#### ssl +##### ssl Enable transport layer encryption. Default: `False` -#### certificate +##### certificate Path of the SSL certifcate. Default: `/etc/ssl/radicale.cert.pem` -#### key +##### key Path to the private key for SSL. Only effective if `ssl` is enabled. Default: `/etc/ssl/radicale.key.pem` -#### certificate_authority +##### certificate_authority Path to the CA certificate for validating client certificates. This can be used to secure TCP traffic between Radicale and a reverse proxy. If you want to @@ -616,21 +627,23 @@ authentication plugin that extracts the user name from the certificate. Default: -### encoding -#### request +#### encoding + +##### request Encoding for responding requests. Default: `utf-8` -#### stock +##### stock Encoding for storing local collections Default: `utf-8` -### auth -#### type +#### auth + +##### type The method to verify usernames and passwords. @@ -656,13 +669,13 @@ Available backends: Default: `none` -#### htpasswd_filename +##### htpasswd_filename Path to the htpasswd file. Default: -#### htpasswd_encryption +##### htpasswd_encryption The encryption method that is used in the htpasswd file. Use the [htpasswd](https://httpd.apache.org/docs/current/programs/htpasswd.html) @@ -673,6 +686,7 @@ Available methods: `plain` : Passwords are stored in plaintext. This is obviously not secure! The htpasswd file for this can be created by hand and looks like: + ```htpasswd user1:password1 user2:password2 @@ -687,20 +701,21 @@ Available methods: Default: `md5` -#### delay +##### delay Average delay after failed login attempts in seconds. Default: `1` -#### realm +##### realm Message displayed in the client when a password is needed. Default: `Radicale - Password Required` -### rights -#### type +#### rights + +##### type The backend that is used to check the access rights of collections. @@ -728,13 +743,14 @@ Available backends: Default: `owner_only` -#### file +##### file File for the rights backend `from_file`. See the [Rights](#documentation/authentication-and-rights) section. -### storage -#### type +#### storage + +##### type The backend that is used to store data. @@ -744,31 +760,33 @@ Available backends: : Stores the data in the filesystem. `multifilesystem_nolock` -: The `multifilesystem` backend without file-based locking. Must only be used with a single process. +: The `multifilesystem` backend without file-based locking. + Must only be used with a single process. Default: `multifilesystem` -#### filesystem_folder +##### filesystem_folder Folder for storing local collections, created if not present. Default: `/var/lib/radicale/collections` -#### max_sync_token_age +##### max_sync_token_age Delete sync-token that are older than the specified time. (seconds) Default: `2592000` -#### hook +##### hook Command that is run after changes to storage. Take a look at the [Versioning with Git](#tutorials/versioning-with-git) tutorial for an example. Default: -### web -#### type +#### web + +##### type The backend that provides the web interface of Radicale. @@ -782,8 +800,9 @@ Available backends: Default: `internal` -### logging -#### level +#### logging + +##### level Set the logging level. @@ -791,13 +810,13 @@ Available levels: **debug**, **info**, **warning**, **error**, **critical** Default: `warning` -#### mask_passwords +##### mask_passwords Don't include passwords in logs. Default: `True` -### headers +#### headers In this section additional HTTP headers that are sent to clients can be specified. @@ -808,38 +827,38 @@ An example to relax the same-origin policy: Access-Control-Allow-Origin = * ``` -## Supported Clients +### Supported Clients Radicale has been tested with: - * [Android](https://android.com/) with - [DAVx⁵](https://www.davx5.com/) (formerly DAVdroid) - * [GNOME Calendar](https://wiki.gnome.org/Apps/Calendar), - [Contacts](https://wiki.gnome.org/Apps/Contacts) and - [Evolution](https://wiki.gnome.org/Apps/Evolution) - * [Mozilla Thunderbird](https://www.mozilla.org/thunderbird/) with - [CardBook](https://addons.mozilla.org/thunderbird/addon/cardbook/) and - [Lightning](https://www.mozilla.org/projects/calendar/) - * [InfCloud](https://www.inf-it.com/open-source/clients/infcloud/), - [CalDavZAP](https://www.inf-it.com/open-source/clients/caldavzap/) and - [CardDavMATE](https://www.inf-it.com/open-source/clients/carddavmate/) +* [Android](https://android.com/) with + [DAVx⁵](https://www.davx5.com/) (formerly DAVdroid) +* [GNOME Calendar](https://wiki.gnome.org/Apps/Calendar), + [Contacts](https://wiki.gnome.org/Apps/Contacts) and + [Evolution](https://wiki.gnome.org/Apps/Evolution) +* [Mozilla Thunderbird](https://www.mozilla.org/thunderbird/) with + [CardBook](https://addons.mozilla.org/thunderbird/addon/cardbook/) and + [Lightning](https://www.mozilla.org/projects/calendar/) +* [InfCloud](https://www.inf-it.com/open-source/clients/infcloud/), + [CalDavZAP](https://www.inf-it.com/open-source/clients/caldavzap/) and + [CardDavMATE](https://www.inf-it.com/open-source/clients/carddavmate/) Many clients do not support the creation of new calendars and address books. You can use Radicale's web interface -(e.g. http://localhost:5232) to create and manage address books and calendars. +(e.g. ) to create and manage address books and calendars. In some clients you can just enter the URL of the Radicale server (e.g. `http://localhost:5232`) and your user name. In others, you have to enter the URL of the collection directly (e.g. `http://localhost:5232/user/calendar`). -### DAVx⁵ +#### DAVx⁵ Enter the URL of the Radicale server (e.g. `http://localhost:5232`) and your user name. DAVx⁵ will show all existing calendars and address books and you can create new. -### GNOME Calendar, Contacts and Evolution +#### GNOME Calendar, Contacts and Evolution **GNOME Calendar** and **Contacts** do not support adding WebDAV calendars and address books directly, but you can add them in **Evolution**. @@ -849,14 +868,15 @@ Enter the URL of the Radicale server (e.g. `http://localhost:5232`) and your user name. Clicking on the search button will list the existing calendars and address books. -### Thunderbird -#### CardBook +#### Thunderbird + +##### CardBook Add a new address book on the network with CardDAV. You have to enter the full URL of the collection (e.g. `http://localhost:5232/user/addressbook`) and your user name. -#### Lightning +##### Lightning Add a new calendar on the network with `CalDAV`. (Don't use `iCalendar (ICS)`!) You have to enter the full URL of the collection (e.g. @@ -864,7 +884,7 @@ You have to enter the full URL of the collection (e.g. different users on the same server, you can specify the user name in the URL (e.g. `http://user@localhost...`) -### InfCloud, CalDavZAP and CardDavMATE +#### InfCloud, CalDavZAP and CardDavMATE You can integrate InfCloud into Radicale's web interface with [RadicaleInfCloud](https://github.com/Unrud/RadicaleInfCloud). No additional @@ -877,7 +897,7 @@ the Radicale server, because of the You have to add additional HTTP header in the `headers` section of Radicale's configuration. The documentation of **InfCloud** has more details on this. -### Command line +#### Command line This is not the recommended way of creating and managing your calendars and address books. Use Radicale's web interface or a client with support for it @@ -935,10 +955,10 @@ children of the path `/USERNAME/`. Delete the collections by running something like: ```bash -$ curl -u user -X DELETE 'http://localhost:5232/user/calendar' +curl -u user -X DELETE 'http://localhost:5232/user/calendar' ``` -## Authentication and Rights +### Authentication and Rights This section describes the format of the rights file for the `from_file` authentication backend. The configuration option `file` in the `rights` @@ -993,14 +1013,14 @@ if you want to use regular curly braces in the `user` and `collection` regexes. The following `permissions` are recognized: - * **R:** read collections (excluding address books and calendars) - * **r:** read address book and calendar collections - * **i:** subset of **r** that only allows direct access via HTTP method GET - (CalDAV/CardDAV is susceptible to expensive search requests) - * **W:** write collections (excluding address books and calendars) - * **w:** write address book and calendar collections +* **R:** read collections (excluding address books and calendars) +* **r:** read address book and calendar collections +* **i:** subset of **r** that only allows direct access via HTTP method GET + (CalDAV/CardDAV is susceptible to expensive search requests) +* **W:** write collections (excluding address books and calendars) +* **w:** write address book and calendar collections -## Storage +### Storage This document describes the layout and format of the file system storage (`multifilesystem` backend). @@ -1011,12 +1031,12 @@ Scripts can be invoked manually, periodically (e.g. with change to the storage with the configuration option `hook` in the `storage` section (e.g. [Versioning with Git](#tutorials/versioning-with-git)). -### Layout +#### Layout The file system contains the following files and folders: - * `.Radicale.lock`: The lock file for locking the storage. - * `collection-root`: This folder contains all collections and items. +* `.Radicale.lock`: The lock file for locking the storage. +* `collection-root`: This folder contains all collections and items. A collection is represented by a folder. This folder may contain the file `.Radicale.props` with all WebDAV properties of the collection encoded @@ -1045,14 +1065,14 @@ They should be deleted after requests are finished but it's possible that they are left behind when Radicale or the computer crashes. It's safe to delete them. -### Locking +#### Locking When the data is accessed by hand or by an externally invoked script, the storage must be locked. The storage can be locked for exclusive or shared access. It prevents Radicale from reading or writing the file system. The storage is locked with exclusive access while the `hook` runs. -#### Linux shell scripts +##### Linux shell scripts Use the [flock](https://manpages.debian.org/unstable/util-linux/flock.1.en.html) @@ -1065,14 +1085,14 @@ $ flock --exclusive /path/to/storage/.Radicale.lock COMMAND $ flock --shared /path/to/storage/.Radicale.lock COMMAND ``` -#### Linux and MacOS +##### Linux and MacOS Use the [flock](https://manpages.debian.org/unstable/manpages-dev/flock.2.en.html) syscall. Python provides it in the [fcntl](https://docs.python.org/3/library/fcntl.html#fcntl.flock) module. -#### Windows +##### Windows Use [LockFile](https://msdn.microsoft.com/en-us/library/windows/desktop/aa365202%28v=vs.85%29.aspx) @@ -1081,7 +1101,7 @@ for exclusive access or which also supports shared access. Setting `nNumberOfBytesToLockLow` to `1` and `nNumberOfBytesToLockHigh` to `0` works. -### Manually creating collections +#### Manually creating collections To create a new collection, you have to create the corresponding folder in the file system storage (e.g. `collection-root/user/calendar`). @@ -1105,65 +1125,38 @@ address books that are direct children of the path `/USERNAME/`. Delete collections by deleting the corresponding folders. -## Logging +### Logging Radicale logs to `stderr`. The verbosity of the log output can be controlled with `--debug` command line argument or the `level` configuration option in the `logging` section. -## Architecture +### Architecture Radicale is a small piece of software, but understanding it is not as easy as it seems. But don't worry, reading this short section is enough to understand what a CalDAV/CardDAV server is, and how Radicale's code is organized. -### Protocol overview +#### Protocol overview Here is a simple overview of the global architecture for reaching a calendar or an address book through network: - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
PartLayerProtocol or Format
ServerCalendar/Contact StorageiCal/vCard
Calendar/Contact ServerCalDAV/CardDAV Server
TransferNetworkCalDAV/CardDAV (HTTP + TLS)
ClientCalendar/Contact ClientCalDAV/CardDAV Client
GUITerminal, GTK, Web interface, etc.
+| Part | Layer | Protocol or Format | +|----------|--------------------------|------------------------------------| +| Server | Calendar/Contact Storage | iCal/vCard | +| '' | Calendar/Contact Server | CalDAV/CardDAV Server | +| Transfer | Network | CalDAV/CardDAV (HTTP + TLS) | +| Client | Calendar/Contact Client | CalDAV/CardDAV Client | +| '' | GUI | Terminal, GTK, Web interface, etc. | Radicale is **only the server part** of this architecture. Please note that: - * CalDAV and CardDAV are superset protocols of WebDAV, - * WebDAV is a superset protocol of HTTP. +* CalDAV and CardDAV are superset protocols of WebDAV, +* WebDAV is a superset protocol of HTTP. Radicale being a CalDAV/CardDAV server, it also can be seen as a special WebDAV and HTTP server. @@ -1177,7 +1170,7 @@ If you want to see or edit your events and your contacts, you have to use another software called a client, that can be a "normal" applications with icons and buttons, a terminal or another web application. -### Code Architecture +#### Code Architecture The ``radicale`` package offers the following modules. @@ -1236,12 +1229,12 @@ The ``radicale`` package offers the following modules. : Helper functions for working with the XML part of CalDAV/CardDAV requests and responses. It's based on the ElementTree XML API. -## Plugins +### Plugins Radicale can be extended by plugins for authentication, rights management and storage. Plugins are **python** modules. -### Getting started +#### Getting started To get started we walk through the creation of a simple authentication plugin, that accepts login attempts with a static password. @@ -1311,103 +1304,108 @@ You can uninstall the module with: python3 -m pip uninstall radicale_static_password_auth ``` -### Authentication plugins +#### Authentication plugins This plugin type is used to check login credentials. The module must contain a class `Auth` that extends `radicale.auth.BaseAuth`. Take a look at the file `radicale/auth/__init__.py` in Radicale's source code for more information. -### Rights management plugins +#### Rights management plugins This plugin type is used to check if a user has access to a path. The module must contain a class `Rights` that extends `radicale.rights.BaseRights`. Take a look at the file `radicale/rights/__init__.py` in Radicale's source code for more information. -### Web plugins +#### Web plugins This plugin type is used to provide the web interface for Radicale. The module must contain a class `Web` that extends `radicale.web.BaseWeb`. Take a look at the file `radicale/web/__init__.py` in Radicale's source code for more information. -### Storage plugins +#### Storage plugins This plugin is used to store collections and items. The module must contain a class `Storage` that extends `radicale.storage.BaseStorage`. Take a look at the file `radicale/storage/__init__.py` in Radicale's source code for more information. -# Contribute +## Contribute -### Chat with Us on IRC +#### Chat with Us on IRC Want to say something? Join our IRC room: `##kozea` on Freenode. -### Report Bugs +#### Report Bugs Found a bug? Want a new feature? Report a new issue on the [Radicale bug-tracker](https://github.com/Kozea/Radicale/issues). -### Hack +#### Hack Interested in hacking? Feel free to clone the [git repository on GitHub](https://github.com/Kozea/Radicale) if you want to add new features, fix bugs or update the documentation. -### Documentation +#### Documentation To change or complement the documentation create a pull request to [DOCUMENTATION.md](https://github.com/Kozea/Radicale/blob/master/DOCUMENTATION.md). -# Download +## Download -### PyPI +#### PyPI Radicale is [available on PyPI](https://pypi.python.org/pypi/Radicale/). To install, just type as superuser: - $ python3 -m pip install --upgrade radicale +```bash +python3 -m pip install --upgrade radicale +``` -### Git Repository +#### Git Repository If you want the development version of Radicale, take a look at the [git repository on GitHub](https://github.com/Kozea/Radicale/), or install it directly with: - $ python3 -m pip install --upgrade https://github.com/Kozea/Radicale/archive/master.tar.gz +```bash +python3 -m pip install --upgrade https://github.com/Kozea/Radicale/archive/master.tar.gz +``` You can also download the content of the repository as an [archive](https://github.com/Kozea/Radicale/tarball/master). -### Source Packages +#### Source Packages You can find the source packages of all releases on [GitHub](https://github.com/Kozea/Radicale/releases). -### Linux Distribution Packages +#### Linux Distribution Packages Radicale has been packaged for: - * [ArchLinux](https://www.archlinux.org/packages/community/any/radicale/) by - David Runge - * [Debian](http://packages.debian.org/radicale) by Jonas Smedegaard - * [Gentoo](https://packages.gentoo.org/packages/www-apps/radicale) - by René Neumann, Maxim Koltsov and Manuel Rüger - * [Fedora/RHEL/CentOS](https://src.fedoraproject.org/rpms/radicale) by Jorti and Peter Bieringer - * [Mageia](http://madb.mageia.org/package/show/application/0/name/radicale) - by Jani Välimaa - * [OpenBSD](http://openports.se/productivity/radicale) by Sergey Bronnikov, - Stuart Henderson and Ian Darwin - * [openSUSE](http://software.opensuse.org/package/Radicale?search_term=radicale) - by Ákos Szőts and Rueckert - * [PyPM](http://code.activestate.com/pypm/radicale/) - * [Slackware](http://schoepfer.info/slackware.xhtml#packages-network) by - Johannes Schöpfer - * [Trisquel](http://packages.trisquel.info/search?searchon=names&keywords=radicale) - * [Ubuntu](http://packages.ubuntu.com/radicale) by the MOTU and Jonas - Smedegaard +* [ArchLinux](https://www.archlinux.org/packages/community/any/radicale/) by + David Runge +* [Debian](http://packages.debian.org/radicale) by Jonas Smedegaard +* [Gentoo](https://packages.gentoo.org/packages/www-apps/radicale) + by René Neumann, Maxim Koltsov and Manuel Rüger +* [Fedora/RHEL/CentOS](https://src.fedoraproject.org/rpms/radicale) by Jorti + and Peter Bieringer +* [Mageia](http://madb.mageia.org/package/show/application/0/name/radicale) + by Jani Välimaa +* [OpenBSD](http://openports.se/productivity/radicale) by Sergey Bronnikov, + Stuart Henderson and Ian Darwin +* [openSUSE](http://software.opensuse.org/package/Radicale?search_term=radicale) + by Ákos Szőts and Rueckert +* [PyPM](http://code.activestate.com/pypm/radicale/) +* [Slackware](http://schoepfer.info/slackware.xhtml#packages-network) by + Johannes Schöpfer +* [Trisquel](http://packages.trisquel.info/search?searchon=names&keywords=radicale) +* [Ubuntu](http://packages.ubuntu.com/radicale) by the MOTU and Jonas + Smedegaard Radicale is also [available on Cloudron](https://cloudron.io/button.html?app=org.radicale.cloudronapp2) @@ -1416,9 +1414,9 @@ and has a Dockerfile. If you are interested in creating packages for other Linux distributions, read the ["Contribute" section](#contribute). -# About +## About -### Main Goals +#### Main Goals Radicale is a complete calendar and contact storing and manipulating solution. It can store multiple calendars and multiple address books. @@ -1433,7 +1431,7 @@ preconfigured to work out-of-the-box. Radicale is written in Python. It runs on most of the UNIX-like platforms (Linux, \*BSD, macOS) and Windows. It is free and open-source software. -### What Radicale Will Never Be +#### What Radicale Will Never Be Radicale is a server, not a client. No interfaces will be created to work with the server. @@ -1446,14 +1444,14 @@ CalDAV and CardDAV are the best open standards available, and they are quite widely used by both clients and servers. We decided to use it, and we will not use another one. -### Technical Choices +#### Technical Choices Important global development choices have been decided before writing code. They are very useful to understand why the Radicale Project is different from other CalDAV and CardDAV servers, and why features are included or not in the code. -#### Oriented to Calendar and Contact User Agents +##### Oriented to Calendar and Contact User Agents Calendar and contact servers work with calendar and contact clients, using a defined protocol. CalDAV and CardDAV are good protocols, covering lots of @@ -1471,7 +1469,7 @@ Even if it tries it best to follow the RFCs, Radicale does not and **will not** blindly implement the CalDAV and CardDAV standards. It is mainly designed to support the CalDAV and CardDAV implementations of different clients. -#### Simple +##### Simple Radicale is designed to be simple to install, simple to configure, simple to use. @@ -1486,7 +1484,7 @@ or need a strong configuration, the Radicale Server can (sometimes, if not often) be launched in a couple of minutes, if you follow the [tutorial](#tutorials/simple-5-minute-setup). -#### Lazy +##### Lazy The CalDAV RFC defines what must be done, what can be done and what cannot be done. Many violations of the protocol are totally defined and behaviors are @@ -1497,7 +1495,7 @@ violations do not exist. That is why most of the errors in client requests have undetermined consequences for the lazy server that can reply good answers, bad answers, or even no answer. -### History +#### History Radicale has been started as a (free topic) stupid school project replacing another (assigned topic) even more stupid school project. diff --git a/NEWS.md b/NEWS.md index e2d05f11..6e5a771e 100644 --- a/NEWS.md +++ b/NEWS.md @@ -4,312 +4,306 @@ ## 3.0.6 - * Allow web plugins to handle POST requests +* Allow web plugins to handle POST requests ## 3.0.5 - * Start storage hook in own process group - * Kill storage hook on error or exit - * Try to kill child processes of storage hook - * Internal Server: Exit immediately when signal is received (do not wait for clients or storage hook to finish) +* Start storage hook in own process group +* Kill storage hook on error or exit +* Try to kill child processes of storage hook +* Internal Server: Exit immediately when signal is received + (do not wait for clients or storage hook to finish) ## 3.0.4 - * Fix internal server on FreeBSD +* Fix internal server on FreeBSD ## 3.0.3 - * Fix internal server on OpenBSD +* Fix internal server on OpenBSD ## 3.0.2 - * Use 403 response for supported-report and valid-sync-token errors - * Internal server: Handle missing IPv6 support +* Use 403 response for supported-report and valid-sync-token errors +* Internal server: Handle missing IPv6 support ## 3.0.1 - * Fix XML error messages +* Fix XML error messages ## 3.0.0 This release is incompatible with previous releases. See the upgrade checklist below. - * Parallel write requests - * Support PyPy - * Protect against XML denial-of-service attacks - * Check for duplicated UIDs in calendars/address books - * Only add missing UIDs for uploaded whole calendars/address books - * Switch from md5 to sha256 for UIDs and tokens +* Parallel write requests +* Support PyPy +* Protect against XML denial-of-service attacks +* Check for duplicated UIDs in calendars/address books +* Only add missing UIDs for uploaded whole calendars/address books +* Switch from md5 to sha256 for UIDs and tokens +* Code cleanup: + * All plugin interfaces were simplified and are incompatible with + old plugins + * Major refactor + * Never sanitize paths multiple times (check if they are sanitized) +* Config + * Multiple configuration files separated by `:` (resp. `;` + on Windows) + * Optional configuration files by prepending file path with `?` + * Check validity of every configuration file and command line + arguments separately + * Report the source of invalid configuration parameters in + error messages * Code cleanup: - * All plugin interfaces were simplified and are incompatible with - old plugins - * Major refactor - * Never sanitize paths multiple times (check if they are sanitized) - * Config - * Multiple configuration files separated by ``:`` (resp. ``;`` - on Windows) - * Optional configuration files by prepending file path with ``?`` - * Check validity of every configuration file and command line - arguments separately - * Report the source of invalid configuration parameters in - error messages - * Code cleanup: - * Store configuration as parsed values - * Use Schema that describes configuration and allow plugins to apply - their own schemas - * Mark internal settings with ``_`` - * Internal server - * Bind to IPv4 and IPv6 address, when both are available for hostname - * Set default address to ``localhost:5232`` - * Remove settings for SSL ciphers and protocol versions (enforce safe - defaults instead) - * Remove settings for file locking because they are of little use - * Remove daemonization (should be handled by service managers) - * Logging - * Replace complex Python logger configuration with simple - ``logging.level`` setting - * Write PID and ``threadName`` instead of cryptic id's in log messages - * Use ``wsgi.errors`` for logging (as required by the WSGI spec) - * Code cleanup: - * Don't pass logger object around (use ``logging.getLogger()`` - instead) - * Auth - * Use ``md5`` as default for ``htpasswd_encryption`` setting - * Move setting ``realm`` from section ``server`` to ``auth`` - * Rights - * Use permissions ``RW`` for non-leaf collections and ``rw`` for - address books/calendars - * New permission ``i`` that only allows access with HTTP method GET - (CalDAV/CardDAV is susceptible to expensive search requests) - * Web - * Add upload dialog for calendars/address books from file - * Show startup loading message - * Show warning if JavaScript is disabled - * Pass HTML Validator - * Storage - * Check for missing UIDs in items - * Check for child collections in address books and calendars - * Code cleanup: - * Split BaseCollection in BaseStorage and BaseCollection + * Store configuration as parsed values + * Use Schema that describes configuration and allow plugins to apply + their own schemas + * Mark internal settings with `_` +* Internal server + * Bind to IPv4 and IPv6 address, when both are available for hostname + * Set default address to `localhost:5232` + * Remove settings for SSL ciphers and protocol versions (enforce safe + defaults instead) + * Remove settings for file locking because they are of little use + * Remove daemonization (should be handled by service managers) +* Logging + * Replace complex Python logger configuration with simple + `logging.level` setting + * Write PID and `threadName` instead of cryptic id's in log messages + * Use `wsgi.errors` for logging (as required by the WSGI spec) + * Code cleanup: + * Don't pass logger object around (use `logging.getLogger()` + instead) +* Auth + * Use `md5` as default for `htpasswd_encryption` setting + * Move setting `realm` from section `server` to `auth` +* Rights + * Use permissions `RW` for non-leaf collections and `rw` for + address books/calendars + * New permission `i` that only allows access with HTTP method GET + (CalDAV/CardDAV is susceptible to expensive search requests) +* Web + * Add upload dialog for calendars/address books from file + * Show startup loading message + * Show warning if JavaScript is disabled + * Pass HTML Validator +* Storage + * Check for missing UIDs in items + * Check for child collections in address books and calendars + * Code cleanup: + * Split BaseCollection in BaseStorage and BaseCollection ## Upgrade checklist - * Config - * Some settings were removed - * The default of ``auth.htpasswd_encryption`` changed to ``md5`` - * The setting ``server.realm`` moved to ``auth.realm`` - * The setting ``logging.debug`` was replaced by ``logging.level`` - * The format of the ``rights.file`` configuration file changed: - * Permission ``r`` replaced by ``Rr`` - * Permission ``w`` replaced by ``Ww`` - * New permission ``i`` added as subset of ``r`` - * Replaced variable ``%(login)s`` by ``{user}`` - * Removed variable ``%(path)s`` - * ``{`` must be escaped as ``{{`` and ``}`` as ``}}`` in regexes - * File system storage - * The storage format is compatible with Radicale 2.x.x - * Run ``radicale --verify-storage`` to check for errors - * Custom plugins: - * ``auth`` and ``web`` plugins require minor adjustments - * ``rights`` plugins must be adapted to the new permission model - * ``storage`` plugins require major changes +* Config + * Some settings were removed + * The default of `auth.htpasswd_encryption` changed to `md5` + * The setting `server.realm` moved to `auth.realm` + * The setting `logging.debug` was replaced by `logging.level` + * The format of the `rights.file` configuration file changed: + * Permission `r` replaced by `Rr` + * Permission `w` replaced by `Ww` + * New permission `i` added as subset of `r` + * Replaced variable `%(login)s` by `{user}` + * Removed variable `%(path)s` + * `{` must be escaped as `{{` and `}` as `}}` in regexes +* File system storage + * The storage format is compatible with Radicale 2.x.x + * Run `radicale --verify-storage` to check for errors +* Custom plugins: + * `auth` and `web` plugins require minor adjustments + * `rights` plugins must be adapted to the new permission model + * `storage` plugins require major changes ## 2.1.10 - Wild Radish This release is compatible with version 2.0.0. - * Update required versions for dependencies - * Get ``RADICALE_CONFIG`` from WSGI environ - * Improve HTTP status codes - * Fix race condition in storage lock creation - * Raise default limits for content length and timeout - * Log output from hook +* Update required versions for dependencies +* Get `RADICALE_CONFIG` from WSGI environ +* Improve HTTP status codes +* Fix race condition in storage lock creation +* Raise default limits for content length and timeout +* Log output from hook ## 2.1.9 - Wild Radish This release is compatible with version 2.0.0. - * Specify versions for dependencies - * Move WSGI initialization into module - * Check if ``REPORT`` method is actually supported - * Include ``rights`` file in source distribution - * Specify ``md5`` and ``bcrypt`` as extras - * Improve logging messages - * Windows: Fix crash when item path is a directory +* Specify versions for dependencies +* Move WSGI initialization into module +* Check if `REPORT` method is actually supported +* Include `rights` file in source distribution +* Specify `md5` and `bcrypt` as extras +* Improve logging messages +* Windows: Fix crash when item path is a directory ## 2.1.8 - Wild Radish This release is compatible with version 2.0.0. - * Flush files before fsync'ing +* Flush files before fsync'ing ## 2.1.7 - Wild Radish This release is compatible with version 2.0.0. - * Don't print warning when cache format changes - * Add documentation for ``BaseAuth`` - * Add ``is_authenticated2(login, user, password)`` to ``BaseAuth`` - * Fix names of custom properties in PROPFIND requests with - ``D:propname`` or ``D:allprop`` - * Return all properties in PROPFIND requests with ``D:propname`` or - ``D:allprop`` - * Allow ``D:displayname`` property on all collections - * Answer with ``D:unauthenticated`` for ``D:current-user-principal`` property - when not logged in - * Remove non-existing ``ICAL:calendar-color`` and ``C:calendar-timezone`` - properties from PROPFIND requests with ``D:propname`` or ``D:allprop`` - * Add ``D:owner`` property to calendar and address book objects - * Remove ``D:getetag`` and ``D:getlastmodified`` properties from regular - collections - +* Don't print warning when cache format changes +* Add documentation for `BaseAuth` +* Add `is_authenticated2(login, user, password)` to `BaseAuth` +* Fix names of custom properties in PROPFIND requests with + `D:propname` or `D:allprop` +* Return all properties in PROPFIND requests with `D:propname` or + `D:allprop` +* Allow `D:displayname` property on all collections +* Answer with `D:unauthenticated` for `D:current-user-principal` property + when not logged in +* Remove non-existing `ICAL:calendar-color` and `C:calendar-timezone` + properties from PROPFIND requests with `D:propname` or `D:allprop` +* Add `D:owner` property to calendar and address book objects +* Remove `D:getetag` and `D:getlastmodified` properties from regular + collections ## 2.1.6 - Wild Radish This release is compatible with version 2.0.0. - * Fix content-type of VLIST - * Specify correct COMPONENT in content-type of VCALENDAR - * Cache COMPONENT of calendar objects (improves speed with some clients) - * Stricter parsing of filters - * Improve support for CardDAV filter - * Fix some smaller bugs in CalDAV filter - * Add X-WR-CALNAME and X-WR-CALDESC to calendars downloaded via HTTP/WebDAV - * Use X-WR-CALNAME and X-WR-CALDESC from calendars published via WebDAV +* Fix content-type of VLIST +* Specify correct COMPONENT in content-type of VCALENDAR +* Cache COMPONENT of calendar objects (improves speed with some clients) +* Stricter parsing of filters +* Improve support for CardDAV filter +* Fix some smaller bugs in CalDAV filter +* Add X-WR-CALNAME and X-WR-CALDESC to calendars downloaded via HTTP/WebDAV +* Use X-WR-CALNAME and X-WR-CALDESC from calendars published via WebDAV ## 2.1.5 - Wild Radish This release is compatible with version 2.0.0. - * Add ``--verify-storage`` command-line argument - * Allow comments in the htpasswd file - * Don't strip whitespaces from user names and passwords in the htpasswd file - * Remove cookies from logging output - * Allow uploads of whole collections with many components - * Show warning message if server.timeout is used with Python < 3.5.2 +* Add `--verify-storage` command-line argument +* Allow comments in the htpasswd file +* Don't strip whitespaces from user names and passwords in the htpasswd file +* Remove cookies from logging output +* Allow uploads of whole collections with many components +* Show warning message if server.timeout is used with Python < 3.5.2 ## 2.1.4 - Wild Radish This release is compatible with version 2.0.0. - * Fix incorrect time range matching and calculation for some edge-cases with - rescheduled recurrences - * Fix owner property +* Fix incorrect time range matching and calculation for some edge-cases with + rescheduled recurrences +* Fix owner property ## 2.1.3 - Wild Radish This release is compatible with version 2.0.0. - * Enable timeout for SSL handshakes and move them out of the main thread - * Create cache entries during upload of items - * Stop built-in server on Windows when Ctrl+C is pressed - * Prevent slow down when multiple requests hit a collection during cache warm-up +* Enable timeout for SSL handshakes and move them out of the main thread +* Create cache entries during upload of items +* Stop built-in server on Windows when Ctrl+C is pressed +* Prevent slow down when multiple requests hit a collection during cache warm-up ## 2.1.2 - Wild Radish This release is compatible with version 2.0.0. - * Remove workarounds for bugs in VObject < 0.9.5 - * Error checking of collection tags and associated components - * Improve error checking of uploaded collections and components - * Don't delete empty collection properties implicitly - * Improve logging of VObject serialization +* Remove workarounds for bugs in VObject < 0.9.5 +* Error checking of collection tags and associated components +* Improve error checking of uploaded collections and components +* Don't delete empty collection properties implicitly +* Improve logging of VObject serialization ## 2.1.1 - Wild Radish Again This release is compatible with version 2.0.0. - * Add missing UIDs instead of failing - * Improve error checking of calendar and address book objects - * Fix upload of whole address books +* Add missing UIDs instead of failing +* Improve error checking of calendar and address book objects +* Fix upload of whole address books ## 2.1.0 - Wild Radish This release is compatible with version 2.0.0. - * Built-in web interface for creating and managing address books and calendars - * can be extended with web plugins - * Much faster storage backend - * Significant reduction in memory usage - * Improved logging - * Include paths (of invalid items / requests) in log messages - * Include configuration values causing problems in log messages - * Log warning message for invalid requests by clients - * Log error message for invalid files in the storage backend - * No stack traces unless debugging is enabled - * Time range filter also regards overwritten recurrences - * Items that couldn't be filtered because of bugs in VObject are always - returned (and a warning message is logged) - * Basic error checking of configuration files - * File system locking isn't disabled implicitly anymore, instead a new - configuration option gets introduced - * The permissions of the lock file are not changed anymore - * Support for sync-token - * Support for client-side SSL certificates - * Rights plugins can decide if access to an item is granted explicitly - * Respond with 403 instead of 404 for principal collections of non-existing - users when ``owner_only`` plugin is used (information leakage) - * Authentication plugins can provide the login and password from the - environment - * new ``remote_user`` plugin, that gets the login from the ``REMOTE_USER`` - environment variable (for WSGI server) - * new ``http_x_remote_user`` plugin, that gets the login from the - ``X-Remote-User`` HTTP header (for reverse proxies) - +* Built-in web interface for creating and managing address books and calendars + * can be extended with web plugins +* Much faster storage backend +* Significant reduction in memory usage +* Improved logging + * Include paths (of invalid items / requests) in log messages + * Include configuration values causing problems in log messages + * Log warning message for invalid requests by clients + * Log error message for invalid files in the storage backend + * No stack traces unless debugging is enabled +* Time range filter also regards overwritten recurrences +* Items that couldn't be filtered because of bugs in VObject are always + returned (and a warning message is logged) +* Basic error checking of configuration files +* File system locking isn't disabled implicitly anymore, instead a new + configuration option gets introduced +* The permissions of the lock file are not changed anymore +* Support for sync-token +* Support for client-side SSL certificates +* Rights plugins can decide if access to an item is granted explicitly + * Respond with 403 instead of 404 for principal collections of non-existing + users when `owner_only` plugin is used (information leakage) +* Authentication plugins can provide the login and password from the + environment + * new `remote_user` plugin, that gets the login from the `REMOTE_USER` + environment variable (for WSGI server) + * new `http_x_remote_user` plugin, that gets the login from the + `X-Remote-User` HTTP header (for reverse proxies) ## 2.0.0 - Little Big Radish This feature is not compatible with the 1.x.x versions. Follow our -[migration guide](https://radicale.org/2.1.html#documentation/migration-from-1xx-to-2xx) if you want to switch from 1.x.x to -2.0.0. - - * Support Python 3.3+ only, Python 2 is not supported anymore - * Keep only one simple filesystem-based storage system - * Remove built-in Git support - * Remove built-in authentication modules - * Keep the WSGI interface, use Python HTTP server by default - * Use a real iCal parser, rely on the "vobject" external module - * Add a solid calendar discovery - * Respect the difference between "files" and "folders", don't rely on slashes - * Remove the calendar creation with GET requests - * Be stateless - * Use a file locker - * Add threading - * Get atomic writes - * Support new filters - * Support read-only permissions - * Allow External plugins for authentication, rights management, storage and - version control +[migration guide](https://radicale.org/2.1.html#documentation/migration-from-1xx-to-2xx) +if you want to switch from 1.x.x to 2.0.0. +* Support Python 3.3+ only, Python 2 is not supported anymore +* Keep only one simple filesystem-based storage system +* Remove built-in Git support +* Remove built-in authentication modules +* Keep the WSGI interface, use Python HTTP server by default +* Use a real iCal parser, rely on the "vobject" external module +* Add a solid calendar discovery +* Respect the difference between "files" and "folders", don't rely on slashes +* Remove the calendar creation with GET requests +* Be stateless +* Use a file locker +* Add threading +* Get atomic writes +* Support new filters +* Support read-only permissions +* Allow External plugins for authentication, rights management, storage and + version control ## 1.1.4 - Fifth Law of Nature - * Use ``shutil.move`` for ``--export-storage`` - +* Use `shutil.move` for `--export-storage` ## 1.1.3 - Fourth Law of Nature - * Add a ``--export-storage=FOLDER`` command-line argument (by Unrud, see #606) - +* Add a `--export-storage=FOLDER` command-line argument (by Unrud, see #606) ## 1.1.2 - Third Law of Nature - * **Security fix**: Add a random timer to avoid timing oracles and simple - bruteforce attacks when using the htpasswd authentication method. - * Various minor fixes. - +* **Security fix**: Add a random timer to avoid timing oracles and simple + bruteforce attacks when using the htpasswd authentication method. +* Various minor fixes. ## 1.1.1 - Second Law of Nature - * Fix the owner_write rights rule - +* Fix the owner_write rights rule ## 1.1 - Law of Nature One feature in this release is **not backward compatible**: - * Use the first matching section for rights (inspired from daald) +* Use the first matching section for rights (inspired from daald) Now, the first section matching the path and current user in your custom rights file is used. In the previous versions, the most permissive rights of all the @@ -319,175 +313,158 @@ specific rules at the top of the file independant from the generic ones. Many **improvements in this release are related to security**, you should upgrade Radicale as soon as possible: - * Improve the regex used for well-known URIs (by Unrud) - * Prevent regex injection in rights management (by Unrud) - * Prevent crafted HTTP request from calling arbitrary functions (by Unrud) - * Improve URI sanitation and conversion to filesystem path (by Unrud) - * Decouple the daemon from its parent environment (by Unrud) +* Improve the regex used for well-known URIs (by Unrud) +* Prevent regex injection in rights management (by Unrud) +* Prevent crafted HTTP request from calling arbitrary functions (by Unrud) +* Improve URI sanitation and conversion to filesystem path (by Unrud) +* Decouple the daemon from its parent environment (by Unrud) Some bugs have been fixed and little enhancements have been added: - * Assign new items to corret key (by Unrud) - * Avoid race condition in PID file creation (by Unrud) - * Improve the docker version (by cdpb) - * Encode message and commiter for git commits - * Test with Python 3.5 - +* Assign new items to corret key (by Unrud) +* Avoid race condition in PID file creation (by Unrud) +* Improve the docker version (by cdpb) +* Encode message and commiter for git commits +* Test with Python 3.5 ## 1.0.1 - Sunflower Again - * Update the version because of a **stupid** "feature"™ of PyPI - +* Update the version because of a **stupid** "feature"™ of PyPI ## 1.0 - Sunflower - * Enhanced performances (by Mathieu Dupuy) - * Add MD5-APR1 and BCRYPT for htpasswd-based authentication (by Jan-Philip Gehrcke) - * Use PAM service (by Stephen Paul Weber) - * Don't discard PROPPATCH on empty collections (by Markus Unterwaditzer) - * Write the path of the collection in the git message (by Matthew Monaco) - * Tests launched on Travis - +* Enhanced performances (by Mathieu Dupuy) +* Add MD5-APR1 and BCRYPT for htpasswd-based authentication (by Jan-Philip Gehrcke) +* Use PAM service (by Stephen Paul Weber) +* Don't discard PROPPATCH on empty collections (by Markus Unterwaditzer) +* Write the path of the collection in the git message (by Matthew Monaco) +* Tests launched on Travis ## 0.10 - Lovely Endless Grass - * Support well-known URLs (by Mathieu Dupuy) - * Fix collection discovery (by Markus Unterwaditzer) - * Reload logger config on SIGHUP (by Élie Bouttier) - * Remove props files when deleting a collection (by Vincent Untz) - * Support salted SHA1 passwords (by Marc Kleine-Budde) - * Don't spam the logs about non-SSL IMAP connections to localhost (by Giel van Schijndel) - +* Support well-known URLs (by Mathieu Dupuy) +* Fix collection discovery (by Markus Unterwaditzer) +* Reload logger config on SIGHUP (by Élie Bouttier) +* Remove props files when deleting a collection (by Vincent Untz) +* Support salted SHA1 passwords (by Marc Kleine-Budde) +* Don't spam the logs about non-SSL IMAP connections to localhost (by Giel van Schijndel) ## 0.9 - Rivers - * Custom handlers for auth, storage and rights (by Sergey Fursov) - * 1-file-per-event storage (by Jean-Marc Martins) - * Git support for filesystem storages (by Jean-Marc Martins) - * DB storage working with PostgreSQL, MariaDB and SQLite (by Jean-Marc Martins) - * Clean rights manager based on regular expressions (by Sweil) - * Support of contacts for Apple's clients - * Support colors (by Jochen Sprickerhof) - * Decode URLs in XML (by Jean-Marc Martins) - * Fix PAM authentication (by Stepan Henek) - * Use consistent etags (by 9m66p93w) - * Use consistent sorting order (by Daniel Danner) - * Return 401 on unauthorized DELETE requests (by Eduard Braun) - * Move pid file creation in child process (by Mathieu Dupuy) - * Allow requests without base_prefix (by jheidemann) - +* Custom handlers for auth, storage and rights (by Sergey Fursov) +* 1-file-per-event storage (by Jean-Marc Martins) +* Git support for filesystem storages (by Jean-Marc Martins) +* DB storage working with PostgreSQL, MariaDB and SQLite (by Jean-Marc Martins) +* Clean rights manager based on regular expressions (by Sweil) +* Support of contacts for Apple's clients +* Support colors (by Jochen Sprickerhof) +* Decode URLs in XML (by Jean-Marc Martins) +* Fix PAM authentication (by Stepan Henek) +* Use consistent etags (by 9m66p93w) +* Use consistent sorting order (by Daniel Danner) +* Return 401 on unauthorized DELETE requests (by Eduard Braun) +* Move pid file creation in child process (by Mathieu Dupuy) +* Allow requests without base_prefix (by jheidemann) ## 0.8 - Rainbow - * New authentication and rights management modules (by Matthias Jordan) - * Experimental database storage - * Command-line option for custom configuration file (by Mark Adams) - * Root URL not at the root of a domain (by Clint Adams, Fabrice Bellet, Vincent Untz) - * Improved support for iCal, CalDAVSync, CardDAVSync, CalDavZAP and CardDavMATE - * Empty PROPFIND requests handled (by Christoph Polcin) - * Colon allowed in passwords - * Configurable realm message - +* New authentication and rights management modules (by Matthias Jordan) +* Experimental database storage +* Command-line option for custom configuration file (by Mark Adams) +* Root URL not at the root of a domain (by Clint Adams, Fabrice Bellet, Vincent Untz) +* Improved support for iCal, CalDAVSync, CardDAVSync, CalDavZAP and CardDavMATE +* Empty PROPFIND requests handled (by Christoph Polcin) +* Colon allowed in passwords +* Configurable realm message ## 0.7.1 - Waterfalls - * Many address books fixes - * New IMAP ACL (by Daniel Aleksandersen) - * PAM ACL fixed (by Daniel Aleksandersen) - * Courier ACL fixed (by Benjamin Frank) - * Always set display name to collections (by Oskari Timperi) - * Various DELETE responses fixed - +* Many address books fixes +* New IMAP ACL (by Daniel Aleksandersen) +* PAM ACL fixed (by Daniel Aleksandersen) +* Courier ACL fixed (by Benjamin Frank) +* Always set display name to collections (by Oskari Timperi) +* Various DELETE responses fixed ## 0.7 - Eternal Sunshine - * Repeating events - * Collection deletion - * Courier and PAM authentication methods - * CardDAV support - * Custom LDAP filters supported - +* Repeating events +* Collection deletion +* Courier and PAM authentication methods +* CardDAV support +* Custom LDAP filters supported ## 0.6.4 - Tulips - * Fix the installation with Python 3.1 - +* Fix the installation with Python 3.1 ## 0.6.3 - Red Roses - * MOVE requests fixed - * Faster REPORT answers - * Executable script moved into the package - +* MOVE requests fixed +* Faster REPORT answers +* Executable script moved into the package ## 0.6.2 - Seeds - * iPhone and iPad support fixed - * Backslashes replaced by slashes in PROPFIND answers on Windows - * PyPI archive set as default download URL - +* iPhone and iPad support fixed +* Backslashes replaced by slashes in PROPFIND answers on Windows +* PyPI archive set as default download URL ## 0.6.1 - Growing Up - * Example files included in the tarball - * htpasswd support fixed - * Redirection loop bug fixed - * Testing message on GET requests - +* Example files included in the tarball +* htpasswd support fixed +* Redirection loop bug fixed +* Testing message on GET requests ## 0.6 - Sapling - * WSGI support - * IPv6 support - * Smart, verbose and configurable logs - * Apple iCal 4 and iPhone support (by Łukasz Langa) - * KDE KOrganizer support - * LDAP auth backend (by Corentin Le Bail) - * Public and private calendars (by René Neumann) - * PID file - * MOVE requests management - * Journal entries support - * Drop Python 2.5 support - +* WSGI support +* IPv6 support +* Smart, verbose and configurable logs +* Apple iCal 4 and iPhone support (by Łukasz Langa) +* KDE KOrganizer support +* LDAP auth backend (by Corentin Le Bail) +* Public and private calendars (by René Neumann) +* PID file +* MOVE requests management +* Journal entries support +* Drop Python 2.5 support ## 0.5 - Historical Artifacts - * Calendar depth - * MacOS and Windows support - * HEAD requests management - * htpasswd user from calendar path - +* Calendar depth +* MacOS and Windows support +* HEAD requests management +* htpasswd user from calendar path ## 0.4 - Hot Days Back - * Personal calendars - * Last-Modified HTTP header - * ``no-ssl`` and ``foreground`` options - * Default configuration file - +* Personal calendars +* Last-Modified HTTP header +* `no-ssl` and `foreground` options +* Default configuration file ## 0.3 - Dancing Flowers - * Evolution support - * Version management - +* Evolution support +* Version management ## 0.2 - Snowflakes - * Sunbird pre-1.0 support - * SSL connection - * Htpasswd authentication - * Daemon mode - * User configuration - * Twisted dependency removed - * Python 3 support - * Real URLs for PUT and DELETE - * Concurrent modification reported to users - * Many bugs fixed (by Roger Wenham) - +* Sunbird pre-1.0 support +* SSL connection +* Htpasswd authentication +* Daemon mode +* User configuration +* Twisted dependency removed +* Python 3 support +* Real URLs for PUT and DELETE +* Concurrent modification reported to users +* Many bugs fixed (by Roger Wenham) ## 0.1 - Crazy Vegetables - * First release - * Lightning/Sunbird 0.9 compatibility - * Easy installer +* First release +* Lightning/Sunbird 0.9 compatibility +* Easy installer From 24ee523cc89c868e7aa8b7a8647430a9f3702b12 Mon Sep 17 00:00:00 2001 From: Unrud Date: Tue, 14 Dec 2021 00:25:34 +0100 Subject: [PATCH 081/238] Add news --- NEWS.md | 19 +++++++++++++++++++ 1 file changed, 19 insertions(+) diff --git a/NEWS.md b/NEWS.md index 6e5a771e..b4365a25 100644 --- a/NEWS.md +++ b/NEWS.md @@ -2,6 +2,25 @@ ## master +* Single `` element in PROPPATCH response +* Allow multiple `` and `` elements +* Improve log messages +* Fix date filter +* Improve sanitization of collection properties +* Cancel mkcalendar request on error +* Use **renameat2** on Linux for atomic overwriting of collections +* Command Line Parser + * Disallow abbreviated arguments + * Support backend specific options and HTTP headers + * Optional argument for boolean options + * Require argument for `--config` +* Allow float for server->timeout setting +* Fix **is-not-defined** filter in **addressbook-query** report +* Add python type hints +* Add **multifilesystem_nolock** storage +* Add support for Python 3.9 and 3.10 +* Drop support for Python 3.5 + ## 3.0.6 * Allow web plugins to handle POST requests From 34771f68509ab160f85731241c57e5557171177e Mon Sep 17 00:00:00 2001 From: Unrud Date: Tue, 14 Dec 2021 22:28:33 +0100 Subject: [PATCH 082/238] Use regular ids --- DOCUMENTATION.md | 22 +++++++++++----------- 1 file changed, 11 insertions(+), 11 deletions(-) diff --git a/DOCUMENTATION.md b/DOCUMENTATION.md index 6e3f4b43..1aac7720 100644 --- a/DOCUMENTATION.md +++ b/DOCUMENTATION.md @@ -13,7 +13,7 @@ Radicale is a small but powerful CalDAV (calendars, to-do lists) and CardDAV * Can limit access by authentication. * Can secure connections with TLS. * Works with many - [CalDAV and CardDAV clients](#documentation/supported-clients). + [CalDAV and CardDAV clients](#supported-clients). * Stores all data on the file system in a simple folder structure. * Can be extended with plugins. * Is GPLv3-licensed free software. @@ -31,7 +31,7 @@ When the server is launched, open in your browser! You can login with any username and password. Want more? Check the [tutorials](#tutorials) and the -[documentation](#documentation). +[documentation](#documentation-1). #### What's New? @@ -45,11 +45,11 @@ Read the You want to try Radicale but only have 5 minutes free in your calendar? Let's go right now and play a bit with Radicale! -When everything works, you can get a [client](#documentation/supported-clients) +When everything works, you can get a [client](#supported-clients) and start creating calendars and address books. The server **only** binds to localhost (is **not** reachable over the network) and you can log in with any user name and password. If Radicale fits your needs, it may be time for -[some basic configuration](#tutorials/basic-configuration). +[some basic configuration](#basic-configuration). Follow one of the chapters below depending on your operating system. @@ -92,7 +92,7 @@ You can log in with any username and password. ### Basic Configuration Installation instructions can be found in the -[simple 5-minute setup](#tutorials/simple-5-minute-setup) tutorial. +[simple 5-minute setup](#simple-5-minute-setup) tutorial. Radicale tries to load configuration files from `/etc/radicale/config` and `~/.config/radicale/config`. @@ -106,7 +106,7 @@ You should create a new configuration file at the desired location. passed via command line arguments.) All configuration options are described in detail in the -[Configuration](#documentation/configuration) section. +[Configuration](#configuration) section. #### Authentication @@ -186,7 +186,7 @@ filesystem_folder = /path/to/storage > **Security:** The storage folder should not be readable by unauthorized users. > Otherwise, they can read the calendar data and lock the storage. > You can find OS dependent instructions in the -> [Running as a service](#tutorials/running-as-a-service) section. +> [Running as a service](#running-as-a-service) section. #### Limits @@ -746,7 +746,7 @@ Default: `owner_only` ##### file File for the rights backend `from_file`. See the -[Rights](#documentation/authentication-and-rights) section. +[Rights](#authentication-and-rights) section. #### storage @@ -780,7 +780,7 @@ Default: `2592000` ##### hook Command that is run after changes to storage. Take a look at the -[Versioning with Git](#tutorials/versioning-with-git) tutorial for an example. +[Versioning with Git](#versioning-with-git) tutorial for an example. Default: @@ -1029,7 +1029,7 @@ It's safe to access and manipulate the data by hand or with scripts. Scripts can be invoked manually, periodically (e.g. with [cron](https://manpages.debian.org/unstable/cron/cron.8.en.html)) or after each change to the storage with the configuration option `hook` in the `storage` -section (e.g. [Versioning with Git](#tutorials/versioning-with-git)). +section (e.g. [Versioning with Git](#versioning-with-git)). #### Layout @@ -1482,7 +1482,7 @@ steps to have a simple remote calendar and contact access. Contrary to other servers that are often complicated, require high privileges or need a strong configuration, the Radicale Server can (sometimes, if not often) be launched in a couple of minutes, if you follow the -[tutorial](#tutorials/simple-5-minute-setup). +[tutorial](#simple-5-minute-setup). ##### Lazy From 425274764612eeaea9990dddb9c00e37cfc1af46 Mon Sep 17 00:00:00 2001 From: Unrud Date: Sat, 18 Dec 2021 22:00:34 +0100 Subject: [PATCH 083/238] Check all RRULE occurrences for infinity --- radicale/item/filter.py | 12 ++++++++---- 1 file changed, 8 insertions(+), 4 deletions(-) diff --git a/radicale/item/filter.py b/radicale/item/filter.py index 4db14658..b3082b55 100644 --- a/radicale/item/filter.py +++ b/radicale/item/filter.py @@ -191,7 +191,7 @@ def visit_time_ranges(vobject_item: vobject.base.Component, child_name: str, datetimes and ``is_recurrence`` as arguments. If the function returns True, the operation is cancelled. - ``infinity_fn`` gets called when an infiite recurrence rule is detected + ``infinity_fn`` gets called when an infinite recurrence rule is detected with ``start`` datetime as argument. If the function returns True, the operation is cancelled. @@ -206,9 +206,13 @@ def visit_time_ranges(vobject_item: vobject.base.Component, child_name: str, def getrruleset(child: vobject.base.Component, ignore: Sequence[date] ) -> Tuple[Iterable[date], bool]: - if (hasattr(child, "rrule") and - ";UNTIL=" not in child.rrule.value.upper() and - ";COUNT=" not in child.rrule.value.upper()): + infinite = False + for rrule in child.contents.get("rrule", []): + if (";UNTIL=" not in child.rrule.value.upper() and + ";COUNT=" not in child.rrule.value.upper()): + infinite = True + break + if infinite: for dtstart in child.getrruleset(addRDate=True): if dtstart in ignore: continue From 83f53cb5cb3f8134aedf3c6ac42fbd6633c1cc44 Mon Sep 17 00:00:00 2001 From: Unrud Date: Sat, 18 Dec 2021 22:01:04 +0100 Subject: [PATCH 084/238] Remove quotation marks --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 17cdb0e8..3a998bf4 100644 --- a/README.md +++ b/README.md @@ -6,4 +6,4 @@ Radicale is a free and open-source CalDAV and CardDAV server. For the complete documentation, please visit -[Radicale "master" Documentation](https://radicale.org/master.html). +[Radicale master Documentation](https://radicale.org/master.html). From bfba027446361ba10df59e43edfa89421c229cda Mon Sep 17 00:00:00 2001 From: Unrud Date: Sat, 18 Dec 2021 22:14:04 +0100 Subject: [PATCH 085/238] Use correct RRULE --- radicale/item/filter.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/radicale/item/filter.py b/radicale/item/filter.py index b3082b55..587dc367 100644 --- a/radicale/item/filter.py +++ b/radicale/item/filter.py @@ -208,8 +208,8 @@ def visit_time_ranges(vobject_item: vobject.base.Component, child_name: str, ) -> Tuple[Iterable[date], bool]: infinite = False for rrule in child.contents.get("rrule", []): - if (";UNTIL=" not in child.rrule.value.upper() and - ";COUNT=" not in child.rrule.value.upper()): + if (";UNTIL=" not in rrule.value.upper() and + ";COUNT=" not in rrule.value.upper()): infinite = True break if infinite: From fb9cfeb81eaf7eb3a824cd11bc582af28fba23f2 Mon Sep 17 00:00:00 2001 From: Unrud Date: Sun, 19 Dec 2021 12:49:26 +0100 Subject: [PATCH 086/238] Change type of signal number to int --- radicale/__main__.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/radicale/__main__.py b/radicale/__main__.py index d0bfe7bb..885be73e 100644 --- a/radicale/__main__.py +++ b/radicale/__main__.py @@ -48,7 +48,7 @@ def run() -> None: # Raise SystemExit when signal arrives to run cleanup code # (like destructors, try-finish etc.), otherwise the process exits # without running any of them - def exit_signal_handler(signal_number: "signal.Signals", + def exit_signal_handler(signal_number: int, stack_frame: FrameType) -> None: sys.exit(1) for signal_number in exit_signal_numbers: @@ -187,7 +187,7 @@ def run() -> None: shutdown_socket, shutdown_socket_out = socket.socketpair() # Shutdown server when signal arrives - def shutdown_signal_handler(signal_number: "signal.Signals", + def shutdown_signal_handler(signal_number: int, stack_frame: FrameType) -> None: shutdown_socket.close() for signal_number in exit_signal_numbers: From 537737da32c63103c62b2c0cf6ef0fff6d4a3dfe Mon Sep 17 00:00:00 2001 From: Unrud Date: Sun, 19 Dec 2021 12:58:35 +0100 Subject: [PATCH 087/238] Change type of stack_frame to Optional[...] --- radicale/__main__.py | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/radicale/__main__.py b/radicale/__main__.py index 885be73e..b03e12ae 100644 --- a/radicale/__main__.py +++ b/radicale/__main__.py @@ -30,7 +30,7 @@ import signal import socket import sys from types import FrameType -from typing import List, cast +from typing import List, Optional, cast from radicale import VERSION, config, log, server, storage, types from radicale.log import logger @@ -49,7 +49,7 @@ def run() -> None: # (like destructors, try-finish etc.), otherwise the process exits # without running any of them def exit_signal_handler(signal_number: int, - stack_frame: FrameType) -> None: + stack_frame: Optional[FrameType]) -> None: sys.exit(1) for signal_number in exit_signal_numbers: signal.signal(signal_number, exit_signal_handler) @@ -188,7 +188,7 @@ def run() -> None: # Shutdown server when signal arrives def shutdown_signal_handler(signal_number: int, - stack_frame: FrameType) -> None: + stack_frame: Optional[FrameType]) -> None: shutdown_socket.close() for signal_number in exit_signal_numbers: signal.signal(signal_number, shutdown_signal_handler) From a20791e0c3f74098fae597de9bd3a8f3256d279c Mon Sep 17 00:00:00 2001 From: Unrud Date: Mon, 20 Dec 2021 00:55:29 +0100 Subject: [PATCH 088/238] Convert EXDATE and RDATE to same type as DTSTART Fixes #1146 Closes #1199 --- radicale/item/__init__.py | 28 ++++++++++++++-- .../static/event_mixed_datetime_and_date.ics | 33 +++++++++++++++++++ radicale/tests/test_base.py | 6 ++++ 3 files changed, 65 insertions(+), 2 deletions(-) create mode 100644 radicale/tests/static/event_mixed_datetime_and_date.ics diff --git a/radicale/item/__init__.py b/radicale/item/__init__.py index e715e2c0..5d52c7c6 100644 --- a/radicale/item/__init__.py +++ b/radicale/item/__init__.py @@ -24,11 +24,13 @@ Module for address books and calendar entries (see ``Item``). """ import binascii +import contextlib import math import os import sys from datetime import datetime, timedelta from hashlib import sha256 +from itertools import chain from typing import (Any, Callable, List, MutableMapping, Optional, Sequence, Tuple) @@ -142,6 +144,28 @@ def check_and_sanitize_items( logger.debug("Quirks: Removing zero duration from %s in " "object %r", component_name, component_uid) del component.duration + # Workaround for Evolution + # EXDATE has value DATE even if DTSTART/DTEND is DATE-TIME. + # The RFC is vaguely formulated on the issue. + # To resolve the issue convert EXDATE and RDATE to + # the same type as DTDSTART + if hasattr(component, "dtstart"): + ref_date = component.dtstart.value + ref_value_param = component.dtstart.params.get("VALUE") + for dates in chain(component.contents.get("exdate", []), + component.contents.get("rdate", [])): + replace_value_param = False + for i, date in enumerate(dates.value): + if type(date) != type(ref_date): + replace_value_param = True + dates.value[i] = ref_date.replace( + date.year, date.month, date.day) + if replace_value_param: + if ref_value_param is None: + with contextlib.suppress(KeyError): + del dates.params["VALUE"] + else: + dates.params["VALUE"] = ref_value_param # vobject interprets recurrence rules on demand try: component.rruleset @@ -176,9 +200,9 @@ def check_and_sanitize_items( else: vobject_item.add("UID").value = object_uid else: - for i in vobject_items: + for item in vobject_items: raise ValueError("Item type %r not supported in %s collection" % - (i.name, repr(tag) if tag else "generic")) + (item.name, repr(tag) if tag else "generic")) def check_and_sanitize_props(props: MutableMapping[Any, Any] diff --git a/radicale/tests/static/event_mixed_datetime_and_date.ics b/radicale/tests/static/event_mixed_datetime_and_date.ics new file mode 100644 index 00000000..241ef6f6 --- /dev/null +++ b/radicale/tests/static/event_mixed_datetime_and_date.ics @@ -0,0 +1,33 @@ +BEGIN:VCALENDAR +PRODID:-//Mozilla.org/NONSGML Mozilla Calendar V1.1//EN +VERSION:2.0 +BEGIN:VTIMEZONE +TZID:Europe/Paris +X-LIC-LOCATION:Europe/Paris +BEGIN:DAYLIGHT +TZOFFSETFROM:+0100 +TZOFFSETTO:+0200 +TZNAME:CEST +DTSTART:19700329T020000 +RRULE:FREQ=YEARLY;BYDAY=-1SU;BYMONTH=3 +END:DAYLIGHT +BEGIN:STANDARD +TZOFFSETFROM:+0200 +TZOFFSETTO:+0100 +TZNAME:CET +DTSTART:19701025T030000 +RRULE:FREQ=YEARLY;BYDAY=-1SU;BYMONTH=10 +END:STANDARD +END:VTIMEZONE +BEGIN:VEVENT +CREATED:20130902T150157Z +LAST-MODIFIED:20130902T150158Z +DTSTAMP:20130902T150158Z +UID:event_mixed_datetime_and_date +SUMMARY:Event +DTSTART;TZID=Europe/Paris:20130901T180000 +DTEND;TZID=Europe/Paris:20130901T190000 +RRULE:FREQ=DAILY;COUNT=3 +EXDATE;VALUE=DATE:20130902 +END:VEVENT +END:VCALENDAR diff --git a/radicale/tests/test_base.py b/radicale/tests/test_base.py index d0557e5b..65f2556e 100644 --- a/radicale/tests/test_base.py +++ b/radicale/tests/test_base.py @@ -97,6 +97,12 @@ permissions: RrWw""") assert xml.tag == xmlutils.make_clark("D:error") assert xml.find(xmlutils.make_clark("C:no-uid-conflict")) is not None + def test_add_event_with_mixed_datetime_and_date(self) -> None: + """Test event with DTSTART as DATE-TIME and EXDATE as DATE.""" + self.mkcalendar("/calendar.ics/") + event = get_file_content("event_mixed_datetime_and_date.ics") + self.put("/calendar.ics/event.ics", event) + def test_add_todo(self) -> None: """Add a todo.""" self.mkcalendar("/calendar.ics/") From 481bd4e4b9731443d89ba7d19dab59cdc175957e Mon Sep 17 00:00:00 2001 From: Unrud Date: Mon, 20 Dec 2021 19:35:22 +0100 Subject: [PATCH 089/238] Update NEWS.md --- NEWS.md | 1 + 1 file changed, 1 insertion(+) diff --git a/NEWS.md b/NEWS.md index b4365a25..2f3778d9 100644 --- a/NEWS.md +++ b/NEWS.md @@ -20,6 +20,7 @@ * Add **multifilesystem_nolock** storage * Add support for Python 3.9 and 3.10 * Drop support for Python 3.5 +* Fix compatibility with Evolution (Exceptions from recurrence rules) ## 3.0.6 From ec19a1a12ce11e03a5ad7ce69a17d57df985f3f7 Mon Sep 17 00:00:00 2001 From: Unrud Date: Mon, 20 Dec 2021 21:33:23 +0100 Subject: [PATCH 090/238] Remove path from powershell --- DOCUMENTATION.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/DOCUMENTATION.md b/DOCUMENTATION.md index 1aac7720..8f761c7f 100644 --- a/DOCUMENTATION.md +++ b/DOCUMENTATION.md @@ -82,8 +82,8 @@ click on "Install now". Wait a couple of minutes, it's done! Launch a command prompt and type: ```powershell -C:\Users\User> python -m pip install --upgrade https://github.com/Kozea/Radicale/archive/master.tar.gz -C:\Users\User> python -m radicale --storage-filesystem-folder=~/radicale/collections +python -m pip install --upgrade https://github.com/Kozea/Radicale/archive/master.tar.gz +python -m radicale --storage-filesystem-folder=~/radicale/collections ``` Victory! Open in your browser! From d90369b67c16ba1b237d143bc216139b01d0c8e1 Mon Sep 17 00:00:00 2001 From: Frank Sachsenheim Date: Sat, 2 Jan 2021 16:33:05 +0100 Subject: [PATCH 091/238] Dockerfile: Reduces layers and size --- Dockerfile | 10 ++++------ 1 file changed, 4 insertions(+), 6 deletions(-) diff --git a/Dockerfile b/Dockerfile index 34971717..9a58b20d 100644 --- a/Dockerfile +++ b/Dockerfile @@ -11,9 +11,7 @@ EXPOSE 5232 # Run Radicale (Configure it here or provide a "config" file!) CMD ["radicale", "--hosts", "0.0.0.0:5232"] -# Install dependencies -RUN apk add --no-cache gcc musl-dev libffi-dev ca-certificates openssl -# Install Radicale -RUN pip install --no-cache-dir "Radicale[bcrypt] @ https://github.com/Kozea/Radicale/archive/${VERSION}.tar.gz" -# Remove build dependencies -RUN apk del gcc musl-dev libffi-dev +RUN apk add --no-cache ca-certificates openssl \ + && apk add --no-cache --virtual .build-deps gcc libffi-dev musl-dev \ + && pip install --no-cache-dir "Radicale[bcrypt] @ https://github.com/Kozea/Radicale/archive/${VERSION}.tar.gz" \ + && apk del .build-deps From 11fd29a2d1cfaea02dea8821448b045843c58f9e Mon Sep 17 00:00:00 2001 From: Frank Sachsenheim Date: Sat, 2 Jan 2021 16:51:25 +0100 Subject: [PATCH 092/238] Dockerfile: Removes arguable comments - user data could be stored in any kind of volume - using a mounted one is often not recommendable - there are other means to publish a service like HTTP reverse proxies - the CMD directive can't and shouldn't be used to expose behaviour - in fact, the value is required by the previous directive --- Dockerfile | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) diff --git a/Dockerfile b/Dockerfile index 9a58b20d..dcb1682c 100644 --- a/Dockerfile +++ b/Dockerfile @@ -1,14 +1,16 @@ +# This file is intended to be used apart from the containing source code tree. + FROM python:3-alpine # Version of Radicale (e.g. 3.0.x) ARG VERSION=master -# Persistent storage for data (Mount it somewhere on the host!) +# Persistent storage for data VOLUME /var/lib/radicale # Configuration data (Put the "config" file here!) VOLUME /etc/radicale -# TCP port of Radicale (Publish it on a host interface!) +# TCP port of Radicale EXPOSE 5232 -# Run Radicale (Configure it here or provide a "config" file!) +# Run Radicale CMD ["radicale", "--hosts", "0.0.0.0:5232"] RUN apk add --no-cache ca-certificates openssl \ From c4745680e00c02309a68a46c70d672abf2950caf Mon Sep 17 00:00:00 2001 From: Frank Sachsenheim Date: Sat, 2 Jan 2021 16:55:08 +0100 Subject: [PATCH 093/238] Dockerfile: Removes volume for config data Configuration data can be provided by either - putting it into a derived image - mounting a volume While an anonymous volume is of no use. --- Dockerfile | 2 -- 1 file changed, 2 deletions(-) diff --git a/Dockerfile b/Dockerfile index dcb1682c..69f581e3 100644 --- a/Dockerfile +++ b/Dockerfile @@ -6,8 +6,6 @@ FROM python:3-alpine ARG VERSION=master # Persistent storage for data VOLUME /var/lib/radicale -# Configuration data (Put the "config" file here!) -VOLUME /etc/radicale # TCP port of Radicale EXPOSE 5232 # Run Radicale From 06f93a032bdb5c9b8c9f7d6c7d4a9aaa0b5c6298 Mon Sep 17 00:00:00 2001 From: Unrud Date: Mon, 20 Dec 2021 22:33:38 +0100 Subject: [PATCH 094/238] Update branch name --- Dockerfile | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Dockerfile b/Dockerfile index 69f581e3..1bfc82ac 100644 --- a/Dockerfile +++ b/Dockerfile @@ -2,7 +2,7 @@ FROM python:3-alpine -# Version of Radicale (e.g. 3.0.x) +# Version of Radicale (e.g. v3) ARG VERSION=master # Persistent storage for data VOLUME /var/lib/radicale From fb3de73d1c8bc321ab10be6544d0f15147c2ba32 Mon Sep 17 00:00:00 2001 From: Unrud Date: Mon, 20 Dec 2021 23:47:06 +0100 Subject: [PATCH 095/238] Assert waiters and waiter are still the same --- radicale/storage/multifilesystem_nolock.py | 1 + 1 file changed, 1 insertion(+) diff --git a/radicale/storage/multifilesystem_nolock.py b/radicale/storage/multifilesystem_nolock.py index 3653de85..f86e7ad2 100644 --- a/radicale/storage/multifilesystem_nolock.py +++ b/radicale/storage/multifilesystem_nolock.py @@ -81,6 +81,7 @@ class LockDict: yield finally: with self._lock: + assert waiters[0] is waiter and self._dict[key] is waiters del waiters[0] if waiters: waiters[0].release() From eac460d4d9e6e38b68bdfcc6eb653b07843fb9b9 Mon Sep 17 00:00:00 2001 From: Unrud Date: Mon, 20 Dec 2021 23:47:39 +0100 Subject: [PATCH 096/238] Replace all dates if any has the wrong type --- radicale/item/__init__.py | 19 ++++++++----------- 1 file changed, 8 insertions(+), 11 deletions(-) diff --git a/radicale/item/__init__.py b/radicale/item/__init__.py index 5d52c7c6..fd293ddc 100644 --- a/radicale/item/__init__.py +++ b/radicale/item/__init__.py @@ -154,18 +154,15 @@ def check_and_sanitize_items( ref_value_param = component.dtstart.params.get("VALUE") for dates in chain(component.contents.get("exdate", []), component.contents.get("rdate", [])): - replace_value_param = False + if all(type(d) == type(ref_date) for d in dates.value): + continue for i, date in enumerate(dates.value): - if type(date) != type(ref_date): - replace_value_param = True - dates.value[i] = ref_date.replace( - date.year, date.month, date.day) - if replace_value_param: - if ref_value_param is None: - with contextlib.suppress(KeyError): - del dates.params["VALUE"] - else: - dates.params["VALUE"] = ref_value_param + dates.value[i] = ref_date.replace( + date.year, date.month, date.day) + with contextlib.suppress(KeyError): + del dates.params["VALUE"] + if ref_value_param is not None: + dates.params["VALUE"] = ref_value_param # vobject interprets recurrence rules on demand try: component.rruleset From 2cd0a3189e9a527e394b22640d88265bd2417c8d Mon Sep 17 00:00:00 2001 From: Unrud Date: Mon, 20 Dec 2021 23:57:55 +0100 Subject: [PATCH 097/238] Run TestBaseRequests only once --- radicale/tests/test_storage.py | 37 +++++++++++++++++----------------- 1 file changed, 19 insertions(+), 18 deletions(-) diff --git a/radicale/tests/test_storage.py b/radicale/tests/test_storage.py index 7dd335ca..12fce2aa 100644 --- a/radicale/tests/test_storage.py +++ b/radicale/tests/test_storage.py @@ -30,14 +30,14 @@ import pytest import radicale.tests.custom.storage_simple_sync from radicale.tests import BaseTest from radicale.tests.helpers import get_file_content -from radicale.tests.test_base import TestBaseRequests +from radicale.tests.test_base import TestBaseRequests as _TestBaseRequests class TestMultiFileSystem(BaseTest): """Tests for multifilesystem.""" def setup(self) -> None: - TestBaseRequests.setup(cast(TestBaseRequests, self)) + _TestBaseRequests.setup(cast(_TestBaseRequests, self)) self.configure({"storage": {"type": "multifilesystem"}}) def test_folder_creation(self) -> None: @@ -104,7 +104,8 @@ class TestMultiFileSystem(BaseTest): reason="Only supported on 'posix' and 'win32'") def test_put_whole_calendar_uids_used_as_file_names(self) -> None: """Test if UIDs are used as file names.""" - TestBaseRequests.test_put_whole_calendar(cast(TestBaseRequests, self)) + _TestBaseRequests.test_put_whole_calendar( + cast(_TestBaseRequests, self)) for uid in ("todo", "event"): _, answer = self.get("/calendar.ics/%s.ics" % uid) assert "\r\nUID:%s\r\n" % uid in answer @@ -113,8 +114,8 @@ class TestMultiFileSystem(BaseTest): reason="Only supported on 'posix' and 'win32'") def test_put_whole_calendar_random_uids_used_as_file_names(self) -> None: """Test if UIDs are used as file names.""" - TestBaseRequests.test_put_whole_calendar_without_uids( - cast(TestBaseRequests, self)) + _TestBaseRequests.test_put_whole_calendar_without_uids( + cast(_TestBaseRequests, self)) _, answer = self.get("/calendar.ics") assert answer is not None uids = [] @@ -130,8 +131,8 @@ class TestMultiFileSystem(BaseTest): reason="Only supported on 'posix' and 'win32'") def test_put_whole_addressbook_uids_used_as_file_names(self) -> None: """Test if UIDs are used as file names.""" - TestBaseRequests.test_put_whole_addressbook( - cast(TestBaseRequests, self)) + _TestBaseRequests.test_put_whole_addressbook( + cast(_TestBaseRequests, self)) for uid in ("contact1", "contact2"): _, answer = self.get("/contacts.vcf/%s.vcf" % uid) assert "\r\nUID:%s\r\n" % uid in answer @@ -141,8 +142,8 @@ class TestMultiFileSystem(BaseTest): def test_put_whole_addressbook_random_uids_used_as_file_names( self) -> None: """Test if UIDs are used as file names.""" - TestBaseRequests.test_put_whole_addressbook_without_uids( - cast(TestBaseRequests, self)) + _TestBaseRequests.test_put_whole_addressbook_without_uids( + cast(_TestBaseRequests, self)) _, answer = self.get("/contacts.vcf") assert answer is not None uids = [] @@ -159,10 +160,10 @@ class TestMultiFileSystemNoLock(BaseTest): """Tests for multifilesystem_nolock.""" def setup(self) -> None: - TestBaseRequests.setup(cast(TestBaseRequests, self)) + _TestBaseRequests.setup(cast(_TestBaseRequests, self)) self.configure({"storage": {"type": "multifilesystem_nolock"}}) - test_add_event = TestBaseRequests.test_add_event + test_add_event = _TestBaseRequests.test_add_event test_item_cache_rebuild = TestMultiFileSystem.test_item_cache_rebuild @@ -170,19 +171,19 @@ class TestCustomStorageSystem(BaseTest): """Test custom backend loading.""" def setup(self) -> None: - TestBaseRequests.setup(cast(TestBaseRequests, self)) + _TestBaseRequests.setup(cast(_TestBaseRequests, self)) self.configure({"storage": { "type": "radicale.tests.custom.storage_simple_sync"}}) full_sync_token_support: ClassVar[bool] = False - test_add_event = TestBaseRequests.test_add_event - _report_sync_token = TestBaseRequests._report_sync_token + test_add_event = _TestBaseRequests.test_add_event + _report_sync_token = _TestBaseRequests._report_sync_token # include tests related to sync token s: str = "" - for s in dir(TestBaseRequests): + for s in dir(_TestBaseRequests): if s.startswith("test_") and "sync" in s.split("_"): - locals()[s] = getattr(TestBaseRequests, s) + locals()[s] = getattr(_TestBaseRequests, s) del s @@ -190,8 +191,8 @@ class TestCustomStorageSystemCallable(BaseTest): """Test custom backend loading with ``callable``.""" def setup(self) -> None: - TestBaseRequests.setup(cast(TestBaseRequests, self)) + _TestBaseRequests.setup(cast(_TestBaseRequests, self)) self.configure({"storage": { "type": radicale.tests.custom.storage_simple_sync.Storage}}) - test_add_event = TestBaseRequests.test_add_event + test_add_event = _TestBaseRequests.test_add_event From f75671354c263fe053985d1db1835932f95c7ab8 Mon Sep 17 00:00:00 2001 From: Unrud Date: Fri, 24 Dec 2021 18:00:09 +0100 Subject: [PATCH 098/238] Revert "Require argument for --config command-line option" This reverts commit e629e9a2e17b7f2461c0b7fab520d6171b7d2b1c. --- radicale/__main__.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/radicale/__main__.py b/radicale/__main__.py index b03e12ae..aa3382f1 100644 --- a/radicale/__main__.py +++ b/radicale/__main__.py @@ -65,7 +65,7 @@ def run() -> None: parser.add_argument("--verify-storage", action="store_true", help="check the storage for errors and exit") parser.add_argument("-C", "--config", - help="use specific configuration files", nargs="+") + help="use specific configuration files", nargs="*") parser.add_argument("-D", "--debug", action="store_const", const="debug", dest="c:logging:level", default=argparse.SUPPRESS, help="print debug information") From 4564de9f9d3af9642afc69aace18584becf0f943 Mon Sep 17 00:00:00 2001 From: Unrud Date: Fri, 24 Dec 2021 18:13:18 +0100 Subject: [PATCH 099/238] Load no config file for --config without argument --- NEWS.md | 2 +- radicale/__main__.py | 3 ++- 2 files changed, 3 insertions(+), 2 deletions(-) diff --git a/NEWS.md b/NEWS.md index 2f3778d9..8206a12e 100644 --- a/NEWS.md +++ b/NEWS.md @@ -13,7 +13,7 @@ * Disallow abbreviated arguments * Support backend specific options and HTTP headers * Optional argument for boolean options - * Require argument for `--config` + * Load no config file for `--config` without argument * Allow float for server->timeout setting * Fix **is-not-defined** filter in **addressbook-query** report * Add python type hints diff --git a/radicale/__main__.py b/radicale/__main__.py index aa3382f1..747dc493 100644 --- a/radicale/__main__.py +++ b/radicale/__main__.py @@ -155,7 +155,8 @@ def run() -> None: configuration = config.load(config.parse_compound_paths( config.DEFAULT_CONFIG_PATH, os.environ.get("RADICALE_CONFIG"), - os.pathsep.join(args_ns.config) if args_ns.config else None)) + os.pathsep.join(args_ns.config) if args_ns.config is not None + else None)) if arguments_config: configuration.update(arguments_config, "command line arguments") except Exception as e: From 7bfb6c0132ccaec4c0d9555ab3a1023ca7b65a20 Mon Sep 17 00:00:00 2001 From: Unrud Date: Sat, 25 Dec 2021 19:58:29 +0100 Subject: [PATCH 100/238] Fix dlopen on Android --- radicale/pathutils.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/radicale/pathutils.py b/radicale/pathutils.py index df039418..5e87fa16 100644 --- a/radicale/pathutils.py +++ b/radicale/pathutils.py @@ -77,7 +77,7 @@ if sys.platform == "linux": RENAME_EXCHANGE: int = 2 try: - renameat2 = ctypes.CDLL("", use_errno=True).renameat2 + renameat2 = ctypes.CDLL(None, use_errno=True).renameat2 except AttributeError: pass else: From bd0a95c09861d1d3d36efd1960427b23a132cce1 Mon Sep 17 00:00:00 2001 From: Unrud Date: Sun, 26 Dec 2021 12:16:42 +0100 Subject: [PATCH 101/238] Update NEWS.md --- NEWS.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/NEWS.md b/NEWS.md index 8206a12e..098e23fd 100644 --- a/NEWS.md +++ b/NEWS.md @@ -2,6 +2,8 @@ ## master +## 3.1.0 + * Single `` element in PROPPATCH response * Allow multiple `` and `` elements * Improve log messages From d3f99d349db59a6f694e111f6bf2dee7529a934a Mon Sep 17 00:00:00 2001 From: Unrud Date: Fri, 7 Jan 2022 23:23:53 +0100 Subject: [PATCH 102/238] Don't manually assemble origin --- radicale/web/internal_data/fn.js | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/radicale/web/internal_data/fn.js b/radicale/web/internal_data/fn.js index ef47d089..a61fd325 100644 --- a/radicale/web/internal_data/fn.js +++ b/radicale/web/internal_data/fn.js @@ -21,8 +21,7 @@ * @const * @type {string} */ -const SERVER = (location.protocol + '//' + location.hostname + - (location.port ? ':' + location.port : '')); +const SERVER = location.origin; /** * Path of the root collection on the server (must end with /) From cfba4c17b62333ac482d23b0905aa8672c13b8cf Mon Sep 17 00:00:00 2001 From: Unrud Date: Fri, 7 Jan 2022 23:51:21 +0100 Subject: [PATCH 103/238] Update Thunderbird documentation --- DOCUMENTATION.md | 18 +++++++----------- 1 file changed, 7 insertions(+), 11 deletions(-) diff --git a/DOCUMENTATION.md b/DOCUMENTATION.md index 8f761c7f..50ec423c 100644 --- a/DOCUMENTATION.md +++ b/DOCUMENTATION.md @@ -870,19 +870,15 @@ address books. #### Thunderbird -##### CardBook +Add a new calendar on the network. Enter your username and the URL of the +Radicale server (e.g. `http://localhost:5232`). After asking for your password, +it will list the existing calendars. -Add a new address book on the network with CardDAV. You have to enter the full -URL of the collection (e.g. `http://localhost:5232/user/addressbook`) and -your user name. +##### Adress books with CardBook add-on -##### Lightning - -Add a new calendar on the network with `CalDAV`. (Don't use `iCalendar (ICS)`!) -You have to enter the full URL of the collection (e.g. -`http://localhost:5232/user/calendar`). If you want to add calendars from -different users on the same server, you can specify the user name in the URL -(e.g. `http://user@localhost...`) +Add a new address book on the network with CardDAV. Enter the URL of the +Radicale server (e.g. `http://localhost:5232`) and your username and password. +It will list your existing address books. #### InfCloud, CalDavZAP and CardDavMATE From 8fa4345b6ffb32cd44154d64bba2caf28d54f214 Mon Sep 17 00:00:00 2001 From: Unrud Date: Fri, 7 Jan 2022 23:54:34 +0100 Subject: [PATCH 104/238] Change "user name" to "username" --- DOCUMENTATION.md | 34 +++++++++++++++++----------------- radicale/auth/__init__.py | 2 +- rights | 2 +- 3 files changed, 19 insertions(+), 19 deletions(-) diff --git a/DOCUMENTATION.md b/DOCUMENTATION.md index 50ec423c..127805c6 100644 --- a/DOCUMENTATION.md +++ b/DOCUMENTATION.md @@ -48,7 +48,7 @@ go right now and play a bit with Radicale! When everything works, you can get a [client](#supported-clients) and start creating calendars and address books. The server **only** binds to localhost (is **not** reachable over the network) and you can log in with any -user name and password. If Radicale fits your needs, it may be time for +username and password. If Radicale fits your needs, it may be time for [some basic configuration](#basic-configuration). Follow one of the chapters below depending on your operating system. @@ -110,10 +110,10 @@ All configuration options are described in detail in the #### Authentication -In its default configuration Radicale doesn't check user names or passwords. +In its default configuration Radicale doesn't check usernames or passwords. If the server is reachable over a network, you should change this. -First a `users` file with all user names and passwords must be created. +First a `users` file with all usernames and passwords must be created. It can be stored in the same directory as the configuration file. ##### The secure way @@ -144,7 +144,7 @@ htpasswd_encryption = md5 ##### The simple but insecure way -Create the `users` file by hand with lines containing the user name and +Create the `users` file by hand with lines containing the username and password separated by `:`. Example: ```htpasswd @@ -376,7 +376,7 @@ incorrect authentication attempts. Connections are terminated after a timeout. Set the configuration option `type` in the `auth` section to `http_x_remote_user`. -Radicale uses the user name provided in the `X-Remote-User` HTTP header and +Radicale uses the username provided in the `X-Remote-User` HTTP header and disables HTTP authentication. Example **nginx** configuration: @@ -500,7 +500,7 @@ gunicorn --bind '127.0.0.1:5232' --env 'RADICALE_CONFIG=/etc/radicale/config' \ #### Manage user accounts with the WSGI server Set the configuration option `type` in the `auth` section to `remote_user`. -Radicale uses the user name provided by the WSGI server and disables +Radicale uses the username provided by the WSGI server and disables authentication over HTTP. ### Versioning with Git @@ -623,7 +623,7 @@ Default: `/etc/ssl/radicale.key.pem` Path to the CA certificate for validating client certificates. This can be used to secure TCP traffic between Radicale and a reverse proxy. If you want to authenticate users with client-side certificates, you also have to write an -authentication plugin that extracts the user name from the certificate. +authentication plugin that extracts the username from the certificate. Default: @@ -658,13 +658,13 @@ Available backends: to store usernames and passwords. `remote_user` -: Takes the user name from the `REMOTE_USER` environment variable and disables - HTTP authentication. This can be used to provide the user name from a WSGI +: Takes the username from the `REMOTE_USER` environment variable and disables + HTTP authentication. This can be used to provide the username from a WSGI server. `http_x_remote_user` -: Takes the user name from the `X-Remote-User` HTTP header and disables HTTP - authentication. This can be used to provide the user name from a reverse +: Takes the username from the `X-Remote-User` HTTP header and disables HTTP + authentication. This can be used to provide the username from a reverse proxy. Default: `none` @@ -848,14 +848,14 @@ You can use Radicale's web interface (e.g. ) to create and manage address books and calendars. In some clients you can just enter the URL of the Radicale server -(e.g. `http://localhost:5232`) and your user name. In others, you have to +(e.g. `http://localhost:5232`) and your username. In others, you have to enter the URL of the collection directly (e.g. `http://localhost:5232/user/calendar`). #### DAVx⁵ Enter the URL of the Radicale server (e.g. `http://localhost:5232`) and your -user name. DAVx⁵ will show all existing calendars and address books and you +username. DAVx⁵ will show all existing calendars and address books and you can create new. #### GNOME Calendar, Contacts and Evolution @@ -865,7 +865,7 @@ and address books directly, but you can add them in **Evolution**. In **Evolution** add a new calendar and address book respectively with WebDAV. Enter the URL of the Radicale server (e.g. `http://localhost:5232`) and your -user name. Clicking on the search button will list the existing calendars and +username. Clicking on the search button will list the existing calendars and address books. #### Thunderbird @@ -975,7 +975,7 @@ user: .+ collection: permissions: R -# Allow reading and writing principal collection (same as user name) +# Allow reading and writing principal collection (same as username) [principal] user: .+ collection: {user} @@ -991,10 +991,10 @@ permissions: rw The titles of the sections are ignored (but must be unique). The keys `user` and `collection` contain regular expressions, that are matched against the -user name and the path of the collection. Permissions from the first +username and the path of the collection. Permissions from the first matching section are used. If no section matches, access gets denied. -The user name is empty for anonymous users. Therefore, the regex `.+` only +The username is empty for anonymous users. Therefore, the regex `.+` only matches authenticated users and `.*` matches everyone (including anonymous users). diff --git a/radicale/auth/__init__.py b/radicale/auth/__init__.py index a7776bdf..9c4dd1c0 100644 --- a/radicale/auth/__init__.py +++ b/radicale/auth/__init__.py @@ -74,7 +74,7 @@ class BaseAuth: ``password`` the password - Returns the user name or ``""`` for invalid credentials. + Returns the username or ``""`` for invalid credentials. """ diff --git a/rights b/rights index 0919cb28..1425003e 100644 --- a/rights +++ b/rights @@ -18,7 +18,7 @@ #collection: #permissions: R -# Allow reading and writing principal collection (same as user name) +# Allow reading and writing principal collection (same as username) #[principal] #user: .+ #collection: {user} From 4c44940ec12a9178efc0cffcd5b0cc61bec3f39a Mon Sep 17 00:00:00 2001 From: Lauri Tirkkonen Date: Tue, 11 Jan 2022 20:22:19 +0200 Subject: [PATCH 105/238] config & rights: use open() for better error messages ConfigParser().read() doesn't differentiate between different types of failure to read files, causing eg. "No such file" to be logged in all cases, for example if permissions are insufficient. fix that by using open() and ConfigParser().read_file() instead. --- radicale/config.py | 15 ++++++++------- radicale/rights/from_file.py | 4 ++-- 2 files changed, 10 insertions(+), 9 deletions(-) diff --git a/radicale/config.py b/radicale/config.py index 0e119109..4b7ed8c4 100644 --- a/radicale/config.py +++ b/radicale/config.py @@ -276,17 +276,18 @@ def load(paths: Optional[Iterable[Tuple[str, bool]]] = None for path, ignore_if_missing in paths: parser = RawConfigParser() config_source = "config file %r" % path + config: types.CONFIG try: - if not parser.read(path): - config = Configuration.SOURCE_MISSING - if not ignore_if_missing: - raise RuntimeError("No such file: %r" % path) - else: + with open(path, "r") as f: + parser.read_file(f) config = {s: {o: parser[s][o] for o in parser.options(s)} for s in parser.sections()} except Exception as e: - raise RuntimeError("Failed to load %s: %s" % (config_source, e) - ) from e + if isinstance(e, FileNotFoundError) and ignore_if_missing: + config = Configuration.SOURCE_MISSING + else: + raise RuntimeError("Failed to load %s: %s" % (config_source, e) + ) from e configuration.update(config, config_source) return configuration diff --git a/radicale/rights/from_file.py b/radicale/rights/from_file.py index c7e9c0cd..01fa2fb7 100644 --- a/radicale/rights/from_file.py +++ b/radicale/rights/from_file.py @@ -56,8 +56,8 @@ class Rights(rights.BaseRights): escaped_user = re.escape(user) rights_config = configparser.ConfigParser() try: - if not rights_config.read(self._filename): - raise RuntimeError("No such file: %r" % self._filename) + with open(self._filename, "r") as f: + rights_config.read_file(f) except Exception as e: raise RuntimeError("Failed to load rights file %r: %s" % (self._filename, e)) from e From e3a982dbcee00d149c4bfec4ad38f5eb54df6eac Mon Sep 17 00:00:00 2001 From: Unrud Date: Sat, 15 Jan 2022 22:32:36 +0100 Subject: [PATCH 106/238] Cosmetics --- radicale/config.py | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/radicale/config.py b/radicale/config.py index 4b7ed8c4..64dc5cc5 100644 --- a/radicale/config.py +++ b/radicale/config.py @@ -283,11 +283,10 @@ def load(paths: Optional[Iterable[Tuple[str, bool]]] = None config = {s: {o: parser[s][o] for o in parser.options(s)} for s in parser.sections()} except Exception as e: - if isinstance(e, FileNotFoundError) and ignore_if_missing: - config = Configuration.SOURCE_MISSING - else: + if not ignore_if_missing or not isinstance(e, FileNotFoundError): raise RuntimeError("Failed to load %s: %s" % (config_source, e) ) from e + config = Configuration.SOURCE_MISSING configuration.update(config, config_source) return configuration From 6dee974b742d17820f049a9e514375502896cbbc Mon Sep 17 00:00:00 2001 From: Unrud Date: Sat, 15 Jan 2022 22:32:37 +0100 Subject: [PATCH 107/238] Don't sanitize WSGI script name --- radicale/app/__init__.py | 19 ++++++------------- 1 file changed, 6 insertions(+), 13 deletions(-) diff --git a/radicale/app/__init__.py b/radicale/app/__init__.py index ffb9e267..d473d76e 100644 --- a/radicale/app/__init__.py +++ b/radicale/app/__init__.py @@ -183,19 +183,12 @@ class Application(ApplicationPartDelete, ApplicationPartHead, logger.debug("Request headers:\n%s", pprint.pformat(self._scrub_headers(environ))) - # Let reverse proxies overwrite SCRIPT_NAME - if "HTTP_X_SCRIPT_NAME" in environ: - # script_name must be removed from PATH_INFO by the client. - unsafe_base_prefix = environ["HTTP_X_SCRIPT_NAME"] - logger.debug("Script name overwritten by client: %r", - unsafe_base_prefix) - else: - # SCRIPT_NAME is already removed from PATH_INFO, according to the - # WSGI specification. - unsafe_base_prefix = environ.get("SCRIPT_NAME", "") - # Sanitize base prefix - base_prefix = pathutils.sanitize_path(unsafe_base_prefix).rstrip("/") - logger.debug("Sanitized script name: %r", base_prefix) + # SCRIPT_NAME is already removed from PATH_INFO, according to the + # WSGI specification. + # Reverse proxies can overwrite SCRIPT_NAME with X-SCRIPT-NAME header + base_prefix = environ.get("HTTP_X_SCRIPT_NAME", + environ.get("SCRIPT_NAME", "")) + logger.debug("Base prefix: %r", base_prefix) # Sanitize request URI (a WSGI server indicates with an empty path, # that the URL targets the application root without a trailing slash) path = pathutils.sanitize_path(environ.get("PATH_INFO", "")) From b93842b10c9bb5d1e74e0cdfdf14eddb5b9e6c84 Mon Sep 17 00:00:00 2001 From: Unrud Date: Sat, 15 Jan 2022 22:32:37 +0100 Subject: [PATCH 108/238] Redirect GET and HEAD requests to sanitized path --- radicale/app/__init__.py | 24 ++++++++++++++++-------- radicale/app/get.py | 9 +++------ radicale/tests/test_base.py | 11 +++++++++-- radicale/web/internal_data/fn.js | 2 +- 4 files changed, 29 insertions(+), 17 deletions(-) diff --git a/radicale/app/__init__.py b/radicale/app/__init__.py index d473d76e..6ff68401 100644 --- a/radicale/app/__init__.py +++ b/radicale/app/__init__.py @@ -161,6 +161,9 @@ class Application(ApplicationPartDelete, ApplicationPartHead, # Return response content return status_text, list(headers.items()), answers + time_begin = datetime.datetime.now() + request_method = environ["REQUEST_METHOD"].upper() + unsafe_path = environ.get("PATH_INFO", "") remote_host = "unknown" if environ.get("REMOTE_HOST"): remote_host = repr(environ["REMOTE_HOST"]) @@ -175,11 +178,9 @@ class Application(ApplicationPartDelete, ApplicationPartHead, depthinfo = "" if environ.get("HTTP_DEPTH"): depthinfo = " with depth %r" % environ["HTTP_DEPTH"] - time_begin = datetime.datetime.now() - logger.info( - "%s request for %r%s received from %s%s", - environ["REQUEST_METHOD"], environ.get("PATH_INFO", ""), depthinfo, - remote_host, remote_useragent) + logger.info("%s request for %r%s received from %s%s", + request_method, unsafe_path, depthinfo, + remote_host, remote_useragent) logger.debug("Request headers:\n%s", pprint.pformat(self._scrub_headers(environ))) @@ -191,12 +192,19 @@ class Application(ApplicationPartDelete, ApplicationPartHead, logger.debug("Base prefix: %r", base_prefix) # Sanitize request URI (a WSGI server indicates with an empty path, # that the URL targets the application root without a trailing slash) - path = pathutils.sanitize_path(environ.get("PATH_INFO", "")) + path = pathutils.sanitize_path(unsafe_path) + if unsafe_path != path and request_method in ["GET", "HEAD"]: + location = base_prefix + path + logger.info("Redirecting to sanitized path: %r ==> %r", + base_prefix + unsafe_path, location) + return response( + client.MOVED_PERMANENTLY, + {"Location": location, "Content-Type": "text/plain"}, + "Redirected to %s" % location) logger.debug("Sanitized path: %r", path) # Get function corresponding to method - function = getattr( - self, "do_%s" % environ["REQUEST_METHOD"].upper(), None) + function = getattr(self, "do_%s" % request_method, None) if not function: return response(*httputils.METHOD_NOT_ALLOWED) diff --git a/radicale/app/get.py b/radicale/app/get.py index 255a3f10..3b26815e 100644 --- a/radicale/app/get.py +++ b/radicale/app/get.py @@ -62,13 +62,10 @@ class ApplicationPartGet(ApplicationBase): """Manage GET request.""" # Redirect to .web if the root URL is requested if not pathutils.strip_path(path): - web_path = ".web" - if not environ.get("PATH_INFO"): - web_path = posixpath.join(posixpath.basename(base_prefix), - web_path) + location = ".web" return (client.FOUND, - {"Location": web_path, "Content-Type": "text/plain"}, - "Redirected to %s" % web_path) + {"Location": location, "Content-Type": "text/plain"}, + "Redirected to %s" % location) # Dispatch .web URL to web module if path == "/.web" or path.startswith("/.web/"): return self._web.get(environ, base_prefix, path, user) diff --git a/radicale/tests/test_base.py b/radicale/tests/test_base.py index 65f2556e..9b16ba61 100644 --- a/radicale/tests/test_base.py +++ b/radicale/tests/test_base.py @@ -60,8 +60,15 @@ permissions: RrWw""") """GET request at "/" with SCRIPT_NAME.""" _, answer = self.get("/", check=302, SCRIPT_NAME="/radicale") assert answer == "Redirected to .web" - _, answer = self.get("", check=302, SCRIPT_NAME="/radicale") - assert answer == "Redirected to radicale/.web" + + def test_sanitized_path(self) -> None: + """GET request with unsanitized paths.""" + for path, sane_path in [("//", "/"), ("", "/"), ("/a//b", "/a/b"), + ("/a//b/", "/a/b/")]: + _, answer = self.get(path, check=301) + assert answer == "Redirected to %s" % sane_path + _, answer = self.get(path, check=301, SCRIPT_NAME="/radicale") + assert answer == "Redirected to /radicale%s" % sane_path def test_add_event(self) -> None: """Add an event.""" diff --git a/radicale/web/internal_data/fn.js b/radicale/web/internal_data/fn.js index a61fd325..82651a36 100644 --- a/radicale/web/internal_data/fn.js +++ b/radicale/web/internal_data/fn.js @@ -28,7 +28,7 @@ const SERVER = location.origin; * @const * @type {string} */ -const ROOT_PATH = location.pathname.replace(new RegExp("/+[^/]+/*(/index\\.html?)?$"), "") + '/'; +const ROOT_PATH = (new URL("..", location.href)).pathname; /** * Regex to match and normalize color From 4a0bcde7a3fe77d2ec1a994e633ed4154c1a2c3c Mon Sep 17 00:00:00 2001 From: Unrud Date: Sat, 15 Jan 2022 22:32:38 +0100 Subject: [PATCH 109/238] Set Content-Length for HEAD requests --- radicale/app/__init__.py | 8 +++++--- radicale/app/head.py | 3 +-- radicale/tests/test_base.py | 3 ++- 3 files changed, 8 insertions(+), 6 deletions(-) diff --git a/radicale/app/__init__.py b/radicale/app/__init__.py index 6ff68401..68799e52 100644 --- a/radicale/app/__init__.py +++ b/radicale/app/__init__.py @@ -121,6 +121,9 @@ class Application(ApplicationPartDelete, ApplicationPartHead, def _handle_request(self, environ: types.WSGIEnviron ) -> _IntermediateResponse: + time_begin = datetime.datetime.now() + request_method = environ["REQUEST_METHOD"].upper() + """Manage a request.""" def response(status: int, headers: types.WSGIResponseHeaders, answer: Union[None, str, bytes]) -> _IntermediateResponse: @@ -144,7 +147,8 @@ class Application(ApplicationPartDelete, ApplicationPartHead, headers["Content-Encoding"] = "gzip" headers["Content-Length"] = str(len(answer)) - answers.append(answer) + if request_method != "HEAD": + answers.append(answer) # Add extra headers set in configuration headers.update(self._extra_headers) @@ -161,8 +165,6 @@ class Application(ApplicationPartDelete, ApplicationPartHead, # Return response content return status_text, list(headers.items()), answers - time_begin = datetime.datetime.now() - request_method = environ["REQUEST_METHOD"].upper() unsafe_path = environ.get("PATH_INFO", "") remote_host = "unknown" if environ.get("REMOTE_HOST"): diff --git a/radicale/app/head.py b/radicale/app/head.py index af39873b..99af5260 100644 --- a/radicale/app/head.py +++ b/radicale/app/head.py @@ -27,5 +27,4 @@ class ApplicationPartHead(ApplicationPartGet, ApplicationBase): def do_HEAD(self, environ: types.WSGIEnviron, base_prefix: str, path: str, user: str) -> types.WSGIResponse: """Manage HEAD request.""" - status, headers, _ = self.do_GET(environ, base_prefix, path, user) - return status, headers, None + return self.do_GET(environ, base_prefix, path, user) diff --git a/radicale/tests/test_base.py b/radicale/tests/test_base.py index 9b16ba61..52c482e0 100644 --- a/radicale/tests/test_base.py +++ b/radicale/tests/test_base.py @@ -382,8 +382,9 @@ permissions: RrWw""") assert xml.find(xmlutils.make_clark("C:no-uid-conflict")) is not None def test_head(self) -> None: - status, _, _ = self.request("HEAD", "/") + status, headers, answer = self.request("HEAD", "/") assert status == 302 + assert int(headers.get("Content-Length", "0")) > 0 and not answer def test_options(self) -> None: status, headers, _ = self.request("OPTIONS", "/") From 75df1093be6eaffd9af1d34937f6a7ccac5eef20 Mon Sep 17 00:00:00 2001 From: Unrud Date: Sat, 15 Jan 2022 23:39:05 +0100 Subject: [PATCH 110/238] Workaround for broken contact PHOTO from InfCloud See issue #1205 --- radicale/app/put.py | 2 +- radicale/item/__init__.py | 11 +++++++++++ radicale/storage/multifilesystem/get.py | 6 ++---- radicale/tests/static/contact_photo_with_data_uri.vcf | 8 ++++++++ radicale/tests/test_base.py | 6 ++++++ 5 files changed, 28 insertions(+), 5 deletions(-) create mode 100644 radicale/tests/static/contact_photo_with_data_uri.vcf diff --git a/radicale/app/put.py b/radicale/app/put.py index ac07bf45..ec495878 100644 --- a/radicale/app/put.py +++ b/radicale/app/put.py @@ -141,7 +141,7 @@ class ApplicationPartPut(ApplicationBase): content_type = environ.get("CONTENT_TYPE", "").split(";", maxsplit=1)[0] try: - vobject_items = list(vobject.readComponents(content or "")) + vobject_items = radicale_item.read_components(content or "") except Exception as e: logger.warning( "Bad PUT request on %r: %s", path, e, exc_info=True) diff --git a/radicale/item/__init__.py b/radicale/item/__init__.py index fd293ddc..3bce12aa 100644 --- a/radicale/item/__init__.py +++ b/radicale/item/__init__.py @@ -27,6 +27,7 @@ import binascii import contextlib import math import os +import re import sys from datetime import datetime, timedelta from hashlib import sha256 @@ -42,6 +43,16 @@ from radicale.item import filter as radicale_filter from radicale.log import logger +def read_components(s: str) -> List[vobject.base.Component]: + """Wrapper for vobject.readComponents""" + # Workaround for bug in InfCloud + # PHOTO is a data URI + s = re.sub(r"^(PHOTO(?:;[^:\r\n]*)?;ENCODING=b(?:;[^:\r\n]*)?:)" + r"data:[^;,\r\n]*;base64,", r"\1", s, + flags=re.MULTILINE | re.IGNORECASE) + return list(vobject.readComponents(s)) + + def predict_tag_of_parent_collection( vobject_items: Sequence[vobject.base.Component]) -> Optional[str]: """Returns the predicted tag or `None`""" diff --git a/radicale/storage/multifilesystem/get.py b/radicale/storage/multifilesystem/get.py index e4f184e0..0a1fd73f 100644 --- a/radicale/storage/multifilesystem/get.py +++ b/radicale/storage/multifilesystem/get.py @@ -21,8 +21,6 @@ import sys import time from typing import Iterable, Iterator, Optional, Tuple -import vobject - import radicale.item as radicale_item from radicale import pathutils from radicale.log import logger @@ -93,8 +91,8 @@ class CollectionPartGet(CollectionPartCache, CollectionPartLock, cache_content = self._load_item_cache(href, cache_hash) if cache_content is None: try: - vobject_items = list(vobject.readComponents( - raw_text.decode(self._encoding))) + vobject_items = radicale_item.read_components( + raw_text.decode(self._encoding)) radicale_item.check_and_sanitize_items( vobject_items, tag=self.tag) vobject_item, = vobject_items diff --git a/radicale/tests/static/contact_photo_with_data_uri.vcf b/radicale/tests/static/contact_photo_with_data_uri.vcf new file mode 100644 index 00000000..b443546f --- /dev/null +++ b/radicale/tests/static/contact_photo_with_data_uri.vcf @@ -0,0 +1,8 @@ +BEGIN:VCARD +VERSION:3.0 +UID:contact +N:Contact;;;; +FN:Contact +NICKNAME:test +PHOTO;ENCODING=b;TYPE=png:data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAIAAACQd1PeAAAAD0lEQVQIHQEEAPv/AP///wX+Av4DfRnGAAAAAElFTkSuQmCC +END:VCARD diff --git a/radicale/tests/test_base.py b/radicale/tests/test_base.py index 52c482e0..2a8c47f0 100644 --- a/radicale/tests/test_base.py +++ b/radicale/tests/test_base.py @@ -139,6 +139,12 @@ permissions: RrWw""") _, answer = self.get(path) assert "UID:contact1" in answer + def test_add_contact_photo_with_data_uri(self) -> None: + """Test workaround for broken PHOTO data from InfCloud""" + self.create_addressbook("/contacts.vcf/") + contact = get_file_content("contact_photo_with_data_uri.vcf") + self.put("/contacts.vcf/contact.vcf", contact) + def test_add_contact_without_uid(self) -> None: """Add a contact without UID.""" self.create_addressbook("/contacts.vcf/") From 9c0b6cdaebc97729c3cbc8e2d29f7d5864d53f86 Mon Sep 17 00:00:00 2001 From: Unrud Date: Sat, 15 Jan 2022 23:58:58 +0100 Subject: [PATCH 111/238] Update NEWS.md --- NEWS.md | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/NEWS.md b/NEWS.md index 098e23fd..2651bd88 100644 --- a/NEWS.md +++ b/NEWS.md @@ -2,6 +2,13 @@ ## master +* Workaround for contact photo bug in InfCloud +* Redirect GET and HEAD requests to sanitized path +* Set `Content-Length` header for HEAD requests +* Never send body for HEAD requests +* Improve error messages for `from_file` rights backend +* Don't sanitize WSGI script name + ## 3.1.0 * Single `` element in PROPPATCH response From 402bd3580ef769427e7f6e335fcab16184ffb3a6 Mon Sep 17 00:00:00 2001 From: Unrud Date: Sun, 16 Jan 2022 13:07:56 +0100 Subject: [PATCH 112/238] Tests: Simplify HTTP status check --- radicale/tests/__init__.py | 76 ++++++++++++++++------------------- radicale/tests/test_base.py | 76 ++++++++++++++--------------------- radicale/tests/test_server.py | 8 ++-- radicale/tests/test_web.py | 3 +- 4 files changed, 71 insertions(+), 92 deletions(-) diff --git a/radicale/tests/__init__.py b/radicale/tests/__init__.py index 0833fc4f..2e132560 100644 --- a/radicale/tests/__init__.py +++ b/radicale/tests/__init__.py @@ -65,7 +65,8 @@ class BaseTest: shutil.rmtree(self.colpath) def request(self, method: str, path: str, data: Optional[str] = None, - **kwargs) -> Tuple[int, Dict[str, str], str]: + check: Optional[int] = None, **kwargs + ) -> Tuple[int, Dict[str, str], str]: """Send a request.""" login = kwargs.pop("login", None) if login is not None and not isinstance(login, str): @@ -92,13 +93,13 @@ class BaseTest: def start_response(status_: str, headers_: List[Tuple[str, str]] ) -> None: nonlocal status, headers - status = status_ - headers = headers_ + status = int(status_.split()[0]) + headers = dict(headers_) answers = list(self.application(environ, start_response)) assert status is not None and headers is not None + assert check is None or status == check, "%d != %d" % (status, check) - return (int(status.split()[0]), dict(headers), - answers[0].decode() if answers else "") + return status, headers, answers[0].decode() if answers else "" @staticmethod def parse_responses(text: str) -> RESPONSES: @@ -130,38 +131,30 @@ class BaseTest: path_responses[href.text] = prop_respones return path_responses - @staticmethod - def _check_status(status: int, good_status: int, - check: Union[bool, int] = True) -> bool: - if check is not False: - expected = good_status if check is True else check - assert status == expected, "%d != %d" % (status, expected) - return status == good_status - - def get(self, path: str, check: Union[bool, int] = True, **kwargs + def get(self, path: str, check: Optional[int] = 200, **kwargs ) -> Tuple[int, str]: assert "data" not in kwargs - status, _, answer = self.request("GET", path, **kwargs) - self._check_status(status, 200, check) + status, _, answer = self.request("GET", path, check=check, **kwargs) return status, answer - def post(self, path: str, data: str = None, check: Union[bool, int] = True, + def post(self, path: str, data: str = None, check: Optional[int] = 200, **kwargs) -> Tuple[int, str]: - status, _, answer = self.request("POST", path, data, **kwargs) - self._check_status(status, 200, check) + status, _, answer = self.request("POST", path, data, check=check, + **kwargs) return status, answer - def put(self, path: str, data: str, check: Union[bool, int] = True, + def put(self, path: str, data: str, check: Optional[int] = 201, **kwargs) -> Tuple[int, str]: - status, _, answer = self.request("PUT", path, data, **kwargs) - self._check_status(status, 201, check) + status, _, answer = self.request("PUT", path, data, check=check, + **kwargs) return status, answer def propfind(self, path: str, data: Optional[str] = None, - check: Union[bool, int] = True, **kwargs + check: Optional[int] = 207, **kwargs ) -> Tuple[int, RESPONSES]: - status, _, answer = self.request("PROPFIND", path, data, **kwargs) - if not self._check_status(status, 207, check): + status, _, answer = self.request("PROPFIND", path, data, check=check, + **kwargs) + if status < 200 or 300 <= status: return status, {} assert answer is not None responses = self.parse_responses(answer) @@ -170,29 +163,31 @@ class BaseTest: return status, responses def proppatch(self, path: str, data: Optional[str] = None, - check: Union[bool, int] = True, **kwargs + check: Optional[int] = 207, **kwargs ) -> Tuple[int, RESPONSES]: - status, _, answer = self.request("PROPPATCH", path, data, **kwargs) - if not self._check_status(status, 207, check): + status, _, answer = self.request("PROPPATCH", path, data, check=check, + **kwargs) + if status < 200 or 300 <= status: return status, {} assert answer is not None responses = self.parse_responses(answer) assert len(responses) == 1 and path in responses return status, responses - def report(self, path: str, data: str, check: Union[bool, int] = True, + def report(self, path: str, data: str, check: Optional[int] = 207, **kwargs) -> Tuple[int, RESPONSES]: - status, _, answer = self.request("REPORT", path, data, **kwargs) - if not self._check_status(status, 207, check): + status, _, answer = self.request("REPORT", path, data, check=check, + **kwargs) + if status < 200 or 300 <= status: return status, {} assert answer is not None return status, self.parse_responses(answer) - def delete(self, path: str, check: Union[bool, int] = True, **kwargs + def delete(self, path: str, check: Optional[int] = 200, **kwargs ) -> Tuple[int, RESPONSES]: assert "data" not in kwargs - status, _, answer = self.request("DELETE", path, **kwargs) - if not self._check_status(status, 200, check): + status, _, answer = self.request("DELETE", path, check=check, **kwargs) + if status < 200 or 300 <= status: return status, {} assert answer is not None responses = self.parse_responses(answer) @@ -200,19 +195,18 @@ class BaseTest: return status, responses def mkcalendar(self, path: str, data: Optional[str] = None, - check: Union[bool, int] = True, **kwargs + check: Optional[int] = 201, **kwargs ) -> Tuple[int, str]: - status, _, answer = self.request("MKCALENDAR", path, data, **kwargs) - self._check_status(status, 201, check) + status, _, answer = self.request("MKCALENDAR", path, data, check=check, + **kwargs) return status, answer def mkcol(self, path: str, data: Optional[str] = None, - check: Union[bool, int] = True, **kwargs) -> int: - status, _, _ = self.request("MKCOL", path, data, **kwargs) - self._check_status(status, 201, check) + check: Optional[int] = 201, **kwargs) -> int: + status, _, _ = self.request("MKCOL", path, data, check=check, **kwargs) return status - def create_addressbook(self, path: str, check: Union[bool, int] = True, + def create_addressbook(self, path: str, check: Optional[int] = 201, **kwargs) -> int: assert "data" not in kwargs return self.mkcol(path, """\ diff --git a/radicale/tests/test_base.py b/radicale/tests/test_base.py index 2a8c47f0..d8d7caf0 100644 --- a/radicale/tests/test_base.py +++ b/radicale/tests/test_base.py @@ -76,8 +76,7 @@ permissions: RrWw""") event = get_file_content("event1.ics") path = "/calendar.ics/event1.ics" self.put(path, event) - status, headers, answer = self.request("GET", path) - assert status == 200 + _, headers, answer = self.request("GET", path, check=200) assert "ETag" in headers assert headers["Content-Type"] == "text/calendar; charset=utf-8" assert "VEVENT" in answer @@ -98,7 +97,7 @@ permissions: RrWw""") event = get_file_content("event1.ics") self.put("/calendar.ics/event1.ics", event) status, answer = self.put( - "/calendar.ics/event1-duplicate.ics", event, check=False) + "/calendar.ics/event1-duplicate.ics", event, check=None) assert status in (403, 409) xml = DefusedET.fromstring(answer) assert xml.tag == xmlutils.make_clark("D:error") @@ -116,8 +115,7 @@ permissions: RrWw""") todo = get_file_content("todo1.ics") path = "/calendar.ics/todo1.ics" self.put(path, todo) - status, headers, answer = self.request("GET", path) - assert status == 200 + _, headers, answer = self.request("GET", path, check=200) assert "ETag" in headers assert headers["Content-Type"] == "text/calendar; charset=utf-8" assert "VTODO" in answer @@ -130,8 +128,7 @@ permissions: RrWw""") contact = get_file_content("contact1.vcf") path = "/contacts.vcf/contact.vcf" self.put(path, contact) - status, headers, answer = self.request("GET", path) - assert status == 200 + _, headers, answer = self.request("GET", path, check=200) assert "ETag" in headers assert headers["Content-Type"] == "text/vcard; charset=utf-8" assert "VCARD" in answer @@ -174,7 +171,7 @@ permissions: RrWw""") event2 = get_file_content("event2.ics") path = "/calendar.ics/event1.ics" self.put(path, event1) - status, answer = self.put(path, event2, check=False) + status, answer = self.put(path, event2, check=None) assert status in (403, 409) xml = DefusedET.fromstring(answer) assert xml.tag == xmlutils.make_clark("D:error") @@ -267,7 +264,7 @@ permissions: RrWw""") def test_mkcalendar_overwrite(self) -> None: """Try to overwrite an existing calendar.""" self.mkcalendar("/calendar.ics/") - status, answer = self.mkcalendar("/calendar.ics/", check=False) + status, answer = self.mkcalendar("/calendar.ics/", check=None) assert status in (403, 409) xml = DefusedET.fromstring(answer) assert xml.tag == xmlutils.make_clark("D:error") @@ -276,8 +273,7 @@ permissions: RrWw""") def test_mkcalendar_intermediate(self) -> None: """Try make a calendar in a unmapped collection.""" - status, _ = self.mkcalendar("/unmapped/calendar.ics/", check=False) - assert status == 409 + self.mkcalendar("/unmapped/calendar.ics/", check=409) def test_mkcol(self) -> None: """Make a collection.""" @@ -286,13 +282,11 @@ permissions: RrWw""") def test_mkcol_overwrite(self) -> None: """Try to overwrite an existing collection.""" self.mkcol("/user/") - status = self.mkcol("/user/", check=False) - assert status == 405 + self.mkcol("/user/", check=405) def test_mkcol_intermediate(self) -> None: """Try make a collection in a unmapped collection.""" - status = self.mkcol("/unmapped/user/", check=False) - assert status == 409 + self.mkcol("/unmapped/user/", check=409) def test_mkcol_make_calendar(self) -> None: """Make a calendar with additional props.""" @@ -317,9 +311,8 @@ permissions: RrWw""") path1 = "/calendar.ics/event1.ics" path2 = "/calendar.ics/event2.ics" self.put(path1, event) - status, _, _ = self.request( - "MOVE", path1, HTTP_DESTINATION=path2, HTTP_HOST="") - assert status == 201 + self.request("MOVE", path1, check=201, + HTTP_DESTINATION=path2, HTTP_HOST="") self.get(path1, check=404) self.get(path2) @@ -331,9 +324,8 @@ permissions: RrWw""") path1 = "/calendar1.ics/event1.ics" path2 = "/calendar2.ics/event2.ics" self.put(path1, event) - status, _, _ = self.request( - "MOVE", path1, HTTP_DESTINATION=path2, HTTP_HOST="") - assert status == 201 + self.request("MOVE", path1, check=201, + HTTP_DESTINATION=path2, HTTP_HOST="") self.get(path1, check=404) self.get(path2) @@ -362,12 +354,10 @@ permissions: RrWw""") path2 = "/calendar2.ics/event1.ics" self.put(path1, event) self.put(path2, event) - status, _, _ = self.request( - "MOVE", path1, HTTP_DESTINATION=path2, HTTP_HOST="") - assert status == 412 - status, _, _ = self.request("MOVE", path1, HTTP_DESTINATION=path2, - HTTP_HOST="", HTTP_OVERWRITE="T") - assert status == 204 + self.request("MOVE", path1, check=412, + HTTP_DESTINATION=path2, HTTP_HOST="") + self.request("MOVE", path1, check=204, + HTTP_DESTINATION=path2, HTTP_HOST="", HTTP_OVERWRITE="T") def test_move_between_colections_overwrite_uid_conflict(self) -> None: """Move a item to a collection which already contains the item with @@ -388,13 +378,11 @@ permissions: RrWw""") assert xml.find(xmlutils.make_clark("C:no-uid-conflict")) is not None def test_head(self) -> None: - status, headers, answer = self.request("HEAD", "/") - assert status == 302 + _, headers, answer = self.request("HEAD", "/", check=302) assert int(headers.get("Content-Length", "0")) > 0 and not answer def test_options(self) -> None: - status, headers, _ = self.request("OPTIONS", "/") - assert status == 200 + _, headers, _ = self.request("OPTIONS", "/", check=200) assert "DAV" in headers def test_delete_collection(self) -> None: @@ -650,7 +638,7 @@ permissions: RrWw""") report = "addressbook-query" else: raise ValueError("Unsupported kind: %r" % kind) - status, _, = self.delete(path, check=False) + status, _, = self.delete(path, check=None) assert status in (200, 404) create_collection_fn(path) for i in items: @@ -1439,9 +1427,8 @@ permissions: RrWw""") self.put(event1_path, event) sync_token, responses = self._report_sync_token(calendar_path) assert len(responses) == 1 and responses[event1_path] == 200 - status, _, _ = self.request( - "MOVE", event1_path, HTTP_DESTINATION=event2_path, HTTP_HOST="") - assert status == 201 + self.request("MOVE", event1_path, check=201, + HTTP_DESTINATION=event2_path, HTTP_HOST="") sync_token, responses = self._report_sync_token( calendar_path, sync_token) if not self.full_sync_token_support and not sync_token: @@ -1459,12 +1446,10 @@ permissions: RrWw""") self.put(event1_path, event) sync_token, responses = self._report_sync_token(calendar_path) assert len(responses) == 1 and responses[event1_path] == 200 - status, _, _ = self.request( - "MOVE", event1_path, HTTP_DESTINATION=event2_path, HTTP_HOST="") - assert status == 201 - status, _, _ = self.request( - "MOVE", event2_path, HTTP_DESTINATION=event1_path, HTTP_HOST="") - assert status == 201 + self.request("MOVE", event1_path, check=201, + HTTP_DESTINATION=event2_path, HTTP_HOST="") + self.request("MOVE", event2_path, check=201, + HTTP_DESTINATION=event1_path, HTTP_HOST="") sync_token, responses = self._report_sync_token( calendar_path, sync_token) if not self.full_sync_token_support and not sync_token: @@ -1518,7 +1503,7 @@ permissions: RrWw""") self.mkcalendar("/test/") for component in ("event", "todo", "journal"): event = get_file_content("%s1.ics" % component) - status, _ = self.delete("/test/test.ics", check=False) + status, _ = self.delete("/test/test.ics", check=None) assert status in (200, 404) self.put("/test/test.ics", event) _, responses = self.report("/test/", """\ @@ -1607,12 +1592,11 @@ permissions: RrWw""") def test_custom_headers(self) -> None: self.configure({"headers": {"test": "123"}}) # Test if header is set on success - status, headers, _ = self.request("OPTIONS", "/") - assert status == 200 + _, headers, _ = self.request("OPTIONS", "/", check=200) assert headers.get("test") == "123" # Test if header is set on failure - status, headers, _ = self.request("GET", "/.well-known/does not exist") - assert status == 404 + _, headers, _ = self.request("GET", "/.well-known/does not exist", + check=404) assert headers.get("test") == "123" @pytest.mark.skipif(sys.version_info < (3, 6), diff --git a/radicale/tests/test_server.py b/radicale/tests/test_server.py index e2f3b138..7f64d47b 100644 --- a/radicale/tests/test_server.py +++ b/radicale/tests/test_server.py @@ -97,7 +97,8 @@ class TestBaseServerRequests(BaseTest): super().teardown() def request(self, method: str, path: str, data: Optional[str] = None, - **kwargs) -> Tuple[int, Dict[str, str], str]: + check: Optional[int] = None, **kwargs + ) -> Tuple[int, Dict[str, str], str]: """Send a request.""" login = kwargs.pop("login", None) if login is not None and not isinstance(login, str): @@ -128,6 +129,8 @@ class TestBaseServerRequests(BaseTest): with self.opener.open(req) as f: return f.getcode(), dict(f.info()), f.read().decode() except HTTPError as e: + assert check is None or e.code == check, "%d != %d" % (e.code, + check) return e.code, dict(e.headers), e.read().decode() except URLError as e: if not isinstance(e.reason, ConnectionRefusedError): @@ -209,8 +212,7 @@ class TestBaseServerRequests(BaseTest): env={**os.environ, "PYTHONPATH": os.pathsep.join(sys.path)}) try: status, headers, _ = self.request( - "GET", "/", is_alive_fn=lambda: p.poll() is None) - self._check_status(status, 302) + "GET", "/", check=302, is_alive_fn=lambda: p.poll() is None) for key in self.configuration.options("headers"): assert headers.get(key) == self.configuration.get( "headers", key) diff --git a/radicale/tests/test_web.py b/radicale/tests/test_web.py index 9432166f..2f6739b7 100644 --- a/radicale/tests/test_web.py +++ b/radicale/tests/test_web.py @@ -26,8 +26,7 @@ class TestBaseWebRequests(BaseTest): """Test web plugin.""" def test_internal(self) -> None: - status, headers, _ = self.request("GET", "/.web") - assert status == 302 + _, headers, _ = self.request("GET", "/.web", check=302) assert headers.get("Location") == ".web/" _, answer = self.get("/.web/") assert answer From e0adecf30cb5b76cfa50f9b52afe40be44667e59 Mon Sep 17 00:00:00 2001 From: Unrud Date: Sun, 16 Jan 2022 13:09:13 +0100 Subject: [PATCH 113/238] Tests: Check Location header and body for redirects --- radicale/tests/test_base.py | 12 ++++++++---- radicale/tests/test_web.py | 3 ++- 2 files changed, 10 insertions(+), 5 deletions(-) diff --git a/radicale/tests/test_base.py b/radicale/tests/test_base.py index d8d7caf0..17e4791b 100644 --- a/radicale/tests/test_base.py +++ b/radicale/tests/test_base.py @@ -53,10 +53,11 @@ permissions: RrWw""") def test_root(self) -> None: """GET request at "/".""" - _, answer = self.get("/", check=302) + status, headers, answer = self.request("GET", "/", check=302) + assert headers.get("Location") == ".web" assert answer == "Redirected to .web" - def test_script_name(self) -> None: + def test_root_script_name(self) -> None: """GET request at "/" with SCRIPT_NAME.""" _, answer = self.get("/", check=302, SCRIPT_NAME="/radicale") assert answer == "Redirected to .web" @@ -65,9 +66,12 @@ permissions: RrWw""") """GET request with unsanitized paths.""" for path, sane_path in [("//", "/"), ("", "/"), ("/a//b", "/a/b"), ("/a//b/", "/a/b/")]: - _, answer = self.get(path, check=301) + _, headers, answer = self.request("GET", path, check=301) + assert headers.get("Location") == sane_path assert answer == "Redirected to %s" % sane_path - _, answer = self.get(path, check=301, SCRIPT_NAME="/radicale") + _, headers, answer = self.request("GET", path, check=301, + SCRIPT_NAME="/radicale") + assert headers.get("Location") == "/radicale%s" % sane_path assert answer == "Redirected to /radicale%s" % sane_path def test_add_event(self) -> None: diff --git a/radicale/tests/test_web.py b/radicale/tests/test_web.py index 2f6739b7..88bf2bcd 100644 --- a/radicale/tests/test_web.py +++ b/radicale/tests/test_web.py @@ -26,8 +26,9 @@ class TestBaseWebRequests(BaseTest): """Test web plugin.""" def test_internal(self) -> None: - _, headers, _ = self.request("GET", "/.web", check=302) + _, headers, answer = self.request("GET", "/.web", check=302) assert headers.get("Location") == ".web/" + assert answer == "Redirected to .web/" _, answer = self.get("/.web/") assert answer self.post("/.web", check=405) From 1336c020797551019ebcff13755d9a4426556de3 Mon Sep 17 00:00:00 2001 From: Unrud Date: Tue, 18 Jan 2022 18:20:14 +0100 Subject: [PATCH 114/238] Re-use variable --- radicale/app/__init__.py | 10 ++++------ 1 file changed, 4 insertions(+), 6 deletions(-) diff --git a/radicale/app/__init__.py b/radicale/app/__init__.py index 68799e52..09cc2d39 100644 --- a/radicale/app/__init__.py +++ b/radicale/app/__init__.py @@ -123,6 +123,7 @@ class Application(ApplicationPartDelete, ApplicationPartHead, ) -> _IntermediateResponse: time_begin = datetime.datetime.now() request_method = environ["REQUEST_METHOD"].upper() + unsafe_path = environ.get("PATH_INFO", "") """Manage a request.""" def response(status: int, headers: types.WSGIResponseHeaders, @@ -157,15 +158,12 @@ class Application(ApplicationPartDelete, ApplicationPartHead, time_end = datetime.datetime.now() status_text = "%d %s" % ( status, client.responses.get(status, "Unknown")) - logger.info( - "%s response status for %r%s in %.3f seconds: %s", - environ["REQUEST_METHOD"], environ.get("PATH_INFO", ""), - depthinfo, (time_end - time_begin).total_seconds(), - status_text) + logger.info("%s response status for %r%s in %.3f seconds: %s", + request_method, unsafe_path, depthinfo, + (time_end - time_begin).total_seconds(), status_text) # Return response content return status_text, list(headers.items()), answers - unsafe_path = environ.get("PATH_INFO", "") remote_host = "unknown" if environ.get("REMOTE_HOST"): remote_host = repr(environ["REMOTE_HOST"]) From d1532aa466021ca31ffc7a13e2ffc1b6ae03c657 Mon Sep 17 00:00:00 2001 From: Unrud Date: Tue, 18 Jan 2022 18:20:15 +0100 Subject: [PATCH 115/238] Extract httputils.redirect --- radicale/app/__init__.py | 6 ++---- radicale/app/get.py | 5 +---- radicale/httputils.py | 6 ++++++ radicale/web/internal.py | 5 +---- 4 files changed, 10 insertions(+), 12 deletions(-) diff --git a/radicale/app/__init__.py b/radicale/app/__init__.py index 09cc2d39..ca8594ec 100644 --- a/radicale/app/__init__.py +++ b/radicale/app/__init__.py @@ -197,10 +197,8 @@ class Application(ApplicationPartDelete, ApplicationPartHead, location = base_prefix + path logger.info("Redirecting to sanitized path: %r ==> %r", base_prefix + unsafe_path, location) - return response( - client.MOVED_PERMANENTLY, - {"Location": location, "Content-Type": "text/plain"}, - "Redirected to %s" % location) + return response(*httputils.redirect( + location, client.MOVED_PERMANENTLY)) logger.debug("Sanitized path: %r", path) # Get function corresponding to method diff --git a/radicale/app/get.py b/radicale/app/get.py index 3b26815e..ce953244 100644 --- a/radicale/app/get.py +++ b/radicale/app/get.py @@ -62,10 +62,7 @@ class ApplicationPartGet(ApplicationBase): """Manage GET request.""" # Redirect to .web if the root URL is requested if not pathutils.strip_path(path): - location = ".web" - return (client.FOUND, - {"Location": location, "Content-Type": "text/plain"}, - "Redirected to %s" % location) + return httputils.redirect(".web") # Dispatch .web URL to web module if path == "/.web" or path.startswith("/.web/"): return self._web.get(environ, base_prefix, path, user) diff --git a/radicale/httputils.py b/radicale/httputils.py index 000bee78..98c77d4f 100644 --- a/radicale/httputils.py +++ b/radicale/httputils.py @@ -114,3 +114,9 @@ def read_request_body(configuration: "config.Configuration", read_raw_request_body(configuration, environ)) logger.debug("Request content:\n%s", content) return content + + +def redirect(location: str, status: int = client.FOUND) -> types.WSGIResponse: + return (status, + {"Location": location, "Content-Type": "text/plain"}, + "Redirected to %s" % location) diff --git a/radicale/web/internal.py b/radicale/web/internal.py index 7bed5e99..4ee62c81 100644 --- a/radicale/web/internal.py +++ b/radicale/web/internal.py @@ -75,10 +75,7 @@ class Web(web.BaseWeb): path, e, exc_info=True) return httputils.NOT_FOUND if os.path.isdir(filesystem_path) and not path.endswith("/"): - location = posixpath.basename(path) + "/" - return (client.FOUND, - {"Location": location, "Content-Type": "text/plain"}, - "Redirected to %s" % location) + return httputils.redirect(posixpath.basename(path) + "/") if os.path.isdir(filesystem_path): filesystem_path = os.path.join(filesystem_path, "index.html") if not os.path.isfile(filesystem_path): From 4ed77cabc6e4c918851b5b3db1aae586303f5adf Mon Sep 17 00:00:00 2001 From: Unrud Date: Tue, 18 Jan 2022 18:20:15 +0100 Subject: [PATCH 116/238] Only redirect to sanitized path under /web --- radicale/app/__init__.py | 6 ------ radicale/app/get.py | 13 ++++++++++--- radicale/tests/test_base.py | 26 ++++++++++++++------------ 3 files changed, 24 insertions(+), 21 deletions(-) diff --git a/radicale/app/__init__.py b/radicale/app/__init__.py index ca8594ec..aab4beb5 100644 --- a/radicale/app/__init__.py +++ b/radicale/app/__init__.py @@ -193,12 +193,6 @@ class Application(ApplicationPartDelete, ApplicationPartHead, # Sanitize request URI (a WSGI server indicates with an empty path, # that the URL targets the application root without a trailing slash) path = pathutils.sanitize_path(unsafe_path) - if unsafe_path != path and request_method in ["GET", "HEAD"]: - location = base_prefix + path - logger.info("Redirecting to sanitized path: %r ==> %r", - base_prefix + unsafe_path, location) - return response(*httputils.redirect( - location, client.MOVED_PERMANENTLY)) logger.debug("Sanitized path: %r", path) # Get function corresponding to method diff --git a/radicale/app/get.py b/radicale/app/get.py index ce953244..7e5feeb4 100644 --- a/radicale/app/get.py +++ b/radicale/app/get.py @@ -60,11 +60,18 @@ class ApplicationPartGet(ApplicationBase): def do_GET(self, environ: types.WSGIEnviron, base_prefix: str, path: str, user: str) -> types.WSGIResponse: """Manage GET request.""" - # Redirect to .web if the root URL is requested + # Redirect to /.web if the root path is requested if not pathutils.strip_path(path): - return httputils.redirect(".web") - # Dispatch .web URL to web module + return httputils.redirect(base_prefix + "/.web") if path == "/.web" or path.startswith("/.web/"): + # Redirect to sanitized path for all subpaths of /.web + unsafe_path = environ.get("PATH_INFO", "") + if unsafe_path != path: + location = base_prefix + path + logger.info("Redirecting to sanitized path: %r ==> %r", + base_prefix + unsafe_path, location) + return httputils.redirect(location, client.MOVED_PERMANENTLY) + # Dispatch /.web path to web module return self._web.get(environ, base_prefix, path, user) access = Access(self._rights, user, path) if not access.check("r") and "i" not in access.permissions: diff --git a/radicale/tests/test_base.py b/radicale/tests/test_base.py index 17e4791b..1b8afd98 100644 --- a/radicale/tests/test_base.py +++ b/radicale/tests/test_base.py @@ -53,26 +53,28 @@ permissions: RrWw""") def test_root(self) -> None: """GET request at "/".""" - status, headers, answer = self.request("GET", "/", check=302) - assert headers.get("Location") == ".web" - assert answer == "Redirected to .web" + for path in ["", "/", "//"]: + _, headers, answer = self.request("GET", path, check=302) + assert headers.get("Location") == "/.web" + assert answer == "Redirected to /.web" def test_root_script_name(self) -> None: """GET request at "/" with SCRIPT_NAME.""" - _, answer = self.get("/", check=302, SCRIPT_NAME="/radicale") - assert answer == "Redirected to .web" + for path in ["", "/", "//"]: + _, headers, _ = self.request("GET", path, check=302, + SCRIPT_NAME="/radicale") + assert headers.get("Location") == "/radicale/.web" def test_sanitized_path(self) -> None: """GET request with unsanitized paths.""" - for path, sane_path in [("//", "/"), ("", "/"), ("/a//b", "/a/b"), - ("/a//b/", "/a/b/")]: - _, headers, answer = self.request("GET", path, check=301) + for path, sane_path in [ + ("//.web", "/.web"), ("//.web/", "/.web/"), + ("/.web//", "/.web/"), ("/.web/a//b", "/.web/a/b")]: + _, headers, _ = self.request("GET", path, check=301) assert headers.get("Location") == sane_path - assert answer == "Redirected to %s" % sane_path - _, headers, answer = self.request("GET", path, check=301, - SCRIPT_NAME="/radicale") + _, headers, _ = self.request("GET", path, check=301, + SCRIPT_NAME="/radicale") assert headers.get("Location") == "/radicale%s" % sane_path - assert answer == "Redirected to /radicale%s" % sane_path def test_add_event(self) -> None: """Add an event.""" From 22fc38850cc2c7a98e419031738d1e20021438e2 Mon Sep 17 00:00:00 2001 From: Unrud Date: Tue, 18 Jan 2022 18:20:15 +0100 Subject: [PATCH 117/238] web.internal: Use absolute path for redirect --- radicale/tests/test_web.py | 5 ++--- radicale/web/internal.py | 3 +-- 2 files changed, 3 insertions(+), 5 deletions(-) diff --git a/radicale/tests/test_web.py b/radicale/tests/test_web.py index 88bf2bcd..ecfec9a9 100644 --- a/radicale/tests/test_web.py +++ b/radicale/tests/test_web.py @@ -26,9 +26,8 @@ class TestBaseWebRequests(BaseTest): """Test web plugin.""" def test_internal(self) -> None: - _, headers, answer = self.request("GET", "/.web", check=302) - assert headers.get("Location") == ".web/" - assert answer == "Redirected to .web/" + _, headers, _ = self.request("GET", "/.web", check=302) + assert headers.get("Location") == "/.web/" _, answer = self.get("/.web/") assert answer self.post("/.web", check=405) diff --git a/radicale/web/internal.py b/radicale/web/internal.py index 4ee62c81..d8f078b0 100644 --- a/radicale/web/internal.py +++ b/radicale/web/internal.py @@ -27,7 +27,6 @@ Features: import os -import posixpath import time from http import client from typing import Mapping @@ -75,7 +74,7 @@ class Web(web.BaseWeb): path, e, exc_info=True) return httputils.NOT_FOUND if os.path.isdir(filesystem_path) and not path.endswith("/"): - return httputils.redirect(posixpath.basename(path) + "/") + return httputils.redirect(base_prefix + path + "/") if os.path.isdir(filesystem_path): filesystem_path = os.path.join(filesystem_path, "index.html") if not os.path.isfile(filesystem_path): From 685a91bfe63250e4db5e1781330047ccc882d0e6 Mon Sep 17 00:00:00 2001 From: Unrud Date: Tue, 18 Jan 2022 18:20:16 +0100 Subject: [PATCH 118/238] web.none: Redirect instead of 404 --- radicale/tests/test_web.py | 3 ++- radicale/web/none.py | 2 +- 2 files changed, 3 insertions(+), 2 deletions(-) diff --git a/radicale/tests/test_web.py b/radicale/tests/test_web.py index ecfec9a9..205b9b6a 100644 --- a/radicale/tests/test_web.py +++ b/radicale/tests/test_web.py @@ -36,7 +36,8 @@ class TestBaseWebRequests(BaseTest): self.configure({"web": {"type": "none"}}) _, answer = self.get("/.web") assert answer - self.get("/.web/", check=404) + _, headers, _ = self.request("GET", "/.web/", check=302) + assert headers.get("Location") == "/.web" self.post("/.web", check=405) def test_custom(self) -> None: diff --git a/radicale/web/none.py b/radicale/web/none.py index 4f114a09..263992ec 100644 --- a/radicale/web/none.py +++ b/radicale/web/none.py @@ -31,5 +31,5 @@ class Web(web.BaseWeb): assert path == "/.web" or path.startswith("/.web/") assert pathutils.sanitize_path(path) == path if path != "/.web": - return httputils.NOT_FOUND + return httputils.redirect(base_prefix + "/.web") return client.OK, {"Content-Type": "text/plain"}, "Radicale works!" From 555e4ccc51265ad3c4a5af4f66fd0062781bf8dc Mon Sep 17 00:00:00 2001 From: Unrud Date: Tue, 18 Jan 2022 18:20:16 +0100 Subject: [PATCH 119/238] Clarify handling of HEAD request --- radicale/app/head.py | 1 + 1 file changed, 1 insertion(+) diff --git a/radicale/app/head.py b/radicale/app/head.py index 99af5260..b6178f69 100644 --- a/radicale/app/head.py +++ b/radicale/app/head.py @@ -27,4 +27,5 @@ class ApplicationPartHead(ApplicationPartGet, ApplicationBase): def do_HEAD(self, environ: types.WSGIEnviron, base_prefix: str, path: str, user: str) -> types.WSGIResponse: """Manage HEAD request.""" + # Body is dropped in `Application._handle_request` for HEAD requests return self.do_GET(environ, base_prefix, path, user) From 33fcda7c32f9ab1d3e78c96ca38759bcddc55eaf Mon Sep 17 00:00:00 2001 From: Unrud Date: Tue, 18 Jan 2022 18:20:16 +0100 Subject: [PATCH 120/238] Extract httputils.serve_folder --- radicale/httputils.py | 57 ++++++++++++++++++++++++++++++++++++++-- radicale/web/internal.py | 57 ++++------------------------------------ 2 files changed, 60 insertions(+), 54 deletions(-) diff --git a/radicale/httputils.py b/radicale/httputils.py index 98c77d4f..1bf25135 100644 --- a/radicale/httputils.py +++ b/radicale/httputils.py @@ -23,10 +23,12 @@ Helper functions for HTTP. """ import contextlib +import os +import time from http import client -from typing import List, cast +from typing import List, Mapping, cast -from radicale import config, types +from radicale import config, pathutils, types from radicale.log import logger NOT_ALLOWED: types.WSGIResponse = ( @@ -67,6 +69,22 @@ INTERNAL_SERVER_ERROR: types.WSGIResponse = ( DAV_HEADERS: str = "1, 2, 3, calendar-access, addressbook, extended-mkcol" +MIMETYPES: Mapping[str, str] = { + ".css": "text/css", + ".eot": "application/vnd.ms-fontobject", + ".gif": "image/gif", + ".html": "text/html", + ".js": "application/javascript", + ".manifest": "text/cache-manifest", + ".png": "image/png", + ".svg": "image/svg+xml", + ".ttf": "application/font-sfnt", + ".txt": "text/plain", + ".woff": "application/font-woff", + ".woff2": "font/woff2", + ".xml": "text/xml"} +FALLBACK_MIMETYPE: str = "application/octet-stream" + def decode_request(configuration: "config.Configuration", environ: types.WSGIEnviron, text: bytes) -> str: @@ -120,3 +138,38 @@ def redirect(location: str, status: int = client.FOUND) -> types.WSGIResponse: return (status, {"Location": location, "Content-Type": "text/plain"}, "Redirected to %s" % location) + + +def serve_folder(folder: str, base_prefix: str, path: str, + path_prefix: str = "/.web", index_file: str = "index.html", + mimetypes: Mapping[str, str] = MIMETYPES, + fallback_mimetype: str = FALLBACK_MIMETYPE, + ) -> types.WSGIResponse: + if path != path_prefix and not path.startswith(path_prefix): + raise ValueError("path must start with path_prefix: %r --> %r" % + (path_prefix, path)) + assert pathutils.sanitize_path(path) == path + try: + filesystem_path = pathutils.path_to_filesystem( + folder, path[len(path_prefix):].strip("/")) + except ValueError as e: + logger.debug("Web content with unsafe path %r requested: %s", + path, e, exc_info=True) + return NOT_FOUND + if os.path.isdir(filesystem_path) and not path.endswith("/"): + return redirect(base_prefix + path + "/") + if os.path.isdir(filesystem_path) and index_file: + filesystem_path = os.path.join(filesystem_path, index_file) + if not os.path.isfile(filesystem_path): + return NOT_FOUND + content_type = MIMETYPES.get( + os.path.splitext(filesystem_path)[1].lower(), FALLBACK_MIMETYPE) + with open(filesystem_path, "rb") as f: + answer = f.read() + last_modified = time.strftime( + "%a, %d %b %Y %H:%M:%S GMT", + time.gmtime(os.fstat(f.fileno()).st_mtime)) + headers = { + "Content-Type": content_type, + "Last-Modified": last_modified} + return client.OK, headers, answer diff --git a/radicale/web/internal.py b/radicale/web/internal.py index d8f078b0..a4427525 100644 --- a/radicale/web/internal.py +++ b/radicale/web/internal.py @@ -25,32 +25,10 @@ Features: """ - -import os -import time -from http import client -from typing import Mapping - import pkg_resources -from radicale import config, httputils, pathutils, types, web -from radicale.log import logger - -MIMETYPES: Mapping[str, str] = { - ".css": "text/css", - ".eot": "application/vnd.ms-fontobject", - ".gif": "image/gif", - ".html": "text/html", - ".js": "application/javascript", - ".manifest": "text/cache-manifest", - ".png": "image/png", - ".svg": "image/svg+xml", - ".ttf": "application/font-sfnt", - ".txt": "text/plain", - ".woff": "application/font-woff", - ".woff2": "font/woff2", - ".xml": "text/xml"} -FALLBACK_MIMETYPE: str = "application/octet-stream" +from radicale import config, httputils, types, web +from radicale.httputils import FALLBACK_MIMETYPE, MIMETYPES # noqa:F401 class Web(web.BaseWeb): @@ -59,34 +37,9 @@ class Web(web.BaseWeb): def __init__(self, configuration: config.Configuration) -> None: super().__init__(configuration) - self.folder = pkg_resources.resource_filename(__name__, - "internal_data") + self.folder = pkg_resources.resource_filename( + __name__, "internal_data") def get(self, environ: types.WSGIEnviron, base_prefix: str, path: str, user: str) -> types.WSGIResponse: - assert path == "/.web" or path.startswith("/.web/") - assert pathutils.sanitize_path(path) == path - try: - filesystem_path = pathutils.path_to_filesystem( - self.folder, path[len("/.web"):].strip("/")) - except ValueError as e: - logger.debug("Web content with unsafe path %r requested: %s", - path, e, exc_info=True) - return httputils.NOT_FOUND - if os.path.isdir(filesystem_path) and not path.endswith("/"): - return httputils.redirect(base_prefix + path + "/") - if os.path.isdir(filesystem_path): - filesystem_path = os.path.join(filesystem_path, "index.html") - if not os.path.isfile(filesystem_path): - return httputils.NOT_FOUND - content_type = MIMETYPES.get( - os.path.splitext(filesystem_path)[1].lower(), FALLBACK_MIMETYPE) - with open(filesystem_path, "rb") as f: - answer = f.read() - last_modified = time.strftime( - "%a, %d %b %Y %H:%M:%S GMT", - time.gmtime(os.fstat(f.fileno()).st_mtime)) - headers = { - "Content-Type": content_type, - "Last-Modified": last_modified} - return client.OK, headers, answer + return httputils.serve_folder(self.folder, base_prefix, path) From 81106fa647ef6a08d0c27b9740320d9ac7751ea8 Mon Sep 17 00:00:00 2001 From: Unrud Date: Tue, 18 Jan 2022 18:24:18 +0100 Subject: [PATCH 121/238] Update NEWS.md --- NEWS.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/NEWS.md b/NEWS.md index 2651bd88..01bae74f 100644 --- a/NEWS.md +++ b/NEWS.md @@ -3,7 +3,7 @@ ## master * Workaround for contact photo bug in InfCloud -* Redirect GET and HEAD requests to sanitized path +* Redirect GET and HEAD requests under `/.web` to sanitized path * Set `Content-Length` header for HEAD requests * Never send body for HEAD requests * Improve error messages for `from_file` rights backend From 59e4f2d59426fc2ba5d96fb3921db56b6d42c967 Mon Sep 17 00:00:00 2001 From: Unrud Date: Tue, 18 Jan 2022 21:39:37 +0100 Subject: [PATCH 122/238] Rename NEWS.md to CHANGELOG.md --- NEWS.md => CHANGELOG.md | 0 DOCUMENTATION.md | 2 +- MANIFEST.in | 2 +- setup.py | 2 +- 4 files changed, 3 insertions(+), 3 deletions(-) rename NEWS.md => CHANGELOG.md (100%) diff --git a/NEWS.md b/CHANGELOG.md similarity index 100% rename from NEWS.md rename to CHANGELOG.md diff --git a/DOCUMENTATION.md b/DOCUMENTATION.md index 127805c6..7214c1be 100644 --- a/DOCUMENTATION.md +++ b/DOCUMENTATION.md @@ -36,7 +36,7 @@ Want more? Check the [tutorials](#tutorials) and the #### What's New? Read the -[changelog on GitHub.](https://github.com/Kozea/Radicale/blob/master/NEWS.md) +[changelog on GitHub.](https://github.com/Kozea/Radicale/blob/master/CHANGELOG.md) ## Tutorials diff --git a/MANIFEST.in b/MANIFEST.in index 7925b3e0..3b23cda0 100644 --- a/MANIFEST.in +++ b/MANIFEST.in @@ -1,3 +1,3 @@ -include COPYING DOCUMENTATION.md NEWS.md README.md +include CHANGELOG.md COPYING DOCUMENTATION.md README.md include config rights include radicale.wsgi diff --git a/setup.py b/setup.py index 114da3a9..f3492186 100644 --- a/setup.py +++ b/setup.py @@ -41,7 +41,7 @@ import sys from setuptools import find_packages, setup -# When the version is updated, a new section in the NEWS.md file must be +# When the version is updated, a new section in the CHANGELOG.md file must be # added too. VERSION = "master" WEB_FILES = ["web/internal_data/css/icon.png", From 4224c60e9bdb7824c515acc5d1b86097797bc835 Mon Sep 17 00:00:00 2001 From: Unrud Date: Tue, 18 Jan 2022 22:35:49 +0100 Subject: [PATCH 123/238] Mark as deprecated --- radicale/web/internal.py | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/radicale/web/internal.py b/radicale/web/internal.py index a4427525..f21d2bcc 100644 --- a/radicale/web/internal.py +++ b/radicale/web/internal.py @@ -28,7 +28,9 @@ Features: import pkg_resources from radicale import config, httputils, types, web -from radicale.httputils import FALLBACK_MIMETYPE, MIMETYPES # noqa:F401 + +MIMETYPES = httputils.MIMETYPES # deprecated +FALLBACK_MIMETYPE = httputils.FALLBACK_MIMETYPE # deprecated class Web(web.BaseWeb): From da8475908eb26f2c6b69100463d8fa5a4dd561e6 Mon Sep 17 00:00:00 2001 From: Unrud Date: Tue, 18 Jan 2022 22:50:32 +0100 Subject: [PATCH 124/238] Change title to Changelog --- CHANGELOG.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 01bae74f..07eb1e15 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,4 +1,4 @@ -# News +# Changelog ## master From 4822807c4d0ab8863aa600354315d99eeeef1209 Mon Sep 17 00:00:00 2001 From: Unrud Date: Wed, 19 Jan 2022 00:27:56 +0100 Subject: [PATCH 125/238] Update CHANGELOG.md --- CHANGELOG.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index 07eb1e15..2818997b 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,8 @@ ## master +## 3.1.1 + * Workaround for contact photo bug in InfCloud * Redirect GET and HEAD requests under `/.web` to sanitized path * Set `Content-Length` header for HEAD requests From c96e5b6667b71174e7b5756aea726308176d3985 Mon Sep 17 00:00:00 2001 From: Unrud Date: Wed, 19 Jan 2022 19:58:05 +0100 Subject: [PATCH 126/238] Drop body for HEAD requests last --- radicale/app/__init__.py | 5 +++-- radicale/app/head.py | 2 +- 2 files changed, 4 insertions(+), 3 deletions(-) diff --git a/radicale/app/__init__.py b/radicale/app/__init__.py index aab4beb5..8ffda13b 100644 --- a/radicale/app/__init__.py +++ b/radicale/app/__init__.py @@ -117,6 +117,8 @@ class Application(ApplicationPartDelete, ApplicationPartHead, headers = [*raw_headers, ("Content-Length", str(len(answer)))] answers = [answer] start_response(status_text, headers) + if environ.get("REQUEST_METHOD") == "HEAD": + return [] return answers def _handle_request(self, environ: types.WSGIEnviron @@ -148,8 +150,7 @@ class Application(ApplicationPartDelete, ApplicationPartHead, headers["Content-Encoding"] = "gzip" headers["Content-Length"] = str(len(answer)) - if request_method != "HEAD": - answers.append(answer) + answers.append(answer) # Add extra headers set in configuration headers.update(self._extra_headers) diff --git a/radicale/app/head.py b/radicale/app/head.py index b6178f69..5166db2d 100644 --- a/radicale/app/head.py +++ b/radicale/app/head.py @@ -27,5 +27,5 @@ class ApplicationPartHead(ApplicationPartGet, ApplicationBase): def do_HEAD(self, environ: types.WSGIEnviron, base_prefix: str, path: str, user: str) -> types.WSGIResponse: """Manage HEAD request.""" - # Body is dropped in `Application._handle_request` for HEAD requests + # Body is dropped in `Application.__call__` for HEAD requests return self.do_GET(environ, base_prefix, path, user) From 0b7e9d73c93cb64c843cad160951654bb13981ae Mon Sep 17 00:00:00 2001 From: Unrud Date: Fri, 21 Jan 2022 19:56:56 +0100 Subject: [PATCH 127/238] Improve log message --- radicale/app/__init__.py | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/radicale/app/__init__.py b/radicale/app/__init__.py index 8ffda13b..fdf0d1f0 100644 --- a/radicale/app/__init__.py +++ b/radicale/app/__init__.py @@ -188,9 +188,10 @@ class Application(ApplicationPartDelete, ApplicationPartHead, # SCRIPT_NAME is already removed from PATH_INFO, according to the # WSGI specification. # Reverse proxies can overwrite SCRIPT_NAME with X-SCRIPT-NAME header - base_prefix = environ.get("HTTP_X_SCRIPT_NAME", - environ.get("SCRIPT_NAME", "")) - logger.debug("Base prefix: %r", base_prefix) + base_prefix_src = ("HTTP_X_SCRIPT_NAME" if "HTTP_X_SCRIPT_NAME" in + environ else "SCRIPT_NAME") + base_prefix = environ.get(base_prefix_src, "") + logger.debug("Base prefix (from %s): %r", base_prefix_src, base_prefix) # Sanitize request URI (a WSGI server indicates with an empty path, # that the URL targets the application root without a trailing slash) path = pathutils.sanitize_path(unsafe_path) From 7fde7d5005e6eb71f44f147c17627b3eb0703122 Mon Sep 17 00:00:00 2001 From: Unrud Date: Fri, 21 Jan 2022 19:56:56 +0100 Subject: [PATCH 128/238] Test X-Script-Name --- radicale/tests/test_base.py | 10 ++++++++++ 1 file changed, 10 insertions(+) diff --git a/radicale/tests/test_base.py b/radicale/tests/test_base.py index 1b8afd98..8c89cf43 100644 --- a/radicale/tests/test_base.py +++ b/radicale/tests/test_base.py @@ -65,6 +65,13 @@ permissions: RrWw""") SCRIPT_NAME="/radicale") assert headers.get("Location") == "/radicale/.web" + def test_root_http_x_script_name(self) -> None: + """GET request at "/" with HTTP_X_SCRIPT_NAME.""" + for path in ["", "/", "//"]: + _, headers, _ = self.request("GET", path, check=302, + HTTP_X_SCRIPT_NAME="/radicale") + assert headers.get("Location") == "/radicale/.web" + def test_sanitized_path(self) -> None: """GET request with unsanitized paths.""" for path, sane_path in [ @@ -75,6 +82,9 @@ permissions: RrWw""") _, headers, _ = self.request("GET", path, check=301, SCRIPT_NAME="/radicale") assert headers.get("Location") == "/radicale%s" % sane_path + _, headers, _ = self.request("GET", path, check=301, + HTTP_X_SCRIPT_NAME="/radicale") + assert headers.get("Location") == "/radicale%s" % sane_path def test_add_event(self) -> None: """Add an event.""" From 3763ed46c448de8a40a898a056e8a4b8c46daf27 Mon Sep 17 00:00:00 2001 From: Unrud Date: Fri, 21 Jan 2022 19:56:57 +0100 Subject: [PATCH 129/238] Error if SCRIPT_NAME ends with '/' --- radicale/app/__init__.py | 6 ++++++ radicale/tests/test_base.py | 8 ++++++++ 2 files changed, 14 insertions(+) diff --git a/radicale/app/__init__.py b/radicale/app/__init__.py index fdf0d1f0..685fb777 100644 --- a/radicale/app/__init__.py +++ b/radicale/app/__init__.py @@ -191,6 +191,12 @@ class Application(ApplicationPartDelete, ApplicationPartHead, base_prefix_src = ("HTTP_X_SCRIPT_NAME" if "HTTP_X_SCRIPT_NAME" in environ else "SCRIPT_NAME") base_prefix = environ.get(base_prefix_src, "") + if base_prefix.endswith("/"): + logger.error("Base prefix (from %s) must not end with '/': %r", + base_prefix_src, base_prefix) + if base_prefix_src == "HTTP_X_SCRIPT_NAME": + return response(*httputils.BAD_REQUEST) + return response(*httputils.INTERNAL_SERVER_ERROR) logger.debug("Base prefix (from %s): %r", base_prefix_src, base_prefix) # Sanitize request URI (a WSGI server indicates with an empty path, # that the URL targets the application root without a trailing slash) diff --git a/radicale/tests/test_base.py b/radicale/tests/test_base.py index 8c89cf43..ea01cf62 100644 --- a/radicale/tests/test_base.py +++ b/radicale/tests/test_base.py @@ -65,6 +65,10 @@ permissions: RrWw""") SCRIPT_NAME="/radicale") assert headers.get("Location") == "/radicale/.web" + def test_root_broken_script_name(self) -> None: + """GET request at "/" with SCRIPT_NAME ending with "/".""" + self.get("/", check=500, SCRIPT_NAME="/radicale/") + def test_root_http_x_script_name(self) -> None: """GET request at "/" with HTTP_X_SCRIPT_NAME.""" for path in ["", "/", "//"]: @@ -72,6 +76,10 @@ permissions: RrWw""") HTTP_X_SCRIPT_NAME="/radicale") assert headers.get("Location") == "/radicale/.web" + def test_root_broken_http_x_script_name(self) -> None: + """GET request at "/" with HTTP_X_SCRIPT_NAME ending with "/".""" + self.get("/", check=400, HTTP_X_SCRIPT_NAME="/radicale/") + def test_sanitized_path(self) -> None: """GET request with unsanitized paths.""" for path, sane_path in [ From 340582f84cec351661d5a0283c04fde7b446f950 Mon Sep 17 00:00:00 2001 From: Unrud Date: Sat, 22 Jan 2022 00:09:34 +0100 Subject: [PATCH 130/238] Update Changelog --- CHANGELOG.md | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index 2818997b..3ceeceea 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,12 @@ ## master +## 3.1.2 + +* Verify that base prefix doesn't end with '/' +* Improve base prefix log message +* Never send body for HEAD requests (again) + ## 3.1.1 * Workaround for contact photo bug in InfCloud From 17a5e5b6e0f34c8e91409f35d8f1d25e854dfd73 Mon Sep 17 00:00:00 2001 From: Unrud Date: Sat, 22 Jan 2022 00:34:38 +0100 Subject: [PATCH 131/238] Verify that base_prefix starts with '/' --- CHANGELOG.md | 2 +- radicale/app/__init__.py | 7 ++++--- radicale/tests/test_base.py | 6 ++++-- 3 files changed, 9 insertions(+), 6 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 3ceeceea..6a6f4fa5 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,7 +4,7 @@ ## 3.1.2 -* Verify that base prefix doesn't end with '/' +* Verify that base prefix starts with '/' but doesn't end with '/' * Improve base prefix log message * Never send body for HEAD requests (again) diff --git a/radicale/app/__init__.py b/radicale/app/__init__.py index 685fb777..f1233e04 100644 --- a/radicale/app/__init__.py +++ b/radicale/app/__init__.py @@ -191,9 +191,10 @@ class Application(ApplicationPartDelete, ApplicationPartHead, base_prefix_src = ("HTTP_X_SCRIPT_NAME" if "HTTP_X_SCRIPT_NAME" in environ else "SCRIPT_NAME") base_prefix = environ.get(base_prefix_src, "") - if base_prefix.endswith("/"): - logger.error("Base prefix (from %s) must not end with '/': %r", - base_prefix_src, base_prefix) + if base_prefix and (base_prefix[0] != "/" or base_prefix[-1] == "/"): + logger.error("Base prefix (from %s) must %s with '/': %r", + base_prefix_src, "not end" if base_prefix[-1] == "/" + else "start", base_prefix) if base_prefix_src == "HTTP_X_SCRIPT_NAME": return response(*httputils.BAD_REQUEST) return response(*httputils.INTERNAL_SERVER_ERROR) diff --git a/radicale/tests/test_base.py b/radicale/tests/test_base.py index ea01cf62..03e2f63a 100644 --- a/radicale/tests/test_base.py +++ b/radicale/tests/test_base.py @@ -67,7 +67,8 @@ permissions: RrWw""") def test_root_broken_script_name(self) -> None: """GET request at "/" with SCRIPT_NAME ending with "/".""" - self.get("/", check=500, SCRIPT_NAME="/radicale/") + for script_name in ["/", "/radicale/", "radicale"]: + self.get("/", check=500, SCRIPT_NAME=script_name) def test_root_http_x_script_name(self) -> None: """GET request at "/" with HTTP_X_SCRIPT_NAME.""" @@ -78,7 +79,8 @@ permissions: RrWw""") def test_root_broken_http_x_script_name(self) -> None: """GET request at "/" with HTTP_X_SCRIPT_NAME ending with "/".""" - self.get("/", check=400, HTTP_X_SCRIPT_NAME="/radicale/") + for script_name in ["/", "/radicale/", "radicale"]: + self.get("/", check=400, HTTP_X_SCRIPT_NAME=script_name) def test_sanitized_path(self) -> None: """GET request with unsanitized paths.""" From 10d2571d89e2a641a68298a035b5c5de8a235196 Mon Sep 17 00:00:00 2001 From: Unrud Date: Sat, 22 Jan 2022 00:47:01 +0100 Subject: [PATCH 132/238] Update test action badge --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 3a998bf4..98ee6602 100644 --- a/README.md +++ b/README.md @@ -1,6 +1,6 @@ # Read Me -![Test](https://github.com/Kozea/Radicale/workflows/Test/badge.svg?branch=master) +[![Test](https://github.com/Kozea/Radicale/actions/workflows/test.yml/badge.svg?branch=master)](https://github.com/Kozea/Radicale/actions/workflows/test.yml) [![Coverage Status](https://coveralls.io/repos/github/Kozea/Radicale/badge.svg?branch=master)](https://coveralls.io/github/Kozea/Radicale?branch=master) Radicale is a free and open-source CalDAV and CardDAV server. From e4cc73098a53462f85f828ba5f16eaee84005233 Mon Sep 17 00:00:00 2001 From: Unrud Date: Sat, 22 Jan 2022 18:19:41 +0100 Subject: [PATCH 133/238] =?UTF-8?q?Redirect=20=E2=80=A6/.well-known/{calda?= =?UTF-8?q?v,carddav}=20to=20/?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Closes #1200 --- radicale/app/__init__.py | 11 +++++++++-- radicale/tests/test_base.py | 21 +++++++++++++++++++-- 2 files changed, 28 insertions(+), 4 deletions(-) diff --git a/radicale/app/__init__.py b/radicale/app/__init__.py index f1233e04..18d9808a 100644 --- a/radicale/app/__init__.py +++ b/radicale/app/__init__.py @@ -209,8 +209,15 @@ class Application(ApplicationPartDelete, ApplicationPartHead, if not function: return response(*httputils.METHOD_NOT_ALLOWED) - # If "/.well-known" is not available, clients query "/" - if path == "/.well-known" or path.startswith("/.well-known/"): + # Redirect all "…/.well-known/{caldav,carddav}" paths to "/". + # This shouldn't be necessary but some clients like TbSync require it. + # Status must be MOVED PERMANENTLY using FOUND causes problems + if (path.rstrip("/").endswith("/.well-known/caldav") or + path.rstrip("/").endswith("/.well-known/carddav")): + return response(*httputils.redirect( + base_prefix + "/", client.MOVED_PERMANENTLY)) + # Return NOT FOUND for all other paths containing ".well-knwon" + if path.endswith("/.well-known") or "/.well-known/" in path: return response(*httputils.NOT_FOUND) # Ask authentication backend to check rights diff --git a/radicale/tests/test_base.py b/radicale/tests/test_base.py index 03e2f63a..f3d6fdb7 100644 --- a/radicale/tests/test_base.py +++ b/radicale/tests/test_base.py @@ -1615,14 +1615,31 @@ permissions: RrWw""") self.delete("/") self.propfind("/") + def test_well_known(self) -> None: + for path in ["/.well-known/caldav", "/.well-known/carddav"]: + for path in [path, "/foo" + path]: + _, headers, _ = self.request("GET", path, check=301) + assert headers.get("Location") == "/" + + def test_well_known_script_name(self) -> None: + for path in ["/.well-known/caldav", "/.well-known/carddav"]: + for path in [path, "/foo" + path]: + _, headers, _ = self.request( + "GET", path, check=301, SCRIPT_NAME="/radicale") + assert headers.get("Location") == "/radicale/" + + def test_well_known_not_found(self) -> None: + for path in ["/.well-known", "/.well-known/", "/.well-known/foo"]: + for path in [path, "/foo" + path]: + self.get(path, check=404) + def test_custom_headers(self) -> None: self.configure({"headers": {"test": "123"}}) # Test if header is set on success _, headers, _ = self.request("OPTIONS", "/", check=200) assert headers.get("test") == "123" # Test if header is set on failure - _, headers, _ = self.request("GET", "/.well-known/does not exist", - check=404) + _, headers, _ = self.request("GET", "/.well-known/foo", check=404) assert headers.get("test") == "123" @pytest.mark.skipif(sys.version_info < (3, 6), From 2cbbd4dc9ceba7942063bb53b54a4825dc7c0452 Mon Sep 17 00:00:00 2001 From: Unrud Date: Wed, 26 Jan 2022 21:37:46 +0100 Subject: [PATCH 134/238] Warning instead of error when base prefix ends with '/' Workaround for #1210 --- radicale/app/__init__.py | 11 +++++++---- radicale/tests/test_base.py | 20 ++++++++++++++++---- 2 files changed, 23 insertions(+), 8 deletions(-) diff --git a/radicale/app/__init__.py b/radicale/app/__init__.py index 18d9808a..6896bc70 100644 --- a/radicale/app/__init__.py +++ b/radicale/app/__init__.py @@ -191,13 +191,16 @@ class Application(ApplicationPartDelete, ApplicationPartHead, base_prefix_src = ("HTTP_X_SCRIPT_NAME" if "HTTP_X_SCRIPT_NAME" in environ else "SCRIPT_NAME") base_prefix = environ.get(base_prefix_src, "") - if base_prefix and (base_prefix[0] != "/" or base_prefix[-1] == "/"): - logger.error("Base prefix (from %s) must %s with '/': %r", - base_prefix_src, "not end" if base_prefix[-1] == "/" - else "start", base_prefix) + if base_prefix and base_prefix[0] != "/": + logger.error("Base prefix (from %s) must start with '/': %r", + base_prefix_src, base_prefix) if base_prefix_src == "HTTP_X_SCRIPT_NAME": return response(*httputils.BAD_REQUEST) return response(*httputils.INTERNAL_SERVER_ERROR) + if base_prefix.endswith("/"): + logger.warning("Base prefix (from %s) must not end with '/': %r", + base_prefix_src, base_prefix) + base_prefix = base_prefix.rstrip("/") logger.debug("Base prefix (from %s): %r", base_prefix_src, base_prefix) # Sanitize request URI (a WSGI server indicates with an empty path, # that the URL targets the application root without a trailing slash) diff --git a/radicale/tests/test_base.py b/radicale/tests/test_base.py index f3d6fdb7..f654f1cd 100644 --- a/radicale/tests/test_base.py +++ b/radicale/tests/test_base.py @@ -67,8 +67,14 @@ permissions: RrWw""") def test_root_broken_script_name(self) -> None: """GET request at "/" with SCRIPT_NAME ending with "/".""" - for script_name in ["/", "/radicale/", "radicale"]: - self.get("/", check=500, SCRIPT_NAME=script_name) + for script_name, prefix in [ + ("/", ""), ("//", ""), ("/radicale/", "/radicale"), + ("radicale", None), ("radicale//", None)]: + _, headers, _ = self.request( + "GET", "/", check=500 if prefix is None else 302, + SCRIPT_NAME=script_name) + assert (prefix is None or + headers.get("Location") == prefix + "/.web") def test_root_http_x_script_name(self) -> None: """GET request at "/" with HTTP_X_SCRIPT_NAME.""" @@ -79,8 +85,14 @@ permissions: RrWw""") def test_root_broken_http_x_script_name(self) -> None: """GET request at "/" with HTTP_X_SCRIPT_NAME ending with "/".""" - for script_name in ["/", "/radicale/", "radicale"]: - self.get("/", check=400, HTTP_X_SCRIPT_NAME=script_name) + for script_name, prefix in [ + ("/", ""), ("//", ""), ("/radicale/", "/radicale"), + ("radicale", None), ("radicale//", None)]: + _, headers, _ = self.request( + "GET", "/", check=400 if prefix is None else 302, + HTTP_X_SCRIPT_NAME=script_name) + assert (prefix is None or + headers.get("Location") == prefix + "/.web") def test_sanitized_path(self) -> None: """GET request with unsanitized paths.""" From 47f3a6d684c543ae5e40d3686e7bf23b0db5e1a2 Mon Sep 17 00:00:00 2001 From: Unrud Date: Wed, 26 Jan 2022 21:53:15 +0100 Subject: [PATCH 135/238] Update Changelog --- CHANGELOG.md | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index 6a6f4fa5..d52edb34 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,11 @@ ## master +## 3.1.3 + +* Redirect '…/.well-known/caldav' and '…/.well-known/carddav' to base prefix +* Warning instead of error when base prefix ends with '/' + ## 3.1.2 * Verify that base prefix starts with '/' but doesn't end with '/' From 45ff34f6c397f9a154d6b4acf8bfa8d13028f5da Mon Sep 17 00:00:00 2001 From: Unrud Date: Tue, 1 Feb 2022 11:28:33 +0100 Subject: [PATCH 136/238] Fallback if RENAME_EXCHANGE not supported by fs Fixes #1213 --- radicale/pathutils.py | 21 ++++++++++++--------- 1 file changed, 12 insertions(+), 9 deletions(-) diff --git a/radicale/pathutils.py b/radicale/pathutils.py index 5e87fa16..f8242380 100644 --- a/radicale/pathutils.py +++ b/radicale/pathutils.py @@ -21,6 +21,7 @@ Helper functions for working with the file system. """ +import errno import os import posixpath import sys @@ -178,19 +179,21 @@ def rename_exchange(src: str, dst: str) -> None: try: if renameat2(src_dir_fd, src_base_bytes, dst_dir_fd, dst_base_bytes, - RENAME_EXCHANGE) != 0: - errno = ctypes.get_errno() - raise OSError(errno, os.strerror(errno)) + RENAME_EXCHANGE) == 0: + return + errno_ = ctypes.get_errno() + # Fallback if RENAME_EXCHANGE not supported by filesystem + if errno_ != errno.EINVAL: + raise OSError(errno_, os.strerror(errno_)) finally: os.close(dst_dir_fd) finally: os.close(src_dir_fd) - else: - with TemporaryDirectory(prefix=".Radicale.tmp-", dir=src_dir - ) as tmp_dir: - os.rename(dst, os.path.join(tmp_dir, "interim")) - os.rename(src, dst) - os.rename(os.path.join(tmp_dir, "interim"), src) + with TemporaryDirectory(prefix=".Radicale.tmp-", dir=src_dir + ) as tmp_dir: + os.rename(dst, os.path.join(tmp_dir, "interim")) + os.rename(src, dst) + os.rename(os.path.join(tmp_dir, "interim"), src) def fsync(fd: int) -> None: From af6c6b96b98cf0fe919998f7679b1d4b75b3f931 Mon Sep 17 00:00:00 2001 From: Unrud Date: Tue, 1 Feb 2022 15:38:23 +0100 Subject: [PATCH 137/238] Actions: Display python info --- .github/workflows/test.yml | 3 +++ 1 file changed, 3 insertions(+) diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml index 8316185e..4ee664aa 100644 --- a/.github/workflows/test.yml +++ b/.github/workflows/test.yml @@ -13,6 +13,9 @@ jobs: - uses: actions/setup-python@v2 with: python-version: ${{ matrix.python-version }} + - name: Python info + run: | + python -c 'import os, sys; print("sys.version: %s\nsys.platform: %s\nos.name: %s" % (sys.version, sys.platform, os.name))' - name: Install from source run: python -m pip install --editable .[test,bcrypt] - name: Run tests From c3d22e680f2feb2fdd164ebcff4acac8ee34549f Mon Sep 17 00:00:00 2001 From: Unrud Date: Tue, 1 Feb 2022 15:47:17 +0100 Subject: [PATCH 138/238] Actions: Run on OS from test matrix --- .github/workflows/test.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml index 4ee664aa..5bb0e952 100644 --- a/.github/workflows/test.yml +++ b/.github/workflows/test.yml @@ -3,11 +3,11 @@ on: [push, pull_request] jobs: test: - runs-on: ubuntu-latest strategy: matrix: os: [ubuntu-latest, macos-latest, windows-latest] python-version: [3.6, 3.7, 3.8, 3.9, pypy3] + runs-on: ${{ matrix.os }} steps: - uses: actions/checkout@v2 - uses: actions/setup-python@v2 From b610c3214d05e092f3c5bc5494e3a46e7c51f380 Mon Sep 17 00:00:00 2001 From: Unrud Date: Tue, 1 Feb 2022 15:54:27 +0100 Subject: [PATCH 139/238] Actions: Test pypy-3.7 and pypy-3.8 --- .github/workflows/test.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml index 5bb0e952..ae403ff1 100644 --- a/.github/workflows/test.yml +++ b/.github/workflows/test.yml @@ -6,7 +6,7 @@ jobs: strategy: matrix: os: [ubuntu-latest, macos-latest, windows-latest] - python-version: [3.6, 3.7, 3.8, 3.9, pypy3] + python-version: [3.6, 3.7, 3.8, 3.9, pypy-3.7, pypy-3.8] runs-on: ${{ matrix.os }} steps: - uses: actions/checkout@v2 From 3779d749cdec221ec3249c6cc3685cd947df14e7 Mon Sep 17 00:00:00 2001 From: Unrud Date: Tue, 1 Feb 2022 15:57:25 +0100 Subject: [PATCH 140/238] Revert "Actions: Display python info" This reverts commit af6c6b96b98cf0fe919998f7679b1d4b75b3f931. --- .github/workflows/test.yml | 3 --- 1 file changed, 3 deletions(-) diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml index ae403ff1..b198f956 100644 --- a/.github/workflows/test.yml +++ b/.github/workflows/test.yml @@ -13,9 +13,6 @@ jobs: - uses: actions/setup-python@v2 with: python-version: ${{ matrix.python-version }} - - name: Python info - run: | - python -c 'import os, sys; print("sys.version: %s\nsys.platform: %s\nos.name: %s" % (sys.version, sys.platform, os.name))' - name: Install from source run: python -m pip install --editable .[test,bcrypt] - name: Run tests From 523960bc9f17ba570071e4a7c0b3f41d5d88c5f8 Mon Sep 17 00:00:00 2001 From: Unrud Date: Tue, 1 Feb 2022 16:19:51 +0100 Subject: [PATCH 141/238] Fix Mypy error --- radicale/pathutils.py | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/radicale/pathutils.py b/radicale/pathutils.py index f8242380..4bda1ae6 100644 --- a/radicale/pathutils.py +++ b/radicale/pathutils.py @@ -72,17 +72,16 @@ if sys.platform == "win32": elif os.name == "posix": import fcntl -HAVE_RENAMEAT2: bool = False if sys.platform == "linux": import ctypes RENAME_EXCHANGE: int = 2 + renameat2 = None try: renameat2 = ctypes.CDLL(None, use_errno=True).renameat2 except AttributeError: pass else: - HAVE_RENAMEAT2 = True renameat2.argtypes = [ ctypes.c_int, ctypes.c_char_p, ctypes.c_int, ctypes.c_char_p, @@ -170,7 +169,7 @@ def rename_exchange(src: str, dst: str) -> None: dst_dir = dst_dir or os.curdir if not src_base or not dst_base: raise ValueError("Invalid arguments: %r -> %r" % (src, dst)) - if HAVE_RENAMEAT2: + if sys.platform == "linux" and renameat2: src_base_bytes = os.fsencode(src_base) dst_base_bytes = os.fsencode(dst_base) src_dir_fd = os.open(src_dir, 0) From 0221fc357b698ec4e71d7a1a487bb4eb0c599bde Mon Sep 17 00:00:00 2001 From: Unrud Date: Tue, 1 Feb 2022 17:53:46 +0100 Subject: [PATCH 142/238] Use sys.platform instead of os.name mypy only recognizes sys.platform --- radicale/__main__.py | 6 +++--- radicale/pathutils.py | 9 +++------ radicale/storage/multifilesystem/base.py | 3 ++- radicale/storage/multifilesystem/lock.py | 8 ++++---- radicale/storage/multifilesystem/upload.py | 17 ++++++++--------- radicale/tests/test_server.py | 2 +- radicale/tests/test_storage.py | 9 --------- 7 files changed, 21 insertions(+), 33 deletions(-) diff --git a/radicale/__main__.py b/radicale/__main__.py index 747dc493..209348f1 100644 --- a/radicale/__main__.py +++ b/radicale/__main__.py @@ -39,11 +39,11 @@ from radicale.log import logger def run() -> None: """Run Radicale as a standalone server.""" exit_signal_numbers = [signal.SIGTERM, signal.SIGINT] - if os.name == "posix": - exit_signal_numbers.append(signal.SIGHUP) - exit_signal_numbers.append(signal.SIGQUIT) if sys.platform == "win32": exit_signal_numbers.append(signal.SIGBREAK) + else: + exit_signal_numbers.append(signal.SIGHUP) + exit_signal_numbers.append(signal.SIGQUIT) # Raise SystemExit when signal arrives to run cleanup code # (like destructors, try-finish etc.), otherwise the process exits diff --git a/radicale/pathutils.py b/radicale/pathutils.py index 4bda1ae6..56e6fa08 100644 --- a/radicale/pathutils.py +++ b/radicale/pathutils.py @@ -69,7 +69,7 @@ if sys.platform == "win32": ctypes.wintypes.DWORD, ctypes.POINTER(Overlapped)] unlock_file_ex.restype = ctypes.wintypes.BOOL -elif os.name == "posix": +else: import fcntl if sys.platform == "linux": @@ -127,16 +127,13 @@ class RwLock: except OSError as e: raise RuntimeError("Locking the storage failed: %s" % e ) from e - elif os.name == "posix": + else: _cmd = fcntl.LOCK_EX if mode == "w" else fcntl.LOCK_SH try: fcntl.flock(lock_file.fileno(), _cmd) except OSError as e: raise RuntimeError("Locking the storage failed: %s" % e ) from e - else: - raise RuntimeError("Locking the storage failed: " - "Unsupported operating system") with self._lock: if self._writer or mode == "w" and self._readers != 0: raise RuntimeError("Locking the storage failed: " @@ -196,7 +193,7 @@ def rename_exchange(src: str, dst: str) -> None: def fsync(fd: int) -> None: - if os.name == "posix" and hasattr(fcntl, "F_FULLFSYNC"): + if sys.platform != "win32" and hasattr(fcntl, "F_FULLFSYNC"): fcntl.fcntl(fd, fcntl.F_FULLFSYNC) else: os.fsync(fd) diff --git a/radicale/storage/multifilesystem/base.py b/radicale/storage/multifilesystem/base.py index 4b1fb5de..7b1b7d28 100644 --- a/radicale/storage/multifilesystem/base.py +++ b/radicale/storage/multifilesystem/base.py @@ -17,6 +17,7 @@ # along with Radicale. If not, see . import os +import sys from tempfile import TemporaryDirectory from typing import IO, AnyStr, ClassVar, Iterator, Optional, Type @@ -93,7 +94,7 @@ class StorageBase(storage.BaseStorage): """ if not self._filesystem_fsync: return - if os.name == "posix": + if sys.platform != "win32": try: fd = os.open(path, 0) try: diff --git a/radicale/storage/multifilesystem/lock.py b/radicale/storage/multifilesystem/lock.py index 803b72f6..7e814391 100644 --- a/radicale/storage/multifilesystem/lock.py +++ b/radicale/storage/multifilesystem/lock.py @@ -68,11 +68,11 @@ class StoragePartLock(StorageBase): # from sending SIGINT etc. preexec_fn = None creationflags = 0 - if os.name == "posix": + if sys.platform == "win32": + creationflags |= subprocess.CREATE_NEW_PROCESS_GROUP + else: # Process group is also used to identify child processes preexec_fn = os.setpgrp - elif sys.platform == "win32": - creationflags |= subprocess.CREATE_NEW_PROCESS_GROUP command = self._hook % { "user": shlex.quote(user or "Anonymous")} logger.debug("Running storage hook") @@ -89,7 +89,7 @@ class StoragePartLock(StorageBase): p.wait() raise finally: - if os.name == "posix": + if sys.platform != "win32": # Kill remaining children identified by process group with contextlib.suppress(OSError): os.killpg(p.pid, signal.SIGKILL) diff --git a/radicale/storage/multifilesystem/upload.py b/radicale/storage/multifilesystem/upload.py index edabeb5d..2d6cd891 100644 --- a/radicale/storage/multifilesystem/upload.py +++ b/radicale/storage/multifilesystem/upload.py @@ -16,6 +16,7 @@ # You should have received a copy of the GNU General Public License # along with Radicale. If not, see . +import errno import os import pickle import sys @@ -76,15 +77,12 @@ class CollectionPartUpload(CollectionPartGet, CollectionPartCache, raise ValueError( "Failed to store item %r in temporary collection %r: %s" % (uid, self.path, e)) from e - href_candidate_funtions = [] - if os.name == "posix" or sys.platform == "win32": - href_candidate_funtions.append( - lambda: uid if uid.lower().endswith(suffix.lower()) - else uid + suffix) - href_candidate_funtions.extend(( + href_candidate_funtions = [ + lambda: uid if uid.lower().endswith(suffix.lower()) + else uid + suffix, lambda: radicale_item.get_etag(uid).strip('"') + suffix, - lambda: radicale_item.find_available_uid(hrefs.__contains__, - suffix))) + lambda: radicale_item.find_available_uid( + hrefs.__contains__, suffix)] href = f = None while href_candidate_funtions: href = href_candidate_funtions.pop(0)() @@ -101,7 +99,8 @@ class CollectionPartUpload(CollectionPartGet, CollectionPartCache, break except OSError as e: if href_candidate_funtions and ( - os.name == "posix" and e.errno == 22 or + sys.platform != "win32" and + e.errno == errno.EINVAL or sys.platform == "win32" and e.errno == 123): continue raise diff --git a/radicale/tests/test_server.py b/radicale/tests/test_server.py index 7f64d47b..4b252e81 100644 --- a/radicale/tests/test_server.py +++ b/radicale/tests/test_server.py @@ -219,7 +219,7 @@ class TestBaseServerRequests(BaseTest): finally: p.terminate() p.wait() - if os.name == "posix": + if sys.platform != "win32": assert p.returncode == 0 def test_command_line_interface_with_bool_options(self) -> None: diff --git a/radicale/tests/test_storage.py b/radicale/tests/test_storage.py index 12fce2aa..35479e98 100644 --- a/radicale/tests/test_storage.py +++ b/radicale/tests/test_storage.py @@ -22,7 +22,6 @@ Tests for storage backends. import os import shutil -import sys from typing import ClassVar, cast import pytest @@ -100,8 +99,6 @@ class TestMultiFileSystem(BaseTest): assert answer1 == answer2 assert os.path.exists(os.path.join(cache_folder, "event1.ics")) - @pytest.mark.skipif(os.name != "posix" and sys.platform != "win32", - reason="Only supported on 'posix' and 'win32'") def test_put_whole_calendar_uids_used_as_file_names(self) -> None: """Test if UIDs are used as file names.""" _TestBaseRequests.test_put_whole_calendar( @@ -110,8 +107,6 @@ class TestMultiFileSystem(BaseTest): _, answer = self.get("/calendar.ics/%s.ics" % uid) assert "\r\nUID:%s\r\n" % uid in answer - @pytest.mark.skipif(os.name != "posix" and sys.platform != "win32", - reason="Only supported on 'posix' and 'win32'") def test_put_whole_calendar_random_uids_used_as_file_names(self) -> None: """Test if UIDs are used as file names.""" _TestBaseRequests.test_put_whole_calendar_without_uids( @@ -127,8 +122,6 @@ class TestMultiFileSystem(BaseTest): assert answer is not None assert "\r\nUID:%s\r\n" % uid in answer - @pytest.mark.skipif(os.name != "posix" and sys.platform != "win32", - reason="Only supported on 'posix' and 'win32'") def test_put_whole_addressbook_uids_used_as_file_names(self) -> None: """Test if UIDs are used as file names.""" _TestBaseRequests.test_put_whole_addressbook( @@ -137,8 +130,6 @@ class TestMultiFileSystem(BaseTest): _, answer = self.get("/contacts.vcf/%s.vcf" % uid) assert "\r\nUID:%s\r\n" % uid in answer - @pytest.mark.skipif(os.name != "posix" and sys.platform != "win32", - reason="Only supported on 'posix' and 'win32'") def test_put_whole_addressbook_random_uids_used_as_file_names( self) -> None: """Test if UIDs are used as file names.""" From 580b97fa0f62e802a42f18896498a81fdc93da1a Mon Sep 17 00:00:00 2001 From: Unrud Date: Tue, 1 Feb 2022 17:53:47 +0100 Subject: [PATCH 143/238] Remove special cases for python < 3.6 --- radicale/item/__init__.py | 9 +-------- radicale/tests/test_base.py | 4 ---- 2 files changed, 1 insertion(+), 12 deletions(-) diff --git a/radicale/item/__init__.py b/radicale/item/__init__.py index 3bce12aa..04362b71 100644 --- a/radicale/item/__init__.py +++ b/radicale/item/__init__.py @@ -28,7 +28,6 @@ import contextlib import math import os import re -import sys from datetime import datetime, timedelta from hashlib import sha256 from itertools import chain @@ -327,13 +326,7 @@ def find_time_range(vobject_item: vobject.base.Component, tag: str start = radicale_filter.DATETIME_MIN if end is None: end = radicale_filter.DATETIME_MAX - try: - return math.floor(start.timestamp()), math.ceil(end.timestamp()) - except ValueError as e: - if str(e) == ("offset must be a timedelta representing a whole " - "number of minutes") and sys.version_info < (3, 6): - raise RuntimeError("Unsupported in Python < 3.6: %s" % e) from e - raise + return math.floor(start.timestamp()), math.ceil(end.timestamp()) class Item: diff --git a/radicale/tests/test_base.py b/radicale/tests/test_base.py index f654f1cd..c0254931 100644 --- a/radicale/tests/test_base.py +++ b/radicale/tests/test_base.py @@ -22,11 +22,9 @@ Radicale tests with simple requests. import os import posixpath -import sys from typing import Any, Callable, ClassVar, Iterable, List, Optional, Tuple import defusedxml.ElementTree as DefusedET -import pytest from radicale import storage, xmlutils from radicale.tests import RESPONSES, BaseTest @@ -1654,8 +1652,6 @@ permissions: RrWw""") _, headers, _ = self.request("GET", "/.well-known/foo", check=404) assert headers.get("test") == "123" - @pytest.mark.skipif(sys.version_info < (3, 6), - reason="Unsupported in Python < 3.6") def test_timezone_seconds(self) -> None: """Verify that timezones with minutes and seconds work.""" self.mkcalendar("/calendar.ics/") From e42b46c722e7a5783eaef17b591b38905cffdc3f Mon Sep 17 00:00:00 2001 From: Unrud Date: Tue, 1 Feb 2022 19:07:54 +0100 Subject: [PATCH 144/238] Actions: Skip pypy on windows --- .github/workflows/test.yml | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml index b198f956..2e015d83 100644 --- a/.github/workflows/test.yml +++ b/.github/workflows/test.yml @@ -7,6 +7,11 @@ jobs: matrix: os: [ubuntu-latest, macos-latest, windows-latest] python-version: [3.6, 3.7, 3.8, 3.9, pypy-3.7, pypy-3.8] + exclude: + - os: windows-latest + python-version: pypy-3.7 + - os: windows-latest + python-version: pypy-3.8 runs-on: ${{ matrix.os }} steps: - uses: actions/checkout@v2 From cd5bc3590f3fd8fe5191b16d8cfc273e052a2f67 Mon Sep 17 00:00:00 2001 From: Unrud Date: Tue, 1 Feb 2022 19:14:40 +0100 Subject: [PATCH 145/238] Assume F_FULLFSYNC on darwin --- radicale/pathutils.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/radicale/pathutils.py b/radicale/pathutils.py index 56e6fa08..448817ea 100644 --- a/radicale/pathutils.py +++ b/radicale/pathutils.py @@ -193,7 +193,7 @@ def rename_exchange(src: str, dst: str) -> None: def fsync(fd: int) -> None: - if sys.platform != "win32" and hasattr(fcntl, "F_FULLFSYNC"): + if sys.platform == "darwin": fcntl.fcntl(fd, fcntl.F_FULLFSYNC) else: os.fsync(fd) From b2b4651fc413ac6770d14e64af256fc8bd7ca54c Mon Sep 17 00:00:00 2001 From: Unrud Date: Tue, 1 Feb 2022 19:35:02 +0100 Subject: [PATCH 146/238] Update Changelog --- CHANGELOG.md | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index d52edb34..86b56772 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,10 @@ ## master +* Fallback if RENAME_EXCHANGE is not supportd by the filesystem +* Assume POSIX compatibility if `sys.platform` is not `win32` +* Assume `F_FULLFSYNC` always exists if `sys.platform` is `darwin` + ## 3.1.3 * Redirect '…/.well-known/caldav' and '…/.well-known/carddav' to base prefix From 8c69bb71aaec3ed774993357aeedd1a081630f02 Mon Sep 17 00:00:00 2001 From: Unrud Date: Tue, 1 Feb 2022 19:58:01 +0100 Subject: [PATCH 147/238] Update Changelog --- CHANGELOG.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index 86b56772..a8e98c47 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,8 @@ ## master +## 3.1.4 + * Fallback if RENAME_EXCHANGE is not supportd by the filesystem * Assume POSIX compatibility if `sys.platform` is not `win32` * Assume `F_FULLFSYNC` always exists if `sys.platform` is `darwin` From 7e29d9b5c36527398d19ac318b28940df3392af8 Mon Sep 17 00:00:00 2001 From: Unrud Date: Tue, 1 Feb 2022 20:23:24 +0100 Subject: [PATCH 148/238] Revert "Assume F_FULLFSYNC on darwin" --- CHANGELOG.md | 1 - radicale/pathutils.py | 2 +- 2 files changed, 1 insertion(+), 2 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index a8e98c47..38389148 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,7 +6,6 @@ * Fallback if RENAME_EXCHANGE is not supportd by the filesystem * Assume POSIX compatibility if `sys.platform` is not `win32` -* Assume `F_FULLFSYNC` always exists if `sys.platform` is `darwin` ## 3.1.3 diff --git a/radicale/pathutils.py b/radicale/pathutils.py index 448817ea..56e6fa08 100644 --- a/radicale/pathutils.py +++ b/radicale/pathutils.py @@ -193,7 +193,7 @@ def rename_exchange(src: str, dst: str) -> None: def fsync(fd: int) -> None: - if sys.platform == "darwin": + if sys.platform != "win32" and hasattr(fcntl, "F_FULLFSYNC"): fcntl.fcntl(fd, fcntl.F_FULLFSYNC) else: os.fsync(fd) From 4d4c3bda75ad9d9a2b373bcd5a998a523d33679e Mon Sep 17 00:00:00 2001 From: Unrud Date: Thu, 3 Feb 2022 14:36:53 +0100 Subject: [PATCH 149/238] Fix F_FULLFSYNC on PyPy + Fallback if unsupported --- radicale/pathutils.py | 17 +++++++++++++---- 1 file changed, 13 insertions(+), 4 deletions(-) diff --git a/radicale/pathutils.py b/radicale/pathutils.py index 56e6fa08..ff4565e8 100644 --- a/radicale/pathutils.py +++ b/radicale/pathutils.py @@ -88,6 +88,10 @@ if sys.platform == "linux": ctypes.c_uint] renameat2.restype = ctypes.c_int +if sys.platform == "darwin": + # Definition missing in PyPy + F_FULLFSYNC: int = getattr(fcntl, "F_FULLFSYNC", 51) + class RwLock: """A readers-Writer lock that locks a file.""" @@ -193,10 +197,15 @@ def rename_exchange(src: str, dst: str) -> None: def fsync(fd: int) -> None: - if sys.platform != "win32" and hasattr(fcntl, "F_FULLFSYNC"): - fcntl.fcntl(fd, fcntl.F_FULLFSYNC) - else: - os.fsync(fd) + if sys.platform == "darwin": + try: + fcntl.fcntl(fd, F_FULLFSYNC) + return + except OSError as e: + # Fallback if F_FULLFSYNC not supported by filesystem + if e.errno != errno.EINVAL: + raise + os.fsync(fd) def strip_path(path: str) -> str: From 11dd0e93807172de8f2ca92281ea635264ce13b2 Mon Sep 17 00:00:00 2001 From: Unrud Date: Mon, 7 Feb 2022 13:38:36 +0100 Subject: [PATCH 150/238] Ignore configuration file if access denied Fixes #1215 Bug was introduced in 4c44940ec12a9178efc0cffcd5b0cc61bec3f39a --- radicale/config.py | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/radicale/config.py b/radicale/config.py index 64dc5cc5..a9b7d7f2 100644 --- a/radicale/config.py +++ b/radicale/config.py @@ -283,7 +283,8 @@ def load(paths: Optional[Iterable[Tuple[str, bool]]] = None config = {s: {o: parser[s][o] for o in parser.options(s)} for s in parser.sections()} except Exception as e: - if not ignore_if_missing or not isinstance(e, FileNotFoundError): + if not (ignore_if_missing and + isinstance(e, (FileNotFoundError, PermissionError))): raise RuntimeError("Failed to load %s: %s" % (config_source, e) ) from e config = Configuration.SOURCE_MISSING From c155e2a3511d2f709091247d171e424075d4ad3b Mon Sep 17 00:00:00 2001 From: Unrud Date: Mon, 7 Feb 2022 14:13:56 +0100 Subject: [PATCH 151/238] Use pytest<7 for tests --- setup.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/setup.py b/setup.py index f3492186..17cd7437 100644 --- a/setup.py +++ b/setup.py @@ -52,7 +52,7 @@ WEB_FILES = ["web/internal_data/css/icon.png", setup_requires = [] if {"pytest", "test", "ptr"}.intersection(sys.argv): setup_requires.append("pytest-runner") -tests_require = ["pytest-runner", "pytest", "pytest-cov", "pytest-flake8", +tests_require = ["pytest-runner", "pytest<7", "pytest-cov", "pytest-flake8", "pytest-isort", "typeguard", "waitress"] os.environ["PYTEST_ADDOPTS"] = os.environ.get("PYTEST_ADDOPTS", "") # Mypy only supports CPython From b87d1c8038dfcc7085497a2d40347c00d7a7dc12 Mon Sep 17 00:00:00 2001 From: Unrud Date: Mon, 7 Feb 2022 14:14:03 +0100 Subject: [PATCH 152/238] Test python 3.10 --- .github/workflows/test.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml index 2e015d83..adb73be9 100644 --- a/.github/workflows/test.yml +++ b/.github/workflows/test.yml @@ -6,7 +6,7 @@ jobs: strategy: matrix: os: [ubuntu-latest, macos-latest, windows-latest] - python-version: [3.6, 3.7, 3.8, 3.9, pypy-3.7, pypy-3.8] + python-version: [3.6, 3.7, 3.8, 3.9, 3.10, pypy-3.7, pypy-3.8] exclude: - os: windows-latest python-version: pypy-3.7 From 730332d68039f400d00c3e0e2aa9c14d6b954dab Mon Sep 17 00:00:00 2001 From: Unrud Date: Mon, 7 Feb 2022 14:20:50 +0100 Subject: [PATCH 153/238] Fix YAML syntax (string not number) --- .github/workflows/test.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml index adb73be9..aef95600 100644 --- a/.github/workflows/test.yml +++ b/.github/workflows/test.yml @@ -6,7 +6,7 @@ jobs: strategy: matrix: os: [ubuntu-latest, macos-latest, windows-latest] - python-version: [3.6, 3.7, 3.8, 3.9, 3.10, pypy-3.7, pypy-3.8] + python-version: ['3.6', '3.7', '3.8', '3.9', '3.10', pypy-3.7, pypy-3.8] exclude: - os: windows-latest python-version: pypy-3.7 From 129ebf7b86b4acc2307298b60724aa371a095631 Mon Sep 17 00:00:00 2001 From: Unrud Date: Mon, 7 Feb 2022 14:42:34 +0100 Subject: [PATCH 154/238] Fix typo --- CHANGELOG.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 38389148..fd6acfe7 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,7 +4,7 @@ ## 3.1.4 -* Fallback if RENAME_EXCHANGE is not supportd by the filesystem +* Fallback if RENAME_EXCHANGE is not supported by the filesystem * Assume POSIX compatibility if `sys.platform` is not `win32` ## 3.1.3 From a7c4a00eb6f9d5ac738dc92ffc810a5fee13b6d6 Mon Sep 17 00:00:00 2001 From: Unrud Date: Mon, 7 Feb 2022 14:42:50 +0100 Subject: [PATCH 155/238] Update changelog --- CHANGELOG.md | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index fd6acfe7..48e53e16 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,10 @@ ## master +* Ignore configuration file if access is denied +* Use F_FULLFSYNC with PyPy on MacOS +* Fallback if F_FULLFSYNC is not supported by the filesystem + ## 3.1.4 * Fallback if RENAME_EXCHANGE is not supported by the filesystem From 47e42a46c1bc0c74722421be6f181435615945d0 Mon Sep 17 00:00:00 2001 From: Unrud Date: Tue, 8 Feb 2022 16:46:49 +0100 Subject: [PATCH 156/238] Update changelog --- CHANGELOG.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index 48e53e16..3ad2ca76 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,8 @@ ## master +## 3.1.5 + * Ignore configuration file if access is denied * Use F_FULLFSYNC with PyPy on MacOS * Fallback if F_FULLFSYNC is not supported by the filesystem From 0baf1dc90819d4dd0a3bb01b25f10fc9158e2bb5 Mon Sep 17 00:00:00 2001 From: Unrud Date: Tue, 22 Mar 2022 17:32:51 +0100 Subject: [PATCH 157/238] Refactor DisableRedirectHandler --- radicale/tests/test_server.py | 27 ++++++--------------------- 1 file changed, 6 insertions(+), 21 deletions(-) diff --git a/radicale/tests/test_server.py b/radicale/tests/test_server.py index 4b252e81..af3cf29b 100644 --- a/radicale/tests/test_server.py +++ b/radicale/tests/test_server.py @@ -28,7 +28,8 @@ import sys import threading import time from configparser import RawConfigParser -from typing import Callable, Dict, NoReturn, Optional, Tuple, cast +from http.client import HTTPMessage +from typing import IO, Callable, Dict, Optional, Tuple, cast from urllib import request from urllib.error import HTTPError, URLError @@ -40,26 +41,10 @@ from radicale.tests.helpers import configuration_to_dict, get_file_path class DisabledRedirectHandler(request.HTTPRedirectHandler): - - # HACK: typeshed annotation are wrong for `fp` and `msg` - # (https://github.com/python/typeshed/pull/5728) - # `headers` is incompatible with `http.client.HTTPMessage` - # (https://github.com/python/typeshed/issues/5729) - def http_error_301(self, req: request.Request, fp, code: int, - msg, headers) -> NoReturn: - raise HTTPError(req.full_url, code, msg, headers, fp) - - def http_error_302(self, req: request.Request, fp, code: int, - msg, headers) -> NoReturn: - raise HTTPError(req.full_url, code, msg, headers, fp) - - def http_error_303(self, req: request.Request, fp, code: int, - msg, headers) -> NoReturn: - raise HTTPError(req.full_url, code, msg, headers, fp) - - def http_error_307(self, req: request.Request, fp, code: int, - msg, headers) -> NoReturn: - raise HTTPError(req.full_url, code, msg, headers, fp) + def redirect_request( + self, req: request.Request, fp: IO[bytes], code: int, msg: str, + headers: HTTPMessage, newurl: str) -> None: + return None class TestBaseServerRequests(BaseTest): From 3c218ecd9c581b83a7e79a4eb1db23ad9a7ed015 Mon Sep 17 00:00:00 2001 From: Unrud Date: Wed, 30 Mar 2022 22:26:02 +0200 Subject: [PATCH 158/238] Windows: Block alternate data streams --- radicale/pathutils.py | 1 + 1 file changed, 1 insertion(+) diff --git a/radicale/pathutils.py b/radicale/pathutils.py index ff4565e8..46306b2e 100644 --- a/radicale/pathutils.py +++ b/radicale/pathutils.py @@ -257,6 +257,7 @@ def is_safe_filesystem_path_component(path: str) -> bool: """ return ( bool(path) and not os.path.splitdrive(path)[0] and + (sys.platform != "win32" or ":" not in path) and # Block NTFS-ADS not os.path.split(path)[0] and path not in (os.curdir, os.pardir) and not path.startswith(".") and not path.endswith("~") and is_safe_path_component(path)) From ed8a2284a4c86f2eae0601cd7a27c29358ea0fdc Mon Sep 17 00:00:00 2001 From: Unrud Date: Wed, 30 Mar 2022 22:26:03 +0200 Subject: [PATCH 159/238] Test calendar with case-sensitive-UIDs --- .../event_multiple_case_sensitive_uids.ics | 16 ++++++++++++++++ radicale/tests/test_base.py | 7 +++++++ 2 files changed, 23 insertions(+) create mode 100644 radicale/tests/static/event_multiple_case_sensitive_uids.ics diff --git a/radicale/tests/static/event_multiple_case_sensitive_uids.ics b/radicale/tests/static/event_multiple_case_sensitive_uids.ics new file mode 100644 index 00000000..ffca585b --- /dev/null +++ b/radicale/tests/static/event_multiple_case_sensitive_uids.ics @@ -0,0 +1,16 @@ +BEGIN:VCALENDAR +PRODID:-//Mozilla.org/NONSGML Mozilla Calendar V1.1//EN +VERSION:2.0 +BEGIN:VEVENT +UID:event +SUMMARY:Event 1 +DTSTART:20130901T190000 +DTEND:20130901T200000 +END:VEVENT +BEGIN:VEVENT +UID:EVENT +SUMMARY:Event 2 +DTSTART:20130901T200000 +DTEND:20130901T210000 +END:VEVENT +END:VCALENDAR diff --git a/radicale/tests/test_base.py b/radicale/tests/test_base.py index c0254931..5ea37bfb 100644 --- a/radicale/tests/test_base.py +++ b/radicale/tests/test_base.py @@ -243,6 +243,13 @@ permissions: RrWw""") for uid2 in uids[i + 1:]: assert uid1 != uid2 + def test_put_whole_calendar_case_sensitive_uids(self) -> None: + """Create a whole calendar with case-sensitive UIDs.""" + events = get_file_content("event_multiple_case_sensitive_uids.ics") + self.put("/calendar.ics/", events) + _, answer = self.get("/calendar.ics/") + assert "\r\nUID:event\r\n" in answer and "\r\nUID:EVENT\r\n" in answer + def test_put_whole_addressbook(self) -> None: """Create and overwrite a whole addressbook.""" contacts = get_file_content("contact_multiple.vcf") From b64c9baa5f89929ab542e304cf0a32583fe0b500 Mon Sep 17 00:00:00 2001 From: Unrud Date: Wed, 30 Mar 2022 22:26:04 +0200 Subject: [PATCH 160/238] Fix upload of calendars with colliding UIDs --- radicale/storage/multifilesystem/upload.py | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/radicale/storage/multifilesystem/upload.py b/radicale/storage/multifilesystem/upload.py index 2d6cd891..c1cc3460 100644 --- a/radicale/storage/multifilesystem/upload.py +++ b/radicale/storage/multifilesystem/upload.py @@ -97,6 +97,10 @@ class CollectionPartUpload(CollectionPartGet, CollectionPartCache, self._filesystem_path, href), "w", newline="", encoding=self._encoding) break + except pathutils.CollidingPathError: + if href_candidate_funtions: + continue + raise except OSError as e: if href_candidate_funtions and ( sys.platform != "win32" and From a97093d0010e342a0f2f2e50d8ce68e7e00f258d Mon Sep 17 00:00:00 2001 From: Unrud Date: Sat, 2 Apr 2022 18:10:53 +0200 Subject: [PATCH 161/238] Check if files exist when uploading items non-atomic --- radicale/storage/multifilesystem/upload.py | 56 +++++++++------------- 1 file changed, 22 insertions(+), 34 deletions(-) diff --git a/radicale/storage/multifilesystem/upload.py b/radicale/storage/multifilesystem/upload.py index c1cc3460..306b85e5 100644 --- a/radicale/storage/multifilesystem/upload.py +++ b/radicale/storage/multifilesystem/upload.py @@ -20,7 +20,7 @@ import errno import os import pickle import sys -from typing import Iterable, Set, TextIO, cast +from typing import Iterable, Iterator, TextIO, cast import radicale.item as radicale_item from radicale import pathutils @@ -59,16 +59,23 @@ class CollectionPartUpload(CollectionPartGet, CollectionPartCache, def _upload_all_nonatomic(self, items: Iterable[radicale_item.Item], suffix: str = "") -> None: - """Upload a new set of items. + """Upload a new set of items non-atomic""" + def is_safe_free_href(href: str) -> bool: + return (pathutils.is_safe_filesystem_path_component(href) and + not os.path.lexists( + os.path.join(self._filesystem_path, href))) - This takes a list of vobject items and - uploads them nonatomic and without existence checks. + def get_safe_free_hrefs(uid: str) -> Iterator[str]: + for href in [uid if uid.lower().endswith(suffix.lower()) + else uid + suffix, + radicale_item.get_etag(uid).strip('"') + suffix]: + if is_safe_free_href(href): + yield href + yield radicale_item.find_available_uid(is_safe_free_href, suffix) - """ cache_folder = os.path.join(self._filesystem_path, ".Radicale.cache", "item") self._storage._makedirs_synced(cache_folder) - hrefs: Set[str] = set() for item in items: uid = item.uid try: @@ -77,43 +84,24 @@ class CollectionPartUpload(CollectionPartGet, CollectionPartCache, raise ValueError( "Failed to store item %r in temporary collection %r: %s" % (uid, self.path, e)) from e - href_candidate_funtions = [ - lambda: uid if uid.lower().endswith(suffix.lower()) - else uid + suffix, - lambda: radicale_item.get_etag(uid).strip('"') + suffix, - lambda: radicale_item.find_available_uid( - hrefs.__contains__, suffix)] - href = f = None - while href_candidate_funtions: - href = href_candidate_funtions.pop(0)() - if href in hrefs: - continue - if not pathutils.is_safe_filesystem_path_component(href): - if not href_candidate_funtions: - raise pathutils.UnsafePathError(href) - continue + for href in get_safe_free_hrefs(uid): try: - f = open(pathutils.path_to_filesystem( - self._filesystem_path, href), - "w", newline="", encoding=self._encoding) - break - except pathutils.CollidingPathError: - if href_candidate_funtions: - continue - raise + f = open(os.path.join(self._filesystem_path, href), + "w", newline="", encoding=self._encoding) except OSError as e: - if href_candidate_funtions and ( - sys.platform != "win32" and - e.errno == errno.EINVAL or + if (sys.platform != "win32" and e.errno == errno.EINVAL or sys.platform == "win32" and e.errno == 123): + # not a valid filename continue raise - assert href is not None and f is not None + break + else: + raise RuntimeError("No href found for item %r in temporary " + "collection %r" % (uid, self.path)) with f: f.write(item.serialize()) f.flush() self._storage._fsync(f) - hrefs.add(href) with open(os.path.join(cache_folder, href), "wb") as fb: pickle.dump(cache_content, fb) fb.flush() From 2b8f4b941984ec2ce46dd1424e93249b48fc95df Mon Sep 17 00:00:00 2001 From: Unrud Date: Mon, 4 Apr 2022 18:17:01 +0200 Subject: [PATCH 162/238] Replace pkg_resources with importlib for Python >= 3.9 Fixes #1184 --- radicale/__init__.py | 6 +-- radicale/httputils.py | 91 +++++++++++++++++++++++++----------- radicale/storage/__init__.py | 3 +- radicale/utils.py | 12 +++++ radicale/web/internal.py | 14 ++---- setup.py | 7 ++- 6 files changed, 88 insertions(+), 45 deletions(-) diff --git a/radicale/__init__.py b/radicale/__init__.py index 1f107739..870bf369 100644 --- a/radicale/__init__.py +++ b/radicale/__init__.py @@ -29,13 +29,11 @@ import os import threading from typing import Iterable, Optional, cast -import pkg_resources - -from radicale import config, log, types +from radicale import config, log, types, utils from radicale.app import Application from radicale.log import logger -VERSION: str = pkg_resources.get_distribution("radicale").version +VERSION: str = utils.package_version("radicale") _application_instance: Optional[Application] = None _application_config_path: Optional[str] = None diff --git a/radicale/httputils.py b/radicale/httputils.py index 1bf25135..8255615f 100644 --- a/radicale/httputils.py +++ b/radicale/httputils.py @@ -24,13 +24,25 @@ Helper functions for HTTP. import contextlib import os +import pathlib +import sys import time from http import client -from typing import List, Mapping, cast +from typing import List, Mapping, Union, cast from radicale import config, pathutils, types from radicale.log import logger +if sys.version_info < (3, 9): + import pkg_resources + + _TRAVERSABLE_LIKE_TYPE = pathlib.Path +else: + import importlib.abc + from importlib import resources + + _TRAVERSABLE_LIKE_TYPE = Union[importlib.abc.Traversable, pathlib.Path] + NOT_ALLOWED: types.WSGIResponse = ( client.FORBIDDEN, (("Content-Type", "text/plain"),), "Access to the requested resource forbidden.") @@ -140,36 +152,63 @@ def redirect(location: str, status: int = client.FOUND) -> types.WSGIResponse: "Redirected to %s" % location) -def serve_folder(folder: str, base_prefix: str, path: str, - path_prefix: str = "/.web", index_file: str = "index.html", - mimetypes: Mapping[str, str] = MIMETYPES, - fallback_mimetype: str = FALLBACK_MIMETYPE, - ) -> types.WSGIResponse: +def _serve_traversable( + traversable: _TRAVERSABLE_LIKE_TYPE, base_prefix: str, path: str, + path_prefix: str, index_file: str, mimetypes: Mapping[str, str], + fallback_mimetype: str) -> types.WSGIResponse: if path != path_prefix and not path.startswith(path_prefix): raise ValueError("path must start with path_prefix: %r --> %r" % (path_prefix, path)) assert pathutils.sanitize_path(path) == path - try: - filesystem_path = pathutils.path_to_filesystem( - folder, path[len(path_prefix):].strip("/")) - except ValueError as e: - logger.debug("Web content with unsafe path %r requested: %s", - path, e, exc_info=True) - return NOT_FOUND - if os.path.isdir(filesystem_path) and not path.endswith("/"): - return redirect(base_prefix + path + "/") - if os.path.isdir(filesystem_path) and index_file: - filesystem_path = os.path.join(filesystem_path, index_file) - if not os.path.isfile(filesystem_path): + parts_path = path[len(path_prefix):].strip('/') + parts = parts_path.split("/") if parts_path else [] + for part in parts: + if not pathutils.is_safe_filesystem_path_component(part): + logger.debug("Web content with unsafe path %r requested", path) + return NOT_FOUND + if (not traversable.is_dir() or + all(part != entry.name for entry in traversable.iterdir())): + return NOT_FOUND + traversable = traversable.joinpath(part) + if traversable.is_dir(): + if not path.endswith("/"): + return redirect(base_prefix + path + "/") + if not index_file: + return NOT_FOUND + traversable = traversable.joinpath(index_file) + if not traversable.is_file(): return NOT_FOUND content_type = MIMETYPES.get( - os.path.splitext(filesystem_path)[1].lower(), FALLBACK_MIMETYPE) - with open(filesystem_path, "rb") as f: - answer = f.read() - last_modified = time.strftime( + os.path.splitext(traversable.name)[1].lower(), FALLBACK_MIMETYPE) + headers = {"Content-Type": content_type} + if isinstance(traversable, pathlib.Path): + headers["Last-Modified"] = time.strftime( "%a, %d %b %Y %H:%M:%S GMT", - time.gmtime(os.fstat(f.fileno()).st_mtime)) - headers = { - "Content-Type": content_type, - "Last-Modified": last_modified} + time.gmtime(traversable.stat().st_mtime)) + answer = traversable.read_bytes() return client.OK, headers, answer + + +def serve_resource( + package: str, resource: str, base_prefix: str, path: str, + path_prefix: str = "/.web", index_file: str = "index.html", + mimetypes: Mapping[str, str] = MIMETYPES, + fallback_mimetype: str = FALLBACK_MIMETYPE) -> types.WSGIResponse: + if sys.version_info < (3, 9): + traversable = pathlib.Path( + pkg_resources.resource_filename(package, resource)) + else: + traversable = resources.files(package).joinpath(resource) + return _serve_traversable(traversable, base_prefix, path, path_prefix, + index_file, mimetypes, fallback_mimetype) + + +def serve_folder( + folder: str, base_prefix: str, path: str, + path_prefix: str = "/.web", index_file: str = "index.html", + mimetypes: Mapping[str, str] = MIMETYPES, + fallback_mimetype: str = FALLBACK_MIMETYPE) -> types.WSGIResponse: + # deprecated: use `serve_resource` instead + traversable = pathlib.Path(folder) + return _serve_traversable(traversable, base_prefix, path, path_prefix, + index_file, mimetypes, fallback_mimetype) diff --git a/radicale/storage/__init__.py b/radicale/storage/__init__.py index db6a8718..6946f59b 100644 --- a/radicale/storage/__init__.py +++ b/radicale/storage/__init__.py @@ -29,7 +29,6 @@ from hashlib import sha256 from typing import (Iterable, Iterator, Mapping, Optional, Sequence, Set, Tuple, Union, overload) -import pkg_resources import vobject from radicale import config @@ -41,7 +40,7 @@ INTERNAL_TYPES: Sequence[str] = ("multifilesystem", "multifilesystem_nolock",) CACHE_DEPS: Sequence[str] = ("radicale", "vobject", "python-dateutil",) CACHE_VERSION: bytes = "".join( - "%s=%s;" % (pkg, pkg_resources.get_distribution(pkg).version) + "%s=%s;" % (pkg, utils.package_version(pkg)) for pkg in CACHE_DEPS).encode() diff --git a/radicale/utils.py b/radicale/utils.py index 33c77354..6125792a 100644 --- a/radicale/utils.py +++ b/radicale/utils.py @@ -16,12 +16,18 @@ # You should have received a copy of the GNU General Public License # along with Radicale. If not, see . +import sys from importlib import import_module from typing import Callable, Sequence, Type, TypeVar, Union from radicale import config from radicale.log import logger +if sys.version_info < (3, 8): + import pkg_resources +else: + from importlib import metadata + _T_co = TypeVar("_T_co", covariant=True) @@ -43,3 +49,9 @@ def load_plugin(internal_types: Sequence[str], module_name: str, (module_name, module, e)) from e logger.info("%s type is %r", module_name, module) return class_(configuration) + + +def package_version(name): + if sys.version_info < (3, 8): + return pkg_resources.get_distribution(name).version + return metadata.version(name) diff --git a/radicale/web/internal.py b/radicale/web/internal.py index f21d2bcc..01516b5b 100644 --- a/radicale/web/internal.py +++ b/radicale/web/internal.py @@ -25,9 +25,7 @@ Features: """ -import pkg_resources - -from radicale import config, httputils, types, web +from radicale import httputils, types, web MIMETYPES = httputils.MIMETYPES # deprecated FALLBACK_MIMETYPE = httputils.FALLBACK_MIMETYPE # deprecated @@ -35,13 +33,7 @@ FALLBACK_MIMETYPE = httputils.FALLBACK_MIMETYPE # deprecated class Web(web.BaseWeb): - folder: str - - def __init__(self, configuration: config.Configuration) -> None: - super().__init__(configuration) - self.folder = pkg_resources.resource_filename( - __name__, "internal_data") - def get(self, environ: types.WSGIEnviron, base_prefix: str, path: str, user: str) -> types.WSGIResponse: - return httputils.serve_folder(self.folder, base_prefix, path) + return httputils.serve_resource("radicale.web", "internal_data", + base_prefix, path) diff --git a/setup.py b/setup.py index 17cd7437..1fd204e8 100644 --- a/setup.py +++ b/setup.py @@ -49,6 +49,10 @@ WEB_FILES = ["web/internal_data/css/icon.png", "web/internal_data/fn.js", "web/internal_data/index.html"] +install_requires = ["defusedxml", "passlib", "vobject>=0.9.6", + "python-dateutil>=2.7.3"] +if sys.version_info < (3, 9): + install_requires.append("setuptools") setup_requires = [] if {"pytest", "test", "ptr"}.intersection(sys.argv): setup_requires.append("pytest-runner") @@ -76,8 +80,7 @@ setup( exclude=["*.tests", "*.tests.*", "tests.*", "tests"]), package_data={"radicale": [*WEB_FILES, "py.typed"]}, entry_points={"console_scripts": ["radicale = radicale.__main__:run"]}, - install_requires=["defusedxml", "passlib", "vobject>=0.9.6", - "python-dateutil>=2.7.3", "setuptools"], + install_requires=install_requires, setup_requires=setup_requires, tests_require=tests_require, extras_require={"test": tests_require, From c14defcba87b7fb83e0556f1000706cdd21b230e Mon Sep 17 00:00:00 2001 From: Unrud Date: Thu, 14 Apr 2022 16:25:31 +0200 Subject: [PATCH 163/238] Ignore NotADirectoryError for optional config files Fixes #1234 --- radicale/config.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/radicale/config.py b/radicale/config.py index a9b7d7f2..02a0b381 100644 --- a/radicale/config.py +++ b/radicale/config.py @@ -283,8 +283,8 @@ def load(paths: Optional[Iterable[Tuple[str, bool]]] = None config = {s: {o: parser[s][o] for o in parser.options(s)} for s in parser.sections()} except Exception as e: - if not (ignore_if_missing and - isinstance(e, (FileNotFoundError, PermissionError))): + if not (ignore_if_missing and isinstance(e, ( + FileNotFoundError, NotADirectoryError, PermissionError))): raise RuntimeError("Failed to load %s: %s" % (config_source, e) ) from e config = Configuration.SOURCE_MISSING From e96277e67199301101939759d1b0a6ab71548a28 Mon Sep 17 00:00:00 2001 From: Unrud Date: Mon, 18 Apr 2022 23:00:04 +0200 Subject: [PATCH 164/238] Update changelog --- CHANGELOG.md | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index 3ad2ca76..13303e21 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,14 @@ ## master +## 3.1.6 + +* Ignore `Not a directory` error for optional config paths +* Fix upload of whole address book/calendar with UIDs that collide on + case-insensitive filesystem +* Remove runtime dependency on setuptools for Python>=3.9 +* Windows: Block ADS paths + ## 3.1.5 * Ignore configuration file if access is denied From f06af066f95243d8b589bed7b71b2f0dc4c9f1b2 Mon Sep 17 00:00:00 2001 From: Unrud Date: Wed, 20 Apr 2022 17:17:01 +0200 Subject: [PATCH 165/238] Improve error message --- radicale/item/__init__.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/radicale/item/__init__.py b/radicale/item/__init__.py index 04362b71..4a3fc22e 100644 --- a/radicale/item/__init__.py +++ b/radicale/item/__init__.py @@ -245,8 +245,8 @@ def find_available_uid(exists_fn: Callable[[str], bool], suffix: str = "" r[:8], r[8:12], r[12:16], r[16:20], r[20:], suffix) if not exists_fn(name): return name - # something is wrong with the PRNG - raise RuntimeError("No unique random sequence found") + # Something is wrong with the PRNG or `exists_fn` + raise RuntimeError("No available random UID found") def get_etag(text: str) -> str: From a5716a7d848cc5129fe82a89b37757da10de8209 Mon Sep 17 00:00:00 2001 From: Unrud Date: Wed, 20 Apr 2022 17:23:35 +0200 Subject: [PATCH 166/238] Fix random href fallback --- radicale/storage/multifilesystem/upload.py | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/radicale/storage/multifilesystem/upload.py b/radicale/storage/multifilesystem/upload.py index 306b85e5..730e4cb2 100644 --- a/radicale/storage/multifilesystem/upload.py +++ b/radicale/storage/multifilesystem/upload.py @@ -71,7 +71,8 @@ class CollectionPartUpload(CollectionPartGet, CollectionPartCache, radicale_item.get_etag(uid).strip('"') + suffix]: if is_safe_free_href(href): yield href - yield radicale_item.find_available_uid(is_safe_free_href, suffix) + yield radicale_item.find_available_uid( + lambda href: not is_safe_free_href(href), suffix) cache_folder = os.path.join(self._filesystem_path, ".Radicale.cache", "item") From 497b5141b066d266c318ea2cd021980e1b21a516 Mon Sep 17 00:00:00 2001 From: Unrud Date: Wed, 20 Apr 2022 17:54:54 +0200 Subject: [PATCH 167/238] Update changelog --- CHANGELOG.md | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index 13303e21..63ac44e0 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,10 @@ ## master +## 3.1.7 + +* Fix random href fallback + ## 3.1.6 * Ignore `Not a directory` error for optional config paths From 8caa90f4be2d94fd1d5d2b72816e90520af3bc49 Mon Sep 17 00:00:00 2001 From: christopher-besch Date: Sun, 29 May 2022 10:22:48 +0200 Subject: [PATCH 168/238] added let's encrypt certbot config --- DOCUMENTATION.md | 9 +++++++++ 1 file changed, 9 insertions(+) diff --git a/DOCUMENTATION.md b/DOCUMENTATION.md index 7214c1be..68b56f16 100644 --- a/DOCUMENTATION.md +++ b/DOCUMENTATION.md @@ -458,6 +458,15 @@ key = /path/to/server_key.pem certificate_authority = /path/to/client_cert.pem ``` +If you're using Let's Encrypt's Certbot, the configuration should look similar to this: + +```ini +[server] +ssl = True +certificate = /etc/letsencrypt/live/{Your Domain}/fullchain.pem +key = /etc/letsencrypt/live/{Your Domain}/privkey.pem +``` + Example **nginx** configuration: ```nginx From 395f53b3d5fb04f628474616bede5614170f3eb2 Mon Sep 17 00:00:00 2001 From: Christopher Besch Date: Sun, 29 May 2022 10:25:22 +0200 Subject: [PATCH 169/238] Update DOCUMENTATION.md --- DOCUMENTATION.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/DOCUMENTATION.md b/DOCUMENTATION.md index 68b56f16..fdfc2339 100644 --- a/DOCUMENTATION.md +++ b/DOCUMENTATION.md @@ -458,7 +458,7 @@ key = /path/to/server_key.pem certificate_authority = /path/to/client_cert.pem ``` -If you're using Let's Encrypt's Certbot, the configuration should look similar to this: +If you're using the Let's Encrypt's Certbot, the configuration should look similar to this: ```ini [server] From 6d8976795cecd04e53140c0cf10e6752e92e2c04 Mon Sep 17 00:00:00 2001 From: Michael Schnerring <3743342+schnerring@users.noreply.github.com> Date: Sat, 2 Jul 2022 16:54:29 +0200 Subject: [PATCH 170/238] Fix docs: default htpasswd_filename --- DOCUMENTATION.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/DOCUMENTATION.md b/DOCUMENTATION.md index 7214c1be..663ffef1 100644 --- a/DOCUMENTATION.md +++ b/DOCUMENTATION.md @@ -673,7 +673,7 @@ Default: `none` Path to the htpasswd file. -Default: +Default: `/etc/radicale/users` ##### htpasswd_encryption From 515b196fdac1177dda716252577d4bf5a68a55cc Mon Sep 17 00:00:00 2001 From: Unrud Date: Sat, 2 Jul 2022 20:37:51 +0200 Subject: [PATCH 171/238] Remove missing type --- radicale/server.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/radicale/server.py b/radicale/server.py index 459c3385..6cb4c7b4 100644 --- a/radicale/server.py +++ b/radicale/server.py @@ -206,7 +206,7 @@ class ServerHandler(wsgiref.simple_server.ServerHandler): # Don't pollute WSGI environ with OS environment os_environ: MutableMapping[str, str] = {} - def log_exception(self, exc_info: "wsgiref.handlers._exc_info") -> None: + def log_exception(self, exc_info) -> None: logger.error("An exception occurred during request: %s", exc_info[1], exc_info=exc_info) # type:ignore[arg-type] From a2ceaa41a4fc7860dc845b85c7221c3ebfa74c42 Mon Sep 17 00:00:00 2001 From: Unrud Date: Sat, 2 Jul 2022 20:37:51 +0200 Subject: [PATCH 172/238] Fix setuptools requirement if installing wheel --- setup.py | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/setup.py b/setup.py index 1fd204e8..c9c4bba8 100644 --- a/setup.py +++ b/setup.py @@ -50,9 +50,8 @@ WEB_FILES = ["web/internal_data/css/icon.png", "web/internal_data/index.html"] install_requires = ["defusedxml", "passlib", "vobject>=0.9.6", - "python-dateutil>=2.7.3"] -if sys.version_info < (3, 9): - install_requires.append("setuptools") + "python-dateutil>=2.7.3", + "setuptools; python_version<'3.9'"] setup_requires = [] if {"pytest", "test", "ptr"}.intersection(sys.argv): setup_requires.append("pytest-runner") From 413c74c27c4c0944dcca6d9a11c5935d32451546 Mon Sep 17 00:00:00 2001 From: Unrud Date: Sat, 2 Jul 2022 20:37:52 +0200 Subject: [PATCH 173/238] Remove pytest-runner --- .github/workflows/test.yml | 2 +- conftest.py | 9 +++++++++ setup.cfg | 8 +++----- setup.py | 18 ++++-------------- 4 files changed, 17 insertions(+), 20 deletions(-) create mode 100644 conftest.py diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml index aef95600..88ebec2d 100644 --- a/.github/workflows/test.yml +++ b/.github/workflows/test.yml @@ -21,7 +21,7 @@ jobs: - name: Install from source run: python -m pip install --editable .[test,bcrypt] - name: Run tests - run: python setup.py test + run: python -m pytest - name: Upload coverage to Coveralls if: github.event_name == 'push' env: diff --git a/conftest.py b/conftest.py new file mode 100644 index 00000000..17753973 --- /dev/null +++ b/conftest.py @@ -0,0 +1,9 @@ +import sys +from importlib.util import find_spec + + +def pytest_addoption(parser, pluginmanager): + # Ignore the "--mypy" argument if pytest-mypy is not installed and + # the implementation is not cpython + if sys.implementation.name != 'cpython' and not find_spec("pytest_mypy"): + parser.addoption("--mypy", action="store_true") diff --git a/setup.cfg b/setup.cfg index 35c2c8ea..06753b4f 100644 --- a/setup.cfg +++ b/setup.cfg @@ -1,12 +1,10 @@ -[aliases] -test = pytest - [bdist_wheel] python-tag = py3 [tool:pytest] -# More options are set in `setup.py` via environment variable `PYTEST_ADDOPTS` -addopts = --flake8 --isort --typeguard-packages=radicale --cov --cov-report=term --cov-report=xml -r s +# The "--mypy" argument is ignored in conftest.py if pytest-mypy is not +# installed and the implementation is not cpython +addopts = --flake8 --isort --typeguard-packages=radicale --mypy --cov --cov-report=term --cov-report=xml -r s norecursedirs = dist .cache .git build Radicale.egg-info .eggs venv [tool:isort] diff --git a/setup.py b/setup.py index c9c4bba8..3aa336f8 100644 --- a/setup.py +++ b/setup.py @@ -36,9 +36,6 @@ For further information, please visit the `Radicale Website """ -import os -import sys - from setuptools import find_packages, setup # When the version is updated, a new section in the CHANGELOG.md file must be @@ -52,16 +49,10 @@ WEB_FILES = ["web/internal_data/css/icon.png", install_requires = ["defusedxml", "passlib", "vobject>=0.9.6", "python-dateutil>=2.7.3", "setuptools; python_version<'3.9'"] -setup_requires = [] -if {"pytest", "test", "ptr"}.intersection(sys.argv): - setup_requires.append("pytest-runner") -tests_require = ["pytest-runner", "pytest<7", "pytest-cov", "pytest-flake8", - "pytest-isort", "typeguard", "waitress"] -os.environ["PYTEST_ADDOPTS"] = os.environ.get("PYTEST_ADDOPTS", "") -# Mypy only supports CPython -if sys.implementation.name == "cpython": - tests_require.extend(["pytest-mypy", "types-setuptools"]) - os.environ["PYTEST_ADDOPTS"] += " --mypy" +tests_require = ["pytest", "pytest-cov", "pytest-flake8", "pytest-isort", + "typeguard", "waitress", + "pytest-mypy; implementation_name=='cpython'", + "types-setuptools; implementation_name=='cpython'"] setup( name="Radicale", @@ -80,7 +71,6 @@ setup( package_data={"radicale": [*WEB_FILES, "py.typed"]}, entry_points={"console_scripts": ["radicale = radicale.__main__:run"]}, install_requires=install_requires, - setup_requires=setup_requires, tests_require=tests_require, extras_require={"test": tests_require, "bcrypt": ["passlib[bcrypt]", "bcrypt"]}, From 9aae5655cfde45c7b4725ba98cc0491ed385e113 Mon Sep 17 00:00:00 2001 From: Unrud Date: Sat, 2 Jul 2022 21:29:17 +0200 Subject: [PATCH 174/238] typeguard requires pytest<7 --- setup.py | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/setup.py b/setup.py index 3aa336f8..2139d174 100644 --- a/setup.py +++ b/setup.py @@ -49,7 +49,8 @@ WEB_FILES = ["web/internal_data/css/icon.png", install_requires = ["defusedxml", "passlib", "vobject>=0.9.6", "python-dateutil>=2.7.3", "setuptools; python_version<'3.9'"] -tests_require = ["pytest", "pytest-cov", "pytest-flake8", "pytest-isort", +# typeguard requires pytest<7 +tests_require = ["pytest<7", "pytest-cov", "pytest-flake8", "pytest-isort", "typeguard", "waitress", "pytest-mypy; implementation_name=='cpython'", "types-setuptools; implementation_name=='cpython'"] From f08912ace11858e74d9507f81c9058c1e509f5b6 Mon Sep 17 00:00:00 2001 From: Unrud Date: Sat, 2 Jul 2022 21:29:53 +0200 Subject: [PATCH 175/238] Remove deprecated tests_require --- setup.py | 1 - 1 file changed, 1 deletion(-) diff --git a/setup.py b/setup.py index 2139d174..cf1502b1 100644 --- a/setup.py +++ b/setup.py @@ -72,7 +72,6 @@ setup( package_data={"radicale": [*WEB_FILES, "py.typed"]}, entry_points={"console_scripts": ["radicale = radicale.__main__:run"]}, install_requires=install_requires, - tests_require=tests_require, extras_require={"test": tests_require, "bcrypt": ["passlib[bcrypt]", "bcrypt"]}, keywords=["calendar", "addressbook", "CalDAV", "CardDAV"], From abcc0c2ef62afd18e898be102d8ccdac1934b017 Mon Sep 17 00:00:00 2001 From: Unrud Date: Sat, 2 Jul 2022 23:03:19 +0200 Subject: [PATCH 176/238] License in markdown format --- COPYING | 674 --------------------------------------------------- COPYING.md | 675 ++++++++++++++++++++++++++++++++++++++++++++++++++++ MANIFEST.in | 2 +- 3 files changed, 676 insertions(+), 675 deletions(-) delete mode 100644 COPYING create mode 100644 COPYING.md diff --git a/COPYING b/COPYING deleted file mode 100644 index 94a9ed02..00000000 --- a/COPYING +++ /dev/null @@ -1,674 +0,0 @@ - GNU GENERAL PUBLIC LICENSE - Version 3, 29 June 2007 - - Copyright (C) 2007 Free Software Foundation, Inc. - Everyone is permitted to copy and distribute verbatim copies - of this license document, but changing it is not allowed. - - Preamble - - The GNU General Public License is a free, copyleft license for -software and other kinds of works. - - The licenses for most software and other practical works are designed -to take away your freedom to share and change the works. By contrast, -the GNU General Public License is intended to guarantee your freedom to -share and change all versions of a program--to make sure it remains free -software for all its users. We, the Free Software Foundation, use the -GNU General Public License for most of our software; it applies also to -any other work released this way by its authors. You can apply it to -your programs, too. - - When we speak of free software, we are referring to freedom, not -price. Our General Public Licenses are designed to make sure that you -have the freedom to distribute copies of free software (and charge for -them if you wish), that you receive source code or can get it if you -want it, that you can change the software or use pieces of it in new -free programs, and that you know you can do these things. - - To protect your rights, we need to prevent others from denying you -these rights or asking you to surrender the rights. Therefore, you have -certain responsibilities if you distribute copies of the software, or if -you modify it: responsibilities to respect the freedom of others. - - For example, if you distribute copies of such a program, whether -gratis or for a fee, you must pass on to the recipients the same -freedoms that you received. You must make sure that they, too, receive -or can get the source code. And you must show them these terms so they -know their rights. - - Developers that use the GNU GPL protect your rights with two steps: -(1) assert copyright on the software, and (2) offer you this License -giving you legal permission to copy, distribute and/or modify it. - - For the developers' and authors' protection, the GPL clearly explains -that there is no warranty for this free software. For both users' and -authors' sake, the GPL requires that modified versions be marked as -changed, so that their problems will not be attributed erroneously to -authors of previous versions. - - Some devices are designed to deny users access to install or run -modified versions of the software inside them, although the manufacturer -can do so. This is fundamentally incompatible with the aim of -protecting users' freedom to change the software. The systematic -pattern of such abuse occurs in the area of products for individuals to -use, which is precisely where it is most unacceptable. Therefore, we -have designed this version of the GPL to prohibit the practice for those -products. If such problems arise substantially in other domains, we -stand ready to extend this provision to those domains in future versions -of the GPL, as needed to protect the freedom of users. - - Finally, every program is threatened constantly by software patents. -States should not allow patents to restrict development and use of -software on general-purpose computers, but in those that do, we wish to -avoid the special danger that patents applied to a free program could -make it effectively proprietary. To prevent this, the GPL assures that -patents cannot be used to render the program non-free. - - The precise terms and conditions for copying, distribution and -modification follow. - - TERMS AND CONDITIONS - - 0. Definitions. - - "This License" refers to version 3 of the GNU General Public License. - - "Copyright" also means copyright-like laws that apply to other kinds of -works, such as semiconductor masks. - - "The Program" refers to any copyrightable work licensed under this -License. Each licensee is addressed as "you". "Licensees" and -"recipients" may be individuals or organizations. - - To "modify" a work means to copy from or adapt all or part of the work -in a fashion requiring copyright permission, other than the making of an -exact copy. The resulting work is called a "modified version" of the -earlier work or a work "based on" the earlier work. - - A "covered work" means either the unmodified Program or a work based -on the Program. - - To "propagate" a work means to do anything with it that, without -permission, would make you directly or secondarily liable for -infringement under applicable copyright law, except executing it on a -computer or modifying a private copy. Propagation includes copying, -distribution (with or without modification), making available to the -public, and in some countries other activities as well. - - To "convey" a work means any kind of propagation that enables other -parties to make or receive copies. Mere interaction with a user through -a computer network, with no transfer of a copy, is not conveying. - - An interactive user interface displays "Appropriate Legal Notices" -to the extent that it includes a convenient and prominently visible -feature that (1) displays an appropriate copyright notice, and (2) -tells the user that there is no warranty for the work (except to the -extent that warranties are provided), that licensees may convey the -work under this License, and how to view a copy of this License. If -the interface presents a list of user commands or options, such as a -menu, a prominent item in the list meets this criterion. - - 1. Source Code. - - The "source code" for a work means the preferred form of the work -for making modifications to it. "Object code" means any non-source -form of a work. - - A "Standard Interface" means an interface that either is an official -standard defined by a recognized standards body, or, in the case of -interfaces specified for a particular programming language, one that -is widely used among developers working in that language. - - The "System Libraries" of an executable work include anything, other -than the work as a whole, that (a) is included in the normal form of -packaging a Major Component, but which is not part of that Major -Component, and (b) serves only to enable use of the work with that -Major Component, or to implement a Standard Interface for which an -implementation is available to the public in source code form. A -"Major Component", in this context, means a major essential component -(kernel, window system, and so on) of the specific operating system -(if any) on which the executable work runs, or a compiler used to -produce the work, or an object code interpreter used to run it. - - The "Corresponding Source" for a work in object code form means all -the source code needed to generate, install, and (for an executable -work) run the object code and to modify the work, including scripts to -control those activities. However, it does not include the work's -System Libraries, or general-purpose tools or generally available free -programs which are used unmodified in performing those activities but -which are not part of the work. For example, Corresponding Source -includes interface definition files associated with source files for -the work, and the source code for shared libraries and dynamically -linked subprograms that the work is specifically designed to require, -such as by intimate data communication or control flow between those -subprograms and other parts of the work. - - The Corresponding Source need not include anything that users -can regenerate automatically from other parts of the Corresponding -Source. - - The Corresponding Source for a work in source code form is that -same work. - - 2. Basic Permissions. - - All rights granted under this License are granted for the term of -copyright on the Program, and are irrevocable provided the stated -conditions are met. This License explicitly affirms your unlimited -permission to run the unmodified Program. The output from running a -covered work is covered by this License only if the output, given its -content, constitutes a covered work. This License acknowledges your -rights of fair use or other equivalent, as provided by copyright law. - - You may make, run and propagate covered works that you do not -convey, without conditions so long as your license otherwise remains -in force. You may convey covered works to others for the sole purpose -of having them make modifications exclusively for you, or provide you -with facilities for running those works, provided that you comply with -the terms of this License in conveying all material for which you do -not control copyright. Those thus making or running the covered works -for you must do so exclusively on your behalf, under your direction -and control, on terms that prohibit them from making any copies of -your copyrighted material outside their relationship with you. - - Conveying under any other circumstances is permitted solely under -the conditions stated below. Sublicensing is not allowed; section 10 -makes it unnecessary. - - 3. Protecting Users' Legal Rights From Anti-Circumvention Law. - - No covered work shall be deemed part of an effective technological -measure under any applicable law fulfilling obligations under article -11 of the WIPO copyright treaty adopted on 20 December 1996, or -similar laws prohibiting or restricting circumvention of such -measures. - - When you convey a covered work, you waive any legal power to forbid -circumvention of technological measures to the extent such circumvention -is effected by exercising rights under this License with respect to -the covered work, and you disclaim any intention to limit operation or -modification of the work as a means of enforcing, against the work's -users, your or third parties' legal rights to forbid circumvention of -technological measures. - - 4. Conveying Verbatim Copies. - - You may convey verbatim copies of the Program's source code as you -receive it, in any medium, provided that you conspicuously and -appropriately publish on each copy an appropriate copyright notice; -keep intact all notices stating that this License and any -non-permissive terms added in accord with section 7 apply to the code; -keep intact all notices of the absence of any warranty; and give all -recipients a copy of this License along with the Program. - - You may charge any price or no price for each copy that you convey, -and you may offer support or warranty protection for a fee. - - 5. Conveying Modified Source Versions. - - You may convey a work based on the Program, or the modifications to -produce it from the Program, in the form of source code under the -terms of section 4, provided that you also meet all of these conditions: - - a) The work must carry prominent notices stating that you modified - it, and giving a relevant date. - - b) The work must carry prominent notices stating that it is - released under this License and any conditions added under section - 7. This requirement modifies the requirement in section 4 to - "keep intact all notices". - - c) You must license the entire work, as a whole, under this - License to anyone who comes into possession of a copy. This - License will therefore apply, along with any applicable section 7 - additional terms, to the whole of the work, and all its parts, - regardless of how they are packaged. This License gives no - permission to license the work in any other way, but it does not - invalidate such permission if you have separately received it. - - d) If the work has interactive user interfaces, each must display - Appropriate Legal Notices; however, if the Program has interactive - interfaces that do not display Appropriate Legal Notices, your - work need not make them do so. - - A compilation of a covered work with other separate and independent -works, which are not by their nature extensions of the covered work, -and which are not combined with it such as to form a larger program, -in or on a volume of a storage or distribution medium, is called an -"aggregate" if the compilation and its resulting copyright are not -used to limit the access or legal rights of the compilation's users -beyond what the individual works permit. Inclusion of a covered work -in an aggregate does not cause this License to apply to the other -parts of the aggregate. - - 6. Conveying Non-Source Forms. - - You may convey a covered work in object code form under the terms -of sections 4 and 5, provided that you also convey the -machine-readable Corresponding Source under the terms of this License, -in one of these ways: - - a) Convey the object code in, or embodied in, a physical product - (including a physical distribution medium), accompanied by the - Corresponding Source fixed on a durable physical medium - customarily used for software interchange. - - b) Convey the object code in, or embodied in, a physical product - (including a physical distribution medium), accompanied by a - written offer, valid for at least three years and valid for as - long as you offer spare parts or customer support for that product - model, to give anyone who possesses the object code either (1) a - copy of the Corresponding Source for all the software in the - product that is covered by this License, on a durable physical - medium customarily used for software interchange, for a price no - more than your reasonable cost of physically performing this - conveying of source, or (2) access to copy the - Corresponding Source from a network server at no charge. - - c) Convey individual copies of the object code with a copy of the - written offer to provide the Corresponding Source. This - alternative is allowed only occasionally and noncommercially, and - only if you received the object code with such an offer, in accord - with subsection 6b. - - d) Convey the object code by offering access from a designated - place (gratis or for a charge), and offer equivalent access to the - Corresponding Source in the same way through the same place at no - further charge. You need not require recipients to copy the - Corresponding Source along with the object code. If the place to - copy the object code is a network server, the Corresponding Source - may be on a different server (operated by you or a third party) - that supports equivalent copying facilities, provided you maintain - clear directions next to the object code saying where to find the - Corresponding Source. Regardless of what server hosts the - Corresponding Source, you remain obligated to ensure that it is - available for as long as needed to satisfy these requirements. - - e) Convey the object code using peer-to-peer transmission, provided - you inform other peers where the object code and Corresponding - Source of the work are being offered to the general public at no - charge under subsection 6d. - - A separable portion of the object code, whose source code is excluded -from the Corresponding Source as a System Library, need not be -included in conveying the object code work. - - A "User Product" is either (1) a "consumer product", which means any -tangible personal property which is normally used for personal, family, -or household purposes, or (2) anything designed or sold for incorporation -into a dwelling. In determining whether a product is a consumer product, -doubtful cases shall be resolved in favor of coverage. For a particular -product received by a particular user, "normally used" refers to a -typical or common use of that class of product, regardless of the status -of the particular user or of the way in which the particular user -actually uses, or expects or is expected to use, the product. A product -is a consumer product regardless of whether the product has substantial -commercial, industrial or non-consumer uses, unless such uses represent -the only significant mode of use of the product. - - "Installation Information" for a User Product means any methods, -procedures, authorization keys, or other information required to install -and execute modified versions of a covered work in that User Product from -a modified version of its Corresponding Source. The information must -suffice to ensure that the continued functioning of the modified object -code is in no case prevented or interfered with solely because -modification has been made. - - If you convey an object code work under this section in, or with, or -specifically for use in, a User Product, and the conveying occurs as -part of a transaction in which the right of possession and use of the -User Product is transferred to the recipient in perpetuity or for a -fixed term (regardless of how the transaction is characterized), the -Corresponding Source conveyed under this section must be accompanied -by the Installation Information. But this requirement does not apply -if neither you nor any third party retains the ability to install -modified object code on the User Product (for example, the work has -been installed in ROM). - - The requirement to provide Installation Information does not include a -requirement to continue to provide support service, warranty, or updates -for a work that has been modified or installed by the recipient, or for -the User Product in which it has been modified or installed. Access to a -network may be denied when the modification itself materially and -adversely affects the operation of the network or violates the rules and -protocols for communication across the network. - - Corresponding Source conveyed, and Installation Information provided, -in accord with this section must be in a format that is publicly -documented (and with an implementation available to the public in -source code form), and must require no special password or key for -unpacking, reading or copying. - - 7. Additional Terms. - - "Additional permissions" are terms that supplement the terms of this -License by making exceptions from one or more of its conditions. -Additional permissions that are applicable to the entire Program shall -be treated as though they were included in this License, to the extent -that they are valid under applicable law. If additional permissions -apply only to part of the Program, that part may be used separately -under those permissions, but the entire Program remains governed by -this License without regard to the additional permissions. - - When you convey a copy of a covered work, you may at your option -remove any additional permissions from that copy, or from any part of -it. (Additional permissions may be written to require their own -removal in certain cases when you modify the work.) You may place -additional permissions on material, added by you to a covered work, -for which you have or can give appropriate copyright permission. - - Notwithstanding any other provision of this License, for material you -add to a covered work, you may (if authorized by the copyright holders of -that material) supplement the terms of this License with terms: - - a) Disclaiming warranty or limiting liability differently from the - terms of sections 15 and 16 of this License; or - - b) Requiring preservation of specified reasonable legal notices or - author attributions in that material or in the Appropriate Legal - Notices displayed by works containing it; or - - c) Prohibiting misrepresentation of the origin of that material, or - requiring that modified versions of such material be marked in - reasonable ways as different from the original version; or - - d) Limiting the use for publicity purposes of names of licensors or - authors of the material; or - - e) Declining to grant rights under trademark law for use of some - trade names, trademarks, or service marks; or - - f) Requiring indemnification of licensors and authors of that - material by anyone who conveys the material (or modified versions of - it) with contractual assumptions of liability to the recipient, for - any liability that these contractual assumptions directly impose on - those licensors and authors. - - All other non-permissive additional terms are considered "further -restrictions" within the meaning of section 10. If the Program as you -received it, or any part of it, contains a notice stating that it is -governed by this License along with a term that is a further -restriction, you may remove that term. If a license document contains -a further restriction but permits relicensing or conveying under this -License, you may add to a covered work material governed by the terms -of that license document, provided that the further restriction does -not survive such relicensing or conveying. - - If you add terms to a covered work in accord with this section, you -must place, in the relevant source files, a statement of the -additional terms that apply to those files, or a notice indicating -where to find the applicable terms. - - Additional terms, permissive or non-permissive, may be stated in the -form of a separately written license, or stated as exceptions; -the above requirements apply either way. - - 8. Termination. - - You may not propagate or modify a covered work except as expressly -provided under this License. Any attempt otherwise to propagate or -modify it is void, and will automatically terminate your rights under -this License (including any patent licenses granted under the third -paragraph of section 11). - - However, if you cease all violation of this License, then your -license from a particular copyright holder is reinstated (a) -provisionally, unless and until the copyright holder explicitly and -finally terminates your license, and (b) permanently, if the copyright -holder fails to notify you of the violation by some reasonable means -prior to 60 days after the cessation. - - Moreover, your license from a particular copyright holder is -reinstated permanently if the copyright holder notifies you of the -violation by some reasonable means, this is the first time you have -received notice of violation of this License (for any work) from that -copyright holder, and you cure the violation prior to 30 days after -your receipt of the notice. - - Termination of your rights under this section does not terminate the -licenses of parties who have received copies or rights from you under -this License. If your rights have been terminated and not permanently -reinstated, you do not qualify to receive new licenses for the same -material under section 10. - - 9. Acceptance Not Required for Having Copies. - - You are not required to accept this License in order to receive or -run a copy of the Program. Ancillary propagation of a covered work -occurring solely as a consequence of using peer-to-peer transmission -to receive a copy likewise does not require acceptance. However, -nothing other than this License grants you permission to propagate or -modify any covered work. These actions infringe copyright if you do -not accept this License. Therefore, by modifying or propagating a -covered work, you indicate your acceptance of this License to do so. - - 10. Automatic Licensing of Downstream Recipients. - - Each time you convey a covered work, the recipient automatically -receives a license from the original licensors, to run, modify and -propagate that work, subject to this License. You are not responsible -for enforcing compliance by third parties with this License. - - An "entity transaction" is a transaction transferring control of an -organization, or substantially all assets of one, or subdividing an -organization, or merging organizations. If propagation of a covered -work results from an entity transaction, each party to that -transaction who receives a copy of the work also receives whatever -licenses to the work the party's predecessor in interest had or could -give under the previous paragraph, plus a right to possession of the -Corresponding Source of the work from the predecessor in interest, if -the predecessor has it or can get it with reasonable efforts. - - You may not impose any further restrictions on the exercise of the -rights granted or affirmed under this License. For example, you may -not impose a license fee, royalty, or other charge for exercise of -rights granted under this License, and you may not initiate litigation -(including a cross-claim or counterclaim in a lawsuit) alleging that -any patent claim is infringed by making, using, selling, offering for -sale, or importing the Program or any portion of it. - - 11. Patents. - - A "contributor" is a copyright holder who authorizes use under this -License of the Program or a work on which the Program is based. The -work thus licensed is called the contributor's "contributor version". - - A contributor's "essential patent claims" are all patent claims -owned or controlled by the contributor, whether already acquired or -hereafter acquired, that would be infringed by some manner, permitted -by this License, of making, using, or selling its contributor version, -but do not include claims that would be infringed only as a -consequence of further modification of the contributor version. For -purposes of this definition, "control" includes the right to grant -patent sublicenses in a manner consistent with the requirements of -this License. - - Each contributor grants you a non-exclusive, worldwide, royalty-free -patent license under the contributor's essential patent claims, to -make, use, sell, offer for sale, import and otherwise run, modify and -propagate the contents of its contributor version. - - In the following three paragraphs, a "patent license" is any express -agreement or commitment, however denominated, not to enforce a patent -(such as an express permission to practice a patent or covenant not to -sue for patent infringement). To "grant" such a patent license to a -party means to make such an agreement or commitment not to enforce a -patent against the party. - - If you convey a covered work, knowingly relying on a patent license, -and the Corresponding Source of the work is not available for anyone -to copy, free of charge and under the terms of this License, through a -publicly available network server or other readily accessible means, -then you must either (1) cause the Corresponding Source to be so -available, or (2) arrange to deprive yourself of the benefit of the -patent license for this particular work, or (3) arrange, in a manner -consistent with the requirements of this License, to extend the patent -license to downstream recipients. "Knowingly relying" means you have -actual knowledge that, but for the patent license, your conveying the -covered work in a country, or your recipient's use of the covered work -in a country, would infringe one or more identifiable patents in that -country that you have reason to believe are valid. - - If, pursuant to or in connection with a single transaction or -arrangement, you convey, or propagate by procuring conveyance of, a -covered work, and grant a patent license to some of the parties -receiving the covered work authorizing them to use, propagate, modify -or convey a specific copy of the covered work, then the patent license -you grant is automatically extended to all recipients of the covered -work and works based on it. - - A patent license is "discriminatory" if it does not include within -the scope of its coverage, prohibits the exercise of, or is -conditioned on the non-exercise of one or more of the rights that are -specifically granted under this License. You may not convey a covered -work if you are a party to an arrangement with a third party that is -in the business of distributing software, under which you make payment -to the third party based on the extent of your activity of conveying -the work, and under which the third party grants, to any of the -parties who would receive the covered work from you, a discriminatory -patent license (a) in connection with copies of the covered work -conveyed by you (or copies made from those copies), or (b) primarily -for and in connection with specific products or compilations that -contain the covered work, unless you entered into that arrangement, -or that patent license was granted, prior to 28 March 2007. - - Nothing in this License shall be construed as excluding or limiting -any implied license or other defenses to infringement that may -otherwise be available to you under applicable patent law. - - 12. No Surrender of Others' Freedom. - - If conditions are imposed on you (whether by court order, agreement or -otherwise) that contradict the conditions of this License, they do not -excuse you from the conditions of this License. If you cannot convey a -covered work so as to satisfy simultaneously your obligations under this -License and any other pertinent obligations, then as a consequence you may -not convey it at all. For example, if you agree to terms that obligate you -to collect a royalty for further conveying from those to whom you convey -the Program, the only way you could satisfy both those terms and this -License would be to refrain entirely from conveying the Program. - - 13. Use with the GNU Affero General Public License. - - Notwithstanding any other provision of this License, you have -permission to link or combine any covered work with a work licensed -under version 3 of the GNU Affero General Public License into a single -combined work, and to convey the resulting work. The terms of this -License will continue to apply to the part which is the covered work, -but the special requirements of the GNU Affero General Public License, -section 13, concerning interaction through a network will apply to the -combination as such. - - 14. Revised Versions of this License. - - The Free Software Foundation may publish revised and/or new versions of -the GNU General Public License from time to time. Such new versions will -be similar in spirit to the present version, but may differ in detail to -address new problems or concerns. - - Each version is given a distinguishing version number. If the -Program specifies that a certain numbered version of the GNU General -Public License "or any later version" applies to it, you have the -option of following the terms and conditions either of that numbered -version or of any later version published by the Free Software -Foundation. If the Program does not specify a version number of the -GNU General Public License, you may choose any version ever published -by the Free Software Foundation. - - If the Program specifies that a proxy can decide which future -versions of the GNU General Public License can be used, that proxy's -public statement of acceptance of a version permanently authorizes you -to choose that version for the Program. - - Later license versions may give you additional or different -permissions. However, no additional obligations are imposed on any -author or copyright holder as a result of your choosing to follow a -later version. - - 15. Disclaimer of Warranty. - - THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY -APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT -HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY -OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, -THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR -PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM -IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF -ALL NECESSARY SERVICING, REPAIR OR CORRECTION. - - 16. Limitation of Liability. - - IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING -WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS -THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY -GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE -USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF -DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD -PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), -EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF -SUCH DAMAGES. - - 17. Interpretation of Sections 15 and 16. - - If the disclaimer of warranty and limitation of liability provided -above cannot be given local legal effect according to their terms, -reviewing courts shall apply local law that most closely approximates -an absolute waiver of all civil liability in connection with the -Program, unless a warranty or assumption of liability accompanies a -copy of the Program in return for a fee. - - END OF TERMS AND CONDITIONS - - How to Apply These Terms to Your New Programs - - If you develop a new program, and you want it to be of the greatest -possible use to the public, the best way to achieve this is to make it -free software which everyone can redistribute and change under these terms. - - To do so, attach the following notices to the program. It is safest -to attach them to the start of each source file to most effectively -state the exclusion of warranty; and each file should have at least -the "copyright" line and a pointer to where the full notice is found. - - - Copyright (C) - - This program is free software: you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with this program. If not, see . - -Also add information on how to contact you by electronic and paper mail. - - If the program does terminal interaction, make it output a short -notice like this when it starts in an interactive mode: - - Copyright (C) - This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. - This is free software, and you are welcome to redistribute it - under certain conditions; type `show c' for details. - -The hypothetical commands `show w' and `show c' should show the appropriate -parts of the General Public License. Of course, your program's commands -might be different; for a GUI interface, you would use an "about box". - - You should also get your employer (if you work as a programmer) or school, -if any, to sign a "copyright disclaimer" for the program, if necessary. -For more information on this, and how to apply and follow the GNU GPL, see -. - - The GNU General Public License does not permit incorporating your program -into proprietary programs. If your program is a subroutine library, you -may consider it more useful to permit linking proprietary applications with -the library. If this is what you want to do, use the GNU Lesser General -Public License instead of this License. But first, please read -. diff --git a/COPYING.md b/COPYING.md new file mode 100644 index 00000000..2fb2e74d --- /dev/null +++ b/COPYING.md @@ -0,0 +1,675 @@ +### GNU GENERAL PUBLIC LICENSE + +Version 3, 29 June 2007 + +Copyright (C) 2007 Free Software Foundation, Inc. + + +Everyone is permitted to copy and distribute verbatim copies of this +license document, but changing it is not allowed. + +### Preamble + +The GNU General Public License is a free, copyleft license for +software and other kinds of works. + +The licenses for most software and other practical works are designed +to take away your freedom to share and change the works. By contrast, +the GNU General Public License is intended to guarantee your freedom +to share and change all versions of a program--to make sure it remains +free software for all its users. We, the Free Software Foundation, use +the GNU General Public License for most of our software; it applies +also to any other work released this way by its authors. You can apply +it to your programs, too. + +When we speak of free software, we are referring to freedom, not +price. Our General Public Licenses are designed to make sure that you +have the freedom to distribute copies of free software (and charge for +them if you wish), that you receive source code or can get it if you +want it, that you can change the software or use pieces of it in new +free programs, and that you know you can do these things. + +To protect your rights, we need to prevent others from denying you +these rights or asking you to surrender the rights. Therefore, you +have certain responsibilities if you distribute copies of the +software, or if you modify it: responsibilities to respect the freedom +of others. + +For example, if you distribute copies of such a program, whether +gratis or for a fee, you must pass on to the recipients the same +freedoms that you received. You must make sure that they, too, receive +or can get the source code. And you must show them these terms so they +know their rights. + +Developers that use the GNU GPL protect your rights with two steps: +(1) assert copyright on the software, and (2) offer you this License +giving you legal permission to copy, distribute and/or modify it. + +For the developers' and authors' protection, the GPL clearly explains +that there is no warranty for this free software. For both users' and +authors' sake, the GPL requires that modified versions be marked as +changed, so that their problems will not be attributed erroneously to +authors of previous versions. + +Some devices are designed to deny users access to install or run +modified versions of the software inside them, although the +manufacturer can do so. This is fundamentally incompatible with the +aim of protecting users' freedom to change the software. The +systematic pattern of such abuse occurs in the area of products for +individuals to use, which is precisely where it is most unacceptable. +Therefore, we have designed this version of the GPL to prohibit the +practice for those products. If such problems arise substantially in +other domains, we stand ready to extend this provision to those +domains in future versions of the GPL, as needed to protect the +freedom of users. + +Finally, every program is threatened constantly by software patents. +States should not allow patents to restrict development and use of +software on general-purpose computers, but in those that do, we wish +to avoid the special danger that patents applied to a free program +could make it effectively proprietary. To prevent this, the GPL +assures that patents cannot be used to render the program non-free. + +The precise terms and conditions for copying, distribution and +modification follow. + +### TERMS AND CONDITIONS + +#### 0. Definitions. + +"This License" refers to version 3 of the GNU General Public License. + +"Copyright" also means copyright-like laws that apply to other kinds +of works, such as semiconductor masks. + +"The Program" refers to any copyrightable work licensed under this +License. Each licensee is addressed as "you". "Licensees" and +"recipients" may be individuals or organizations. + +To "modify" a work means to copy from or adapt all or part of the work +in a fashion requiring copyright permission, other than the making of +an exact copy. The resulting work is called a "modified version" of +the earlier work or a work "based on" the earlier work. + +A "covered work" means either the unmodified Program or a work based +on the Program. + +To "propagate" a work means to do anything with it that, without +permission, would make you directly or secondarily liable for +infringement under applicable copyright law, except executing it on a +computer or modifying a private copy. Propagation includes copying, +distribution (with or without modification), making available to the +public, and in some countries other activities as well. + +To "convey" a work means any kind of propagation that enables other +parties to make or receive copies. Mere interaction with a user +through a computer network, with no transfer of a copy, is not +conveying. + +An interactive user interface displays "Appropriate Legal Notices" to +the extent that it includes a convenient and prominently visible +feature that (1) displays an appropriate copyright notice, and (2) +tells the user that there is no warranty for the work (except to the +extent that warranties are provided), that licensees may convey the +work under this License, and how to view a copy of this License. If +the interface presents a list of user commands or options, such as a +menu, a prominent item in the list meets this criterion. + +#### 1. Source Code. + +The "source code" for a work means the preferred form of the work for +making modifications to it. "Object code" means any non-source form of +a work. + +A "Standard Interface" means an interface that either is an official +standard defined by a recognized standards body, or, in the case of +interfaces specified for a particular programming language, one that +is widely used among developers working in that language. + +The "System Libraries" of an executable work include anything, other +than the work as a whole, that (a) is included in the normal form of +packaging a Major Component, but which is not part of that Major +Component, and (b) serves only to enable use of the work with that +Major Component, or to implement a Standard Interface for which an +implementation is available to the public in source code form. A +"Major Component", in this context, means a major essential component +(kernel, window system, and so on) of the specific operating system +(if any) on which the executable work runs, or a compiler used to +produce the work, or an object code interpreter used to run it. + +The "Corresponding Source" for a work in object code form means all +the source code needed to generate, install, and (for an executable +work) run the object code and to modify the work, including scripts to +control those activities. However, it does not include the work's +System Libraries, or general-purpose tools or generally available free +programs which are used unmodified in performing those activities but +which are not part of the work. For example, Corresponding Source +includes interface definition files associated with source files for +the work, and the source code for shared libraries and dynamically +linked subprograms that the work is specifically designed to require, +such as by intimate data communication or control flow between those +subprograms and other parts of the work. + +The Corresponding Source need not include anything that users can +regenerate automatically from other parts of the Corresponding Source. + +The Corresponding Source for a work in source code form is that same +work. + +#### 2. Basic Permissions. + +All rights granted under this License are granted for the term of +copyright on the Program, and are irrevocable provided the stated +conditions are met. This License explicitly affirms your unlimited +permission to run the unmodified Program. The output from running a +covered work is covered by this License only if the output, given its +content, constitutes a covered work. This License acknowledges your +rights of fair use or other equivalent, as provided by copyright law. + +You may make, run and propagate covered works that you do not convey, +without conditions so long as your license otherwise remains in force. +You may convey covered works to others for the sole purpose of having +them make modifications exclusively for you, or provide you with +facilities for running those works, provided that you comply with the +terms of this License in conveying all material for which you do not +control copyright. Those thus making or running the covered works for +you must do so exclusively on your behalf, under your direction and +control, on terms that prohibit them from making any copies of your +copyrighted material outside their relationship with you. + +Conveying under any other circumstances is permitted solely under the +conditions stated below. Sublicensing is not allowed; section 10 makes +it unnecessary. + +#### 3. Protecting Users' Legal Rights From Anti-Circumvention Law. + +No covered work shall be deemed part of an effective technological +measure under any applicable law fulfilling obligations under article +11 of the WIPO copyright treaty adopted on 20 December 1996, or +similar laws prohibiting or restricting circumvention of such +measures. + +When you convey a covered work, you waive any legal power to forbid +circumvention of technological measures to the extent such +circumvention is effected by exercising rights under this License with +respect to the covered work, and you disclaim any intention to limit +operation or modification of the work as a means of enforcing, against +the work's users, your or third parties' legal rights to forbid +circumvention of technological measures. + +#### 4. Conveying Verbatim Copies. + +You may convey verbatim copies of the Program's source code as you +receive it, in any medium, provided that you conspicuously and +appropriately publish on each copy an appropriate copyright notice; +keep intact all notices stating that this License and any +non-permissive terms added in accord with section 7 apply to the code; +keep intact all notices of the absence of any warranty; and give all +recipients a copy of this License along with the Program. + +You may charge any price or no price for each copy that you convey, +and you may offer support or warranty protection for a fee. + +#### 5. Conveying Modified Source Versions. + +You may convey a work based on the Program, or the modifications to +produce it from the Program, in the form of source code under the +terms of section 4, provided that you also meet all of these +conditions: + +- a) The work must carry prominent notices stating that you modified + it, and giving a relevant date. +- b) The work must carry prominent notices stating that it is + released under this License and any conditions added under + section 7. This requirement modifies the requirement in section 4 + to "keep intact all notices". +- c) You must license the entire work, as a whole, under this + License to anyone who comes into possession of a copy. This + License will therefore apply, along with any applicable section 7 + additional terms, to the whole of the work, and all its parts, + regardless of how they are packaged. This License gives no + permission to license the work in any other way, but it does not + invalidate such permission if you have separately received it. +- d) If the work has interactive user interfaces, each must display + Appropriate Legal Notices; however, if the Program has interactive + interfaces that do not display Appropriate Legal Notices, your + work need not make them do so. + +A compilation of a covered work with other separate and independent +works, which are not by their nature extensions of the covered work, +and which are not combined with it such as to form a larger program, +in or on a volume of a storage or distribution medium, is called an +"aggregate" if the compilation and its resulting copyright are not +used to limit the access or legal rights of the compilation's users +beyond what the individual works permit. Inclusion of a covered work +in an aggregate does not cause this License to apply to the other +parts of the aggregate. + +#### 6. Conveying Non-Source Forms. + +You may convey a covered work in object code form under the terms of +sections 4 and 5, provided that you also convey the machine-readable +Corresponding Source under the terms of this License, in one of these +ways: + +- a) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by the + Corresponding Source fixed on a durable physical medium + customarily used for software interchange. +- b) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by a + written offer, valid for at least three years and valid for as + long as you offer spare parts or customer support for that product + model, to give anyone who possesses the object code either (1) a + copy of the Corresponding Source for all the software in the + product that is covered by this License, on a durable physical + medium customarily used for software interchange, for a price no + more than your reasonable cost of physically performing this + conveying of source, or (2) access to copy the Corresponding + Source from a network server at no charge. +- c) Convey individual copies of the object code with a copy of the + written offer to provide the Corresponding Source. This + alternative is allowed only occasionally and noncommercially, and + only if you received the object code with such an offer, in accord + with subsection 6b. +- d) Convey the object code by offering access from a designated + place (gratis or for a charge), and offer equivalent access to the + Corresponding Source in the same way through the same place at no + further charge. You need not require recipients to copy the + Corresponding Source along with the object code. If the place to + copy the object code is a network server, the Corresponding Source + may be on a different server (operated by you or a third party) + that supports equivalent copying facilities, provided you maintain + clear directions next to the object code saying where to find the + Corresponding Source. Regardless of what server hosts the + Corresponding Source, you remain obligated to ensure that it is + available for as long as needed to satisfy these requirements. +- e) Convey the object code using peer-to-peer transmission, + provided you inform other peers where the object code and + Corresponding Source of the work are being offered to the general + public at no charge under subsection 6d. + +A separable portion of the object code, whose source code is excluded +from the Corresponding Source as a System Library, need not be +included in conveying the object code work. + +A "User Product" is either (1) a "consumer product", which means any +tangible personal property which is normally used for personal, +family, or household purposes, or (2) anything designed or sold for +incorporation into a dwelling. In determining whether a product is a +consumer product, doubtful cases shall be resolved in favor of +coverage. For a particular product received by a particular user, +"normally used" refers to a typical or common use of that class of +product, regardless of the status of the particular user or of the way +in which the particular user actually uses, or expects or is expected +to use, the product. A product is a consumer product regardless of +whether the product has substantial commercial, industrial or +non-consumer uses, unless such uses represent the only significant +mode of use of the product. + +"Installation Information" for a User Product means any methods, +procedures, authorization keys, or other information required to +install and execute modified versions of a covered work in that User +Product from a modified version of its Corresponding Source. The +information must suffice to ensure that the continued functioning of +the modified object code is in no case prevented or interfered with +solely because modification has been made. + +If you convey an object code work under this section in, or with, or +specifically for use in, a User Product, and the conveying occurs as +part of a transaction in which the right of possession and use of the +User Product is transferred to the recipient in perpetuity or for a +fixed term (regardless of how the transaction is characterized), the +Corresponding Source conveyed under this section must be accompanied +by the Installation Information. But this requirement does not apply +if neither you nor any third party retains the ability to install +modified object code on the User Product (for example, the work has +been installed in ROM). + +The requirement to provide Installation Information does not include a +requirement to continue to provide support service, warranty, or +updates for a work that has been modified or installed by the +recipient, or for the User Product in which it has been modified or +installed. Access to a network may be denied when the modification +itself materially and adversely affects the operation of the network +or violates the rules and protocols for communication across the +network. + +Corresponding Source conveyed, and Installation Information provided, +in accord with this section must be in a format that is publicly +documented (and with an implementation available to the public in +source code form), and must require no special password or key for +unpacking, reading or copying. + +#### 7. Additional Terms. + +"Additional permissions" are terms that supplement the terms of this +License by making exceptions from one or more of its conditions. +Additional permissions that are applicable to the entire Program shall +be treated as though they were included in this License, to the extent +that they are valid under applicable law. If additional permissions +apply only to part of the Program, that part may be used separately +under those permissions, but the entire Program remains governed by +this License without regard to the additional permissions. + +When you convey a copy of a covered work, you may at your option +remove any additional permissions from that copy, or from any part of +it. (Additional permissions may be written to require their own +removal in certain cases when you modify the work.) You may place +additional permissions on material, added by you to a covered work, +for which you have or can give appropriate copyright permission. + +Notwithstanding any other provision of this License, for material you +add to a covered work, you may (if authorized by the copyright holders +of that material) supplement the terms of this License with terms: + +- a) Disclaiming warranty or limiting liability differently from the + terms of sections 15 and 16 of this License; or +- b) Requiring preservation of specified reasonable legal notices or + author attributions in that material or in the Appropriate Legal + Notices displayed by works containing it; or +- c) Prohibiting misrepresentation of the origin of that material, + or requiring that modified versions of such material be marked in + reasonable ways as different from the original version; or +- d) Limiting the use for publicity purposes of names of licensors + or authors of the material; or +- e) Declining to grant rights under trademark law for use of some + trade names, trademarks, or service marks; or +- f) Requiring indemnification of licensors and authors of that + material by anyone who conveys the material (or modified versions + of it) with contractual assumptions of liability to the recipient, + for any liability that these contractual assumptions directly + impose on those licensors and authors. + +All other non-permissive additional terms are considered "further +restrictions" within the meaning of section 10. If the Program as you +received it, or any part of it, contains a notice stating that it is +governed by this License along with a term that is a further +restriction, you may remove that term. If a license document contains +a further restriction but permits relicensing or conveying under this +License, you may add to a covered work material governed by the terms +of that license document, provided that the further restriction does +not survive such relicensing or conveying. + +If you add terms to a covered work in accord with this section, you +must place, in the relevant source files, a statement of the +additional terms that apply to those files, or a notice indicating +where to find the applicable terms. + +Additional terms, permissive or non-permissive, may be stated in the +form of a separately written license, or stated as exceptions; the +above requirements apply either way. + +#### 8. Termination. + +You may not propagate or modify a covered work except as expressly +provided under this License. Any attempt otherwise to propagate or +modify it is void, and will automatically terminate your rights under +this License (including any patent licenses granted under the third +paragraph of section 11). + +However, if you cease all violation of this License, then your license +from a particular copyright holder is reinstated (a) provisionally, +unless and until the copyright holder explicitly and finally +terminates your license, and (b) permanently, if the copyright holder +fails to notify you of the violation by some reasonable means prior to +60 days after the cessation. + +Moreover, your license from a particular copyright holder is +reinstated permanently if the copyright holder notifies you of the +violation by some reasonable means, this is the first time you have +received notice of violation of this License (for any work) from that +copyright holder, and you cure the violation prior to 30 days after +your receipt of the notice. + +Termination of your rights under this section does not terminate the +licenses of parties who have received copies or rights from you under +this License. If your rights have been terminated and not permanently +reinstated, you do not qualify to receive new licenses for the same +material under section 10. + +#### 9. Acceptance Not Required for Having Copies. + +You are not required to accept this License in order to receive or run +a copy of the Program. Ancillary propagation of a covered work +occurring solely as a consequence of using peer-to-peer transmission +to receive a copy likewise does not require acceptance. However, +nothing other than this License grants you permission to propagate or +modify any covered work. These actions infringe copyright if you do +not accept this License. Therefore, by modifying or propagating a +covered work, you indicate your acceptance of this License to do so. + +#### 10. Automatic Licensing of Downstream Recipients. + +Each time you convey a covered work, the recipient automatically +receives a license from the original licensors, to run, modify and +propagate that work, subject to this License. You are not responsible +for enforcing compliance by third parties with this License. + +An "entity transaction" is a transaction transferring control of an +organization, or substantially all assets of one, or subdividing an +organization, or merging organizations. If propagation of a covered +work results from an entity transaction, each party to that +transaction who receives a copy of the work also receives whatever +licenses to the work the party's predecessor in interest had or could +give under the previous paragraph, plus a right to possession of the +Corresponding Source of the work from the predecessor in interest, if +the predecessor has it or can get it with reasonable efforts. + +You may not impose any further restrictions on the exercise of the +rights granted or affirmed under this License. For example, you may +not impose a license fee, royalty, or other charge for exercise of +rights granted under this License, and you may not initiate litigation +(including a cross-claim or counterclaim in a lawsuit) alleging that +any patent claim is infringed by making, using, selling, offering for +sale, or importing the Program or any portion of it. + +#### 11. Patents. + +A "contributor" is a copyright holder who authorizes use under this +License of the Program or a work on which the Program is based. The +work thus licensed is called the contributor's "contributor version". + +A contributor's "essential patent claims" are all patent claims owned +or controlled by the contributor, whether already acquired or +hereafter acquired, that would be infringed by some manner, permitted +by this License, of making, using, or selling its contributor version, +but do not include claims that would be infringed only as a +consequence of further modification of the contributor version. For +purposes of this definition, "control" includes the right to grant +patent sublicenses in a manner consistent with the requirements of +this License. + +Each contributor grants you a non-exclusive, worldwide, royalty-free +patent license under the contributor's essential patent claims, to +make, use, sell, offer for sale, import and otherwise run, modify and +propagate the contents of its contributor version. + +In the following three paragraphs, a "patent license" is any express +agreement or commitment, however denominated, not to enforce a patent +(such as an express permission to practice a patent or covenant not to +sue for patent infringement). To "grant" such a patent license to a +party means to make such an agreement or commitment not to enforce a +patent against the party. + +If you convey a covered work, knowingly relying on a patent license, +and the Corresponding Source of the work is not available for anyone +to copy, free of charge and under the terms of this License, through a +publicly available network server or other readily accessible means, +then you must either (1) cause the Corresponding Source to be so +available, or (2) arrange to deprive yourself of the benefit of the +patent license for this particular work, or (3) arrange, in a manner +consistent with the requirements of this License, to extend the patent +license to downstream recipients. "Knowingly relying" means you have +actual knowledge that, but for the patent license, your conveying the +covered work in a country, or your recipient's use of the covered work +in a country, would infringe one or more identifiable patents in that +country that you have reason to believe are valid. + +If, pursuant to or in connection with a single transaction or +arrangement, you convey, or propagate by procuring conveyance of, a +covered work, and grant a patent license to some of the parties +receiving the covered work authorizing them to use, propagate, modify +or convey a specific copy of the covered work, then the patent license +you grant is automatically extended to all recipients of the covered +work and works based on it. + +A patent license is "discriminatory" if it does not include within the +scope of its coverage, prohibits the exercise of, or is conditioned on +the non-exercise of one or more of the rights that are specifically +granted under this License. You may not convey a covered work if you +are a party to an arrangement with a third party that is in the +business of distributing software, under which you make payment to the +third party based on the extent of your activity of conveying the +work, and under which the third party grants, to any of the parties +who would receive the covered work from you, a discriminatory patent +license (a) in connection with copies of the covered work conveyed by +you (or copies made from those copies), or (b) primarily for and in +connection with specific products or compilations that contain the +covered work, unless you entered into that arrangement, or that patent +license was granted, prior to 28 March 2007. + +Nothing in this License shall be construed as excluding or limiting +any implied license or other defenses to infringement that may +otherwise be available to you under applicable patent law. + +#### 12. No Surrender of Others' Freedom. + +If conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot convey a +covered work so as to satisfy simultaneously your obligations under +this License and any other pertinent obligations, then as a +consequence you may not convey it at all. For example, if you agree to +terms that obligate you to collect a royalty for further conveying +from those to whom you convey the Program, the only way you could +satisfy both those terms and this License would be to refrain entirely +from conveying the Program. + +#### 13. Use with the GNU Affero General Public License. + +Notwithstanding any other provision of this License, you have +permission to link or combine any covered work with a work licensed +under version 3 of the GNU Affero General Public License into a single +combined work, and to convey the resulting work. The terms of this +License will continue to apply to the part which is the covered work, +but the special requirements of the GNU Affero General Public License, +section 13, concerning interaction through a network will apply to the +combination as such. + +#### 14. Revised Versions of this License. + +The Free Software Foundation may publish revised and/or new versions +of the GNU General Public License from time to time. Such new versions +will be similar in spirit to the present version, but may differ in +detail to address new problems or concerns. + +Each version is given a distinguishing version number. If the Program +specifies that a certain numbered version of the GNU General Public +License "or any later version" applies to it, you have the option of +following the terms and conditions either of that numbered version or +of any later version published by the Free Software Foundation. If the +Program does not specify a version number of the GNU General Public +License, you may choose any version ever published by the Free +Software Foundation. + +If the Program specifies that a proxy can decide which future versions +of the GNU General Public License can be used, that proxy's public +statement of acceptance of a version permanently authorizes you to +choose that version for the Program. + +Later license versions may give you additional or different +permissions. However, no additional obligations are imposed on any +author or copyright holder as a result of your choosing to follow a +later version. + +#### 15. Disclaimer of Warranty. + +THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY +APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT +HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT +WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT +LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND +PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE +DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR +CORRECTION. + +#### 16. Limitation of Liability. + +IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING +WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR +CONVEYS THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, +INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES +ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT +NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR +LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM +TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER +PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. + +#### 17. Interpretation of Sections 15 and 16. + +If the disclaimer of warranty and limitation of liability provided +above cannot be given local legal effect according to their terms, +reviewing courts shall apply local law that most closely approximates +an absolute waiver of all civil liability in connection with the +Program, unless a warranty or assumption of liability accompanies a +copy of the Program in return for a fee. + +END OF TERMS AND CONDITIONS + +### How to Apply These Terms to Your New Programs + +If you develop a new program, and you want it to be of the greatest +possible use to the public, the best way to achieve this is to make it +free software which everyone can redistribute and change under these +terms. + +To do so, attach the following notices to the program. It is safest to +attach them to the start of each source file to most effectively state +the exclusion of warranty; and each file should have at least the +"copyright" line and a pointer to where the full notice is found. + + + Copyright (C) + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see . + +Also add information on how to contact you by electronic and paper +mail. + +If the program does terminal interaction, make it output a short +notice like this when it starts in an interactive mode: + + Copyright (C) + This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. + This is free software, and you are welcome to redistribute it + under certain conditions; type `show c' for details. + +The hypothetical commands \`show w' and \`show c' should show the +appropriate parts of the General Public License. Of course, your +program's commands might be different; for a GUI interface, you would +use an "about box". + +You should also get your employer (if you work as a programmer) or +school, if any, to sign a "copyright disclaimer" for the program, if +necessary. For more information on this, and how to apply and follow +the GNU GPL, see . + +The GNU General Public License does not permit incorporating your +program into proprietary programs. If your program is a subroutine +library, you may consider it more useful to permit linking proprietary +applications with the library. If this is what you want to do, use the +GNU Lesser General Public License instead of this License. But first, +please read . diff --git a/MANIFEST.in b/MANIFEST.in index 3b23cda0..339fc61d 100644 --- a/MANIFEST.in +++ b/MANIFEST.in @@ -1,3 +1,3 @@ -include CHANGELOG.md COPYING DOCUMENTATION.md README.md +include CHANGELOG.md COPYING.md DOCUMENTATION.md README.md include config rights include radicale.wsgi From 14a3c3d763ea05124a53a5aa2cec1cc48634d93a Mon Sep 17 00:00:00 2001 From: Unrud Date: Sun, 3 Jul 2022 10:14:38 +0200 Subject: [PATCH 177/238] Use tox for tests --- .github/workflows/test.yml | 6 +++--- conftest.py | 9 --------- setup.cfg | 23 +++++++++++++++++++---- setup.py | 5 +---- 4 files changed, 23 insertions(+), 20 deletions(-) delete mode 100644 conftest.py diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml index 88ebec2d..2b729a57 100644 --- a/.github/workflows/test.yml +++ b/.github/workflows/test.yml @@ -18,10 +18,10 @@ jobs: - uses: actions/setup-python@v2 with: python-version: ${{ matrix.python-version }} - - name: Install from source - run: python -m pip install --editable .[test,bcrypt] + - name: Install dependencies + run: python -m pip install tox - name: Run tests - run: python -m pytest + run: python -m tox - name: Upload coverage to Coveralls if: github.event_name == 'push' env: diff --git a/conftest.py b/conftest.py deleted file mode 100644 index 17753973..00000000 --- a/conftest.py +++ /dev/null @@ -1,9 +0,0 @@ -import sys -from importlib.util import find_spec - - -def pytest_addoption(parser, pluginmanager): - # Ignore the "--mypy" argument if pytest-mypy is not installed and - # the implementation is not cpython - if sys.implementation.name != 'cpython' and not find_spec("pytest_mypy"): - parser.addoption("--mypy", action="store_true") diff --git a/setup.cfg b/setup.cfg index 06753b4f..24d6c958 100644 --- a/setup.cfg +++ b/setup.cfg @@ -2,10 +2,25 @@ python-tag = py3 [tool:pytest] -# The "--mypy" argument is ignored in conftest.py if pytest-mypy is not -# installed and the implementation is not cpython -addopts = --flake8 --isort --typeguard-packages=radicale --mypy --cov --cov-report=term --cov-report=xml -r s -norecursedirs = dist .cache .git build Radicale.egg-info .eggs venv +addopts = --typeguard-packages=radicale + +[tox:tox] + +[testenv] +extras = + bcrypt + test +deps = + flake8 + isort + mypy + types-setuptools + pytest-cov +commands = + flake8 . + isort --check --diff . + mypy . + pytest -r s --cov --cov-report=term --cov-report=xml . [tool:isort] known_standard_library = _dummy_thread,_thread,abc,aifc,argparse,array,ast,asynchat,asyncio,asyncore,atexit,audioop,base64,bdb,binascii,binhex,bisect,builtins,bz2,cProfile,calendar,cgi,cgitb,chunk,cmath,cmd,code,codecs,codeop,collections,colorsys,compileall,concurrent,configparser,contextlib,contextvars,copy,copyreg,crypt,csv,ctypes,curses,dataclasses,datetime,dbm,decimal,difflib,dis,distutils,doctest,dummy_threading,email,encodings,ensurepip,enum,errno,faulthandler,fcntl,filecmp,fileinput,fnmatch,formatter,fpectl,fractions,ftplib,functools,gc,getopt,getpass,gettext,glob,grp,gzip,hashlib,heapq,hmac,html,http,imaplib,imghdr,imp,importlib,inspect,io,ipaddress,itertools,json,keyword,lib2to3,linecache,locale,logging,lzma,macpath,mailbox,mailcap,marshal,math,mimetypes,mmap,modulefinder,msilib,msvcrt,multiprocessing,netrc,nis,nntplib,ntpath,numbers,operator,optparse,os,ossaudiodev,parser,pathlib,pdb,pickle,pickletools,pipes,pkgutil,platform,plistlib,poplib,posix,posixpath,pprint,profile,pstats,pty,pwd,py_compile,pyclbr,pydoc,queue,quopri,random,re,readline,reprlib,resource,rlcompleter,runpy,sched,secrets,select,selectors,shelve,shlex,shutil,signal,site,smtpd,smtplib,sndhdr,socket,socketserver,spwd,sqlite3,sre,sre_compile,sre_constants,sre_parse,ssl,stat,statistics,string,stringprep,struct,subprocess,sunau,symbol,symtable,sys,sysconfig,syslog,tabnanny,tarfile,telnetlib,tempfile,termios,test,textwrap,threading,time,timeit,tkinter,token,tokenize,trace,traceback,tracemalloc,tty,turtle,turtledemo,types,typing,unicodedata,unittest,urllib,uu,uuid,venv,warnings,wave,weakref,webbrowser,winreg,winsound,wsgiref,xdrlib,xml,xmlrpc,zipapp,zipfile,zipimport,zlib diff --git a/setup.py b/setup.py index cf1502b1..e64cdc10 100644 --- a/setup.py +++ b/setup.py @@ -50,10 +50,7 @@ install_requires = ["defusedxml", "passlib", "vobject>=0.9.6", "python-dateutil>=2.7.3", "setuptools; python_version<'3.9'"] # typeguard requires pytest<7 -tests_require = ["pytest<7", "pytest-cov", "pytest-flake8", "pytest-isort", - "typeguard", "waitress", - "pytest-mypy; implementation_name=='cpython'", - "types-setuptools; implementation_name=='cpython'"] +tests_require = ["pytest<7", "typeguard", "waitress"] setup( name="Radicale", From c589c9fc0dc1efb61e785748b47aee290a651c7d Mon Sep 17 00:00:00 2001 From: Unrud Date: Sun, 3 Jul 2022 11:36:28 +0200 Subject: [PATCH 178/238] Skip mypy installation for pypy<3.9 --- setup.cfg | 9 +++++++-- 1 file changed, 7 insertions(+), 2 deletions(-) diff --git a/setup.cfg b/setup.cfg index 24d6c958..1bf92919 100644 --- a/setup.cfg +++ b/setup.cfg @@ -13,13 +13,18 @@ extras = deps = flake8 isort - mypy + # mypy installation fails with pypy<3.9 + mypy; implementation_name!='pypy' or python_version>='3.9' types-setuptools pytest-cov commands = flake8 . isort --check --diff . - mypy . + # Run mypy if it's installed + python -c 'import importlib.util, subprocess, sys; \ + importlib.util.find_spec("mypy") \ + and sys.exit(subprocess.run(["mypy", "."]).returncode) \ + or print("mypy is not installed")' pytest -r s --cov --cov-report=term --cov-report=xml . [tool:isort] From 86ada4cf973011815771550ab2ca24a6a8d27933 Mon Sep 17 00:00:00 2001 From: Unrud Date: Sun, 3 Jul 2022 12:04:32 +0200 Subject: [PATCH 179/238] Improve message --- setup.cfg | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/setup.cfg b/setup.cfg index 1bf92919..756aefdb 100644 --- a/setup.cfg +++ b/setup.cfg @@ -24,7 +24,7 @@ commands = python -c 'import importlib.util, subprocess, sys; \ importlib.util.find_spec("mypy") \ and sys.exit(subprocess.run(["mypy", "."]).returncode) \ - or print("mypy is not installed")' + or print("Skipped: mypy is not installed")' pytest -r s --cov --cov-report=term --cov-report=xml . [tool:isort] From f9d9b88a77cfeb385ce21738e2f31b3f5434b86e Mon Sep 17 00:00:00 2001 From: Unrud Date: Sun, 3 Jul 2022 12:28:47 +0200 Subject: [PATCH 180/238] Update github-actions --- .github/workflows/pypi-publish.yml | 4 ++-- .github/workflows/test.yml | 27 ++++++++++++++------------- 2 files changed, 16 insertions(+), 15 deletions(-) diff --git a/.github/workflows/pypi-publish.yml b/.github/workflows/pypi-publish.yml index a73ca0b6..ea027e9d 100644 --- a/.github/workflows/pypi-publish.yml +++ b/.github/workflows/pypi-publish.yml @@ -11,8 +11,8 @@ jobs: - uses: actions/setup-python@v2 with: python-version: 3.x - - name: Install dependencies - run: python -m pip install wheel + - name: Install build dependencies + run: pip install setuptools wheel - name: Build run: python setup.py sdist bdist_wheel - name: Publish to PyPI diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml index 2b729a57..fcba10b9 100644 --- a/.github/workflows/test.yml +++ b/.github/workflows/test.yml @@ -6,30 +6,31 @@ jobs: strategy: matrix: os: [ubuntu-latest, macos-latest, windows-latest] - python-version: ['3.6', '3.7', '3.8', '3.9', '3.10', pypy-3.7, pypy-3.8] + python-version: ['3.6', '3.7', '3.8', '3.9', '3.10', pypy3.7, pypy3.8] exclude: - os: windows-latest - python-version: pypy-3.7 + python-version: pypy3.7 - os: windows-latest - python-version: pypy-3.8 + python-version: pypy3.8 runs-on: ${{ matrix.os }} steps: - uses: actions/checkout@v2 - uses: actions/setup-python@v2 with: python-version: ${{ matrix.python-version }} - - name: Install dependencies - run: python -m pip install tox - - name: Run tests - run: python -m tox + - name: Install test dependencies + run: pip install tox + - name: Test + run: tox + - name: Install coveralls + if: github.event_name == 'push' + run: pip install coveralls - name: Upload coverage to Coveralls if: github.event_name == 'push' env: COVERALLS_PARALLEL: true GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} - run: | - python -m pip install coveralls - python -m coveralls --service=github + run: coveralls --service=github coveralls-finish: needs: test @@ -39,9 +40,9 @@ jobs: - uses: actions/setup-python@v2 with: python-version: 3.x + - name: Install coveralls + run: pip install coveralls - name: Finish Coveralls parallel builds env: GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} - run: | - python -m pip install coveralls - python -m coveralls --service=github --finish + run: coveralls --service=github --finish From f7fd323dea9279ee4fd56b6626823afde4ec4b61 Mon Sep 17 00:00:00 2001 From: Unrud Date: Sun, 3 Jul 2022 12:29:02 +0200 Subject: [PATCH 181/238] Test pypy3.9 --- .github/workflows/test.yml | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml index fcba10b9..54ebb92b 100644 --- a/.github/workflows/test.yml +++ b/.github/workflows/test.yml @@ -6,12 +6,14 @@ jobs: strategy: matrix: os: [ubuntu-latest, macos-latest, windows-latest] - python-version: ['3.6', '3.7', '3.8', '3.9', '3.10', pypy3.7, pypy3.8] + python-version: ['3.6', '3.7', '3.8', '3.9', '3.10', pypy3.7, pypy3.8, pypy3.9] exclude: - os: windows-latest python-version: pypy3.7 - os: windows-latest python-version: pypy3.8 + - os: windows-latest + python-version: pypy3.9 runs-on: ${{ matrix.os }} steps: - uses: actions/checkout@v2 From d8604becd0edd5a28324e955559c7e4c57019f0b Mon Sep 17 00:00:00 2001 From: Unrud Date: Sun, 3 Jul 2022 12:29:51 +0200 Subject: [PATCH 182/238] Build with PEP 517 --- .github/workflows/pypi-publish.yml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/.github/workflows/pypi-publish.yml b/.github/workflows/pypi-publish.yml index ea027e9d..970c6722 100644 --- a/.github/workflows/pypi-publish.yml +++ b/.github/workflows/pypi-publish.yml @@ -12,9 +12,9 @@ jobs: with: python-version: 3.x - name: Install build dependencies - run: pip install setuptools wheel + run: pip install build - name: Build - run: python setup.py sdist bdist_wheel + run: python -m build --sdist --wheel - name: Publish to PyPI uses: pypa/gh-action-pypi-publish@master with: From 3594217570b2549f85647a1d7867e42894422703 Mon Sep 17 00:00:00 2001 From: Unrud Date: Sun, 3 Jul 2022 12:33:07 +0200 Subject: [PATCH 183/238] github-actions: Fix pypy versions --- .github/workflows/test.yml | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml index 54ebb92b..03b04f1a 100644 --- a/.github/workflows/test.yml +++ b/.github/workflows/test.yml @@ -6,14 +6,14 @@ jobs: strategy: matrix: os: [ubuntu-latest, macos-latest, windows-latest] - python-version: ['3.6', '3.7', '3.8', '3.9', '3.10', pypy3.7, pypy3.8, pypy3.9] + python-version: ['3.6', '3.7', '3.8', '3.9', '3.10', pypy-3.7, pypy-3.8, pypy-3.9] exclude: - os: windows-latest - python-version: pypy3.7 + python-version: pypy-3.7 - os: windows-latest - python-version: pypy3.8 + python-version: pypy-3.8 - os: windows-latest - python-version: pypy3.9 + python-version: pypy-3.9 runs-on: ${{ matrix.os }} steps: - uses: actions/checkout@v2 From 156ce91f3527cc043e0c5caba1dc7c9952d1eb94 Mon Sep 17 00:00:00 2001 From: Unrud Date: Sun, 3 Jul 2022 12:37:54 +0200 Subject: [PATCH 184/238] Cosmetics --- .github/workflows/pypi-publish.yml | 2 +- .github/workflows/test.yml | 6 +++--- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/.github/workflows/pypi-publish.yml b/.github/workflows/pypi-publish.yml index 970c6722..a6bd720f 100644 --- a/.github/workflows/pypi-publish.yml +++ b/.github/workflows/pypi-publish.yml @@ -11,7 +11,7 @@ jobs: - uses: actions/setup-python@v2 with: python-version: 3.x - - name: Install build dependencies + - name: Install Build dependencies run: pip install build - name: Build run: python -m build --sdist --wheel diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml index 03b04f1a..4b82fa58 100644 --- a/.github/workflows/test.yml +++ b/.github/workflows/test.yml @@ -20,11 +20,11 @@ jobs: - uses: actions/setup-python@v2 with: python-version: ${{ matrix.python-version }} - - name: Install test dependencies + - name: Install Test dependencies run: pip install tox - name: Test run: tox - - name: Install coveralls + - name: Install Coveralls if: github.event_name == 'push' run: pip install coveralls - name: Upload coverage to Coveralls @@ -42,7 +42,7 @@ jobs: - uses: actions/setup-python@v2 with: python-version: 3.x - - name: Install coveralls + - name: Install Coveralls run: pip install coveralls - name: Finish Coveralls parallel builds env: From 5aa2f59b382522802e63bfc58b11b02e7f418a07 Mon Sep 17 00:00:00 2001 From: Unrud Date: Sun, 3 Jul 2022 12:56:24 +0200 Subject: [PATCH 185/238] Always test bcrypt --- radicale/tests/test_auth.py | 10 ---------- setup.cfg | 4 +--- setup.py | 6 +++--- 3 files changed, 4 insertions(+), 16 deletions(-) diff --git a/radicale/tests/test_auth.py b/radicale/tests/test_auth.py index 516a6f8e..f33780b6 100644 --- a/radicale/tests/test_auth.py +++ b/radicale/tests/test_auth.py @@ -44,16 +44,6 @@ class TestBaseAuthRequests(BaseTest): """Test htpasswd authentication with user "tmp" and password "bepo" for ``test_matrix`` "ascii" or user "😀" and password "🔑" for ``test_matrix`` "unicode".""" - if htpasswd_encryption == "bcrypt": - try: - from passlib.exc import MissingBackendError - from passlib.hash import bcrypt - except ImportError: - pytest.skip("passlib[bcrypt] is not installed") - try: - bcrypt.hash("test-bcrypt-backend") - except MissingBackendError: - pytest.skip("bcrypt backend for passlib is not installed") htpasswd_file_path = os.path.join(self.colpath, ".htpasswd") encoding: str = self.configuration.get("encoding", "stock") with open(htpasswd_file_path, "w", encoding=encoding) as f: diff --git a/setup.cfg b/setup.cfg index 756aefdb..8f9822c1 100644 --- a/setup.cfg +++ b/setup.cfg @@ -7,9 +7,7 @@ addopts = --typeguard-packages=radicale [tox:tox] [testenv] -extras = - bcrypt - test +extras = test deps = flake8 isort diff --git a/setup.py b/setup.py index e64cdc10..d2664417 100644 --- a/setup.py +++ b/setup.py @@ -49,8 +49,9 @@ WEB_FILES = ["web/internal_data/css/icon.png", install_requires = ["defusedxml", "passlib", "vobject>=0.9.6", "python-dateutil>=2.7.3", "setuptools; python_version<'3.9'"] +bcrypt_requires = ["passlib[bcrypt]", "bcrypt"] # typeguard requires pytest<7 -tests_require = ["pytest<7", "typeguard", "waitress"] +test_requires = ["pytest<7", "typeguard", "waitress", *bcrypt_requires] setup( name="Radicale", @@ -69,8 +70,7 @@ setup( package_data={"radicale": [*WEB_FILES, "py.typed"]}, entry_points={"console_scripts": ["radicale = radicale.__main__:run"]}, install_requires=install_requires, - extras_require={"test": tests_require, - "bcrypt": ["passlib[bcrypt]", "bcrypt"]}, + extras_require={"test": test_requires, "bcrypt": bcrypt_requires}, keywords=["calendar", "addressbook", "CalDAV", "CardDAV"], python_requires=">=3.6.0", classifiers=[ From f8f6e470813134b9c04cf97f2a36bf4459f1a9a3 Mon Sep 17 00:00:00 2001 From: Unrud Date: Sun, 3 Jul 2022 13:05:16 +0200 Subject: [PATCH 186/238] Remove python-tag (no longer required) --- setup.cfg | 3 --- 1 file changed, 3 deletions(-) diff --git a/setup.cfg b/setup.cfg index 8f9822c1..dcad9544 100644 --- a/setup.cfg +++ b/setup.cfg @@ -1,6 +1,3 @@ -[bdist_wheel] -python-tag = py3 - [tool:pytest] addopts = --typeguard-packages=radicale From cd6ebaae1a90687a81741b3398a7672d287cb804 Mon Sep 17 00:00:00 2001 From: Unrud Date: Sun, 3 Jul 2022 13:27:43 +0200 Subject: [PATCH 187/238] flake8/mypy: Ignore /build folder --- setup.cfg | 2 ++ 1 file changed, 2 insertions(+) diff --git a/setup.cfg b/setup.cfg index dcad9544..47784a78 100644 --- a/setup.cfg +++ b/setup.cfg @@ -30,10 +30,12 @@ known_third_party = defusedxml,passlib,pkg_resources,pytest,vobject # Only enable default tests (https://github.com/PyCQA/flake8/issues/790#issuecomment-812823398) select = E,F,W,C90,DOES-NOT-EXIST ignore = E121,E123,E126,E226,E24,E704,W503,W504,DOES-NOT-EXIST +extend-exclude = ./build/ [mypy] ignore_missing_imports = True show_error_codes = True +exclude = ^build/ [coverage:run] branch = True From 9bed0af669ae699efaf76c7965430bfc3f3a5e1c Mon Sep 17 00:00:00 2001 From: Unrud Date: Thu, 14 Jul 2022 17:21:50 +0200 Subject: [PATCH 188/238] Remove shebang and executable bit --- radicale.wsgi | 0 setup.py | 2 -- 2 files changed, 2 deletions(-) mode change 100755 => 100644 radicale.wsgi diff --git a/radicale.wsgi b/radicale.wsgi old mode 100755 new mode 100644 diff --git a/setup.py b/setup.py index d2664417..4eeb9776 100644 --- a/setup.py +++ b/setup.py @@ -1,5 +1,3 @@ -#!/usr/bin/env python3 - # This file is part of Radicale - CalDAV and CardDAV server # Copyright © 2009-2017 Guillaume Ayoub # Copyright © 2017-2018 Unrud From 865e0dd629dcdda73c5fb000936a998dea489cb8 Mon Sep 17 00:00:00 2001 From: Unrud Date: Thu, 14 Jul 2022 17:21:53 +0200 Subject: [PATCH 189/238] flake8/mypy: Ignore build folder --- setup.cfg | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/setup.cfg b/setup.cfg index 47784a78..a77b43bc 100644 --- a/setup.cfg +++ b/setup.cfg @@ -30,12 +30,12 @@ known_third_party = defusedxml,passlib,pkg_resources,pytest,vobject # Only enable default tests (https://github.com/PyCQA/flake8/issues/790#issuecomment-812823398) select = E,F,W,C90,DOES-NOT-EXIST ignore = E121,E123,E126,E226,E24,E704,W503,W504,DOES-NOT-EXIST -extend-exclude = ./build/ +extend-exclude = build [mypy] ignore_missing_imports = True show_error_codes = True -exclude = ^build/ +exclude = (^|/)build($|/) [coverage:run] branch = True From ad5ce948179e10f86978c4fc14917401b5797c6e Mon Sep 17 00:00:00 2001 From: Unrud Date: Thu, 14 Jul 2022 17:21:57 +0200 Subject: [PATCH 190/238] Remove download url from metadata --- setup.py | 2 -- 1 file changed, 2 deletions(-) diff --git a/setup.py b/setup.py index 4eeb9776..e366888e 100644 --- a/setup.py +++ b/setup.py @@ -59,8 +59,6 @@ setup( author="Guillaume Ayoub", author_email="guillaume.ayoub@kozea.fr", url="https://radicale.org/", - download_url=("https://pypi.python.org/packages/source/R/Radicale/" - "Radicale-%s.tar.gz" % VERSION), license="GNU GPL v3", platforms="Any", packages=find_packages( From c2a159a6cd07b4e04d0d3cbda2b679e9edb8390a Mon Sep 17 00:00:00 2001 From: Unrud Date: Thu, 14 Jul 2022 17:22:00 +0200 Subject: [PATCH 191/238] Move project description to README.MD Fixes #831 --- README.md | 15 +++++++++++++-- setup.py | 29 +++++++---------------------- 2 files changed, 20 insertions(+), 24 deletions(-) diff --git a/README.md b/README.md index 98ee6602..aed74fce 100644 --- a/README.md +++ b/README.md @@ -1,9 +1,20 @@ -# Read Me +# Radicale [![Test](https://github.com/Kozea/Radicale/actions/workflows/test.yml/badge.svg?branch=master)](https://github.com/Kozea/Radicale/actions/workflows/test.yml) [![Coverage Status](https://coveralls.io/repos/github/Kozea/Radicale/badge.svg?branch=master)](https://coveralls.io/github/Kozea/Radicale?branch=master) -Radicale is a free and open-source CalDAV and CardDAV server. +Radicale is a small but powerful CalDAV (calendars, to-do lists) and CardDAV +(contacts) server, that: + +* Shares calendars and contact lists through CalDAV, CardDAV and HTTP. +* Supports events, todos, journal entries and business cards. +* Works out-of-the-box, no complicated setup or configuration required. +* Can limit access by authentication. +* Can secure connections with TLS. +* Works with many CalDAV and CardDAV clients +* Stores all data on the file system in a simple folder structure. +* Can be extended with plugins. +* Is GPLv3-licensed free software. For the complete documentation, please visit [Radicale master Documentation](https://radicale.org/master.html). diff --git a/setup.py b/setup.py index e366888e..7e142997 100644 --- a/setup.py +++ b/setup.py @@ -15,31 +15,15 @@ # You should have received a copy of the GNU General Public License # along with Radicale. If not, see . -""" -Radicale CalDAV and CardDAV server -================================== - -The Radicale Project is a CalDAV (calendar) and CardDAV (contact) server. It -aims to be a light solution, easy to use, easy to install, easy to configure. -As a consequence, it requires few software dependances and is pre-configured to -work out-of-the-box. - -The Radicale Project runs on most of the UNIX-like platforms (Linux, BSD, -MacOS X) and Windows. It is known to work with Evolution, Lightning, iPhone -and Android clients. It is free and open-source software, released under GPL -version 3. - -For further information, please visit the `Radicale Website -`_. - -""" - from setuptools import find_packages, setup # When the version is updated, a new section in the CHANGELOG.md file must be # added too. VERSION = "master" -WEB_FILES = ["web/internal_data/css/icon.png", + +with open("README.md", encoding="utf-8") as f: + long_description = f.read() +web_files = ["web/internal_data/css/icon.png", "web/internal_data/css/main.css", "web/internal_data/fn.js", "web/internal_data/index.html"] @@ -55,7 +39,8 @@ setup( name="Radicale", version=VERSION, description="CalDAV and CardDAV Server", - long_description=__doc__, + long_description=long_description, + long_description_content_type="text/markdown", author="Guillaume Ayoub", author_email="guillaume.ayoub@kozea.fr", url="https://radicale.org/", @@ -63,7 +48,7 @@ setup( platforms="Any", packages=find_packages( exclude=["*.tests", "*.tests.*", "tests.*", "tests"]), - package_data={"radicale": [*WEB_FILES, "py.typed"]}, + package_data={"radicale": [*web_files, "py.typed"]}, entry_points={"console_scripts": ["radicale = radicale.__main__:run"]}, install_requires=install_requires, extras_require={"test": test_requires, "bcrypt": bcrypt_requires}, From 6a56a6026f6ec463d6eb77da29e03c48c0c736c6 Mon Sep 17 00:00:00 2001 From: Unrud Date: Thu, 14 Jul 2022 22:06:48 +0200 Subject: [PATCH 192/238] Update changelog --- CHANGELOG.md | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index 63ac44e0..0a1577c3 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,12 @@ ## master +## 3.1.8 + +* Fix setuptools requirement if installing wheel +* Tests: Switch from `python setup.py test` to `tox` +* Small changes to build system configuration and tests + ## 3.1.7 * Fix random href fallback From f4a87afab7b08e0eebe3e9f66b40f2ada7499730 Mon Sep 17 00:00:00 2001 From: "trougnouf (Benoit Brummer)" Date: Tue, 19 Jul 2022 00:15:33 +0200 Subject: [PATCH 193/238] fix #715 (Main Component is missing when only recurrence id exists) with balrok's patch --- radicale/item/filter.py | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/radicale/item/filter.py b/radicale/item/filter.py index 587dc367..217f503c 100644 --- a/radicale/item/filter.py +++ b/radicale/item/filter.py @@ -225,6 +225,7 @@ def visit_time_ranges(vobject_item: vobject.base.Component, child_name: str, def get_children(components: Iterable[vobject.base.Component]) -> Iterator[ Tuple[vobject.base.Component, bool, List[date]]]: main = None + rec_main = None recurrences = [] for comp in components: if hasattr(comp, "recurrence_id") and comp.recurrence_id.value: @@ -232,11 +233,14 @@ def visit_time_ranges(vobject_item: vobject.base.Component, child_name: str, if comp.rruleset: # Prevent possible infinite loop raise ValueError("Overwritten recurrence with RRULESET") + rec_main = comp yield comp, True, [] else: if main is not None: raise ValueError("Multiple main components") main = comp + if main is None and len(recurrences) == 1: + main = rec_main if main is None: raise ValueError("Main component missing") yield main, False, recurrences From cdb5160c3e3b3782916973bb77dca0a5986f8f19 Mon Sep 17 00:00:00 2001 From: ky-tt <63500586+ky-tt@users.noreply.github.com> Date: Sun, 11 Dec 2022 18:34:02 +0100 Subject: [PATCH 194/238] Update DOCUMENTATION.md: changes permissions As proposed in https://github.com/Kozea/Radicale/issues/898#issuecomment-444035927 this helps using the web interface. --- DOCUMENTATION.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/DOCUMENTATION.md b/DOCUMENTATION.md index 663ffef1..ef877770 100644 --- a/DOCUMENTATION.md +++ b/DOCUMENTATION.md @@ -973,7 +973,7 @@ An example rights file: [root] user: .+ collection: -permissions: R +permissions: r # Allow reading and writing principal collection (same as username) [principal] From 526d835b594dafa36c6b8b2a54efaa7ccceca1bf Mon Sep 17 00:00:00 2001 From: Unrud Date: Sun, 5 Mar 2023 16:52:06 +0100 Subject: [PATCH 195/238] Tests: Fix flake8 configuration --- setup.cfg | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/setup.cfg b/setup.cfg index a77b43bc..fe2038fb 100644 --- a/setup.cfg +++ b/setup.cfg @@ -28,8 +28,9 @@ known_third_party = defusedxml,passlib,pkg_resources,pytest,vobject [flake8] # Only enable default tests (https://github.com/PyCQA/flake8/issues/790#issuecomment-812823398) -select = E,F,W,C90,DOES-NOT-EXIST -ignore = E121,E123,E126,E226,E24,E704,W503,W504,DOES-NOT-EXIST +# DNE: DOES-NOT-EXIST +select = E,F,W,C90,DNE000 +ignore = E121,E123,E126,E226,E24,E704,W503,W504,DNE000 extend-exclude = build [mypy] From f8e28f6b6e8075820a2229219a5dc9d87483ea78 Mon Sep 17 00:00:00 2001 From: Unrud Date: Sun, 5 Mar 2023 16:52:07 +0100 Subject: [PATCH 196/238] Fix new type error --- radicale/server.py | 9 +++++++-- radicale/tests/__init__.py | 4 ++-- 2 files changed, 9 insertions(+), 4 deletions(-) diff --git a/radicale/server.py b/radicale/server.py index 6cb4c7b4..62fe4ef3 100644 --- a/radicale/server.py +++ b/radicale/server.py @@ -58,11 +58,16 @@ elif sys.platform == "win32": # IPv4 (host, port) and IPv6 (host, port, flowinfo, scopeid) -ADDRESS_TYPE = Union[Tuple[str, int], Tuple[str, int, int, int]] +ADDRESS_TYPE = Union[Tuple[Union[str, bytes, bytearray], int], + Tuple[str, int, int, int]] def format_address(address: ADDRESS_TYPE) -> str: - return "[%s]:%d" % address[:2] + host, port, *_ = address + if not isinstance(host, str): + raise NotImplementedError("Unsupported address format: %r" % + (address,)) + return "[%s]:%d" % (host, port) class ParallelHTTPServer(socketserver.ThreadingMixIn, diff --git a/radicale/tests/__init__.py b/radicale/tests/__init__.py index 2e132560..fe8dbdef 100644 --- a/radicale/tests/__init__.py +++ b/radicale/tests/__init__.py @@ -137,8 +137,8 @@ class BaseTest: status, _, answer = self.request("GET", path, check=check, **kwargs) return status, answer - def post(self, path: str, data: str = None, check: Optional[int] = 200, - **kwargs) -> Tuple[int, str]: + def post(self, path: str, data: Optional[str] = None, + check: Optional[int] = 200, **kwargs) -> Tuple[int, str]: status, _, answer = self.request("POST", path, data, check=check, **kwargs) return status, answer From 794c1f84fb0a012734118e8ece29c20bc765cb5d Mon Sep 17 00:00:00 2001 From: Unrud Date: Sun, 5 Mar 2023 16:52:07 +0100 Subject: [PATCH 197/238] Drop support for python 3.6 --- .github/workflows/test.yml | 2 +- setup.py | 3 +-- 2 files changed, 2 insertions(+), 3 deletions(-) diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml index 4b82fa58..fa6b760b 100644 --- a/.github/workflows/test.yml +++ b/.github/workflows/test.yml @@ -6,7 +6,7 @@ jobs: strategy: matrix: os: [ubuntu-latest, macos-latest, windows-latest] - python-version: ['3.6', '3.7', '3.8', '3.9', '3.10', pypy-3.7, pypy-3.8, pypy-3.9] + python-version: ['3.7', '3.8', '3.9', '3.10', pypy-3.7, pypy-3.8, pypy-3.9] exclude: - os: windows-latest python-version: pypy-3.7 diff --git a/setup.py b/setup.py index 7e142997..5836549f 100644 --- a/setup.py +++ b/setup.py @@ -53,7 +53,7 @@ setup( install_requires=install_requires, extras_require={"test": test_requires, "bcrypt": bcrypt_requires}, keywords=["calendar", "addressbook", "CalDAV", "CardDAV"], - python_requires=">=3.6.0", + python_requires=">=3.7.0", classifiers=[ "Development Status :: 5 - Production/Stable", "Environment :: Console", @@ -63,7 +63,6 @@ setup( "License :: OSI Approved :: GNU General Public License (GPL)", "Operating System :: OS Independent", "Programming Language :: Python :: 3", - "Programming Language :: Python :: 3.6", "Programming Language :: Python :: 3.7", "Programming Language :: Python :: 3.8", "Programming Language :: Python :: 3.9", From 6a96b1f5a704e945d8b39293cbc20110670bbfa2 Mon Sep 17 00:00:00 2001 From: Unrud Date: Sun, 5 Mar 2023 16:52:07 +0100 Subject: [PATCH 198/238] Test python 3.11 --- .github/workflows/test.yml | 2 +- setup.py | 1 + 2 files changed, 2 insertions(+), 1 deletion(-) diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml index fa6b760b..4eebaa38 100644 --- a/.github/workflows/test.yml +++ b/.github/workflows/test.yml @@ -6,7 +6,7 @@ jobs: strategy: matrix: os: [ubuntu-latest, macos-latest, windows-latest] - python-version: ['3.7', '3.8', '3.9', '3.10', pypy-3.7, pypy-3.8, pypy-3.9] + python-version: ['3.7', '3.8', '3.9', '3.10', '3.11', pypy-3.7, pypy-3.8, pypy-3.9] exclude: - os: windows-latest python-version: pypy-3.7 diff --git a/setup.py b/setup.py index 5836549f..002abce3 100644 --- a/setup.py +++ b/setup.py @@ -67,6 +67,7 @@ setup( "Programming Language :: Python :: 3.8", "Programming Language :: Python :: 3.9", "Programming Language :: Python :: 3.10", + "Programming Language :: Python :: 3.11", "Programming Language :: Python :: Implementation :: CPython", "Programming Language :: Python :: Implementation :: PyPy", "Topic :: Office/Business :: Groupware"]) From 11a2b43b60fd0e05163416ecea0beb08e99775de Mon Sep 17 00:00:00 2001 From: Unrud Date: Sun, 5 Mar 2023 16:58:25 +0100 Subject: [PATCH 199/238] Use compliant version name --- setup.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/setup.py b/setup.py index 002abce3..3e0852b9 100644 --- a/setup.py +++ b/setup.py @@ -19,7 +19,7 @@ from setuptools import find_packages, setup # When the version is updated, a new section in the CHANGELOG.md file must be # added too. -VERSION = "master" +VERSION = "3.dev" with open("README.md", encoding="utf-8") as f: long_description = f.read() From 7b98a0028b0e9b4b75a8a6a3ff092a738e5d68b4 Mon Sep 17 00:00:00 2001 From: David Greaves Date: Fri, 20 Jan 2023 15:30:49 +0000 Subject: [PATCH 200/238] Handle lists in filter values for CATEGORIES Issue #1125 Signed-off-by: David Greaves --- radicale/item/filter.py | 10 +++++++++- 1 file changed, 9 insertions(+), 1 deletion(-) diff --git a/radicale/item/filter.py b/radicale/item/filter.py index 587dc367..6a89ffa3 100644 --- a/radicale/item/filter.py +++ b/radicale/item/filter.py @@ -468,7 +468,15 @@ def text_match(vobject_item: vobject.base.Component, match(attrib) for child in children for attrib in child.params.get(attrib_name, [])) else: - condition = any(match(child.value) for child in children) + res = [] + for child in children: + # Some filters such as CATEGORIES provide a list in child.value + if type(child.value) is list: + for value in child.value: + res.append(match(value)) + else: + res.append(match(child.value)) + condition = any(res) if filter_.get("negate-condition") == "yes": return not condition return condition From 7d4a0fe70eec21b8e410df1a92d4ae6bd2e94a7b Mon Sep 17 00:00:00 2001 From: Tobias Brox Date: Fri, 27 Jan 2023 19:07:50 +0100 Subject: [PATCH 201/238] Test code for category search issue (ref https://github.com/Kozea/Radicale/issues/1280 and https://github.com/Kozea/Radicale/issues/1125) --- radicale/tests/static/event1.ics | 1 + radicale/tests/test_base.py | 16 ++++++++++++++++ 2 files changed, 17 insertions(+) diff --git a/radicale/tests/static/event1.ics b/radicale/tests/static/event1.ics index bc04d80a..4e669175 100644 --- a/radicale/tests/static/event1.ics +++ b/radicale/tests/static/event1.ics @@ -25,6 +25,7 @@ LAST-MODIFIED:20130902T150158Z DTSTAMP:20130902T150158Z UID:event1 SUMMARY:Event +CATEGORIES:some_category1,another_category2 ORGANIZER:mailto:unclesam@example.com ATTENDEE;ROLE=REQ-PARTICIPANT;PARTSTAT=TENTATIVE;CN=Jane Doe:MAILTO:janedoe@example.com ATTENDEE;ROLE=REQ-PARTICIPANT;DELEGATED-FROM="MAILTO:bob@host.com";PARTSTAT=ACCEPTED;CN=John Doe:MAILTO:johndoe@example.com diff --git a/radicale/tests/test_base.py b/radicale/tests/test_base.py index 5ea37bfb..6bd4b2f8 100644 --- a/radicale/tests/test_base.py +++ b/radicale/tests/test_base.py @@ -916,6 +916,22 @@ permissions: RrWw""") event
+
"""]) + assert "/calendar.ics/event1.ics" in self._test_filter(["""\ + + + + some_category1 + + +"""]) + assert "/calendar.ics/event1.ics" in self._test_filter(["""\ + + + + some_category1 + + """]) assert "/calendar.ics/event1.ics" not in self._test_filter(["""\ From 1a78114a5636d9278f5df5385946cc2808f1af70 Mon Sep 17 00:00:00 2001 From: Unrud Date: Wed, 8 Mar 2023 15:49:45 +0100 Subject: [PATCH 202/238] Compare network location with port --- radicale/app/move.py | 17 ++++++++++++++++- radicale/tests/__init__.py | 4 +++- radicale/tests/test_base.py | 23 ++++++++++++----------- 3 files changed, 31 insertions(+), 13 deletions(-) diff --git a/radicale/app/move.py b/radicale/app/move.py index fda85257..0c990e3f 100644 --- a/radicale/app/move.py +++ b/radicale/app/move.py @@ -18,6 +18,7 @@ # along with Radicale. If not, see . import posixpath +import re from http import client from urllib.parse import urlparse @@ -26,6 +27,16 @@ from radicale.app.base import Access, ApplicationBase from radicale.log import logger +def get_server_netloc(environ: types.WSGIEnviron, force_port: bool = False): + host = environ.get("HTTP_HOST") or environ["SERVER_NAME"] + proto = environ["wsgi.url_scheme"] + port = environ["SERVER_PORT"] + if (not force_port and port == ("443" if proto == "https" else "80") or + re.search(r":\d+$", host)): + return host + return host + ":" + port + + class ApplicationPartMove(ApplicationBase): def do_MOVE(self, environ: types.WSGIEnviron, base_prefix: str, @@ -33,7 +44,11 @@ class ApplicationPartMove(ApplicationBase): """Manage MOVE request.""" raw_dest = environ.get("HTTP_DESTINATION", "") to_url = urlparse(raw_dest) - if to_url.netloc != environ["HTTP_HOST"]: + to_netloc_with_port = to_url.netloc + if to_url.port is None: + to_netloc_with_port += (":443" if to_url.scheme == "https" + else ":80") + if to_netloc_with_port != get_server_netloc(environ, force_port=True): logger.info("Unsupported destination address: %r", raw_dest) # Remote destination server, not supported return httputils.REMOTE_DESTINATION diff --git a/radicale/tests/__init__.py b/radicale/tests/__init__.py index fe8dbdef..942cbe89 100644 --- a/radicale/tests/__init__.py +++ b/radicale/tests/__init__.py @@ -25,6 +25,7 @@ import logging import shutil import sys import tempfile +import wsgiref.util import xml.etree.ElementTree as ET from io import BytesIO from typing import Any, Dict, List, Optional, Tuple, Union @@ -83,11 +84,12 @@ class BaseTest: login.encode(encoding)).decode() environ["REQUEST_METHOD"] = method.upper() environ["PATH_INFO"] = path - if data: + if data is not None: data_bytes = data.encode(encoding) environ["wsgi.input"] = BytesIO(data_bytes) environ["CONTENT_LENGTH"] = str(len(data_bytes)) environ["wsgi.errors"] = sys.stderr + wsgiref.util.setup_testing_defaults(environ) status = headers = None def start_response(status_: str, headers_: List[Tuple[str, str]] diff --git a/radicale/tests/test_base.py b/radicale/tests/test_base.py index 6bd4b2f8..a0d3d534 100644 --- a/radicale/tests/test_base.py +++ b/radicale/tests/test_base.py @@ -355,7 +355,7 @@ permissions: RrWw""") path2 = "/calendar.ics/event2.ics" self.put(path1, event) self.request("MOVE", path1, check=201, - HTTP_DESTINATION=path2, HTTP_HOST="") + HTTP_DESTINATION="http://127.0.0.1/"+path2) self.get(path1, check=404) self.get(path2) @@ -368,7 +368,7 @@ permissions: RrWw""") path2 = "/calendar2.ics/event2.ics" self.put(path1, event) self.request("MOVE", path1, check=201, - HTTP_DESTINATION=path2, HTTP_HOST="") + HTTP_DESTINATION="http://127.0.0.1/"+path2) self.get(path1, check=404) self.get(path2) @@ -382,7 +382,7 @@ permissions: RrWw""") self.put(path1, event) self.put("/calendar2.ics/event1.ics", event) status, _, answer = self.request( - "MOVE", path1, HTTP_DESTINATION=path2, HTTP_HOST="") + "MOVE", path1, HTTP_DESTINATION="http://127.0.0.1/"+path2) assert status in (403, 409) xml = DefusedET.fromstring(answer) assert xml.tag == xmlutils.make_clark("D:error") @@ -398,9 +398,9 @@ permissions: RrWw""") self.put(path1, event) self.put(path2, event) self.request("MOVE", path1, check=412, - HTTP_DESTINATION=path2, HTTP_HOST="") - self.request("MOVE", path1, check=204, - HTTP_DESTINATION=path2, HTTP_HOST="", HTTP_OVERWRITE="T") + HTTP_DESTINATION="http://127.0.0.1/"+path2) + self.request("MOVE", path1, check=204, HTTP_OVERWRITE="T", + HTTP_DESTINATION="http://127.0.0.1/"+path2) def test_move_between_colections_overwrite_uid_conflict(self) -> None: """Move a item to a collection which already contains the item with @@ -413,8 +413,9 @@ permissions: RrWw""") path2 = "/calendar2.ics/event2.ics" self.put(path1, event1) self.put(path2, event2) - status, _, answer = self.request("MOVE", path1, HTTP_DESTINATION=path2, - HTTP_HOST="", HTTP_OVERWRITE="T") + status, _, answer = self.request( + "MOVE", path1, HTTP_OVERWRITE="T", + HTTP_DESTINATION="http://127.0.0.1/"+path2) assert status in (403, 409) xml = DefusedET.fromstring(answer) assert xml.tag == xmlutils.make_clark("D:error") @@ -1487,7 +1488,7 @@ permissions: RrWw""") sync_token, responses = self._report_sync_token(calendar_path) assert len(responses) == 1 and responses[event1_path] == 200 self.request("MOVE", event1_path, check=201, - HTTP_DESTINATION=event2_path, HTTP_HOST="") + HTTP_DESTINATION="http://127.0.0.1/"+event2_path) sync_token, responses = self._report_sync_token( calendar_path, sync_token) if not self.full_sync_token_support and not sync_token: @@ -1506,9 +1507,9 @@ permissions: RrWw""") sync_token, responses = self._report_sync_token(calendar_path) assert len(responses) == 1 and responses[event1_path] == 200 self.request("MOVE", event1_path, check=201, - HTTP_DESTINATION=event2_path, HTTP_HOST="") + HTTP_DESTINATION="http://127.0.0.1/"+event2_path) self.request("MOVE", event2_path, check=201, - HTTP_DESTINATION=event1_path, HTTP_HOST="") + HTTP_DESTINATION="http://127.0.0.1/"+event1_path) sync_token, responses = self._report_sync_token( calendar_path, sync_token) if not self.full_sync_token_support and not sync_token: From 360484e2d515f746755c355ae0aecc1d4f2852fa Mon Sep 17 00:00:00 2001 From: Unrud Date: Wed, 8 Mar 2023 15:49:46 +0100 Subject: [PATCH 203/238] Use X-Forwarded-* for server netloc when available Closes #1271 --- radicale/app/move.py | 11 ++++++++--- 1 file changed, 8 insertions(+), 3 deletions(-) diff --git a/radicale/app/move.py b/radicale/app/move.py index 0c990e3f..0c38eed5 100644 --- a/radicale/app/move.py +++ b/radicale/app/move.py @@ -28,9 +28,14 @@ from radicale.log import logger def get_server_netloc(environ: types.WSGIEnviron, force_port: bool = False): - host = environ.get("HTTP_HOST") or environ["SERVER_NAME"] - proto = environ["wsgi.url_scheme"] - port = environ["SERVER_PORT"] + if environ.get("HTTP_X_FORWARDED_HOST"): + host = environ["HTTP_X_FORWARDED_HOST"] + proto = environ.get("HTTP_X_FORWARDED_PROTO") or "http" + port = "443" if proto == "https" else "80" + else: + host = environ.get("HTTP_HOST") or environ["SERVER_NAME"] + proto = environ["wsgi.url_scheme"] + port = environ["SERVER_PORT"] if (not force_port and port == ("443" if proto == "https" else "80") or re.search(r":\d+$", host)): return host From 9276c6546237100fd374347ff9987e7b0591e48e Mon Sep 17 00:00:00 2001 From: Unrud Date: Tue, 21 Mar 2023 00:03:29 +0100 Subject: [PATCH 204/238] Upgrade to journald's native journal protocol --- radicale/log.py | 72 ++++++++++++++++++++++++++++++++++++++++++++++++- 1 file changed, 71 insertions(+), 1 deletion(-) diff --git a/radicale/log.py b/radicale/log.py index eaa842bf..d45a6ef2 100644 --- a/radicale/log.py +++ b/radicale/log.py @@ -25,11 +25,16 @@ Log messages are sent to the first available target of: """ +import contextlib import logging import os +import socket +import struct import sys import threading -from typing import Any, Callable, ClassVar, Dict, Iterator, Union +import time +from typing import (Any, Callable, ClassVar, Dict, Iterator, Optional, Tuple, + Union) from radicale import types @@ -65,6 +70,9 @@ class IdentLogRecordFactory: if current_thread.name and main_thread != current_thread: ident += "/%s" % current_thread.name record.ident = ident # type:ignore[attr-defined] + record.tid = None # type:ignore[attr-defined] + if sys.version_info >= (3, 8): + record.tid = current_thread.native_id return record @@ -75,14 +83,76 @@ class ThreadedStreamHandler(logging.Handler): terminator: ClassVar[str] = "\n" _streams: Dict[int, types.ErrorStream] + _journal_stream_id: Optional[Tuple[int, int]] + _journal_socket: Optional[socket.socket] def __init__(self) -> None: super().__init__() self._streams = {} + self._journal_stream_id = None + with contextlib.suppress(TypeError, ValueError): + dev, inode = os.environ.get("JOURNAL_STREAM", "").split(":", 1) + self._journal_stream_id = int(dev), int(inode) + self._journal_socket = None + if self._journal_stream_id and hasattr(socket, "AF_UNIX"): + journal_socket = socket.socket(socket.AF_UNIX, socket.SOCK_DGRAM) + try: + journal_socket.connect("/run/systemd/journal/socket") + except OSError: + journal_socket.close() + else: + self._journal_socket = journal_socket + + def _detect_journal(self, stream): + if not self._journal_stream_id: + return False + try: + stat = os.fstat(stream.fileno()) + except Exception: + return False + return self._journal_stream_id == (stat.st_dev, stat.st_ino) + + @staticmethod + def _encode_journal(data): + msg = b"" + for key, value in data.items(): + if key is None: + continue + key = key.encode() + value = str(value).encode() + if b"\n" in value: + msg += (key + b"\n" + + struct.pack(" None: try: stream = self._streams.get(threading.get_ident(), sys.stderr) + if self._journal_socket and self._detect_journal(stream): + self._emit_journal(record) + return msg = self.format(record) stream.write(msg) stream.write(self.terminator) From e8e709191ae907ae36410b067ab5a2880c3dc4c3 Mon Sep 17 00:00:00 2001 From: Unrud Date: Tue, 21 Mar 2023 00:41:47 +0100 Subject: [PATCH 205/238] Tests: Specify typeguard version --- setup.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/setup.py b/setup.py index 3e0852b9..144e77c5 100644 --- a/setup.py +++ b/setup.py @@ -33,7 +33,7 @@ install_requires = ["defusedxml", "passlib", "vobject>=0.9.6", "setuptools; python_version<'3.9'"] bcrypt_requires = ["passlib[bcrypt]", "bcrypt"] # typeguard requires pytest<7 -test_requires = ["pytest<7", "typeguard", "waitress", *bcrypt_requires] +test_requires = ["pytest<7", "typeguard<3", "waitress", *bcrypt_requires] setup( name="Radicale", From e23f0283b007dc5e1d8807bb3d492cd051934a06 Mon Sep 17 00:00:00 2001 From: Unrud Date: Tue, 21 Mar 2023 01:29:29 +0100 Subject: [PATCH 206/238] Fix: Filter empty entries from journal protocol --- radicale/log.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/radicale/log.py b/radicale/log.py index d45a6ef2..49143457 100644 --- a/radicale/log.py +++ b/radicale/log.py @@ -116,7 +116,7 @@ class ThreadedStreamHandler(logging.Handler): def _encode_journal(data): msg = b"" for key, value in data.items(): - if key is None: + if value is None: continue key = key.encode() value = str(value).encode() From 5070533a0b12cc063d486cd06640376f1e412ef6 Mon Sep 17 00:00:00 2001 From: Unrud Date: Wed, 22 Mar 2023 10:23:54 +0100 Subject: [PATCH 207/238] Defer connection to systemd journal --- radicale/log.py | 62 ++++++++++++++++++++++++++++------------------- radicale/types.py | 4 +-- 2 files changed, 39 insertions(+), 27 deletions(-) diff --git a/radicale/log.py b/radicale/log.py index 49143457..64304c1f 100644 --- a/radicale/log.py +++ b/radicale/log.py @@ -26,6 +26,7 @@ Log messages are sent to the first available target of: """ import contextlib +import io import logging import os import socket @@ -33,8 +34,8 @@ import struct import sys import threading import time -from typing import (Any, Callable, ClassVar, Dict, Iterator, Optional, Tuple, - Union) +from typing import (Any, Callable, ClassVar, Dict, Iterator, Mapping, Optional, + Tuple, Union, cast) from radicale import types @@ -85,6 +86,7 @@ class ThreadedStreamHandler(logging.Handler): _streams: Dict[int, types.ErrorStream] _journal_stream_id: Optional[Tuple[int, int]] _journal_socket: Optional[socket.socket] + _journal_socket_failed: bool def __init__(self) -> None: super().__init__() @@ -92,42 +94,52 @@ class ThreadedStreamHandler(logging.Handler): self._journal_stream_id = None with contextlib.suppress(TypeError, ValueError): dev, inode = os.environ.get("JOURNAL_STREAM", "").split(":", 1) - self._journal_stream_id = int(dev), int(inode) + self._journal_stream_id = (int(dev), int(inode)) self._journal_socket = None - if self._journal_stream_id and hasattr(socket, "AF_UNIX"): - journal_socket = socket.socket(socket.AF_UNIX, socket.SOCK_DGRAM) - try: - journal_socket.connect("/run/systemd/journal/socket") - except OSError: - journal_socket.close() - else: - self._journal_socket = journal_socket + self._journal_socket_failed = False - def _detect_journal(self, stream): - if not self._journal_stream_id: + def _detect_journal(self, stream: types.ErrorStream) -> bool: + if not self._journal_stream_id or not isinstance(stream, io.IOBase): return False try: stat = os.fstat(stream.fileno()) - except Exception: + except OSError: return False return self._journal_stream_id == (stat.st_dev, stat.st_ino) @staticmethod - def _encode_journal(data): + def _encode_journal(data: Mapping[str, Optional[Union[str, int]]] + ) -> bytes: msg = b"" for key, value in data.items(): if value is None: continue - key = key.encode() - value = str(value).encode() - if b"\n" in value: - msg += (key + b"\n" + - struct.pack(" bool: + if not self._journal_socket: + # Try to connect to systemd journal socket + if self._journal_socket_failed or not hasattr(socket, "AF_UNIX"): + return False + journal_socket = None + try: + journal_socket = socket.socket( + socket.AF_UNIX, socket.SOCK_DGRAM) + journal_socket.connect("/run/systemd/journal/socket") + except OSError: + self._journal_socket_failed = True + if journal_socket: + journal_socket.close() + return False + self._journal_socket = journal_socket + priority = {"DEBUG": 7, "INFO": 6, "WARNING": 4, @@ -136,7 +148,7 @@ class ThreadedStreamHandler(logging.Handler): timestamp = time.strftime("%Y-%m-%dT%H:%M:%S.%%03dZ", time.gmtime(record.created)) % record.msecs data = {"PRIORITY": priority, - "TID": record.tid, + "TID": cast(Optional[int], getattr(record, "tid", None)), "SYSLOG_IDENTIFIER": record.name, "SYSLOG_FACILITY": 1, "SYSLOG_PID": record.process, @@ -146,12 +158,12 @@ class ThreadedStreamHandler(logging.Handler): "CODE_FUNC": record.funcName, "MESSAGE": self.format(record)} self._journal_socket.sendall(self._encode_journal(data)) + return True def emit(self, record: logging.LogRecord) -> None: try: stream = self._streams.get(threading.get_ident(), sys.stderr) - if self._journal_socket and self._detect_journal(stream): - self._emit_journal(record) + if self._detect_journal(stream) and self._try_emit_journal(record): return msg = self.format(record) stream.write(msg) diff --git a/radicale/types.py b/radicale/types.py index 0eb3fd6a..c7e1904a 100644 --- a/radicale/types.py +++ b/radicale/types.py @@ -50,8 +50,8 @@ if sys.version_info >= (3, 8): @runtime_checkable class ErrorStream(Protocol): - def flush(self) -> None: ... - def write(self, s: str) -> None: ... + def flush(self) -> object: ... + def write(self, s: str) -> object: ... else: ErrorStream = Any InputStream = Any From 390240c35a94625624f297a8f5dba6af9439f495 Mon Sep 17 00:00:00 2001 From: Unrud Date: Wed, 22 Mar 2023 10:23:55 +0100 Subject: [PATCH 208/238] Write log with single syscall --- radicale/log.py | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/radicale/log.py b/radicale/log.py index 64304c1f..57542395 100644 --- a/radicale/log.py +++ b/radicale/log.py @@ -166,8 +166,7 @@ class ThreadedStreamHandler(logging.Handler): if self._detect_journal(stream) and self._try_emit_journal(record): return msg = self.format(record) - stream.write(msg) - stream.write(self.terminator) + stream.write(msg + self.terminator) if hasattr(stream, "flush"): stream.flush() except Exception: From 77626e5aed3fa437216f2e5113384f61a8b744eb Mon Sep 17 00:00:00 2001 From: Unrud Date: Wed, 22 Mar 2023 10:23:56 +0100 Subject: [PATCH 209/238] Remove unnecessary check --- radicale/log.py | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/radicale/log.py b/radicale/log.py index 57542395..b4c6586f 100644 --- a/radicale/log.py +++ b/radicale/log.py @@ -167,8 +167,7 @@ class ThreadedStreamHandler(logging.Handler): return msg = self.format(record) stream.write(msg + self.terminator) - if hasattr(stream, "flush"): - stream.flush() + stream.flush() except Exception: self.handleError(record) From a2be03fdafdb8b2171a51ab2578a15412a7e3594 Mon Sep 17 00:00:00 2001 From: Unrud Date: Wed, 22 Mar 2023 10:23:57 +0100 Subject: [PATCH 210/238] Log systemd journal connection error --- radicale/log.py | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/radicale/log.py b/radicale/log.py index b4c6586f..42b03d60 100644 --- a/radicale/log.py +++ b/radicale/log.py @@ -133,10 +133,13 @@ class ThreadedStreamHandler(logging.Handler): journal_socket = socket.socket( socket.AF_UNIX, socket.SOCK_DGRAM) journal_socket.connect("/run/systemd/journal/socket") - except OSError: + except OSError as e: self._journal_socket_failed = True if journal_socket: journal_socket.close() + # Log after setting `_journal_socket_failed` to prevent loop! + logger.error("Failed to connect to systemd journal: %s", + e, exc_info=True) return False self._journal_socket = journal_socket From 8efb942892471ebbcced2628af5d44578367b78d Mon Sep 17 00:00:00 2001 From: Unrud Date: Tue, 21 Mar 2023 16:48:39 +0100 Subject: [PATCH 211/238] Use existing record for building ident --- radicale/log.py | 18 ++++++++++-------- 1 file changed, 10 insertions(+), 8 deletions(-) diff --git a/radicale/log.py b/radicale/log.py index 42b03d60..b750c8ac 100644 --- a/radicale/log.py +++ b/radicale/log.py @@ -65,15 +65,17 @@ class IdentLogRecordFactory: def __call__(self, *args: Any, **kwargs: Any) -> logging.LogRecord: record = self._upstream_factory(*args, **kwargs) - ident = "%d" % os.getpid() - main_thread = threading.main_thread() - current_thread = threading.current_thread() - if current_thread.name and main_thread != current_thread: - ident += "/%s" % current_thread.name + ident = ("%d" % record.process if record.process is not None + else record.processName or "unknown") + tid = None + if record.thread is not None: + if record.thread != threading.main_thread().ident: + ident += "/%s" % (record.threadName or "unknown") + if (sys.version_info >= (3, 8) and + record.thread == threading.get_ident()): + tid = threading.get_native_id() record.ident = ident # type:ignore[attr-defined] - record.tid = None # type:ignore[attr-defined] - if sys.version_info >= (3, 8): - record.tid = current_thread.native_id + record.tid = tid # type:ignore[attr-defined] return record From 6ae831a324a12d9f06b75cf11b026330ad410284 Mon Sep 17 00:00:00 2001 From: Unrud Date: Tue, 21 Mar 2023 16:48:39 +0100 Subject: [PATCH 212/238] User-selectable logger formats --- radicale/log.py | 29 ++++++++++++++++++++++------- 1 file changed, 22 insertions(+), 7 deletions(-) diff --git a/radicale/log.py b/radicale/log.py index b750c8ac..8d54a1b0 100644 --- a/radicale/log.py +++ b/radicale/log.py @@ -40,7 +40,10 @@ from typing import (Any, Callable, ClassVar, Dict, Iterator, Mapping, Optional, from radicale import types LOGGER_NAME: str = "radicale" -LOGGER_FORMAT: str = "[%(asctime)s] [%(ident)s] [%(levelname)s] %(message)s" +LOGGER_FORMATS: Mapping[str, str] = { + "verbose": "[%(asctime)s] [%(ident)s] [%(levelname)s] %(message)s", + "journal": "[%(ident)s] [%(levelname)s] %(message)s", +} DATE_FORMAT: str = "%Y-%m-%d %H:%M:%S %z" logger: logging.Logger = logging.getLogger(LOGGER_NAME) @@ -89,8 +92,10 @@ class ThreadedStreamHandler(logging.Handler): _journal_stream_id: Optional[Tuple[int, int]] _journal_socket: Optional[socket.socket] _journal_socket_failed: bool + _formatters: Mapping[str, logging.Formatter] + _formatter: Optional[logging.Formatter] - def __init__(self) -> None: + def __init__(self, format_name: Optional[str] = None) -> None: super().__init__() self._streams = {} self._journal_stream_id = None @@ -99,6 +104,13 @@ class ThreadedStreamHandler(logging.Handler): self._journal_stream_id = (int(dev), int(inode)) self._journal_socket = None self._journal_socket_failed = False + self._formatters = {name: logging.Formatter(fmt, DATE_FORMAT) + for name, fmt in LOGGER_FORMATS.items()} + self._formatter = (self._formatters[format_name] + if format_name is not None else None) + + def _get_formatter(self, default_format_name: str) -> logging.Formatter: + return self._formatter or self._formatters[default_format_name] def _detect_journal(self, stream: types.ErrorStream) -> bool: if not self._journal_stream_id or not isinstance(stream, io.IOBase): @@ -161,7 +173,7 @@ class ThreadedStreamHandler(logging.Handler): "CODE_FILE": record.pathname, "CODE_LINE": record.lineno, "CODE_FUNC": record.funcName, - "MESSAGE": self.format(record)} + "MESSAGE": self._get_formatter("journal").format(record)} self._journal_socket.sendall(self._encode_journal(data)) return True @@ -170,7 +182,7 @@ class ThreadedStreamHandler(logging.Handler): stream = self._streams.get(threading.get_ident(), sys.stderr) if self._detect_journal(stream) and self._try_emit_journal(record): return - msg = self.format(record) + msg = self._get_formatter("verbose").format(record) stream.write(msg + self.terminator) stream.flush() except Exception: @@ -196,13 +208,16 @@ def register_stream(stream: types.ErrorStream) -> Iterator[None]: def setup() -> None: """Set global logging up.""" global register_stream - handler = ThreadedStreamHandler() - logging.basicConfig(format=LOGGER_FORMAT, datefmt=DATE_FORMAT, - handlers=[handler]) + format_name = os.environ.get("RADICALE_LOG_FORMAT") or None + sane_format_name = format_name if format_name in LOGGER_FORMATS else None + handler = ThreadedStreamHandler(sane_format_name) + logging.basicConfig(handlers=[handler]) register_stream = handler.register_stream log_record_factory = IdentLogRecordFactory(logging.getLogRecordFactory()) logging.setLogRecordFactory(log_record_factory) set_level(logging.WARNING) + if format_name != sane_format_name: + logger.error("Invalid RADICALE_LOG_FORMAT: %r", format_name) def set_level(level: Union[int, str]) -> None: From d7ce2f0b98589400b0e1718cfd7bb29b7ebeaebe Mon Sep 17 00:00:00 2001 From: Unrud Date: Sat, 22 Apr 2023 20:01:58 +0200 Subject: [PATCH 213/238] Fix typo in Content-Disposition header Fixes #1298 --- radicale/app/get.py | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/radicale/app/get.py b/radicale/app/get.py index 7e5feeb4..d8b01520 100644 --- a/radicale/app/get.py +++ b/radicale/app/get.py @@ -45,8 +45,8 @@ def propose_filename(collection: storage.BaseCollection) -> str: class ApplicationPartGet(ApplicationBase): - def _content_disposition_attachement(self, filename: str) -> str: - value = "attachement" + def _content_disposition_attachment(self, filename: str) -> str: + value = "attachment" try: encoded_filename = quote(filename, encoding=self._encoding) except UnicodeEncodeError: @@ -91,7 +91,7 @@ class ApplicationPartGet(ApplicationBase): return (httputils.NOT_ALLOWED if limited_access else httputils.DIRECTORY_LISTING) content_type = xmlutils.MIMETYPES[item.tag] - content_disposition = self._content_disposition_attachement( + content_disposition = self._content_disposition_attachment( propose_filename(item)) elif limited_access: return httputils.NOT_ALLOWED From ecafa1d32bfc322bea46afdd62a657c42ce7dd8e Mon Sep 17 00:00:00 2001 From: Peter Bieringer Date: Sun, 30 Apr 2023 08:56:46 +0200 Subject: [PATCH 214/238] update Apache reverse proxy documentation to be aligned with destination check of MOVE request --- DOCUMENTATION.md | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/DOCUMENTATION.md b/DOCUMENTATION.md index 663ffef1..5f14fa87 100644 --- a/DOCUMENTATION.md +++ b/DOCUMENTATION.md @@ -354,6 +354,10 @@ RewriteRule ^/radicale$ /radicale/ [R,L] ProxyPass http://localhost:5232/ retry=0 ProxyPassReverse http://localhost:5232/ RequestHeader set X-Script-Name /radicale + RequestHeader set X-Forwarded-Port "%{SERVER_PORT}s" + + RequestHeader set X-Forwarded-Proto "https" + ``` @@ -366,6 +370,10 @@ RewriteRule ^(.*)$ http://localhost:5232/$1 [P,L] # Set to directory of .htaccess file: RequestHeader set X-Script-Name /radicale +RequestHeader set X-Forwarded-Port "%{SERVER_PORT}s" + +RequestHeader set X-Forwarded-Proto "https" + ``` Be reminded that Radicale's default configuration enforces limits on the From a3aa0ce7d9e39e00842331a8b7737f8c8fba5ffb Mon Sep 17 00:00:00 2001 From: Peter Bieringer Date: Sun, 30 Apr 2023 08:58:50 +0200 Subject: [PATCH 215/238] add support for non-standard server ports --- radicale/app/move.py | 1 + 1 file changed, 1 insertion(+) diff --git a/radicale/app/move.py b/radicale/app/move.py index 0c38eed5..5bd8a579 100644 --- a/radicale/app/move.py +++ b/radicale/app/move.py @@ -32,6 +32,7 @@ def get_server_netloc(environ: types.WSGIEnviron, force_port: bool = False): host = environ["HTTP_X_FORWARDED_HOST"] proto = environ.get("HTTP_X_FORWARDED_PROTO") or "http" port = "443" if proto == "https" else "80" + port = environ["HTTP_X_FORWARDED_PORT"] or port else: host = environ.get("HTTP_HOST") or environ["SERVER_NAME"] proto = environ["wsgi.url_scheme"] From fadf281734a9925eb9c36c534a6d3da523aceb2d Mon Sep 17 00:00:00 2001 From: Peter Bieringer Date: Sun, 30 Apr 2023 09:01:26 +0200 Subject: [PATCH 216/238] don't trust headers from external --- DOCUMENTATION.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/DOCUMENTATION.md b/DOCUMENTATION.md index 5f14fa87..8d59d958 100644 --- a/DOCUMENTATION.md +++ b/DOCUMENTATION.md @@ -355,6 +355,7 @@ RewriteRule ^/radicale$ /radicale/ [R,L] ProxyPassReverse http://localhost:5232/ RequestHeader set X-Script-Name /radicale RequestHeader set X-Forwarded-Port "%{SERVER_PORT}s" + RequestHeader unset X-Forwarded-Proto RequestHeader set X-Forwarded-Proto "https" @@ -371,6 +372,7 @@ RewriteRule ^(.*)$ http://localhost:5232/$1 [P,L] # Set to directory of .htaccess file: RequestHeader set X-Script-Name /radicale RequestHeader set X-Forwarded-Port "%{SERVER_PORT}s" +RequestHeader unset X-Forwarded-Proto RequestHeader set X-Forwarded-Proto "https" From 7c25c7715f617877149f193e1a83f1bcd383c843 Mon Sep 17 00:00:00 2001 From: Henning Date: Tue, 6 Jun 2023 12:54:51 +0200 Subject: [PATCH 217/238] changed rel="shortcut icon" to rel="icon" "icon" is standard and used by all modern browsers. Only IE needed "shortcut icon". Since is it not longer supported and would have needed an .ico-file, "icon" is the right value for rel. --- radicale/web/internal_data/index.html | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/radicale/web/internal_data/index.html b/radicale/web/internal_data/index.html index c526195a..3b74fe41 100644 --- a/radicale/web/internal_data/index.html +++ b/radicale/web/internal_data/index.html @@ -7,7 +7,7 @@ Radicale Web Interface - + From 3e95c0ab0ec3fb05ce4f97df5970b7a64bc5f2f7 Mon Sep 17 00:00:00 2001 From: Henning Date: Tue, 6 Jun 2023 13:21:05 +0200 Subject: [PATCH 218/238] Added html-tags HTML5 needs and to valid. Also has to be closed. --- radicale/web/internal_data/index.html | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/radicale/web/internal_data/index.html b/radicale/web/internal_data/index.html index c526195a..9e1f1c8a 100644 --- a/radicale/web/internal_data/index.html +++ b/radicale/web/internal_data/index.html @@ -1,6 +1,7 @@ + @@ -11,7 +12,9 @@ + + +

Loading

Please wait...

@@ -131,6 +132,7 @@
+
From 3fd3bf5192e8a4ead603ffa81d940a9b388a1f35 Mon Sep 17 00:00:00 2001 From: Daniel Lublin Date: Thu, 15 Jun 2023 10:57:44 +0200 Subject: [PATCH 220/238] Document removal of X-Script-Name when serving Radicale at root (/) See https://github.com/Kozea/Radicale/issues/1210 If X-Script-Name header is still set to `/` we get warnings in the log --- DOCUMENTATION.md | 10 +++++++--- 1 file changed, 7 insertions(+), 3 deletions(-) diff --git a/DOCUMENTATION.md b/DOCUMENTATION.md index 663ffef1..ab0b2776 100644 --- a/DOCUMENTATION.md +++ b/DOCUMENTATION.md @@ -328,9 +328,13 @@ start the **Radicale** service. ### Reverse Proxy -When a reverse proxy is used, the path at which Radicale is available must -be provided via the `X-Script-Name` header. The proxy must remove the location -from the URL path that is forwarded to Radicale. +When a reverse proxy is used, and Radicale should be made available at a path +below the root (such as `/radicale/`), then this path must be provided via +the `X-Script-Name` header (without a trailing `/`). The proxy must remove +the location from the URL path that is forwarded to Radicale. If Radicale +should be made available at the root of the web server (in the nginx case +using `location /`), then the setting of the `X-Script-Name` header should be +removed from the example below. Example **nginx** configuration: From 701a9794bc5cf4a6e864aae31b98ba88440517d3 Mon Sep 17 00:00:00 2001 From: Patrick Date: Sat, 5 Aug 2023 18:35:05 +0200 Subject: [PATCH 221/238] Add example configuration for Caddy web server --- DOCUMENTATION.md | 14 ++++++++++++++ 1 file changed, 14 insertions(+) diff --git a/DOCUMENTATION.md b/DOCUMENTATION.md index 663ffef1..a9eb038e 100644 --- a/DOCUMENTATION.md +++ b/DOCUMENTATION.md @@ -344,6 +344,20 @@ location /radicale/ { # The trailing / is important! } ``` +Example **Caddy** configuration with basicauth from Caddy: + +```Caddy +handle_path /radicale* { + basicauth { + user hash + } + reverse_proxy localhost:5232 { + header_up +X-Script-Name "/radicale" + header_up +X-remote-user "{http.auth.user.id}" + } +} +``` + Example **Apache** configuration: ```apache From fa6ec95e8c943d6a590fbd3eefb901cb7b0c6d7d Mon Sep 17 00:00:00 2001 From: Patrick Date: Sat, 5 Aug 2023 18:37:26 +0200 Subject: [PATCH 222/238] Formatting --- DOCUMENTATION.md | 14 +++++++------- 1 file changed, 7 insertions(+), 7 deletions(-) diff --git a/DOCUMENTATION.md b/DOCUMENTATION.md index a9eb038e..c605ddaa 100644 --- a/DOCUMENTATION.md +++ b/DOCUMENTATION.md @@ -348,13 +348,13 @@ Example **Caddy** configuration with basicauth from Caddy: ```Caddy handle_path /radicale* { - basicauth { - user hash - } - reverse_proxy localhost:5232 { - header_up +X-Script-Name "/radicale" - header_up +X-remote-user "{http.auth.user.id}" - } + basicauth { + user hash + } + reverse_proxy localhost:5232 { + header_up +X-Script-Name "/radicale" + header_up +X-remote-user "{http.auth.user.id}" + } } ``` From 110ec3a7885f523ce894a8c0e336c1a081dcd092 Mon Sep 17 00:00:00 2001 From: Theodore Ni <3806110+tjni@users.noreply.github.com> Date: Tue, 29 Aug 2023 20:49:00 -0700 Subject: [PATCH 223/238] Remove brackets from IPv4 test hostnames Python 3.11 follows the URI spec more closely and no longer allows braces surrounding IPv4 addresses in hostnames. --- radicale/tests/test_server.py | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/radicale/tests/test_server.py b/radicale/tests/test_server.py index af3cf29b..73c73e0e 100644 --- a/radicale/tests/test_server.py +++ b/radicale/tests/test_server.py @@ -60,8 +60,9 @@ class TestBaseServerRequests(BaseTest): with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as sock: # Find available port sock.bind(("127.0.0.1", 0)) + self.sockfamily = socket.AF_INET self.sockname = sock.getsockname() - self.configure({"server": {"hosts": "[%s]:%d" % self.sockname}, + self.configure({"server": {"hosts": "%s:%d" % self.sockname}, # Enable debugging for new processes "logging": {"level": "debug"}}) self.thread = threading.Thread(target=server.serve, args=( @@ -105,8 +106,9 @@ class TestBaseServerRequests(BaseTest): data_bytes = None if data: data_bytes = data.encode(encoding) + req_host = ("[%s]" % self.sockname[0]) if self.sockfamily == socket.AF_INET6 else self.sockname[0] req = request.Request( - "%s://[%s]:%d%s" % (scheme, *self.sockname, path), + "%s://%s:%d%s" % (scheme, req_host, self.sockname[1], path), data=data_bytes, headers=headers, method=method) while True: assert is_alive_fn() @@ -161,6 +163,7 @@ class TestBaseServerRequests(BaseTest): server.COMPAT_IPPROTO_IPV6, socket.IPV6_V6ONLY, 1) # Find available port sock.bind(("::1", 0)) + self.sockfamily = socket.AF_INET6 self.sockname = sock.getsockname()[:2] except OSError as e: if e.errno in (errno.EADDRNOTAVAIL, errno.EAFNOSUPPORT, From d3b78e0246eb88e7f7f44ee615138187ffa4617e Mon Sep 17 00:00:00 2001 From: Rob Pilling Date: Sun, 18 Apr 2021 20:45:19 +0100 Subject: [PATCH 224/238] Add reverse proxy example for lighttpd --- DOCUMENTATION.md | 16 ++++++++++++++++ 1 file changed, 16 insertions(+) diff --git a/DOCUMENTATION.md b/DOCUMENTATION.md index 663ffef1..d82b64bb 100644 --- a/DOCUMENTATION.md +++ b/DOCUMENTATION.md @@ -368,6 +368,22 @@ RewriteRule ^(.*)$ http://localhost:5232/$1 [P,L] RequestHeader set X-Script-Name /radicale ``` +Example **lighttpd** configuration: + +```lighttpd +server.modules += ( "mod_proxy" , "mod_setenv" ) + +$HTTP["url"] =~ "^/radicale/" { + proxy.server = ( "" => (( "host" => "127.0.0.1", "port" => "5232" )) ) + proxy.header = ( "map-urlpath" => ( "/radicale/" => "/" )) + + setenv.add-request-header = ( + "X-Script-Name" => "/radicale", + "Script-Name" => "/radicale", + ) +} +``` + Be reminded that Radicale's default configuration enforces limits on the maximum number of parallel connections, the maximum file size and the rate of incorrect authentication attempts. Connections are terminated after a timeout. From 8e8c65222575d64a90d4fe2d3f57a0d824cef918 Mon Sep 17 00:00:00 2001 From: Rob Pilling Date: Mon, 18 Sep 2023 18:03:17 +0100 Subject: [PATCH 225/238] Ensure lighttpd docs handle doubled-path redirects --- DOCUMENTATION.md | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/DOCUMENTATION.md b/DOCUMENTATION.md index d82b64bb..6d760f22 100644 --- a/DOCUMENTATION.md +++ b/DOCUMENTATION.md @@ -371,7 +371,7 @@ RequestHeader set X-Script-Name /radicale Example **lighttpd** configuration: ```lighttpd -server.modules += ( "mod_proxy" , "mod_setenv" ) +server.modules += ( "mod_proxy" , "mod_setenv", "mod_rewrite" ) $HTTP["url"] =~ "^/radicale/" { proxy.server = ( "" => (( "host" => "127.0.0.1", "port" => "5232" )) ) @@ -381,6 +381,7 @@ $HTTP["url"] =~ "^/radicale/" { "X-Script-Name" => "/radicale", "Script-Name" => "/radicale", ) + url.rewrite-once = ( "^/radicale/radicale/(.*)" => "/radicale/$1" ) } ``` From 02c949d5d304c87fd588a1b486b6db0903432f1c Mon Sep 17 00:00:00 2001 From: G-Huber <37844848+G-Huber@users.noreply.github.com> Date: Tue, 31 Oct 2023 23:13:46 +0100 Subject: [PATCH 226/238] Update DOCUMENTATION.md Explain possible pitfall when using git with systemd --- DOCUMENTATION.md | 10 ++++++++++ 1 file changed, 10 insertions(+) diff --git a/DOCUMENTATION.md b/DOCUMENTATION.md index 663ffef1..15a91b6c 100644 --- a/DOCUMENTATION.md +++ b/DOCUMENTATION.md @@ -528,6 +528,16 @@ git add -A && (git diff --cached --quiet || git commit -m "Changes by "%(user)s) The command gets executed after every change to the storage and commits the changes into the **git** repository. +For the hook to not cause errors either **git** user details need to be set and match the owner of the collections directory or the repository needs to be marked as safe. + +When using the systemd unit file from the [Running as a service](#running-as-a-service) section this **cannot** be done via a `.gitconfig` file in the users home directory, as Radicale won't have read permissions! + +In `/var/lib/radicale/collections` run: +```bash +git config user.name "radicale" +git config user.email "radicale@example.com" +``` + ## Documentation ### Configuration From 4cac895901aae69bf4c0b960fbdef0b8a86801cd Mon Sep 17 00:00:00 2001 From: G-Huber <37844848+G-Huber@users.noreply.github.com> Date: Wed, 1 Nov 2023 08:38:02 +0100 Subject: [PATCH 227/238] Update DOCUMENTATION.md Mention correct directory for git config --- DOCUMENTATION.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/DOCUMENTATION.md b/DOCUMENTATION.md index 15a91b6c..95cf7b30 100644 --- a/DOCUMENTATION.md +++ b/DOCUMENTATION.md @@ -532,7 +532,7 @@ For the hook to not cause errors either **git** user details need to be set and When using the systemd unit file from the [Running as a service](#running-as-a-service) section this **cannot** be done via a `.gitconfig` file in the users home directory, as Radicale won't have read permissions! -In `/var/lib/radicale/collections` run: +In `/var/lib/radicale/collections/.git` run: ```bash git config user.name "radicale" git config user.email "radicale@example.com" From 1c82eb5e05d7c54c77b2bb88da037bb5be5124be Mon Sep 17 00:00:00 2001 From: Eugene Davis Date: Mon, 26 Sep 2022 10:27:05 +0200 Subject: [PATCH 228/238] Add a Dockerfile for building the current code as a Dockerfile --- Dockerfile.dev | 19 +++++++++++++++++++ 1 file changed, 19 insertions(+) create mode 100644 Dockerfile.dev diff --git a/Dockerfile.dev b/Dockerfile.dev new file mode 100644 index 00000000..edf1f4af --- /dev/null +++ b/Dockerfile.dev @@ -0,0 +1,19 @@ +FROM python:3-alpine + +# Version of Radicale (e.g. v3) +ARG VERSION=master +# Persistent storage for data +VOLUME /var/lib/radicale +# TCP port of Radicale +EXPOSE 5232 +# Run Radicale +CMD ["radicale", "--hosts", "0.0.0.0:5232"] + +COPY . /app + +WORKDIR /app + +RUN apk add --no-cache ca-certificates openssl \ + && apk add --no-cache --virtual .build-deps gcc libffi-dev musl-dev \ + && pip install --no-cache-dir -e . \ + && apk del .build-deps From 5b0830ea083f5c512c563a3af71df578d448832e Mon Sep 17 00:00:00 2001 From: Eugene Davis Date: Mon, 26 Sep 2022 12:18:48 +0200 Subject: [PATCH 229/238] Update Dockerfile to use build stage and set non-root user --- Dockerfile | 25 +++++++++++++++++++------ Dockerfile.dev | 36 +++++++++++++++++++++++------------- 2 files changed, 42 insertions(+), 19 deletions(-) diff --git a/Dockerfile b/Dockerfile index 1bfc82ac..67c5fc1b 100644 --- a/Dockerfile +++ b/Dockerfile @@ -1,17 +1,30 @@ # This file is intended to be used apart from the containing source code tree. -FROM python:3-alpine +FROM python:3-alpine as builder # Version of Radicale (e.g. v3) ARG VERSION=master + +RUN apk add --no-cache --virtual gcc libffi-dev musl-dev \ + && python -m venv /app/venv \ + && /app/venv/bin/pip install --no-cache-dir "Radicale[bcrypt] @ https://github.com/Kozea/Radicale/archive/${VERSION}.tar.gz" + + +FROM python:3-alpine + +WORKDIR /app + +RUN adduser radicale --home /var/lib/radicale --system --uid 1000 --disabled-password \ + && apk add --no-cache ca-certificates openssl + +COPY --chown=1000 --from=builder /app/venv /app + # Persistent storage for data VOLUME /var/lib/radicale # TCP port of Radicale EXPOSE 5232 # Run Radicale -CMD ["radicale", "--hosts", "0.0.0.0:5232"] +ENTRYPOINT [ "/app/bin/python", "/app/bin/radicale"] +CMD ["--hosts", "0.0.0.0:5232"] -RUN apk add --no-cache ca-certificates openssl \ - && apk add --no-cache --virtual .build-deps gcc libffi-dev musl-dev \ - && pip install --no-cache-dir "Radicale[bcrypt] @ https://github.com/Kozea/Radicale/archive/${VERSION}.tar.gz" \ - && apk del .build-deps +USER 1000 \ No newline at end of file diff --git a/Dockerfile.dev b/Dockerfile.dev index edf1f4af..879c5e39 100644 --- a/Dockerfile.dev +++ b/Dockerfile.dev @@ -1,19 +1,29 @@ -FROM python:3-alpine +FROM python:3-alpine as builder -# Version of Radicale (e.g. v3) -ARG VERSION=master -# Persistent storage for data -VOLUME /var/lib/radicale -# TCP port of Radicale -EXPOSE 5232 -# Run Radicale -CMD ["radicale", "--hosts", "0.0.0.0:5232"] COPY . /app WORKDIR /app -RUN apk add --no-cache ca-certificates openssl \ - && apk add --no-cache --virtual .build-deps gcc libffi-dev musl-dev \ - && pip install --no-cache-dir -e . \ - && apk del .build-deps +RUN apk add --no-cache --virtual gcc libffi-dev musl-dev \ + && python -m venv /app/venv \ + && /app/venv/bin/pip install --no-cache-dir .[bcrypt] + +FROM python:3-alpine + +WORKDIR /app + +RUN adduser radicale --home /var/lib/radicale --system --uid 1000 --disabled-password \ + && apk add --no-cache ca-certificates openssl + +COPY --chown=1000 --from=builder /app/venv /app + +# Persistent storage for data +VOLUME /var/lib/radicale +# TCP port of Radicale +EXPOSE 5232 +# Run Radicale +ENTRYPOINT [ "/app/bin/python", "/app/bin/radicale"] +CMD ["--hosts", "0.0.0.0:5232"] + +USER 1000 \ No newline at end of file From 2dd7328859bea10a3f69a0759377845aef67785e Mon Sep 17 00:00:00 2001 From: Eugene Davis Date: Mon, 26 Sep 2022 12:25:56 +0200 Subject: [PATCH 230/238] Add argument for specifying optional dependencies --- Dockerfile | 5 ++++- Dockerfile.dev | 4 +++- 2 files changed, 7 insertions(+), 2 deletions(-) diff --git a/Dockerfile b/Dockerfile index 67c5fc1b..1af0d855 100644 --- a/Dockerfile +++ b/Dockerfile @@ -5,9 +5,12 @@ FROM python:3-alpine as builder # Version of Radicale (e.g. v3) ARG VERSION=master +# Optional dependencies (e.g. bcrypt) +ARG DEPENDENCIES=bcrypt + RUN apk add --no-cache --virtual gcc libffi-dev musl-dev \ && python -m venv /app/venv \ - && /app/venv/bin/pip install --no-cache-dir "Radicale[bcrypt] @ https://github.com/Kozea/Radicale/archive/${VERSION}.tar.gz" + && /app/venv/bin/pip install --no-cache-dir "Radicale[${DEPENDENCIES}] @ https://github.com/Kozea/Radicale/archive/${VERSION}.tar.gz" FROM python:3-alpine diff --git a/Dockerfile.dev b/Dockerfile.dev index 879c5e39..f2644997 100644 --- a/Dockerfile.dev +++ b/Dockerfile.dev @@ -1,5 +1,7 @@ FROM python:3-alpine as builder +# Optional dependencies (e.g. bcrypt) +ARG DEPENDENCIES=bcrypt COPY . /app @@ -7,7 +9,7 @@ WORKDIR /app RUN apk add --no-cache --virtual gcc libffi-dev musl-dev \ && python -m venv /app/venv \ - && /app/venv/bin/pip install --no-cache-dir .[bcrypt] + && /app/venv/bin/pip install --no-cache-dir .[${DEPENDENCIES}] FROM python:3-alpine From f57e738156987da440ae264707ee28bffb71b926 Mon Sep 17 00:00:00 2001 From: Eugene Davis Date: Wed, 1 Feb 2023 19:17:47 +0100 Subject: [PATCH 231/238] fix: dockerfile user from UID to username --- Dockerfile | 4 ++-- Dockerfile.dev | 4 ++-- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/Dockerfile b/Dockerfile index 1af0d855..16732839 100644 --- a/Dockerfile +++ b/Dockerfile @@ -20,7 +20,7 @@ WORKDIR /app RUN adduser radicale --home /var/lib/radicale --system --uid 1000 --disabled-password \ && apk add --no-cache ca-certificates openssl -COPY --chown=1000 --from=builder /app/venv /app +COPY --chown=radicale --from=builder /app/venv /app # Persistent storage for data VOLUME /var/lib/radicale @@ -30,4 +30,4 @@ EXPOSE 5232 ENTRYPOINT [ "/app/bin/python", "/app/bin/radicale"] CMD ["--hosts", "0.0.0.0:5232"] -USER 1000 \ No newline at end of file +USER radicale \ No newline at end of file diff --git a/Dockerfile.dev b/Dockerfile.dev index f2644997..b2d996ce 100644 --- a/Dockerfile.dev +++ b/Dockerfile.dev @@ -18,7 +18,7 @@ WORKDIR /app RUN adduser radicale --home /var/lib/radicale --system --uid 1000 --disabled-password \ && apk add --no-cache ca-certificates openssl -COPY --chown=1000 --from=builder /app/venv /app +COPY --chown=radicale --from=builder /app/venv /app # Persistent storage for data VOLUME /var/lib/radicale @@ -28,4 +28,4 @@ EXPOSE 5232 ENTRYPOINT [ "/app/bin/python", "/app/bin/radicale"] CMD ["--hosts", "0.0.0.0:5232"] -USER 1000 \ No newline at end of file +USER radicale \ No newline at end of file From 93e5dd4a707200aab6afabbc9c21bd51d02da378 Mon Sep 17 00:00:00 2001 From: Ian Bishop <1296987+porjo@users.noreply.github.com> Date: Fri, 1 Mar 2024 20:04:14 +1000 Subject: [PATCH 232/238] Listen on IPv4 and IPv6 --- Dockerfile | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Dockerfile b/Dockerfile index 16732839..65c5e681 100644 --- a/Dockerfile +++ b/Dockerfile @@ -28,6 +28,6 @@ VOLUME /var/lib/radicale EXPOSE 5232 # Run Radicale ENTRYPOINT [ "/app/bin/python", "/app/bin/radicale"] -CMD ["--hosts", "0.0.0.0:5232"] +CMD ["--hosts", "0.0.0.0:5232,[::]:5232"] -USER radicale \ No newline at end of file +USER radicale From 8e3f3b5bf2f7679604aee1a6503b2d38e1f45309 Mon Sep 17 00:00:00 2001 From: Peter Bieringer Date: Fri, 1 Mar 2024 21:35:54 +0100 Subject: [PATCH 233/238] fix for actions: ./radicale/tests/test_server.py:109:80: E501 line too long (106 > 79 characters) --- radicale/tests/test_server.py | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/radicale/tests/test_server.py b/radicale/tests/test_server.py index 73c73e0e..67ce10d4 100644 --- a/radicale/tests/test_server.py +++ b/radicale/tests/test_server.py @@ -106,7 +106,10 @@ class TestBaseServerRequests(BaseTest): data_bytes = None if data: data_bytes = data.encode(encoding) - req_host = ("[%s]" % self.sockname[0]) if self.sockfamily == socket.AF_INET6 else self.sockname[0] + if self.sockfamily == socket.AF_INET6: + req_host = ("[%s]" % self.sockname[0]) + else: + req_host = self.sockname[0] req = request.Request( "%s://%s:%d%s" % (scheme, req_host, self.sockname[1], path), data=data_bytes, headers=headers, method=method) From 76e06ea3fcfd7efa808e7c2f9955c6f8fb04dbd0 Mon Sep 17 00:00:00 2001 From: Peter Bieringer Date: Fri, 1 Mar 2024 21:40:51 +0100 Subject: [PATCH 234/238] fix found by actions/python3.11: ./radicale/item/__init__.py:167:28: E721 do not compare types, for exact checks use `is` / `is not`, for instance checks use `isinstance()` --- radicale/item/__init__.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/radicale/item/__init__.py b/radicale/item/__init__.py index 4a3fc22e..b0cef222 100644 --- a/radicale/item/__init__.py +++ b/radicale/item/__init__.py @@ -164,7 +164,7 @@ def check_and_sanitize_items( ref_value_param = component.dtstart.params.get("VALUE") for dates in chain(component.contents.get("exdate", []), component.contents.get("rdate", [])): - if all(type(d) == type(ref_date) for d in dates.value): + if all(type(d) is type(ref_date) for d in dates.value): continue for i, date in enumerate(dates.value): dates.value[i] = ref_date.replace( From cc2e1553d36b722de2afc88f7ce8ab48c3477924 Mon Sep 17 00:00:00 2001 From: Peter Bieringer Date: Sat, 2 Mar 2024 07:36:14 +0100 Subject: [PATCH 235/238] ignore "mypy" type checks for now --- radicale/storage/multifilesystem/base.py | 2 +- radicale/storage/multifilesystem/cache.py | 2 +- radicale/storage/multifilesystem/meta.py | 2 +- radicale/storage/multifilesystem/sync.py | 2 +- radicale/storage/multifilesystem/upload.py | 2 +- 5 files changed, 5 insertions(+), 5 deletions(-) diff --git a/radicale/storage/multifilesystem/base.py b/radicale/storage/multifilesystem/base.py index 7b1b7d28..f6e56b3a 100644 --- a/radicale/storage/multifilesystem/base.py +++ b/radicale/storage/multifilesystem/base.py @@ -44,7 +44,7 @@ class CollectionBase(storage.BaseCollection): filesystem_path = pathutils.path_to_filesystem(folder, self.path) self._filesystem_path = filesystem_path - @types.contextmanager + @types.contextmanager # type: ignore # for now, TODO fix for "mypy" def _atomic_write(self, path: str, mode: str = "w", newline: Optional[str] = None) -> Iterator[IO[AnyStr]]: # TODO: Overload with Literal when dropping support for Python < 3.8 diff --git a/radicale/storage/multifilesystem/cache.py b/radicale/storage/multifilesystem/cache.py index 9cb4dda6..086f2ac3 100644 --- a/radicale/storage/multifilesystem/cache.py +++ b/radicale/storage/multifilesystem/cache.py @@ -86,7 +86,7 @@ class CollectionPartCache(CollectionBase): content = self._item_cache_content(item) self._storage._makedirs_synced(cache_folder) # Race: Other processes might have created and locked the file. - with contextlib.suppress(PermissionError), self._atomic_write( + with contextlib.suppress(PermissionError), self._atomic_write( # type: ignore # for now, TODO fix for "mypy" os.path.join(cache_folder, href), "wb") as fo: fb = cast(BinaryIO, fo) pickle.dump((cache_hash, *content), fb) diff --git a/radicale/storage/multifilesystem/meta.py b/radicale/storage/multifilesystem/meta.py index edce6513..47c8323e 100644 --- a/radicale/storage/multifilesystem/meta.py +++ b/radicale/storage/multifilesystem/meta.py @@ -61,6 +61,6 @@ class CollectionPartMeta(CollectionBase): return self._meta_cache if key is None else self._meta_cache.get(key) def set_meta(self, props: Mapping[str, str]) -> None: - with self._atomic_write(self._props_path, "w") as fo: + with self._atomic_write(self._props_path, "w") as fo: # type: ignore # for now, TODO fix for "mypy" f = cast(TextIO, fo) json.dump(props, f, sort_keys=True) diff --git a/radicale/storage/multifilesystem/sync.py b/radicale/storage/multifilesystem/sync.py index 83cbe2a0..75eae84a 100644 --- a/radicale/storage/multifilesystem/sync.py +++ b/radicale/storage/multifilesystem/sync.py @@ -95,7 +95,7 @@ class CollectionPartSync(CollectionPartCache, CollectionPartHistory, self._storage._makedirs_synced(token_folder) try: # Race: Other processes might have created and locked the file. - with self._atomic_write(token_path, "wb") as fo: + with self._atomic_write(token_path, "wb") as fo: # type: ignore # for now, TODO fix for "mypy" fb = cast(BinaryIO, fo) pickle.dump(state, fb) except PermissionError: diff --git a/radicale/storage/multifilesystem/upload.py b/radicale/storage/multifilesystem/upload.py index 730e4cb2..a91f83b7 100644 --- a/radicale/storage/multifilesystem/upload.py +++ b/radicale/storage/multifilesystem/upload.py @@ -43,7 +43,7 @@ class CollectionPartUpload(CollectionPartGet, CollectionPartCache, raise ValueError("Failed to store item %r in collection %r: %s" % (href, self.path, e)) from e path = pathutils.path_to_filesystem(self._filesystem_path, href) - with self._atomic_write(path, newline="") as fo: + with self._atomic_write(path, newline="") as fo: # type: ignore # for now, TODO fix for "mypy" f = cast(TextIO, fo) f.write(item.serialize()) # Clean the cache after the actual item is stored, or the cache entry From 551b5c227257b033037a4ac066fabd2ad56dbe65 Mon Sep 17 00:00:00 2001 From: Peter Bieringer Date: Sat, 2 Mar 2024 07:42:39 +0100 Subject: [PATCH 236/238] fix for code validation --- radicale/storage/multifilesystem/base.py | 3 ++- radicale/storage/multifilesystem/cache.py | 3 ++- radicale/storage/multifilesystem/meta.py | 3 ++- radicale/storage/multifilesystem/sync.py | 3 ++- radicale/storage/multifilesystem/upload.py | 3 ++- 5 files changed, 10 insertions(+), 5 deletions(-) diff --git a/radicale/storage/multifilesystem/base.py b/radicale/storage/multifilesystem/base.py index f6e56b3a..c2257b34 100644 --- a/radicale/storage/multifilesystem/base.py +++ b/radicale/storage/multifilesystem/base.py @@ -44,7 +44,8 @@ class CollectionBase(storage.BaseCollection): filesystem_path = pathutils.path_to_filesystem(folder, self.path) self._filesystem_path = filesystem_path - @types.contextmanager # type: ignore # for now, TODO fix for "mypy" + # TODO: better fix for "mypy" + @types.contextmanager # type: ignore def _atomic_write(self, path: str, mode: str = "w", newline: Optional[str] = None) -> Iterator[IO[AnyStr]]: # TODO: Overload with Literal when dropping support for Python < 3.8 diff --git a/radicale/storage/multifilesystem/cache.py b/radicale/storage/multifilesystem/cache.py index 086f2ac3..fc6b10f6 100644 --- a/radicale/storage/multifilesystem/cache.py +++ b/radicale/storage/multifilesystem/cache.py @@ -86,7 +86,8 @@ class CollectionPartCache(CollectionBase): content = self._item_cache_content(item) self._storage._makedirs_synced(cache_folder) # Race: Other processes might have created and locked the file. - with contextlib.suppress(PermissionError), self._atomic_write( # type: ignore # for now, TODO fix for "mypy" + # TODO: better fix for "mypy" + with contextlib.suppress(PermissionError), self._atomic_write( # type: ignore os.path.join(cache_folder, href), "wb") as fo: fb = cast(BinaryIO, fo) pickle.dump((cache_hash, *content), fb) diff --git a/radicale/storage/multifilesystem/meta.py b/radicale/storage/multifilesystem/meta.py index 47c8323e..577bfa14 100644 --- a/radicale/storage/multifilesystem/meta.py +++ b/radicale/storage/multifilesystem/meta.py @@ -61,6 +61,7 @@ class CollectionPartMeta(CollectionBase): return self._meta_cache if key is None else self._meta_cache.get(key) def set_meta(self, props: Mapping[str, str]) -> None: - with self._atomic_write(self._props_path, "w") as fo: # type: ignore # for now, TODO fix for "mypy" + # TODO: better fix for "mypy" + with self._atomic_write(self._props_path, "w") as fo: # type: ignore f = cast(TextIO, fo) json.dump(props, f, sort_keys=True) diff --git a/radicale/storage/multifilesystem/sync.py b/radicale/storage/multifilesystem/sync.py index 75eae84a..7f2f8223 100644 --- a/radicale/storage/multifilesystem/sync.py +++ b/radicale/storage/multifilesystem/sync.py @@ -95,7 +95,8 @@ class CollectionPartSync(CollectionPartCache, CollectionPartHistory, self._storage._makedirs_synced(token_folder) try: # Race: Other processes might have created and locked the file. - with self._atomic_write(token_path, "wb") as fo: # type: ignore # for now, TODO fix for "mypy" + # TODO: better fix for "mypy" + with self._atomic_write(token_path, "wb") as fo: # type: ignore fb = cast(BinaryIO, fo) pickle.dump(state, fb) except PermissionError: diff --git a/radicale/storage/multifilesystem/upload.py b/radicale/storage/multifilesystem/upload.py index a91f83b7..58a2a5e1 100644 --- a/radicale/storage/multifilesystem/upload.py +++ b/radicale/storage/multifilesystem/upload.py @@ -43,7 +43,8 @@ class CollectionPartUpload(CollectionPartGet, CollectionPartCache, raise ValueError("Failed to store item %r in collection %r: %s" % (href, self.path, e)) from e path = pathutils.path_to_filesystem(self._filesystem_path, href) - with self._atomic_write(path, newline="") as fo: # type: ignore # for now, TODO fix for "mypy" + # TODO: better fix for "mypy" + with self._atomic_write(path, newline="") as fo: # type: ignore f = cast(TextIO, fo) f.write(item.serialize()) # Clean the cache after the actual item is stored, or the cache entry From 913635a17ead8f63ecd7533424d4ad227503f27b Mon Sep 17 00:00:00 2001 From: Peter Bieringer Date: Sat, 2 Mar 2024 07:47:23 +0100 Subject: [PATCH 237/238] fix fo E261 at least two spaces before inline comment --- radicale/storage/multifilesystem/base.py | 2 +- radicale/storage/multifilesystem/cache.py | 2 +- radicale/storage/multifilesystem/meta.py | 2 +- radicale/storage/multifilesystem/sync.py | 2 +- radicale/storage/multifilesystem/upload.py | 2 +- 5 files changed, 5 insertions(+), 5 deletions(-) diff --git a/radicale/storage/multifilesystem/base.py b/radicale/storage/multifilesystem/base.py index c2257b34..bbb02198 100644 --- a/radicale/storage/multifilesystem/base.py +++ b/radicale/storage/multifilesystem/base.py @@ -45,7 +45,7 @@ class CollectionBase(storage.BaseCollection): self._filesystem_path = filesystem_path # TODO: better fix for "mypy" - @types.contextmanager # type: ignore + @types.contextmanager # type: ignore def _atomic_write(self, path: str, mode: str = "w", newline: Optional[str] = None) -> Iterator[IO[AnyStr]]: # TODO: Overload with Literal when dropping support for Python < 3.8 diff --git a/radicale/storage/multifilesystem/cache.py b/radicale/storage/multifilesystem/cache.py index fc6b10f6..31ab4715 100644 --- a/radicale/storage/multifilesystem/cache.py +++ b/radicale/storage/multifilesystem/cache.py @@ -87,7 +87,7 @@ class CollectionPartCache(CollectionBase): self._storage._makedirs_synced(cache_folder) # Race: Other processes might have created and locked the file. # TODO: better fix for "mypy" - with contextlib.suppress(PermissionError), self._atomic_write( # type: ignore + with contextlib.suppress(PermissionError), self._atomic_write( # type: ignore os.path.join(cache_folder, href), "wb") as fo: fb = cast(BinaryIO, fo) pickle.dump((cache_hash, *content), fb) diff --git a/radicale/storage/multifilesystem/meta.py b/radicale/storage/multifilesystem/meta.py index 577bfa14..b95fb162 100644 --- a/radicale/storage/multifilesystem/meta.py +++ b/radicale/storage/multifilesystem/meta.py @@ -62,6 +62,6 @@ class CollectionPartMeta(CollectionBase): def set_meta(self, props: Mapping[str, str]) -> None: # TODO: better fix for "mypy" - with self._atomic_write(self._props_path, "w") as fo: # type: ignore + with self._atomic_write(self._props_path, "w") as fo: # type: ignore f = cast(TextIO, fo) json.dump(props, f, sort_keys=True) diff --git a/radicale/storage/multifilesystem/sync.py b/radicale/storage/multifilesystem/sync.py index 7f2f8223..ae703c91 100644 --- a/radicale/storage/multifilesystem/sync.py +++ b/radicale/storage/multifilesystem/sync.py @@ -96,7 +96,7 @@ class CollectionPartSync(CollectionPartCache, CollectionPartHistory, try: # Race: Other processes might have created and locked the file. # TODO: better fix for "mypy" - with self._atomic_write(token_path, "wb") as fo: # type: ignore + with self._atomic_write(token_path, "wb") as fo: # type: ignore fb = cast(BinaryIO, fo) pickle.dump(state, fb) except PermissionError: diff --git a/radicale/storage/multifilesystem/upload.py b/radicale/storage/multifilesystem/upload.py index 58a2a5e1..a9fcdc2c 100644 --- a/radicale/storage/multifilesystem/upload.py +++ b/radicale/storage/multifilesystem/upload.py @@ -44,7 +44,7 @@ class CollectionPartUpload(CollectionPartGet, CollectionPartCache, (href, self.path, e)) from e path = pathutils.path_to_filesystem(self._filesystem_path, href) # TODO: better fix for "mypy" - with self._atomic_write(path, newline="") as fo: # type: ignore + with self._atomic_write(path, newline="") as fo: # type: ignore f = cast(TextIO, fo) f.write(item.serialize()) # Clean the cache after the actual item is stored, or the cache entry From 88f65671ced50c6ba1b569c79796e5e584a8c499 Mon Sep 17 00:00:00 2001 From: Peter Bieringer Date: Sat, 2 Mar 2024 08:00:24 +0100 Subject: [PATCH 238/238] ignore "E501 line too long" which turned into deadlock making "mypy" happy --- setup.cfg | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/setup.cfg b/setup.cfg index fe2038fb..4326cd97 100644 --- a/setup.cfg +++ b/setup.cfg @@ -30,7 +30,7 @@ known_third_party = defusedxml,passlib,pkg_resources,pytest,vobject # Only enable default tests (https://github.com/PyCQA/flake8/issues/790#issuecomment-812823398) # DNE: DOES-NOT-EXIST select = E,F,W,C90,DNE000 -ignore = E121,E123,E126,E226,E24,E704,W503,W504,DNE000 +ignore = E121,E123,E126,E226,E24,E704,W503,W504,DNE000,E501 extend-exclude = build [mypy]