1
0
Fork 0
mirror of https://github.com/Kozea/Radicale.git synced 2025-06-26 16:45:52 +00:00
Radicale/radicale/__init__.py

312 lines
11 KiB
Python
Raw Normal View History

# -*- coding: utf-8 -*-
#
# This file is part of Radicale Server - Calendar Server
2011-01-09 17:46:22 +01:00
# Copyright © 2008-2011 Guillaume Ayoub
# Copyright © 2008 Nicolas Kandel
# Copyright © 2008 Pascal Halter
#
# 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 <http://www.gnu.org/licenses/>.
"""
Radicale Server module.
This module offers 3 useful classes:
- ``HTTPServer`` is a simple HTTP server;
- ``HTTPSServer`` is a HTTPS server, wrapping the HTTP server in a socket
managing SSL connections;
- ``CalendarHTTPHandler`` is a CalDAV request handler for HTTP(S) servers.
To use this module, you should take a look at the file ``radicale.py`` that
should have been included in this package.
"""
2010-02-10 23:52:50 +01:00
import os
import posixpath
import base64
2010-01-19 17:49:32 +01:00
import socket
2010-02-10 23:52:50 +01:00
# Manage Python2/3 different modules
# pylint: disable=F0401
2010-01-15 16:04:03 +01:00
try:
from http import client, server
except ImportError:
import httplib as client
import BaseHTTPServer as server
# pylint: enable=F0401
2011-02-16 13:53:27 +01:00
from radicale import acl, config, ical, xmlutils, log
2010-08-07 23:37:05 +02:00
VERSION = "git"
def _check(request, function):
"""Check if user has sufficient rights for performing ``request``."""
log.log(10, "Check if user has sufficient rights for performing ``request`` %s." % (request.command))
# ``_check`` decorator can access ``request`` protected functions
# pylint: disable=W0212
# If we have no calendar, don't check rights
if not request._calendar:
return function(request)
authorization = request.headers.get("Authorization", None)
if authorization:
challenge = authorization.lstrip("Basic").strip().encode("ascii")
plain = request._decode(base64.b64decode(challenge))
user, password = plain.split(":")
else:
user = password = None
if request.server.acl.has_right(request._calendar.owner, user, password):
log.log(20, "Sufficient rights for performing ``request`` %s." % (request.command))
function(request)
else:
2011-02-16 13:53:27 +01:00
log.log(40, "No sufficient rights for performing ``request``.")
request.send_response(client.UNAUTHORIZED)
request.send_header(
"WWW-Authenticate",
"Basic realm=\"Radicale Server - Password Required\"")
request.end_headers()
# pylint: enable=W0212
class HTTPServer(server.HTTPServer):
"""HTTP server."""
PROTOCOL = "http"
# Maybe a Pylint bug, ``__init__`` calls ``server.HTTPServer.__init__``
# pylint: disable=W0231
2011-04-02 21:45:45 +02:00
def __init__(self, address, handler, bind_and_activate=True):
"""Create server."""
2011-02-16 13:53:27 +01:00
log.log(10, "Create HTTP server.")
server.HTTPServer.__init__(self, address, handler)
2011-04-02 21:45:45 +02:00
ipv6 = ":" in address[0]
2011-04-02 21:45:45 +02:00
if ipv6:
self.address_family = socket.AF_INET6
2011-04-02 21:45:45 +02:00
# Do not bind and activate, as we might change socketopts
server.HTTPServer.__init__(self, address, handler, False)
2011-04-02 21:45:45 +02:00
if ipv6:
# Only allow IPv6 connections to the IPv6 socket
self.socket.setsockopt(socket.IPPROTO_IPV6, socket.IPV6_V6ONLY, 1)
if bind_and_activate:
self.server_bind()
self.server_activate()
self.acl = acl.load()
# pylint: enable=W0231
2010-01-19 17:49:32 +01:00
2010-01-19 17:49:32 +01:00
class HTTPSServer(HTTPServer):
"""HTTPS server."""
PROTOCOL = "https"
2011-01-09 17:41:42 +01:00
2011-04-02 21:45:45 +02:00
def __init__(self, address, handler, bind_and_activate=True):
"""Create server by wrapping HTTP socket in an SSL socket."""
2011-02-16 13:53:27 +01:00
log.log(10, "Create server by wrapping HTTP socket in an SSL socket.")
2010-01-19 17:49:32 +01:00
# Fails with Python 2.5, import if needed
# pylint: disable=F0401
2010-01-19 17:49:32 +01:00
import ssl
# pylint: enable=F0401
2010-01-19 17:49:32 +01:00
HTTPServer.__init__(self, address, handler, False)
2010-01-19 17:49:32 +01:00
self.socket = ssl.wrap_socket(
2011-04-02 21:45:45 +02:00
self.socket,
2010-04-10 00:18:38 +02:00
server_side=True,
2010-01-19 17:49:32 +01:00
certfile=config.get("server", "certificate"),
keyfile=config.get("server", "key"),
ssl_version=ssl.PROTOCOL_SSLv23)
if bind_and_activate:
self.server_bind()
self.server_activate()
2010-01-19 17:49:32 +01:00
2010-01-19 17:49:32 +01:00
class CalendarHTTPHandler(server.BaseHTTPRequestHandler):
2010-01-10 18:55:32 +01:00
"""HTTP requests handler for calendars."""
2011-02-16 13:53:27 +01:00
log.log(10, "HTTP requests handler for calendars.")
_encoding = config.get("encoding", "request")
# Decorator checking rights before performing request
check_rights = lambda function: lambda request: _check(request, function)
@property
2010-02-10 23:52:50 +01:00
def _calendar(self):
"""The ``ical.Calendar`` object corresponding to the given path."""
log.log(10, "The ``ical.Calendar`` object corresponding to the given path. (%s)" % (self.path))
# ``self.path`` must be something like a posix path
2010-02-10 23:52:50 +01:00
# ``normpath`` should clean malformed and malicious request paths
attributes = posixpath.normpath(self.path.strip("/")).split("/")
2010-02-10 23:52:50 +01:00
if len(attributes) >= 2:
path = "%s/%s" % (attributes[0], attributes[1])
return ical.Calendar(path)
2010-02-10 23:52:50 +01:00
def _decode(self, text):
"""Try to decode text according to various parameters."""
2011-02-16 13:53:27 +01:00
log.log(10, "Try to decode text according to various parameters.")
# List of charsets to try
charsets = []
# First append content charset given in the request
content_type = self.headers.get("Content-Type", None)
if content_type and "charset=" in content_type:
charsets.append(content_type.split("charset=")[1].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
# Naming methods ``do_*`` is OK here
# pylint: disable=C0103
2010-01-16 13:33:50 +01:00
def do_GET(self):
"""Manage GET request."""
2011-02-16 13:53:27 +01:00
log.log(10, "Manage GET request.")
self.do_HEAD()
2010-12-20 15:49:48 +01:00
if self._answer:
self.wfile.write(self._answer)
@check_rights
def do_HEAD(self):
"""Manage HEAD request."""
2011-02-16 13:53:27 +01:00
log.log(10, "Manage HEAD request.")
2010-06-24 00:36:00 +02:00
item_name = xmlutils.name_from_path(self.path)
if item_name:
# Get calendar item
item = self._calendar.get_item(item_name)
if item:
items = self._calendar.timezones
items.append(item)
answer_text = ical.serialize(
headers=self._calendar.headers, items=items)
etag = item.etag
else:
2010-12-20 15:49:48 +01:00
self._answer = None
self.send_response(client.GONE)
return
else:
# Get whole calendar
answer_text = self._calendar.text
etag = self._calendar.etag
2010-01-16 13:33:50 +01:00
self._answer = answer_text.encode(self._encoding)
2010-01-16 13:33:50 +01:00
self.send_response(client.OK)
self.send_header("Content-Length", len(self._answer))
self.send_header("Content-Type", "text/calendar")
self.send_header("Last-Modified", self._calendar.last_modified)
self.send_header("ETag", etag)
2010-01-16 13:33:50 +01:00
self.end_headers()
@check_rights
2010-01-10 18:55:32 +01:00
def do_DELETE(self):
"""Manage DELETE request."""
2011-02-16 13:53:27 +01:00
log.log(10, "Manage DELETE request.")
item = self._calendar.get_item(xmlutils.name_from_path(self.path))
if item and self.headers.get("If-Match", item.etag) == item.etag:
# No ETag precondition or precondition verified, delete item
self._answer = xmlutils.delete(self.path, self._calendar)
self.send_response(client.NO_CONTENT)
self.send_header("Content-Length", len(self._answer))
self.end_headers()
self.wfile.write(self._answer)
else:
# No item or ETag precondition not verified, do not delete item
self.send_response(client.PRECONDITION_FAILED)
2011-02-01 17:01:30 +01:00
@check_rights
def do_MKCALENDAR(self):
"""Manage MKCALENDAR request."""
self.send_response(client.CREATED)
self.end_headers()
2010-01-10 18:55:32 +01:00
def do_OPTIONS(self):
"""Manage OPTIONS request."""
2011-02-16 13:53:27 +01:00
log.log(10, "Manage OPTIONS request.")
2010-01-15 16:04:03 +01:00
self.send_response(client.OK)
2010-09-28 16:04:17 +02:00
self.send_header(
2011-02-01 17:01:30 +01:00
"Allow", "DELETE, HEAD, GET, MKCALENDAR, "
"OPTIONS, PROPFIND, PUT, REPORT")
2010-01-10 18:55:32 +01:00
self.send_header("DAV", "1, calendar-access")
self.end_headers()
2010-01-10 18:55:32 +01:00
def do_PROPFIND(self):
"""Manage PROPFIND request."""
2011-02-16 13:53:27 +01:00
log.log(10, "Manage PROPFIND request.")
2010-01-10 18:55:32 +01:00
xml_request = self.rfile.read(int(self.headers["Content-Length"]))
2010-09-28 16:04:17 +02:00
self._answer = xmlutils.propfind(
self.path, xml_request, self._calendar,
2011-01-07 15:25:05 +01:00
self.headers.get("depth", "infinity"))
2010-01-15 16:04:03 +01:00
self.send_response(client.MULTI_STATUS)
2010-01-10 18:55:32 +01:00
self.send_header("DAV", "1, calendar-access")
self.send_header("Content-Length", len(self._answer))
self.send_header("Content-Type", "text/xml")
2010-01-10 18:55:32 +01:00
self.end_headers()
self.wfile.write(self._answer)
2010-01-10 18:55:32 +01:00
@check_rights
2010-01-10 18:55:32 +01:00
def do_PUT(self):
"""Manage PUT request."""
2011-02-16 13:53:27 +01:00
log.log(10, "Manage PUT request.")
item_name = xmlutils.name_from_path(self.path)
item = self._calendar.get_item(item_name)
if (not item and not self.headers.get("If-Match")) or \
(item and self.headers.get("If-Match", item.etag) == item.etag):
# PUT allowed in 3 cases
# Case 1: No item and no ETag precondition: Add new item
# Case 2: Item and ETag precondition verified: Modify item
# Case 3: Item and no Etag precondition: Force modifying item
ical_request = self._decode(
self.rfile.read(int(self.headers["Content-Length"])))
xmlutils.put(self.path, ical_request, self._calendar)
etag = self._calendar.get_item(item_name).etag
self.send_response(client.CREATED)
self.send_header("ETag", etag)
self.end_headers()
else:
# PUT rejected in all other cases
self.send_response(client.PRECONDITION_FAILED)
@check_rights
2010-01-10 18:55:32 +01:00
def do_REPORT(self):
"""Manage REPORT request."""
2011-02-16 13:53:27 +01:00
log.log(10, "Manage REPORT request.")
2010-01-10 18:55:32 +01:00
xml_request = self.rfile.read(int(self.headers["Content-Length"]))
self._answer = xmlutils.report(self.path, xml_request, self._calendar)
2010-01-15 16:04:03 +01:00
self.send_response(client.MULTI_STATUS)
self.send_header("Content-Length", len(self._answer))
2010-01-10 18:55:32 +01:00
self.end_headers()
self.wfile.write(self._answer)
2010-02-10 23:52:50 +01:00
2011-02-16 13:53:27 +01:00
def log_message(self, format, *args):
log.log(10, format % (args))
# pylint: enable=C0103