__init__.py 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571
  1. # -*- coding: utf-8 -*-
  2. #
  3. # This file is part of Radicale Server - Calendar Server
  4. # Copyright © 2008 Nicolas Kandel
  5. # Copyright © 2008 Pascal Halter
  6. # Copyright © 2008-2013 Guillaume Ayoub
  7. #
  8. # This library is free software: you can redistribute it and/or modify
  9. # it under the terms of the GNU General Public License as published by
  10. # the Free Software Foundation, either version 3 of the License, or
  11. # (at your option) any later version.
  12. #
  13. # This library is distributed in the hope that it will be useful,
  14. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  15. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  16. # GNU General Public License for more details.
  17. #
  18. # You should have received a copy of the GNU General Public License
  19. # along with Radicale. If not, see <http://www.gnu.org/licenses/>.
  20. """
  21. Radicale Server module.
  22. This module offers a WSGI application class.
  23. To use this module, you should take a look at the file ``radicale.py`` that
  24. should have been included in this package.
  25. """
  26. import os
  27. import pprint
  28. import base64
  29. import posixpath
  30. import socket
  31. import ssl
  32. import wsgiref.simple_server
  33. # Manage Python2/3 different modules
  34. # pylint: disable=F0401,E0611
  35. try:
  36. from http import client
  37. from urllib.parse import unquote, urlparse
  38. except ImportError:
  39. import httplib as client
  40. from urllib import unquote
  41. from urlparse import urlparse
  42. # pylint: enable=F0401,E0611
  43. from . import auth, config, ical, log, rights, storage, xmlutils
  44. VERSION = "git"
  45. # Standard "not allowed" response that is returned when an authenticated user
  46. # tries to access information they don't have rights to
  47. NOT_ALLOWED = (client.FORBIDDEN, {}, None)
  48. class HTTPServer(wsgiref.simple_server.WSGIServer, object):
  49. """HTTP server."""
  50. def __init__(self, address, handler, bind_and_activate=True):
  51. """Create server."""
  52. ipv6 = ":" in address[0]
  53. if ipv6:
  54. self.address_family = socket.AF_INET6
  55. # Do not bind and activate, as we might change socket options
  56. super(HTTPServer, self).__init__(address, handler, False)
  57. if ipv6:
  58. # Only allow IPv6 connections to the IPv6 socket
  59. self.socket.setsockopt(socket.IPPROTO_IPV6, socket.IPV6_V6ONLY, 1)
  60. if bind_and_activate:
  61. self.server_bind()
  62. self.server_activate()
  63. class HTTPSServer(HTTPServer):
  64. """HTTPS server."""
  65. def __init__(self, address, handler):
  66. """Create server by wrapping HTTP socket in an SSL socket."""
  67. super(HTTPSServer, self).__init__(address, handler, False)
  68. # Test if the SSL files can be read
  69. for name in ("certificate", "key"):
  70. filename = config.get("server", name)
  71. try:
  72. open(filename, "r").close()
  73. except IOError as exception:
  74. log.LOGGER.warn(
  75. "Error while reading SSL %s %r: %s" % (
  76. name, filename, exception))
  77. self.socket = ssl.wrap_socket(
  78. self.socket,
  79. server_side=True,
  80. certfile=config.get("server", "certificate"),
  81. keyfile=config.get("server", "key"),
  82. ssl_version=getattr(ssl, config.get("server", "protocol"),
  83. ssl.PROTOCOL_SSLv23),
  84. ciphers=config.get("server", "ciphers") or None)
  85. self.server_bind()
  86. self.server_activate()
  87. class RequestHandler(wsgiref.simple_server.WSGIRequestHandler):
  88. """HTTP requests handler."""
  89. def log_message(self, *args, **kwargs):
  90. """Disable inner logging management."""
  91. def address_string(self):
  92. """Client address, formatted for logging."""
  93. if config.getboolean("server", "dns_lookup"):
  94. return \
  95. wsgiref.simple_server.WSGIRequestHandler.address_string(self)
  96. else:
  97. return self.client_address[0]
  98. class Application(object):
  99. """WSGI application managing collections."""
  100. def __init__(self):
  101. """Initialize application."""
  102. super(Application, self).__init__()
  103. auth.load()
  104. storage.load()
  105. self.encoding = config.get("encoding", "request")
  106. if config.getboolean("logging", "full_environment"):
  107. self.headers_log = lambda environ: environ
  108. # This method is overriden in __init__ if full_environment is set
  109. # pylint: disable=E0202
  110. @staticmethod
  111. def headers_log(environ):
  112. """Remove environment variables from the headers for logging."""
  113. request_environ = dict(environ)
  114. for shell_variable in os.environ:
  115. if shell_variable in request_environ:
  116. del request_environ[shell_variable]
  117. return request_environ
  118. # pylint: enable=E0202
  119. def decode(self, text, environ):
  120. """Try to magically decode ``text`` according to given ``environ``."""
  121. # List of charsets to try
  122. charsets = []
  123. # First append content charset given in the request
  124. content_type = environ.get("CONTENT_TYPE")
  125. if content_type and "charset=" in content_type:
  126. charsets.append(content_type.split("charset=")[1].strip())
  127. # Then append default Radicale charset
  128. charsets.append(self.encoding)
  129. # Then append various fallbacks
  130. charsets.append("utf-8")
  131. charsets.append("iso8859-1")
  132. # Try to decode
  133. for charset in charsets:
  134. try:
  135. return text.decode(charset)
  136. except UnicodeDecodeError:
  137. pass
  138. raise UnicodeDecodeError
  139. @staticmethod
  140. def sanitize_uri(uri):
  141. """Unquote and remove /../ to prevent access to other data."""
  142. uri = unquote(uri)
  143. trailing_slash = "/" if uri.endswith("/") else ""
  144. uri = posixpath.normpath(uri)
  145. trailing_slash = "" if uri == "/" else trailing_slash
  146. return uri + trailing_slash
  147. def collect_allowed_items(self, items, user):
  148. """Get items from request that user is allowed to access."""
  149. read_last_collection_allowed = None
  150. write_last_collection_allowed = None
  151. read_allowed_items = []
  152. write_allowed_items = []
  153. for item in items:
  154. if isinstance(item, ical.Collection):
  155. if rights.authorized(user, item, "r"):
  156. log.LOGGER.debug(
  157. "%s has read access to collection %s" %
  158. (user or "Anonymous", item.url or "/"))
  159. read_last_collection_allowed = True
  160. read_allowed_items.append(item)
  161. else:
  162. log.LOGGER.debug(
  163. "%s has NO read access to collection %s" %
  164. (user or "Anonymous", item.url or "/"))
  165. read_last_collection_allowed = False
  166. if rights.authorized(user, item, "w"):
  167. log.LOGGER.debug(
  168. "%s has write access to collection %s" %
  169. (user or "Anonymous", item.url or "/"))
  170. write_last_collection_allowed = True
  171. write_allowed_items.append(item)
  172. else:
  173. log.LOGGER.debug(
  174. "%s has NO write access to collection %s" %
  175. (user or "Anonymous", item.url or "/"))
  176. write_last_collection_allowed = False
  177. else:
  178. # item is not a collection, it's the child of the last
  179. # collection we've met in the loop. Only add this item
  180. # if this last collection was allowed.
  181. if read_last_collection_allowed:
  182. log.LOGGER.debug(
  183. "%s has read access to item %s" %
  184. (user or "Anonymous", item.name))
  185. read_allowed_items.append(item)
  186. else:
  187. log.LOGGER.debug(
  188. "%s has NO read access to item %s" %
  189. (user or "Anonymous", item.name))
  190. if write_last_collection_allowed:
  191. log.LOGGER.debug(
  192. "%s has write access to item %s" %
  193. (user or "Anonymous", item.name))
  194. write_allowed_items.append(item)
  195. else:
  196. log.LOGGER.debug(
  197. "%s has NO write access to item %s" %
  198. (user or "Anonymous", item.name))
  199. return read_allowed_items, write_allowed_items
  200. def __call__(self, environ, start_response):
  201. """Manage a request."""
  202. log.LOGGER.info("%s request at %s received" % (
  203. environ["REQUEST_METHOD"], environ["PATH_INFO"]))
  204. headers = pprint.pformat(self.headers_log(environ))
  205. log.LOGGER.debug("Request headers:\n%s" % headers)
  206. base_prefix = config.get("server", "base_prefix")
  207. if environ["PATH_INFO"].startswith(base_prefix):
  208. # Sanitize request URI
  209. environ["PATH_INFO"] = self.sanitize_uri(
  210. "/%s" % environ["PATH_INFO"][len(base_prefix):])
  211. log.LOGGER.debug("Sanitized path: %s", environ["PATH_INFO"])
  212. else:
  213. # Request path not starting with base_prefix, not allowed
  214. log.LOGGER.debug(
  215. "Path not starting with prefix: %s", environ["PATH_INFO"])
  216. environ["PATH_INFO"] = None
  217. # Get content
  218. content_length = int(environ.get("CONTENT_LENGTH") or 0)
  219. if content_length:
  220. content = self.decode(
  221. environ["wsgi.input"].read(content_length), environ)
  222. log.LOGGER.debug("Request content:\n%s" % content)
  223. else:
  224. content = None
  225. path = environ["PATH_INFO"]
  226. # Find collection(s)
  227. items = ical.Collection.from_path(path, environ.get("HTTP_DEPTH", "0"))
  228. # Get function corresponding to method
  229. function = getattr(self, environ["REQUEST_METHOD"].lower())
  230. # Ask authentication backend to check rights
  231. authorization = environ.get("HTTP_AUTHORIZATION", None)
  232. if authorization:
  233. authorization = authorization.lstrip("Basic").strip()
  234. user, password = self.decode(base64.b64decode(
  235. authorization.encode("ascii")), environ).split(":", 1)
  236. else:
  237. user = password = None
  238. read_allowed_items, write_allowed_items = \
  239. self.collect_allowed_items(items, user)
  240. if ((read_allowed_items or write_allowed_items)
  241. and (not user or auth.is_authenticated(user, password))) or \
  242. function == self.options or not items:
  243. # Collections found, or OPTIONS request, or no items at all
  244. status, headers, answer = function(
  245. environ, read_allowed_items, write_allowed_items, content,
  246. user)
  247. else:
  248. status, headers, answer = NOT_ALLOWED
  249. if ((status, headers, answer) == NOT_ALLOWED and
  250. not auth.is_authenticated(user, password) and
  251. config.get("auth", "type") != "None"):
  252. # Unknown or unauthorized user
  253. log.LOGGER.info("%s refused" % (user or "Anonymous user"))
  254. status = client.UNAUTHORIZED
  255. headers = {
  256. "WWW-Authenticate":
  257. "Basic realm=\"%s\"" % config.get("server", "realm")}
  258. answer = None
  259. # Set content length
  260. if answer:
  261. log.LOGGER.debug(
  262. "Response content:\n%s" % self.decode(answer, environ))
  263. headers["Content-Length"] = str(len(answer))
  264. if config.has_section("headers"):
  265. for key in config.options("headers"):
  266. headers[key] = config.get("headers", key)
  267. # Start response
  268. status = "%i %s" % (status, client.responses.get(status, "Unknown"))
  269. log.LOGGER.debug("Answer status: %s" % status)
  270. start_response(status, list(headers.items()))
  271. # Return response content
  272. return [answer] if answer else []
  273. # All these functions must have the same parameters, some are useless
  274. # pylint: disable=W0612,W0613,R0201
  275. def delete(self, environ, read_collections, write_collections, content,
  276. user):
  277. """Manage DELETE request."""
  278. if not len(write_collections):
  279. return client.PRECONDITION_FAILED, {}, None
  280. collection = write_collections[0]
  281. if collection.path == environ["PATH_INFO"].strip("/"):
  282. # Path matching the collection, the collection must be deleted
  283. item = collection
  284. else:
  285. # Try to get an item matching the path
  286. item = collection.get_item(
  287. xmlutils.name_from_path(environ["PATH_INFO"], collection))
  288. if item:
  289. # Evolution bug workaround
  290. etag = environ.get("HTTP_IF_MATCH", item.etag).replace("\\", "")
  291. if etag == item.etag:
  292. # No ETag precondition or precondition verified, delete item
  293. answer = xmlutils.delete(environ["PATH_INFO"], collection)
  294. return client.OK, {}, answer
  295. # No item or ETag precondition not verified, do not delete item
  296. return client.PRECONDITION_FAILED, {}, None
  297. def get(self, environ, read_collections, write_collections, content, user):
  298. """Manage GET request.
  299. In Radicale, GET requests create collections when the URL is not
  300. available. This is useful for clients with no MKCOL or MKCALENDAR
  301. support.
  302. """
  303. # Display a "Radicale works!" message if the root URL is requested
  304. if environ["PATH_INFO"] == "/":
  305. headers = {"Content-type": "text/html"}
  306. answer = b"<!DOCTYPE html>\n<title>Radicale</title>Radicale works!"
  307. return client.OK, headers, answer
  308. if not len(read_collections):
  309. return NOT_ALLOWED
  310. collection = read_collections[0]
  311. item_name = xmlutils.name_from_path(environ["PATH_INFO"], collection)
  312. if item_name:
  313. # Get collection item
  314. item = collection.get_item(item_name)
  315. if item:
  316. items = collection.timezones
  317. items.append(item)
  318. answer_text = ical.serialize(
  319. collection.tag, collection.headers, items)
  320. etag = item.etag
  321. else:
  322. return client.GONE, {}, None
  323. else:
  324. # Create the collection if it does not exist
  325. if not collection.exists:
  326. if collection in write_collections:
  327. log.LOGGER.debug(
  328. "Creating collection %s" % collection.name)
  329. collection.write()
  330. else:
  331. log.LOGGER.debug(
  332. "Collection %s not available and could not be created "
  333. "due to missing write rights" % collection.name)
  334. return NOT_ALLOWED
  335. # Get whole collection
  336. answer_text = collection.text
  337. etag = collection.etag
  338. headers = {
  339. "Content-Type": collection.mimetype,
  340. "Last-Modified": collection.last_modified,
  341. "ETag": etag}
  342. answer = answer_text.encode(self.encoding)
  343. return client.OK, headers, answer
  344. def head(self, environ, read_collections, write_collections, content,
  345. user):
  346. """Manage HEAD request."""
  347. status, headers, answer = self.get(
  348. environ, read_collections, write_collections, content, user)
  349. return status, headers, None
  350. def mkcalendar(self, environ, read_collections, write_collections, content,
  351. user):
  352. """Manage MKCALENDAR request."""
  353. if not len(write_collections):
  354. return NOT_ALLOWED
  355. collection = write_collections[0]
  356. props = xmlutils.props_from_request(content)
  357. timezone = props.get("C:calendar-timezone")
  358. if timezone:
  359. collection.replace("", timezone)
  360. del props["C:calendar-timezone"]
  361. with collection.props as collection_props:
  362. for key, value in props.items():
  363. collection_props[key] = value
  364. collection.write()
  365. return client.CREATED, {}, None
  366. def mkcol(self, environ, read_collections, write_collections, content,
  367. user):
  368. """Manage MKCOL request."""
  369. if not len(write_collections):
  370. return NOT_ALLOWED
  371. collection = write_collections[0]
  372. props = xmlutils.props_from_request(content)
  373. with collection.props as collection_props:
  374. for key, value in props.items():
  375. collection_props[key] = value
  376. collection.write()
  377. return client.CREATED, {}, None
  378. def move(self, environ, read_collections, write_collections, content,
  379. user):
  380. """Manage MOVE request."""
  381. if not len(write_collections):
  382. return NOT_ALLOWED
  383. from_collection = write_collections[0]
  384. from_name = xmlutils.name_from_path(
  385. environ["PATH_INFO"], from_collection)
  386. if from_name:
  387. item = from_collection.get_item(from_name)
  388. if item:
  389. # Move the item
  390. to_url_parts = urlparse(environ["HTTP_DESTINATION"])
  391. if to_url_parts.netloc == environ["HTTP_HOST"]:
  392. to_url = to_url_parts.path
  393. to_path, to_name = to_url.rstrip("/").rsplit("/", 1)
  394. to_collection = ical.Collection.from_path(
  395. to_path, depth="0")[0]
  396. if to_collection in write_collections:
  397. to_collection.append(to_name, item.text)
  398. from_collection.remove(from_name)
  399. return client.CREATED, {}, None
  400. else:
  401. return NOT_ALLOWED
  402. else:
  403. # Remote destination server, not supported
  404. return client.BAD_GATEWAY, {}, None
  405. else:
  406. # No item found
  407. return client.GONE, {}, None
  408. else:
  409. # Moving collections, not supported
  410. return client.FORBIDDEN, {}, None
  411. def options(self, environ, read_collections, write_collections, content,
  412. user):
  413. """Manage OPTIONS request."""
  414. headers = {
  415. "Allow": ("DELETE, HEAD, GET, MKCALENDAR, MKCOL, MOVE, "
  416. "OPTIONS, PROPFIND, PROPPATCH, PUT, REPORT"),
  417. "DAV": "1, 2, 3, calendar-access, addressbook, extended-mkcol"}
  418. return client.OK, headers, None
  419. def propfind(self, environ, read_collections, write_collections, content,
  420. user):
  421. """Manage PROPFIND request."""
  422. # Rights is handled by collection in xmlutils.propfind
  423. headers = {
  424. "DAV": "1, 2, 3, calendar-access, addressbook, extended-mkcol",
  425. "Content-Type": "text/xml"}
  426. collections = set(read_collections + write_collections)
  427. answer = xmlutils.propfind(
  428. environ["PATH_INFO"], content, collections, user)
  429. return client.MULTI_STATUS, headers, answer
  430. def proppatch(self, environ, read_collections, write_collections, content,
  431. user):
  432. """Manage PROPPATCH request."""
  433. if not len(write_collections):
  434. return NOT_ALLOWED
  435. collection = write_collections[0]
  436. answer = xmlutils.proppatch(
  437. environ["PATH_INFO"], content, collection)
  438. headers = {
  439. "DAV": "1, 2, 3, calendar-access, addressbook, extended-mkcol",
  440. "Content-Type": "text/xml"}
  441. return client.MULTI_STATUS, headers, answer
  442. def put(self, environ, read_collections, write_collections, content, user):
  443. """Manage PUT request."""
  444. if not len(write_collections):
  445. return NOT_ALLOWED
  446. collection = write_collections[0]
  447. collection.set_mimetype(environ.get("CONTENT_TYPE"))
  448. headers = {}
  449. item_name = xmlutils.name_from_path(environ["PATH_INFO"], collection)
  450. item = collection.get_item(item_name)
  451. # Evolution bug workaround
  452. etag = environ.get("HTTP_IF_MATCH", "").replace("\\", "")
  453. match = environ.get("HTTP_IF_NONE_MATCH", "") == "*"
  454. if (not item and not etag) or (
  455. item and ((etag or item.etag) == item.etag) and not match):
  456. # PUT allowed in 3 cases
  457. # Case 1: No item and no ETag precondition: Add new item
  458. # Case 2: Item and ETag precondition verified: Modify item
  459. # Case 3: Item and no Etag precondition: Force modifying item
  460. xmlutils.put(environ["PATH_INFO"], content, collection)
  461. status = client.CREATED
  462. # Try to return the etag in the header.
  463. # If the added item doesn't have the same name as the one given
  464. # by the client, then there's no obvious way to generate an
  465. # etag, we can safely ignore it.
  466. new_item = collection.get_item(item_name)
  467. if new_item:
  468. headers["ETag"] = new_item.etag
  469. else:
  470. # PUT rejected in all other cases
  471. status = client.PRECONDITION_FAILED
  472. return status, headers, None
  473. def report(self, environ, read_collections, write_collections, content,
  474. user):
  475. """Manage REPORT request."""
  476. if not len(read_collections):
  477. return NOT_ALLOWED
  478. collection = read_collections[0]
  479. headers = {"Content-Type": "text/xml"}
  480. answer = xmlutils.report(environ["PATH_INFO"], content, collection)
  481. return client.MULTI_STATUS, headers, answer
  482. # pylint: enable=W0612,W0613,R0201