radicale/radicale/__init__.py

346 lines
12 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.
2011-05-01 14:46:29 +02:00
This module offers a WSGI application class.
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 pprint
import base64
2011-05-01 15:25:52 +02:00
import socket
2011-05-11 06:21:35 +02:00
import ssl
2011-05-01 15:25:52 +02:00
import wsgiref.simple_server
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-04-10 18:17:06 +02:00
from radicale import acl, config, ical, log, xmlutils
2010-08-07 23:37:05 +02:00
VERSION = "git"
class HTTPServer(wsgiref.simple_server.WSGIServer, object):
2011-05-01 15:25:52 +02:00
"""HTTP server."""
def __init__(self, address, handler, bind_and_activate=True):
"""Create server."""
ipv6 = ":" in address[0]
if ipv6:
self.address_family = socket.AF_INET6
# Do not bind and activate, as we might change socket options
super(HTTPServer, self).__init__(address, handler, False)
2011-05-01 15:25:52 +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()
class HTTPSServer(HTTPServer):
"""HTTPS server."""
def __init__(self, address, handler):
2011-05-01 15:25:52 +02:00
"""Create server by wrapping HTTP socket in an SSL socket."""
super(HTTPSServer, self).__init__(address, handler, False)
2011-05-01 15:25:52 +02:00
self.socket = ssl.wrap_socket(
self.socket,
server_side=True,
certfile=config.get("server", "certificate"),
keyfile=config.get("server", "key"),
ssl_version=ssl.PROTOCOL_SSLv23)
self.server_bind()
self.server_activate()
2011-05-01 15:25:52 +02:00
2011-05-07 12:18:32 +02:00
class RequestHandler(wsgiref.simple_server.WSGIRequestHandler):
"""HTTP requests handler."""
def log_message(self, *args, **kwargs):
"""Disable inner logging management."""
2011-05-01 14:46:29 +02:00
class Application(object):
"""WSGI application managing calendars."""
def __init__(self):
"""Initialize application."""
super(Application, self).__init__()
self.acl = acl.load()
2011-05-01 14:46:29 +02:00
self.encoding = config.get("encoding", "request")
if config.getboolean('logging', 'full_environment'):
self.headers_log = lambda environ: environ
# This method is overriden in __init__ if full_environment is set
# pylint: disable=E0202
@staticmethod
def headers_log(environ):
"""Remove environment variables from the headers for logging purpose."""
request_environ = dict(environ)
for shell_variable in os.environ:
del request_environ[shell_variable]
return request_environ
# pylint: enable=E0202
2011-05-01 14:46:29 +02:00
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
2011-05-01 14:46:29 +02:00
content_type = environ.get("CONTENT_TYPE")
if content_type and "charset=" in content_type:
charsets.append(content_type.split("charset=")[1].strip())
# Then append default Radicale charset
2011-05-01 14:46:29 +02:00
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
2011-05-01 14:46:29 +02:00
def __call__(self, environ, start_response):
"""Manage a request."""
2011-05-07 14:32:21 +02:00
log.LOGGER.info("%s request at %s received" % (
2011-05-01 14:46:29 +02:00
environ["REQUEST_METHOD"], environ["PATH_INFO"]))
headers = pprint.pformat(self.headers_log(environ))
log.LOGGER.debug("Request headers:\n%s" % headers)
2011-05-01 14:46:29 +02:00
# Get content
content_length = int(environ.get("CONTENT_LENGTH") or 0)
2011-05-01 14:46:29 +02:00
if content_length:
content = self.decode(
environ["wsgi.input"].read(content_length), environ)
log.LOGGER.debug("Request content:\n%s" % content)
else:
content = None
2011-04-10 18:17:06 +02:00
# Find calendar(s)
items = ical.Calendar.from_path(environ["PATH_INFO"],
environ.get("HTTP_DEPTH", "0"))
2011-05-01 14:46:29 +02:00
# Get function corresponding to method
function = getattr(self, environ["REQUEST_METHOD"].lower())
# Check rights
if not items or not self.acl:
2011-05-01 14:46:29 +02:00
# No calendar or no acl, don't check rights
status, headers, answer = function(environ, items, content)
2011-05-01 14:46:29 +02:00
else:
# Ask authentication backend to check rights
2011-05-01 14:46:29 +02:00
authorization = environ.get("HTTP_AUTHORIZATION", None)
if authorization:
auth = authorization.lstrip("Basic").strip().encode("ascii")
user, password = self.decode(
base64.b64decode(auth), environ).split(":")
environ['USER'] = user
2011-05-01 14:46:29 +02:00
else:
user = password = None
last_allowed = False
calendars = []
for calendar in items:
if not isinstance(calendar, ical.Calendar):
if last_allowed:
calendars.append(calendar)
continue
if calendar.owner in acl.PUBLIC_USERS:
log.LOGGER.info("Public calendar")
calendars.append(calendar)
last_allowed = True
else:
log.LOGGER.info(
"Checking rights for calendar owned by %s" % (
calendar.owner or "nobody"))
if self.acl.has_right(calendar.owner, user, password):
log.LOGGER.info(
"%s allowed" % (user or "Anonymous user"))
calendars.append(calendar)
last_allowed = True
else:
log.LOGGER.info(
"%s refused" % (user or "Anonymous user"))
last_allowed = False
if calendars:
status, headers, answer = function(environ, calendars, content)
2011-05-01 14:46:29 +02:00
else:
status = client.UNAUTHORIZED
headers = {
"WWW-Authenticate":
"Basic realm=\"Radicale Server - Password Required\""}
answer = None
# Set content length
if answer:
log.LOGGER.debug(
"Response content:\n%s" % self.decode(answer, environ))
2011-05-11 06:56:34 +02:00
headers["Content-Length"] = str(len(answer))
2011-05-01 14:46:29 +02:00
# Start response
status = "%i %s" % (status, client.responses.get(status, ""))
start_response(status, list(headers.items()))
2011-05-01 14:46:29 +02:00
# Return response content
return [answer] if answer else []
# All these functions must have the same parameters, some are useless
# pylint: disable=W0612,W0613,R0201
def get(self, environ, calendars, content):
2011-05-01 14:46:29 +02:00
"""Manage GET request."""
calendar = calendars[0]
2011-05-01 14:46:29 +02:00
item_name = xmlutils.name_from_path(environ["PATH_INFO"], calendar)
if item_name:
# Get calendar item
2011-05-01 14:46:29 +02:00
item = calendar.get_item(item_name)
if item:
2011-05-01 14:46:29 +02:00
items = calendar.timezones
items.append(item)
answer_text = ical.serialize(
2011-05-01 14:46:29 +02:00
headers=calendar.headers, items=items)
etag = item.etag
else:
2011-05-01 14:46:29 +02:00
return client.GONE, {}, None
else:
# Get whole calendar
2011-05-01 14:46:29 +02:00
answer_text = calendar.text
etag = calendar.etag
headers = {
"Content-Type": "text/calendar",
"Last-Modified": calendar.last_modified,
"ETag": etag}
answer = answer_text.encode(self.encoding)
return client.OK, headers, answer
def head(self, environ, calendars, content):
2011-05-01 14:46:29 +02:00
"""Manage HEAD request."""
status, headers, answer = self.get(environ, calendars, content)
2011-05-01 14:46:29 +02:00
return status, headers, None
def delete(self, environ, calendars, content):
"""Manage DELETE request."""
calendar = calendars[0]
2011-05-01 14:46:29 +02:00
item = calendar.get_item(
xmlutils.name_from_path(environ["PATH_INFO"], calendar))
if item and environ.get("HTTP_IF_MATCH", item.etag) == item.etag:
# No ETag precondition or precondition verified, delete item
2011-05-01 14:46:29 +02:00
answer = xmlutils.delete(environ["PATH_INFO"], calendar)
status = client.NO_CONTENT
else:
# No item or ETag precondition not verified, do not delete item
2011-05-01 14:46:29 +02:00
answer = None
status = client.PRECONDITION_FAILED
return status, {}, answer
def mkcalendar(self, environ, calendars, content):
2011-02-01 17:01:30 +01:00
"""Manage MKCALENDAR request."""
calendar = calendars[0]
props = xmlutils.props_from_request(content)
timezone = props.get('C:calendar-timezone')
if timezone:
calendar.replace('', timezone)
2011-05-24 17:33:57 +02:00
del props['C:calendar-timezone']
with calendar.props as calendar_props:
for key, value in props.items():
calendar_props[key] = value
calendar.write()
2011-05-01 14:46:29 +02:00
return client.CREATED, {}, None
2011-02-01 17:01:30 +01:00
def options(self, environ, calendars, content):
"""Manage OPTIONS request."""
2011-05-01 14:46:29 +02:00
headers = {
"Allow": "DELETE, HEAD, GET, MKCALENDAR, " \
"OPTIONS, PROPFIND, PROPPATCH, PUT, REPORT",
"DAV": "1, calendar-access"}
return client.OK, headers, None
def propfind(self, environ, calendars, content):
"""Manage PROPFIND request."""
2011-05-01 14:46:29 +02:00
headers = {
"DAV": "1, calendar-access",
"Content-Type": "text/xml"}
answer = xmlutils.propfind(
environ["PATH_INFO"], content, calendars, environ.get("USER"))
2011-05-01 14:46:29 +02:00
return client.MULTI_STATUS, headers, answer
def proppatch(self, environ, calendars, content):
2011-04-28 18:04:34 +02:00
"""Manage PROPPATCH request."""
calendar = calendars[0]
2011-05-24 17:33:57 +02:00
answer = xmlutils.proppatch(environ["PATH_INFO"], content, calendar)
2011-05-01 14:46:29 +02:00
headers = {
"DAV": "1, calendar-access",
"Content-Type": "text/xml"}
2011-05-24 17:33:57 +02:00
return client.MULTI_STATUS, headers, answer
2011-05-01 14:46:29 +02:00
def put(self, environ, calendars, content):
"""Manage PUT request."""
calendar = calendars[0]
2011-05-01 14:46:29 +02:00
headers = {}
item_name = xmlutils.name_from_path(environ["PATH_INFO"], calendar)
item = calendar.get_item(item_name)
if (not item and not environ.get("HTTP_IF_MATCH")) or (
item and environ.get("HTTP_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
2011-05-01 14:46:29 +02:00
xmlutils.put(environ["PATH_INFO"], content, calendar)
status = client.CREATED
headers["ETag"] = calendar.get_item(item_name).etag
else:
# PUT rejected in all other cases
2011-05-01 14:46:29 +02:00
status = client.PRECONDITION_FAILED
return status, headers, None
def report(self, environ, calendars, content):
"""Manage REPORT request."""
# TODO: support multiple calendars here
calendar = calendars[0]
2011-05-11 14:57:27 +02:00
headers = {'Content-Type': 'text/xml'}
2011-05-01 14:46:29 +02:00
answer = xmlutils.report(environ["PATH_INFO"], content, calendar)
2011-05-11 14:57:27 +02:00
return client.MULTI_STATUS, headers, answer
# pylint: enable=W0612,W0613,R0201