1
0

__init__.py 22 KB

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