__init__.py 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628
  1. # This file is part of Radicale Server - Calendar Server
  2. # Copyright © 2008 Nicolas Kandel
  3. # Copyright © 2008 Pascal Halter
  4. # Copyright © 2008-2016 Guillaume Ayoub
  5. #
  6. # This library is free software: you can redistribute it and/or modify
  7. # it under the terms of the GNU General Public License as published by
  8. # the Free Software Foundation, either version 3 of the License, or
  9. # (at your option) any later version.
  10. #
  11. # This library is distributed in the hope that it will be useful,
  12. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  13. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  14. # GNU General Public License for more details.
  15. #
  16. # You should have received a copy of the GNU General Public License
  17. # along with Radicale. If not, see <http://www.gnu.org/licenses/>.
  18. """
  19. Radicale Server module.
  20. This module offers a WSGI application class.
  21. To use this module, you should take a look at the file ``radicale.py`` that
  22. should have been included in this package.
  23. """
  24. import os
  25. import pprint
  26. import base64
  27. import contextlib
  28. import shlex
  29. import socket
  30. import socketserver
  31. import ssl
  32. import threading
  33. import subprocess
  34. import wsgiref.simple_server
  35. import re
  36. import zlib
  37. from http import client
  38. from urllib.parse import unquote, urlparse
  39. import vobject
  40. from . import auth, rights, storage, xmlutils
  41. VERSION = "2.0.0rc0"
  42. # Standard "not allowed" response that is returned when an authenticated user
  43. # tries to access information they don't have rights to
  44. NOT_ALLOWED = (client.FORBIDDEN, {}, None)
  45. class HTTPServer(wsgiref.simple_server.WSGIServer):
  46. """HTTP server."""
  47. # These class attributes must be set before creating instance
  48. client_timeout = None
  49. max_connections = None
  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().__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. if self.max_connections:
  64. self.connections_guard = threading.BoundedSemaphore(
  65. self.max_connections)
  66. else:
  67. # use dummy context manager
  68. self.connections_guard = contextlib.suppress()
  69. def get_request(self):
  70. # Set timeout for client
  71. _socket, address = super().get_request()
  72. if self.client_timeout:
  73. _socket.settimeout(self.client_timeout)
  74. return _socket, address
  75. class HTTPSServer(HTTPServer):
  76. """HTTPS server."""
  77. # These class attributes must be set before creating instance
  78. certificate = None
  79. key = None
  80. protocol = None
  81. cyphers = None
  82. def __init__(self, address, handler):
  83. """Create server by wrapping HTTP socket in an SSL socket."""
  84. super().__init__(address, handler, bind_and_activate=False)
  85. self.socket = ssl.wrap_socket(
  86. self.socket, self.key, self.certificate, server_side=True,
  87. ssl_version=self.protocol, cyphers=self.cyphers)
  88. self.server_bind()
  89. self.server_activate()
  90. class ThreadedHTTPServer(socketserver.ThreadingMixIn, HTTPServer):
  91. def process_request_thread(self, request, client_address):
  92. with self.connections_guard:
  93. return super().process_request_thread(request, client_address)
  94. class ThreadedHTTPSServer(socketserver.ThreadingMixIn, HTTPSServer):
  95. def process_request_thread(self, request, client_address):
  96. with self.connections_guard:
  97. return super().process_request_thread(request, client_address)
  98. class RequestHandler(wsgiref.simple_server.WSGIRequestHandler):
  99. """HTTP requests handler."""
  100. def log_message(self, *args, **kwargs):
  101. """Disable inner logging management."""
  102. class Application:
  103. """WSGI application managing collections."""
  104. def __init__(self, configuration, logger):
  105. """Initialize application."""
  106. super().__init__()
  107. self.configuration = configuration
  108. self.logger = logger
  109. self.is_authenticated = auth.load(configuration, logger)
  110. self.Collection = storage.load(configuration, logger)
  111. self.authorized = rights.load(configuration, logger)
  112. self.encoding = configuration.get("encoding", "request")
  113. def headers_log(self, environ):
  114. """Sanitize headers for logging."""
  115. request_environ = dict(environ)
  116. # Remove environment variables
  117. if not self.configuration.getboolean("logging", "full_environment"):
  118. for shell_variable in os.environ:
  119. request_environ.pop(shell_variable, None)
  120. # Mask credentials
  121. if (self.configuration.getboolean("logging", "mask_passwords") and
  122. request_environ.get("HTTP_AUTHORIZATION",
  123. "").startswith("Basic")):
  124. request_environ["HTTP_AUTHORIZATION"] = "Basic **masked**"
  125. return request_environ
  126. def decode(self, text, environ):
  127. """Try to magically decode ``text`` according to given ``environ``."""
  128. # List of charsets to try
  129. charsets = []
  130. # First append content charset given in the request
  131. content_type = environ.get("CONTENT_TYPE")
  132. if content_type and "charset=" in content_type:
  133. charsets.append(
  134. content_type.split("charset=")[1].split(";")[0].strip())
  135. # Then append default Radicale charset
  136. charsets.append(self.encoding)
  137. # Then append various fallbacks
  138. charsets.append("utf-8")
  139. charsets.append("iso8859-1")
  140. # Try to decode
  141. for charset in charsets:
  142. try:
  143. return text.decode(charset)
  144. except UnicodeDecodeError:
  145. pass
  146. raise UnicodeDecodeError
  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, self.Collection):
  155. if self.authorized(user, item, "r"):
  156. self.logger.debug(
  157. "%s has read access to collection %s" %
  158. (user or "Anonymous", item.path or "/"))
  159. read_last_collection_allowed = True
  160. read_allowed_items.append(item)
  161. else:
  162. self.logger.debug(
  163. "%s has NO read access to collection %s" %
  164. (user or "Anonymous", item.path or "/"))
  165. read_last_collection_allowed = False
  166. if self.authorized(user, item, "w"):
  167. self.logger.debug(
  168. "%s has write access to collection %s" %
  169. (user or "Anonymous", item.path or "/"))
  170. write_last_collection_allowed = True
  171. write_allowed_items.append(item)
  172. else:
  173. self.logger.debug(
  174. "%s has NO write access to collection %s" %
  175. (user or "Anonymous", item.path 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. self.logger.debug(
  183. "%s has read access to item %s" %
  184. (user or "Anonymous", item.href))
  185. read_allowed_items.append(item)
  186. else:
  187. self.logger.debug(
  188. "%s has NO read access to item %s" %
  189. (user or "Anonymous", item.href))
  190. if write_last_collection_allowed:
  191. self.logger.debug(
  192. "%s has write access to item %s" %
  193. (user or "Anonymous", item.href))
  194. write_allowed_items.append(item)
  195. else:
  196. self.logger.debug(
  197. "%s has NO write access to item %s" %
  198. (user or "Anonymous", item.href))
  199. return read_allowed_items, write_allowed_items
  200. def __call__(self, environ, start_response):
  201. """Manage a request."""
  202. def response(status, headers={}, answer=None):
  203. # Start response
  204. status = "%i %s" % (status,
  205. client.responses.get(status, "Unknown"))
  206. self.logger.debug("Answer status: %s" % status)
  207. start_response(status, list(headers.items()))
  208. # Return response content
  209. return [answer] if answer else []
  210. self.logger.info("%s request at %s received" % (
  211. environ["REQUEST_METHOD"], environ["PATH_INFO"]))
  212. headers = pprint.pformat(self.headers_log(environ))
  213. self.logger.debug("Request headers:\n%s" % headers)
  214. # Strip base_prefix from request URI
  215. base_prefix = self.configuration.get("server", "base_prefix")
  216. if environ["PATH_INFO"].startswith(base_prefix):
  217. environ["PATH_INFO"] = environ["PATH_INFO"][len(base_prefix):]
  218. elif self.configuration.get("server", "can_skip_base_prefix"):
  219. self.logger.debug(
  220. "Prefix already stripped from path: %s", environ["PATH_INFO"])
  221. else:
  222. # Request path not starting with base_prefix, not allowed
  223. self.logger.debug(
  224. "Path not starting with prefix: %s", environ["PATH_INFO"])
  225. return response(*NOT_ALLOWED)
  226. # Sanitize request URI
  227. environ["PATH_INFO"] = storage.sanitize_path(
  228. unquote(environ["PATH_INFO"]))
  229. self.logger.debug("Sanitized path: %s", environ["PATH_INFO"])
  230. path = environ["PATH_INFO"]
  231. # Get function corresponding to method
  232. function = getattr(self, "do_%s" % environ["REQUEST_METHOD"].upper())
  233. # Ask authentication backend to check rights
  234. authorization = environ.get("HTTP_AUTHORIZATION", None)
  235. if authorization and authorization.startswith("Basic"):
  236. authorization = authorization[len("Basic"):].strip()
  237. user, password = self.decode(base64.b64decode(
  238. authorization.encode("ascii")), environ).split(":", 1)
  239. else:
  240. user = environ.get("REMOTE_USER")
  241. password = None
  242. # If /.well-known is not available, clients query /
  243. if path == "/.well-known" or path.startswith("/.well-known/"):
  244. return response(client.NOT_FOUND, {})
  245. if user and not storage.is_safe_path_component(user):
  246. # Prevent usernames like "user/calendar.ics"
  247. self.logger.info("Refused unsafe username: %s", user)
  248. is_authenticated = False
  249. else:
  250. is_authenticated = self.is_authenticated(user, password)
  251. is_valid_user = is_authenticated or not user
  252. # Get content
  253. content_length = int(environ.get("CONTENT_LENGTH") or 0)
  254. if content_length:
  255. max_content_length = self.configuration.getint(
  256. "server", "max_content_length")
  257. if max_content_length and content_length > max_content_length:
  258. self.logger.debug(
  259. "Request body too large: %d", content_length)
  260. return response(client.REQUEST_ENTITY_TOO_LARGE)
  261. try:
  262. content = self.decode(
  263. environ["wsgi.input"].read(content_length), environ)
  264. except socket.timeout:
  265. return response(client.REQUEST_TIMEOUT)
  266. self.logger.debug("Request content:\n%s" % content)
  267. else:
  268. content = None
  269. if is_valid_user:
  270. if function in (self.do_GET, self.do_HEAD,
  271. self.do_OPTIONS, self.do_PROPFIND,
  272. self.do_REPORT):
  273. lock_mode = "r"
  274. else:
  275. lock_mode = "w"
  276. with self.Collection.acquire_lock(lock_mode):
  277. items = self.Collection.discover(
  278. path, environ.get("HTTP_DEPTH", "0"))
  279. read_allowed_items, write_allowed_items = (
  280. self.collect_allowed_items(items, user))
  281. if (read_allowed_items or write_allowed_items or
  282. is_authenticated and function == self.do_PROPFIND or
  283. function == self.do_OPTIONS):
  284. status, headers, answer = function(
  285. environ, read_allowed_items, write_allowed_items,
  286. content, user)
  287. hook = self.configuration.get("storage", "hook")
  288. if lock_mode == "w" and hook:
  289. self.logger.debug("Running hook")
  290. folder = os.path.expanduser(
  291. self.configuration.get("storage",
  292. "filesystem_folder"))
  293. subprocess.check_call(
  294. hook % {"user": shlex.quote(user or "Anonymous")},
  295. shell=True, cwd=folder)
  296. else:
  297. status, headers, answer = NOT_ALLOWED
  298. else:
  299. status, headers, answer = NOT_ALLOWED
  300. if (status, headers, answer) == NOT_ALLOWED and not is_authenticated:
  301. # Unknown or unauthorized user
  302. self.logger.info("%s refused" % (user or "Anonymous user"))
  303. status = client.UNAUTHORIZED
  304. realm = self.configuration.get("server", "realm")
  305. headers = {
  306. "WWW-Authenticate":
  307. "Basic realm=\"%s\"" % realm}
  308. answer = None
  309. # Set content length
  310. if answer:
  311. self.logger.debug("Response content:\n%s" % answer, environ)
  312. answer = answer.encode(self.encoding)
  313. accept_encoding = [
  314. encoding.strip() for encoding in
  315. environ.get("HTTP_ACCEPT_ENCODING", "").split(",")
  316. if encoding.strip()]
  317. if "gzip" in accept_encoding:
  318. zcomp = zlib.compressobj(wbits=16 + zlib.MAX_WBITS)
  319. answer = zcomp.compress(answer) + zcomp.flush()
  320. headers["Content-Encoding"] = "gzip"
  321. headers["Content-Length"] = str(len(answer))
  322. if self.configuration.has_section("headers"):
  323. for key in self.configuration.options("headers"):
  324. headers[key] = self.configuration.get("headers", key)
  325. return response(status, headers, answer)
  326. # All these functions must have the same parameters, some are useless
  327. # pylint: disable=W0612,W0613,R0201
  328. def do_DELETE(self, environ, read_collections, write_collections, content,
  329. user):
  330. """Manage DELETE request."""
  331. if not write_collections:
  332. return NOT_ALLOWED
  333. collection = write_collections[0]
  334. if collection.path == environ["PATH_INFO"].strip("/"):
  335. # Path matching the collection, the collection must be deleted
  336. item = collection
  337. else:
  338. # Try to get an item matching the path
  339. name = xmlutils.name_from_path(environ["PATH_INFO"], collection)
  340. item = collection.get(name)
  341. if item:
  342. if_match = environ.get("HTTP_IF_MATCH", "*")
  343. if if_match in ("*", item.etag):
  344. # No ETag precondition or precondition verified, delete item
  345. answer = xmlutils.delete(environ["PATH_INFO"], collection)
  346. return client.OK, {}, answer
  347. # No item or ETag precondition not verified, do not delete item
  348. return client.PRECONDITION_FAILED, {}, None
  349. def do_GET(self, environ, read_collections, write_collections, content,
  350. user):
  351. """Manage GET request."""
  352. # Display a "Radicale works!" message if the root URL is requested
  353. if environ["PATH_INFO"] == "/":
  354. headers = {"Content-type": "text/html"}
  355. answer = "<!DOCTYPE html>\n<title>Radicale</title>Radicale works!"
  356. return client.OK, headers, answer
  357. if not read_collections:
  358. return NOT_ALLOWED
  359. collection = read_collections[0]
  360. item_name = xmlutils.name_from_path(environ["PATH_INFO"], collection)
  361. if item_name:
  362. # Get collection item
  363. item = collection.get(item_name)
  364. if item:
  365. answer = item.serialize()
  366. etag = item.etag
  367. else:
  368. return client.NOT_FOUND, {}, None
  369. else:
  370. # Get whole collection
  371. answer = collection.serialize()
  372. if answer is None:
  373. return client.NOT_FOUND, {}, None
  374. else:
  375. etag = collection.etag
  376. if answer:
  377. headers = {
  378. "Content-Type": storage.MIMETYPES[collection.get_meta("tag")],
  379. "Last-Modified": collection.last_modified,
  380. "ETag": etag}
  381. else:
  382. headers = {}
  383. return client.OK, headers, answer
  384. def do_HEAD(self, environ, read_collections, write_collections, content,
  385. user):
  386. """Manage HEAD request."""
  387. status, headers, answer = self.do_GET(
  388. environ, read_collections, write_collections, content, user)
  389. return status, headers, None
  390. def do_MKCALENDAR(self, environ, read_collections, write_collections,
  391. content, user):
  392. """Manage MKCALENDAR request."""
  393. if not write_collections:
  394. return NOT_ALLOWED
  395. collection = write_collections[0]
  396. props = xmlutils.props_from_request(content)
  397. # TODO: use this?
  398. # timezone = props.get("C:calendar-timezone")
  399. collection = self.Collection.create_collection(
  400. environ["PATH_INFO"], tag="VCALENDAR")
  401. for key, value in props.items():
  402. collection.set_meta(key, value)
  403. return client.CREATED, {}, None
  404. def do_MKCOL(self, environ, read_collections, write_collections, content,
  405. user):
  406. """Manage MKCOL request."""
  407. if not write_collections:
  408. return NOT_ALLOWED
  409. collection = write_collections[0]
  410. props = xmlutils.props_from_request(content)
  411. collection = self.Collection.create_collection(environ["PATH_INFO"])
  412. for key, value in props.items():
  413. collection.set_meta(key, value)
  414. return client.CREATED, {}, None
  415. def do_MOVE(self, environ, read_collections, write_collections, content,
  416. user):
  417. """Manage MOVE request."""
  418. if not write_collections:
  419. return NOT_ALLOWED
  420. from_collection = write_collections[0]
  421. from_name = xmlutils.name_from_path(
  422. environ["PATH_INFO"], from_collection)
  423. item = from_collection.get(from_name)
  424. if item:
  425. # Move the item
  426. to_url_parts = urlparse(environ["HTTP_DESTINATION"])
  427. if to_url_parts.netloc == environ["HTTP_HOST"]:
  428. to_url = to_url_parts.path
  429. to_path, to_name = to_url.rstrip("/").rsplit("/", 1)
  430. for to_collection in self.Collection.discover(
  431. to_path, depth="0"):
  432. if to_collection in write_collections:
  433. to_collection.upload(to_name, item)
  434. from_collection.delete(from_name)
  435. return client.CREATED, {}, None
  436. else:
  437. return NOT_ALLOWED
  438. else:
  439. # Remote destination server, not supported
  440. return client.BAD_GATEWAY, {}, None
  441. else:
  442. # No item found
  443. return client.GONE, {}, None
  444. def do_OPTIONS(self, environ, read_collections, write_collections,
  445. content, user):
  446. """Manage OPTIONS request."""
  447. headers = {
  448. "Allow": ("DELETE, HEAD, GET, MKCALENDAR, MKCOL, MOVE, "
  449. "OPTIONS, PROPFIND, PROPPATCH, PUT, REPORT"),
  450. "DAV": "1, 2, 3, calendar-access, addressbook, extended-mkcol"}
  451. return client.OK, headers, None
  452. def do_PROPFIND(self, environ, read_collections, write_collections,
  453. content, user):
  454. """Manage PROPFIND request."""
  455. if not read_collections:
  456. return client.NOT_FOUND, {}, None
  457. headers = {
  458. "DAV": "1, 2, 3, calendar-access, addressbook, extended-mkcol",
  459. "Content-Type": "text/xml"}
  460. answer = xmlutils.propfind(
  461. environ["PATH_INFO"], content, read_collections, write_collections,
  462. user)
  463. return client.MULTI_STATUS, headers, answer
  464. def do_PROPPATCH(self, environ, read_collections, write_collections,
  465. content, user):
  466. """Manage PROPPATCH request."""
  467. if not write_collections:
  468. return NOT_ALLOWED
  469. collection = write_collections[0]
  470. answer = xmlutils.proppatch(environ["PATH_INFO"], content, collection)
  471. headers = {
  472. "DAV": "1, 2, 3, calendar-access, addressbook, extended-mkcol",
  473. "Content-Type": "text/xml"}
  474. return client.MULTI_STATUS, headers, answer
  475. def do_PUT(self, environ, read_collections, write_collections, content,
  476. user):
  477. """Manage PUT request."""
  478. if not write_collections:
  479. return NOT_ALLOWED
  480. collection = write_collections[0]
  481. content_type = environ.get("CONTENT_TYPE")
  482. if content_type:
  483. tags = {value: key for key, value in storage.MIMETYPES.items()}
  484. tag = tags.get(content_type.split(";")[0])
  485. if tag:
  486. collection.set_meta("tag", tag)
  487. headers = {}
  488. item_name = xmlutils.name_from_path(environ["PATH_INFO"], collection)
  489. item = collection.get(item_name)
  490. etag = environ.get("HTTP_IF_MATCH", "")
  491. match = environ.get("HTTP_IF_NONE_MATCH", "") == "*"
  492. if (not item and not etag) or (
  493. item and ((etag or item.etag) == item.etag) and not match):
  494. # PUT allowed in 3 cases
  495. # Case 1: No item and no ETag precondition: Add new item
  496. # Case 2: Item and ETag precondition verified: Modify item
  497. # Case 3: Item and no Etag precondition: Force modifying item
  498. items = list(vobject.readComponents(content or ""))
  499. if item:
  500. # PUT is modifying an existing item
  501. if items:
  502. new_item = collection.update(item_name, items[0])
  503. else:
  504. new_item = None
  505. elif item_name:
  506. # PUT is adding a new item
  507. if items:
  508. new_item = collection.upload(item_name, items[0])
  509. else:
  510. new_item = None
  511. else:
  512. # PUT is replacing the whole collection
  513. collection.delete()
  514. new_item = self.Collection.create_collection(
  515. environ["PATH_INFO"], items)
  516. if new_item:
  517. headers["ETag"] = new_item.etag
  518. status = client.CREATED
  519. else:
  520. # PUT rejected in all other cases
  521. status = client.PRECONDITION_FAILED
  522. return status, headers, None
  523. def do_REPORT(self, environ, read_collections, write_collections, content,
  524. user):
  525. """Manage REPORT request."""
  526. if not read_collections:
  527. return NOT_ALLOWED
  528. collection = read_collections[0]
  529. headers = {"Content-Type": "text/xml"}
  530. answer = xmlutils.report(environ["PATH_INFO"], content, collection)
  531. return client.MULTI_STATUS, headers, answer
  532. # pylint: enable=W0612,W0613,R0201