__init__.py 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754
  1. # This file is part of Radicale Server - Calendar Server
  2. # Copyright © 2008 Nicolas Kandel
  3. # Copyright © 2008 Pascal Halter
  4. # Copyright © 2008-2017 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 base64
  25. import contextlib
  26. import datetime
  27. import io
  28. import itertools
  29. import logging
  30. import os
  31. import posixpath
  32. import pprint
  33. import random
  34. import socket
  35. import socketserver
  36. import ssl
  37. import sys
  38. import threading
  39. import time
  40. import traceback
  41. import wsgiref.simple_server
  42. import zlib
  43. from http import client
  44. from urllib.parse import unquote, urlparse
  45. from xml.etree import ElementTree as ET
  46. import vobject
  47. from . import auth, rights, storage, xmlutils
  48. VERSION = "2.0.0"
  49. NOT_ALLOWED = (
  50. client.FORBIDDEN, (("Content-Type", "text/plain"),),
  51. "Access to the requested resource forbidden.")
  52. NOT_FOUND = (
  53. client.NOT_FOUND, (("Content-Type", "text/plain"),),
  54. "The requested resource could not be found.")
  55. WEBDAV_PRECONDITION_FAILED = (
  56. client.CONFLICT, (("Content-Type", "text/plain"),),
  57. "WebDAV precondition failed.")
  58. PRECONDITION_FAILED = (
  59. client.PRECONDITION_FAILED,
  60. (("Content-Type", "text/plain"),), "Precondition failed.")
  61. REQUEST_TIMEOUT = (
  62. client.REQUEST_TIMEOUT, (("Content-Type", "text/plain"),),
  63. "Connection timed out.")
  64. REQUEST_ENTITY_TOO_LARGE = (
  65. client.REQUEST_ENTITY_TOO_LARGE, (("Content-Type", "text/plain"),),
  66. "Request body too large.")
  67. REMOTE_DESTINATION = (
  68. client.BAD_GATEWAY, (("Content-Type", "text/plain"),),
  69. "Remote destination not supported.")
  70. DIRECTORY_LISTING = (
  71. client.FORBIDDEN, (("Content-Type", "text/plain"),),
  72. "Directory listings are not supported.")
  73. DAV_HEADERS = "1, 2, 3, calendar-access, addressbook, extended-mkcol"
  74. class HTTPServer(wsgiref.simple_server.WSGIServer):
  75. """HTTP server."""
  76. # These class attributes must be set before creating instance
  77. client_timeout = None
  78. max_connections = None
  79. logger = None
  80. def __init__(self, address, handler, bind_and_activate=True):
  81. """Create server."""
  82. ipv6 = ":" in address[0]
  83. if ipv6:
  84. self.address_family = socket.AF_INET6
  85. # Do not bind and activate, as we might change socket options
  86. super().__init__(address, handler, False)
  87. if ipv6:
  88. # Only allow IPv6 connections to the IPv6 socket
  89. self.socket.setsockopt(socket.IPPROTO_IPV6, socket.IPV6_V6ONLY, 1)
  90. if bind_and_activate:
  91. self.server_bind()
  92. self.server_activate()
  93. if self.max_connections:
  94. self.connections_guard = threading.BoundedSemaphore(
  95. self.max_connections)
  96. else:
  97. # use dummy context manager
  98. self.connections_guard = contextlib.suppress()
  99. def get_request(self):
  100. # Set timeout for client
  101. _socket, address = super().get_request()
  102. if self.client_timeout:
  103. _socket.settimeout(self.client_timeout)
  104. return _socket, address
  105. def handle_error(self, request, client_address):
  106. if issubclass(sys.exc_info()[0], socket.timeout):
  107. self.logger.error("connection timeout")
  108. else:
  109. self.logger.error(
  110. "An exception occurred during request:\n%s",
  111. traceback.format_exc())
  112. class HTTPSServer(HTTPServer):
  113. """HTTPS server."""
  114. # These class attributes must be set before creating instance
  115. certificate = None
  116. key = None
  117. protocol = None
  118. ciphers = None
  119. def __init__(self, address, handler):
  120. """Create server by wrapping HTTP socket in an SSL socket."""
  121. super().__init__(address, handler, bind_and_activate=False)
  122. self.socket = ssl.wrap_socket(
  123. self.socket, self.key, self.certificate, server_side=True,
  124. ssl_version=self.protocol, ciphers=self.ciphers)
  125. self.server_bind()
  126. self.server_activate()
  127. class ThreadedHTTPServer(socketserver.ThreadingMixIn, HTTPServer):
  128. def process_request_thread(self, request, client_address):
  129. with self.connections_guard:
  130. return super().process_request_thread(request, client_address)
  131. class ThreadedHTTPSServer(socketserver.ThreadingMixIn, HTTPSServer):
  132. def process_request_thread(self, request, client_address):
  133. with self.connections_guard:
  134. return super().process_request_thread(request, client_address)
  135. class RequestHandler(wsgiref.simple_server.WSGIRequestHandler):
  136. """HTTP requests handler."""
  137. # These class attributes must be set before creating instance
  138. logger = None
  139. def __init__(self, *args, **kwargs):
  140. # Store exception for logging
  141. self.error_stream = io.StringIO()
  142. super().__init__(*args, **kwargs)
  143. def get_stderr(self):
  144. return self.error_stream
  145. def log_message(self, *args, **kwargs):
  146. """Disable inner logging management."""
  147. def get_environ(self):
  148. env = super().get_environ()
  149. # Parent class only tries latin1 encoding
  150. env["PATH_INFO"] = unquote(self.path.split("?", 1)[0])
  151. return env
  152. def handle(self):
  153. super().handle()
  154. # Log exception
  155. error = self.error_stream.getvalue().strip("\n")
  156. if error:
  157. self.logger.error(
  158. "An exception occurred during request:\n%s" % error)
  159. class Application:
  160. """WSGI application managing collections."""
  161. def __init__(self, configuration, logger):
  162. """Initialize application."""
  163. super().__init__()
  164. self.configuration = configuration
  165. self.logger = logger
  166. self.Auth = auth.load(configuration, logger)
  167. self.Collection = storage.load(configuration, logger)
  168. self.authorized = rights.load(configuration, logger)
  169. self.encoding = configuration.get("encoding", "request")
  170. def headers_log(self, environ):
  171. """Sanitize headers for logging."""
  172. request_environ = dict(environ)
  173. # Remove environment variables
  174. if not self.configuration.getboolean("logging", "full_environment"):
  175. for shell_variable in os.environ:
  176. request_environ.pop(shell_variable, None)
  177. # Mask passwords
  178. mask_passwords = self.configuration.getboolean(
  179. "logging", "mask_passwords")
  180. authorization = request_environ.get(
  181. "HTTP_AUTHORIZATION", "").startswith("Basic")
  182. if mask_passwords and authorization:
  183. request_environ["HTTP_AUTHORIZATION"] = "Basic **masked**"
  184. return request_environ
  185. def decode(self, text, environ):
  186. """Try to magically decode ``text`` according to given ``environ``."""
  187. # List of charsets to try
  188. charsets = []
  189. # First append content charset given in the request
  190. content_type = environ.get("CONTENT_TYPE")
  191. if content_type and "charset=" in content_type:
  192. charsets.append(
  193. content_type.split("charset=")[1].split(";")[0].strip())
  194. # Then append default Radicale charset
  195. charsets.append(self.encoding)
  196. # Then append various fallbacks
  197. charsets.append("utf-8")
  198. charsets.append("iso8859-1")
  199. # Try to decode
  200. for charset in charsets:
  201. try:
  202. return text.decode(charset)
  203. except UnicodeDecodeError:
  204. pass
  205. raise UnicodeDecodeError
  206. def collect_allowed_items(self, items, user):
  207. """Get items from request that user is allowed to access."""
  208. read_allowed_items = []
  209. write_allowed_items = []
  210. for item in items:
  211. if not item:
  212. continue
  213. if isinstance(item, self.Collection):
  214. path = item.path
  215. else:
  216. path = item.collection.path
  217. if self.authorized(user, path, "r"):
  218. self.logger.debug(
  219. "%s has read access to collection %s",
  220. user or "Anonymous", path or "/")
  221. read_allowed_items.append(item)
  222. else:
  223. self.logger.debug(
  224. "%s has NO read access to collection %s",
  225. user or "Anonymous", path or "/")
  226. if self.authorized(user, path, "w"):
  227. self.logger.debug(
  228. "%s has write access to collection %s",
  229. user or "Anonymous", path or "/")
  230. write_allowed_items.append(item)
  231. else:
  232. self.logger.debug(
  233. "%s has NO write access to collection %s",
  234. user or "Anonymous", path or "/")
  235. return read_allowed_items, write_allowed_items
  236. def __call__(self, environ, start_response):
  237. """Manage a request."""
  238. def response(status, headers=(), answer=None):
  239. headers = dict(headers)
  240. # Set content length
  241. if answer:
  242. if hasattr(answer, "encode"):
  243. self.logger.debug("Response content:\n%s", answer)
  244. headers["Content-Type"] += "; charset=%s" % self.encoding
  245. answer = answer.encode(self.encoding)
  246. accept_encoding = [
  247. encoding.strip() for encoding in
  248. environ.get("HTTP_ACCEPT_ENCODING", "").split(",")
  249. if encoding.strip()]
  250. if "gzip" in accept_encoding:
  251. zcomp = zlib.compressobj(wbits=16 + zlib.MAX_WBITS)
  252. answer = zcomp.compress(answer) + zcomp.flush()
  253. headers["Content-Encoding"] = "gzip"
  254. headers["Content-Length"] = str(len(answer))
  255. # Add extra headers set in configuration
  256. if self.configuration.has_section("headers"):
  257. for key in self.configuration.options("headers"):
  258. headers[key] = self.configuration.get("headers", key)
  259. # Start response
  260. time_end = datetime.datetime.now()
  261. status = "%i %s" % (
  262. status, client.responses.get(status, "Unknown"))
  263. self.logger.info(
  264. "%s answer status for %s in %.3f seconds: %s",
  265. environ["REQUEST_METHOD"], environ["PATH_INFO"] + depthinfo,
  266. (time_end - time_begin).total_seconds(), status)
  267. start_response(status, list(headers.items()))
  268. # Return response content
  269. return [answer] if answer else []
  270. remote_host = "UNKNOWN"
  271. if environ.get("REMOTE_HOST"):
  272. remote_host = environ["REMOTE_HOST"]
  273. elif environ.get("REMOTE_ADDR"):
  274. remote_host = environ["REMOTE_ADDR"]
  275. if environ.get("HTTP_X_FORWARDED_FOR"):
  276. remote_host = "%s (forwarded by %s)" % (
  277. environ["HTTP_X_FORWARDED_FOR"], remote_host)
  278. remote_useragent = "UNKNOWN"
  279. if environ.get("HTTP_USER_AGENT"):
  280. remote_useragent = environ["HTTP_USER_AGENT"]
  281. depthinfo = ""
  282. if environ.get("HTTP_DEPTH"):
  283. depthinfo = " with depth " + environ["HTTP_DEPTH"]
  284. time_begin = datetime.datetime.now()
  285. self.logger.info(
  286. "%s request for %s received from %s using \"%s\"",
  287. environ["REQUEST_METHOD"], environ["PATH_INFO"] + depthinfo,
  288. remote_host, remote_useragent)
  289. headers = pprint.pformat(self.headers_log(environ))
  290. self.logger.debug("Request headers:\n%s", headers)
  291. # Let reverse proxies overwrite SCRIPT_NAME
  292. if "HTTP_X_SCRIPT_NAME" in environ:
  293. environ["SCRIPT_NAME"] = environ["HTTP_X_SCRIPT_NAME"]
  294. self.logger.debug(
  295. "Script name overwritten by client: %s",
  296. environ["SCRIPT_NAME"])
  297. # Sanitize base prefix
  298. environ["SCRIPT_NAME"] = storage.sanitize_path(
  299. environ.get("SCRIPT_NAME", "")).rstrip("/")
  300. self.logger.debug("Sanitized script name: %s", environ["SCRIPT_NAME"])
  301. base_prefix = environ["SCRIPT_NAME"]
  302. # Sanitize request URI (a WSGI server indicates with an empty path,
  303. # that the URL targets the application root without a trailing slash)
  304. if environ["PATH_INFO"]:
  305. environ["PATH_INFO"] = storage.sanitize_path(environ["PATH_INFO"])
  306. self.logger.debug("Sanitized path: %s", environ["PATH_INFO"])
  307. path = environ["PATH_INFO"]
  308. if base_prefix and path.startswith(base_prefix):
  309. path = path[len(base_prefix):]
  310. self.logger.debug("Stripped script name from path: %s", path)
  311. # Get function corresponding to method
  312. function = getattr(self, "do_%s" % environ["REQUEST_METHOD"].upper())
  313. # Ask authentication backend to check rights
  314. authorization = environ.get("HTTP_AUTHORIZATION", None)
  315. if authorization and authorization.startswith("Basic"):
  316. authorization = authorization[len("Basic"):].strip()
  317. login, password = self.decode(base64.b64decode(
  318. authorization.encode("ascii")), environ).split(":", 1)
  319. user = self.Auth.map_login_to_user(login)
  320. else:
  321. user = self.Auth.map_login_to_user(environ.get("REMOTE_USER", ""))
  322. password = ""
  323. # If "/.well-known" is not available, clients query "/"
  324. if path == "/.well-known" or path.startswith("/.well-known/"):
  325. return response(*NOT_FOUND)
  326. if not user:
  327. is_authenticated = True
  328. elif not storage.is_safe_path_component(user):
  329. # Prevent usernames like "user/calendar.ics"
  330. self.logger.info("Refused unsafe username: %s", user)
  331. is_authenticated = False
  332. else:
  333. is_authenticated = self.Auth.is_authenticated(user, password)
  334. if not is_authenticated:
  335. self.logger.info("Failed login attempt: %s", user)
  336. # Random delay to avoid timing oracles and bruteforce attacks
  337. delay = self.configuration.getfloat("auth", "delay")
  338. if delay > 0:
  339. random_delay = delay * (0.5 + random.random())
  340. self.logger.debug("Sleeping %.3f seconds", random_delay)
  341. time.sleep(random_delay)
  342. # Create principal collection
  343. if user and is_authenticated:
  344. principal_path = "/%s/" % user
  345. if self.authorized(user, principal_path, "w"):
  346. with self.Collection.acquire_lock("r", user):
  347. principal = next(
  348. self.Collection.discover(principal_path, depth="1"),
  349. None)
  350. if not principal:
  351. with self.Collection.acquire_lock("w", user):
  352. self.Collection.create_collection(principal_path)
  353. # Verify content length
  354. content_length = int(environ.get("CONTENT_LENGTH") or 0)
  355. if content_length:
  356. max_content_length = self.configuration.getint(
  357. "server", "max_content_length")
  358. if max_content_length and content_length > max_content_length:
  359. self.logger.debug(
  360. "Request body too large: %d", content_length)
  361. return response(*REQUEST_ENTITY_TOO_LARGE)
  362. if is_authenticated:
  363. try:
  364. status, headers, answer = function(
  365. environ, base_prefix, path, user)
  366. except socket.timeout:
  367. return response(*REQUEST_TIMEOUT)
  368. if (status, headers, answer) == NOT_ALLOWED:
  369. self.logger.info("Access denied for %s",
  370. "'%s'" % user if user else "anonymous user")
  371. else:
  372. status, headers, answer = NOT_ALLOWED
  373. if (status, headers, answer) == NOT_ALLOWED and not (
  374. user and is_authenticated):
  375. # Unknown or unauthorized user
  376. self.logger.debug("Asking client for authentication")
  377. status = client.UNAUTHORIZED
  378. realm = self.configuration.get("server", "realm")
  379. headers = dict(headers)
  380. headers.update({
  381. "WWW-Authenticate":
  382. "Basic realm=\"%s\"" % realm})
  383. return response(status, headers, answer)
  384. def _access(self, user, path, permission, item=None):
  385. """Check if ``user`` can access ``path`` or the parent collection.
  386. ``permission`` must either be "r" or "w".
  387. If ``item`` is given, only access to that class of item is checked.
  388. """
  389. path = storage.sanitize_path(path)
  390. parent_path = storage.sanitize_path(
  391. "/%s/" % posixpath.dirname(path.strip("/")))
  392. allowed = False
  393. if not item or isinstance(item, self.Collection):
  394. allowed |= self.authorized(user, path, permission)
  395. if not item or not isinstance(item, self.Collection):
  396. allowed |= self.authorized(user, parent_path, permission)
  397. return allowed
  398. def _read_raw_content(self, environ):
  399. content_length = int(environ.get("CONTENT_LENGTH") or 0)
  400. if not content_length:
  401. return b""
  402. content = environ["wsgi.input"].read(content_length)
  403. if len(content) < content_length:
  404. raise ValueError("Request body too short: %d" % len(content))
  405. return content
  406. def _read_content(self, environ):
  407. content = self.decode(self._read_raw_content(environ), environ)
  408. self.logger.debug("Request content:\n%s", content)
  409. return content
  410. def _read_xml_content(self, environ):
  411. content = self.decode(self._read_raw_content(environ), environ)
  412. if not content:
  413. return None
  414. try:
  415. xml_content = ET.fromstring(content)
  416. except ET.ParseError:
  417. self.logger.debug("Request content (Invalid XML):\n%s", content)
  418. raise
  419. if self.logger.isEnabledFor(logging.DEBUG):
  420. self.logger.debug("Request content:\n%s",
  421. xmlutils.pretty_xml(xml_content))
  422. return xml_content
  423. def _write_xml_content(self, xml_content):
  424. if self.logger.isEnabledFor(logging.DEBUG):
  425. self.logger.debug("Response content:\n%s",
  426. xmlutils.pretty_xml(xml_content))
  427. f = io.BytesIO()
  428. ET.ElementTree(xml_content).write(f, encoding=self.encoding,
  429. xml_declaration=True)
  430. return f.getvalue()
  431. def do_DELETE(self, environ, base_prefix, path, user):
  432. """Manage DELETE request."""
  433. if not self._access(user, path, "w"):
  434. return NOT_ALLOWED
  435. with self.Collection.acquire_lock("w", user):
  436. item = next(self.Collection.discover(path), None)
  437. if not self._access(user, path, "w", item):
  438. return NOT_ALLOWED
  439. if not item:
  440. return NOT_FOUND
  441. if_match = environ.get("HTTP_IF_MATCH", "*")
  442. if if_match not in ("*", item.etag):
  443. # ETag precondition not verified, do not delete item
  444. return PRECONDITION_FAILED
  445. if isinstance(item, self.Collection):
  446. xml_answer = xmlutils.delete(base_prefix, path, item)
  447. else:
  448. xml_answer = xmlutils.delete(
  449. base_prefix, path, item.collection, item.href)
  450. headers = {"Content-Type": "text/xml; charset=%s" % self.encoding}
  451. return client.OK, headers, self._write_xml_content(xml_answer)
  452. def do_GET(self, environ, base_prefix, path, user):
  453. """Manage GET request."""
  454. # Display a "Radicale works!" message if the root URL is requested
  455. if not path.strip("/"):
  456. return client.OK, {"Content-Type": "text/plain"}, "Radicale works!"
  457. if not self._access(user, path, "r"):
  458. return NOT_ALLOWED
  459. with self.Collection.acquire_lock("r", user):
  460. item = next(self.Collection.discover(path), None)
  461. if not self._access(user, path, "r", item):
  462. return NOT_ALLOWED
  463. if not item:
  464. return NOT_FOUND
  465. if isinstance(item, self.Collection):
  466. collection = item
  467. if collection.get_meta("tag") not in (
  468. "VADDRESSBOOK", "VCALENDAR"):
  469. return DIRECTORY_LISTING
  470. else:
  471. collection = item.collection
  472. content_type = xmlutils.MIMETYPES.get(
  473. collection.get_meta("tag"), "text/plain")
  474. headers = {
  475. "Content-Type": content_type,
  476. "Last-Modified": collection.last_modified,
  477. "ETag": item.etag}
  478. answer = item.serialize()
  479. return client.OK, headers, answer
  480. def do_HEAD(self, environ, base_prefix, path, user):
  481. """Manage HEAD request."""
  482. status, headers, answer = self.do_GET(
  483. environ, base_prefix, path, user)
  484. return status, headers, None
  485. def do_MKCALENDAR(self, environ, base_prefix, path, user):
  486. """Manage MKCALENDAR request."""
  487. if not self.authorized(user, path, "w"):
  488. return NOT_ALLOWED
  489. xml_content = self._read_xml_content(environ)
  490. with self.Collection.acquire_lock("w", user):
  491. item = next(self.Collection.discover(path), None)
  492. if item:
  493. return WEBDAV_PRECONDITION_FAILED
  494. props = xmlutils.props_from_request(xml_content)
  495. props["tag"] = "VCALENDAR"
  496. # TODO: use this?
  497. # timezone = props.get("C:calendar-timezone")
  498. self.Collection.create_collection(path, props=props)
  499. return client.CREATED, {}, None
  500. def do_MKCOL(self, environ, base_prefix, path, user):
  501. """Manage MKCOL request."""
  502. if not self.authorized(user, path, "w"):
  503. return NOT_ALLOWED
  504. xml_content = self._read_xml_content(environ)
  505. with self.Collection.acquire_lock("w", user):
  506. item = next(self.Collection.discover(path), None)
  507. if item:
  508. return WEBDAV_PRECONDITION_FAILED
  509. props = xmlutils.props_from_request(xml_content)
  510. self.Collection.create_collection(path, props=props)
  511. return client.CREATED, {}, None
  512. def do_MOVE(self, environ, base_prefix, path, user):
  513. """Manage MOVE request."""
  514. to_url = urlparse(environ["HTTP_DESTINATION"])
  515. if to_url.netloc != environ["HTTP_HOST"]:
  516. # Remote destination server, not supported
  517. return REMOTE_DESTINATION
  518. if not self._access(user, path, "w"):
  519. return NOT_ALLOWED
  520. to_path = storage.sanitize_path(to_url.path)
  521. if not (to_path + "/").startswith(base_prefix + "/"):
  522. return NOT_ALLOWED
  523. to_path = to_path[len(base_prefix):]
  524. if not self._access(user, to_path, "w"):
  525. return NOT_ALLOWED
  526. with self.Collection.acquire_lock("w", user):
  527. item = next(self.Collection.discover(path), None)
  528. if not self._access(user, path, "w", item):
  529. return NOT_ALLOWED
  530. if not self._access(user, to_path, "w", item):
  531. return NOT_ALLOWED
  532. if not item:
  533. return NOT_FOUND
  534. if isinstance(item, self.Collection):
  535. return WEBDAV_PRECONDITION_FAILED
  536. to_item = next(self.Collection.discover(to_path), None)
  537. if (isinstance(to_item, self.Collection) or
  538. to_item and environ.get("HTTP_OVERWRITE", "F") != "T"):
  539. return WEBDAV_PRECONDITION_FAILED
  540. to_parent_path = storage.sanitize_path(
  541. "/%s/" % posixpath.dirname(to_path.strip("/")))
  542. to_collection = next(
  543. self.Collection.discover(to_parent_path), None)
  544. if not to_collection:
  545. return WEBDAV_PRECONDITION_FAILED
  546. to_href = posixpath.basename(to_path.strip("/"))
  547. self.Collection.move(item, to_collection, to_href)
  548. return client.CREATED, {}, None
  549. def do_OPTIONS(self, environ, base_prefix, path, user):
  550. """Manage OPTIONS request."""
  551. headers = {
  552. "Allow": ", ".join(
  553. name[3:] for name in dir(self) if name.startswith("do_")),
  554. "DAV": DAV_HEADERS}
  555. return client.OK, headers, None
  556. def do_PROPFIND(self, environ, base_prefix, path, user):
  557. """Manage PROPFIND request."""
  558. if not self._access(user, path, "r"):
  559. return NOT_ALLOWED
  560. xml_content = self._read_xml_content(environ)
  561. with self.Collection.acquire_lock("r", user):
  562. items = self.Collection.discover(
  563. path, environ.get("HTTP_DEPTH", "0"))
  564. # take root item for rights checking
  565. item = next(items, None)
  566. if not self._access(user, path, "r", item):
  567. return NOT_ALLOWED
  568. if not item:
  569. return NOT_FOUND
  570. # put item back
  571. items = itertools.chain([item], items)
  572. read_items, write_items = self.collect_allowed_items(items, user)
  573. headers = {"DAV": DAV_HEADERS,
  574. "Content-Type": "text/xml; charset=%s" % self.encoding}
  575. status, xml_answer = xmlutils.propfind(
  576. base_prefix, path, xml_content, read_items, write_items, user)
  577. if status == client.FORBIDDEN:
  578. return NOT_ALLOWED
  579. else:
  580. return status, headers, self._write_xml_content(xml_answer)
  581. def do_PROPPATCH(self, environ, base_prefix, path, user):
  582. """Manage PROPPATCH request."""
  583. if not self.authorized(user, path, "w"):
  584. return NOT_ALLOWED
  585. xml_content = self._read_xml_content(environ)
  586. with self.Collection.acquire_lock("w", user):
  587. item = next(self.Collection.discover(path), None)
  588. if not isinstance(item, self.Collection):
  589. return WEBDAV_PRECONDITION_FAILED
  590. headers = {"DAV": DAV_HEADERS,
  591. "Content-Type": "text/xml; charset=%s" % self.encoding}
  592. xml_answer = xmlutils.proppatch(base_prefix, path, xml_content,
  593. item)
  594. return (client.MULTI_STATUS, headers,
  595. self._write_xml_content(xml_answer))
  596. def do_PUT(self, environ, base_prefix, path, user):
  597. """Manage PUT request."""
  598. if not self._access(user, path, "w"):
  599. return NOT_ALLOWED
  600. content = self._read_content(environ)
  601. with self.Collection.acquire_lock("w", user):
  602. parent_path = storage.sanitize_path(
  603. "/%s/" % posixpath.dirname(path.strip("/")))
  604. item = next(self.Collection.discover(path), None)
  605. parent_item = next(self.Collection.discover(parent_path), None)
  606. write_whole_collection = (
  607. isinstance(item, self.Collection) or
  608. not parent_item or (
  609. not next(parent_item.list(), None) and
  610. parent_item.get_meta("tag") not in (
  611. "VADDRESSBOOK", "VCALENDAR")))
  612. if write_whole_collection:
  613. if not self.authorized(user, path, "w"):
  614. return NOT_ALLOWED
  615. elif not self.authorized(user, parent_path, "w"):
  616. return NOT_ALLOWED
  617. etag = environ.get("HTTP_IF_MATCH", "")
  618. if not item and etag:
  619. # Etag asked but no item found: item has been removed
  620. return PRECONDITION_FAILED
  621. if item and etag and item.etag != etag:
  622. # Etag asked but item not matching: item has changed
  623. return PRECONDITION_FAILED
  624. match = environ.get("HTTP_IF_NONE_MATCH", "") == "*"
  625. if item and match:
  626. # Creation asked but item found: item can't be replaced
  627. return PRECONDITION_FAILED
  628. items = list(vobject.readComponents(content or ""))
  629. content_type = environ.get("CONTENT_TYPE", "").split(";")[0]
  630. tags = {value: key for key, value in xmlutils.MIMETYPES.items()}
  631. tag = tags.get(content_type)
  632. if write_whole_collection:
  633. new_item = self.Collection.create_collection(
  634. path, items, {"tag": tag})
  635. else:
  636. if tag:
  637. parent_item.set_meta({"tag": tag})
  638. href = posixpath.basename(path.strip("/"))
  639. new_item = parent_item.upload(href, items[0])
  640. headers = {"ETag": new_item.etag}
  641. return client.CREATED, headers, None
  642. def do_REPORT(self, environ, base_prefix, path, user):
  643. """Manage REPORT request."""
  644. if not self._access(user, path, "r"):
  645. return NOT_ALLOWED
  646. xml_content = self._read_xml_content(environ)
  647. with self.Collection.acquire_lock("r", user):
  648. item = next(self.Collection.discover(path), None)
  649. if not self._access(user, path, "r", item):
  650. return NOT_ALLOWED
  651. if not item:
  652. return NOT_FOUND
  653. if isinstance(item, self.Collection):
  654. collection = item
  655. else:
  656. collection = item.collection
  657. headers = {"Content-Type": "text/xml; charset=%s" % self.encoding}
  658. xml_answer = xmlutils.report(
  659. base_prefix, path, xml_content, collection)
  660. return (client.MULTI_STATUS, headers,
  661. self._write_xml_content(xml_answer))