__init__.py 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758
  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. external_login = self.Auth.get_external_login(environ)
  315. authorization = environ.get("HTTP_AUTHORIZATION", "")
  316. if external_login:
  317. login, password = external_login
  318. elif authorization.startswith("Basic"):
  319. authorization = authorization[len("Basic"):].strip()
  320. login, password = self.decode(base64.b64decode(
  321. authorization.encode("ascii")), environ).split(":", 1)
  322. else:
  323. # DEPRECATED: use remote_user backend instead
  324. login = environ.get("REMOTE_USER", "")
  325. password = ""
  326. user = self.Auth.map_login_to_user(login)
  327. # If "/.well-known" is not available, clients query "/"
  328. if path == "/.well-known" or path.startswith("/.well-known/"):
  329. return response(*NOT_FOUND)
  330. if not user:
  331. is_authenticated = True
  332. elif not storage.is_safe_path_component(user):
  333. # Prevent usernames like "user/calendar.ics"
  334. self.logger.info("Refused unsafe username: %s", user)
  335. is_authenticated = False
  336. else:
  337. is_authenticated = self.Auth.is_authenticated(user, password)
  338. if not is_authenticated:
  339. self.logger.info("Failed login attempt: %s", user)
  340. # Random delay to avoid timing oracles and bruteforce attacks
  341. delay = self.configuration.getfloat("auth", "delay")
  342. if delay > 0:
  343. random_delay = delay * (0.5 + random.random())
  344. self.logger.debug("Sleeping %.3f seconds", random_delay)
  345. time.sleep(random_delay)
  346. # Create principal collection
  347. if user and is_authenticated:
  348. principal_path = "/%s/" % user
  349. if self.authorized(user, principal_path, "w"):
  350. with self.Collection.acquire_lock("r", user):
  351. principal = next(
  352. self.Collection.discover(principal_path, depth="1"),
  353. None)
  354. if not principal:
  355. with self.Collection.acquire_lock("w", user):
  356. self.Collection.create_collection(principal_path)
  357. # Verify content length
  358. content_length = int(environ.get("CONTENT_LENGTH") or 0)
  359. if content_length:
  360. max_content_length = self.configuration.getint(
  361. "server", "max_content_length")
  362. if max_content_length and content_length > max_content_length:
  363. self.logger.debug(
  364. "Request body too large: %d", content_length)
  365. return response(*REQUEST_ENTITY_TOO_LARGE)
  366. if is_authenticated:
  367. try:
  368. status, headers, answer = function(
  369. environ, base_prefix, path, user)
  370. except socket.timeout:
  371. return response(*REQUEST_TIMEOUT)
  372. if (status, headers, answer) == NOT_ALLOWED:
  373. self.logger.info("Access denied for %s",
  374. "'%s'" % user if user else "anonymous user")
  375. else:
  376. status, headers, answer = NOT_ALLOWED
  377. if (status, headers, answer) == NOT_ALLOWED and not (
  378. user and is_authenticated) and not external_login:
  379. # Unknown or unauthorized user
  380. self.logger.debug("Asking client for authentication")
  381. status = client.UNAUTHORIZED
  382. realm = self.configuration.get("server", "realm")
  383. headers = dict(headers)
  384. headers.update({
  385. "WWW-Authenticate":
  386. "Basic realm=\"%s\"" % realm})
  387. return response(status, headers, answer)
  388. def _access(self, user, path, permission, item=None):
  389. """Check if ``user`` can access ``path`` or the parent collection.
  390. ``permission`` must either be "r" or "w".
  391. If ``item`` is given, only access to that class of item is checked.
  392. """
  393. path = storage.sanitize_path(path)
  394. parent_path = storage.sanitize_path(
  395. "/%s/" % posixpath.dirname(path.strip("/")))
  396. allowed = False
  397. if not item or isinstance(item, self.Collection):
  398. allowed |= self.authorized(user, path, permission)
  399. if not item or not isinstance(item, self.Collection):
  400. allowed |= self.authorized(user, parent_path, permission)
  401. return allowed
  402. def _read_raw_content(self, environ):
  403. content_length = int(environ.get("CONTENT_LENGTH") or 0)
  404. if not content_length:
  405. return b""
  406. content = environ["wsgi.input"].read(content_length)
  407. if len(content) < content_length:
  408. raise ValueError("Request body too short: %d" % len(content))
  409. return content
  410. def _read_content(self, environ):
  411. content = self.decode(self._read_raw_content(environ), environ)
  412. self.logger.debug("Request content:\n%s", content)
  413. return content
  414. def _read_xml_content(self, environ):
  415. content = self.decode(self._read_raw_content(environ), environ)
  416. if not content:
  417. return None
  418. try:
  419. xml_content = ET.fromstring(content)
  420. except ET.ParseError:
  421. self.logger.debug("Request content (Invalid XML):\n%s", content)
  422. raise
  423. if self.logger.isEnabledFor(logging.DEBUG):
  424. self.logger.debug("Request content:\n%s",
  425. xmlutils.pretty_xml(xml_content))
  426. return xml_content
  427. def _write_xml_content(self, xml_content):
  428. if self.logger.isEnabledFor(logging.DEBUG):
  429. self.logger.debug("Response content:\n%s",
  430. xmlutils.pretty_xml(xml_content))
  431. f = io.BytesIO()
  432. ET.ElementTree(xml_content).write(f, encoding=self.encoding,
  433. xml_declaration=True)
  434. return f.getvalue()
  435. def do_DELETE(self, environ, base_prefix, path, user):
  436. """Manage DELETE request."""
  437. if not self._access(user, path, "w"):
  438. return NOT_ALLOWED
  439. with self.Collection.acquire_lock("w", user):
  440. item = next(self.Collection.discover(path), None)
  441. if not self._access(user, path, "w", item):
  442. return NOT_ALLOWED
  443. if not item:
  444. return NOT_FOUND
  445. if_match = environ.get("HTTP_IF_MATCH", "*")
  446. if if_match not in ("*", item.etag):
  447. # ETag precondition not verified, do not delete item
  448. return PRECONDITION_FAILED
  449. if isinstance(item, self.Collection):
  450. xml_answer = xmlutils.delete(base_prefix, path, item)
  451. else:
  452. xml_answer = xmlutils.delete(
  453. base_prefix, path, item.collection, item.href)
  454. headers = {"Content-Type": "text/xml; charset=%s" % self.encoding}
  455. return client.OK, headers, self._write_xml_content(xml_answer)
  456. def do_GET(self, environ, base_prefix, path, user):
  457. """Manage GET request."""
  458. # Display a "Radicale works!" message if the root URL is requested
  459. if not path.strip("/"):
  460. return client.OK, {"Content-Type": "text/plain"}, "Radicale works!"
  461. if not self._access(user, path, "r"):
  462. return NOT_ALLOWED
  463. with self.Collection.acquire_lock("r", user):
  464. item = next(self.Collection.discover(path), None)
  465. if not self._access(user, path, "r", item):
  466. return NOT_ALLOWED
  467. if not item:
  468. return NOT_FOUND
  469. if isinstance(item, self.Collection):
  470. collection = item
  471. if collection.get_meta("tag") not in (
  472. "VADDRESSBOOK", "VCALENDAR"):
  473. return DIRECTORY_LISTING
  474. else:
  475. collection = item.collection
  476. content_type = xmlutils.MIMETYPES.get(
  477. collection.get_meta("tag"), "text/plain")
  478. headers = {
  479. "Content-Type": content_type,
  480. "Last-Modified": collection.last_modified,
  481. "ETag": item.etag}
  482. answer = item.serialize()
  483. return client.OK, headers, answer
  484. def do_HEAD(self, environ, base_prefix, path, user):
  485. """Manage HEAD request."""
  486. status, headers, answer = self.do_GET(
  487. environ, base_prefix, path, user)
  488. return status, headers, None
  489. def do_MKCALENDAR(self, environ, base_prefix, path, user):
  490. """Manage MKCALENDAR request."""
  491. if not self.authorized(user, path, "w"):
  492. return NOT_ALLOWED
  493. xml_content = self._read_xml_content(environ)
  494. with self.Collection.acquire_lock("w", user):
  495. item = next(self.Collection.discover(path), None)
  496. if item:
  497. return WEBDAV_PRECONDITION_FAILED
  498. props = xmlutils.props_from_request(xml_content)
  499. props["tag"] = "VCALENDAR"
  500. # TODO: use this?
  501. # timezone = props.get("C:calendar-timezone")
  502. self.Collection.create_collection(path, props=props)
  503. return client.CREATED, {}, None
  504. def do_MKCOL(self, environ, base_prefix, path, user):
  505. """Manage MKCOL request."""
  506. if not self.authorized(user, path, "w"):
  507. return NOT_ALLOWED
  508. xml_content = self._read_xml_content(environ)
  509. with self.Collection.acquire_lock("w", user):
  510. item = next(self.Collection.discover(path), None)
  511. if item:
  512. return WEBDAV_PRECONDITION_FAILED
  513. props = xmlutils.props_from_request(xml_content)
  514. self.Collection.create_collection(path, props=props)
  515. return client.CREATED, {}, None
  516. def do_MOVE(self, environ, base_prefix, path, user):
  517. """Manage MOVE request."""
  518. to_url = urlparse(environ["HTTP_DESTINATION"])
  519. if to_url.netloc != environ["HTTP_HOST"]:
  520. # Remote destination server, not supported
  521. return REMOTE_DESTINATION
  522. if not self._access(user, path, "w"):
  523. return NOT_ALLOWED
  524. to_path = storage.sanitize_path(to_url.path)
  525. if not (to_path + "/").startswith(base_prefix + "/"):
  526. return NOT_ALLOWED
  527. to_path = to_path[len(base_prefix):]
  528. if not self._access(user, to_path, "w"):
  529. return NOT_ALLOWED
  530. with self.Collection.acquire_lock("w", user):
  531. item = next(self.Collection.discover(path), None)
  532. if not self._access(user, path, "w", item):
  533. return NOT_ALLOWED
  534. if not self._access(user, to_path, "w", item):
  535. return NOT_ALLOWED
  536. if not item:
  537. return NOT_FOUND
  538. if isinstance(item, self.Collection):
  539. return WEBDAV_PRECONDITION_FAILED
  540. to_item = next(self.Collection.discover(to_path), None)
  541. if (isinstance(to_item, self.Collection) or
  542. to_item and environ.get("HTTP_OVERWRITE", "F") != "T"):
  543. return WEBDAV_PRECONDITION_FAILED
  544. to_parent_path = storage.sanitize_path(
  545. "/%s/" % posixpath.dirname(to_path.strip("/")))
  546. to_collection = next(
  547. self.Collection.discover(to_parent_path), None)
  548. if not to_collection:
  549. return WEBDAV_PRECONDITION_FAILED
  550. to_href = posixpath.basename(to_path.strip("/"))
  551. self.Collection.move(item, to_collection, to_href)
  552. return client.CREATED, {}, None
  553. def do_OPTIONS(self, environ, base_prefix, path, user):
  554. """Manage OPTIONS request."""
  555. headers = {
  556. "Allow": ", ".join(
  557. name[3:] for name in dir(self) if name.startswith("do_")),
  558. "DAV": DAV_HEADERS}
  559. return client.OK, headers, None
  560. def do_PROPFIND(self, environ, base_prefix, path, user):
  561. """Manage PROPFIND request."""
  562. if not self._access(user, path, "r"):
  563. return NOT_ALLOWED
  564. xml_content = self._read_xml_content(environ)
  565. with self.Collection.acquire_lock("r", user):
  566. items = self.Collection.discover(
  567. path, environ.get("HTTP_DEPTH", "0"))
  568. # take root item for rights checking
  569. item = next(items, None)
  570. if not self._access(user, path, "r", item):
  571. return NOT_ALLOWED
  572. if not item:
  573. return NOT_FOUND
  574. # put item back
  575. items = itertools.chain([item], items)
  576. read_items, write_items = self.collect_allowed_items(items, user)
  577. headers = {"DAV": DAV_HEADERS,
  578. "Content-Type": "text/xml; charset=%s" % self.encoding}
  579. status, xml_answer = xmlutils.propfind(
  580. base_prefix, path, xml_content, read_items, write_items, user)
  581. if status == client.FORBIDDEN:
  582. return NOT_ALLOWED
  583. else:
  584. return status, headers, self._write_xml_content(xml_answer)
  585. def do_PROPPATCH(self, environ, base_prefix, path, user):
  586. """Manage PROPPATCH request."""
  587. if not self.authorized(user, path, "w"):
  588. return NOT_ALLOWED
  589. xml_content = self._read_xml_content(environ)
  590. with self.Collection.acquire_lock("w", user):
  591. item = next(self.Collection.discover(path), None)
  592. if not isinstance(item, self.Collection):
  593. return WEBDAV_PRECONDITION_FAILED
  594. headers = {"DAV": DAV_HEADERS,
  595. "Content-Type": "text/xml; charset=%s" % self.encoding}
  596. xml_answer = xmlutils.proppatch(base_prefix, path, xml_content,
  597. item)
  598. return (client.MULTI_STATUS, headers,
  599. self._write_xml_content(xml_answer))
  600. def do_PUT(self, environ, base_prefix, path, user):
  601. """Manage PUT request."""
  602. if not self._access(user, path, "w"):
  603. return NOT_ALLOWED
  604. content = self._read_content(environ)
  605. with self.Collection.acquire_lock("w", user):
  606. parent_path = storage.sanitize_path(
  607. "/%s/" % posixpath.dirname(path.strip("/")))
  608. item = next(self.Collection.discover(path), None)
  609. parent_item = next(self.Collection.discover(parent_path), None)
  610. write_whole_collection = (
  611. isinstance(item, self.Collection) or
  612. not parent_item or (
  613. not next(parent_item.list(), None) and
  614. parent_item.get_meta("tag") not in (
  615. "VADDRESSBOOK", "VCALENDAR")))
  616. if write_whole_collection:
  617. if not self.authorized(user, path, "w"):
  618. return NOT_ALLOWED
  619. elif not self.authorized(user, parent_path, "w"):
  620. return NOT_ALLOWED
  621. etag = environ.get("HTTP_IF_MATCH", "")
  622. if not item and etag:
  623. # Etag asked but no item found: item has been removed
  624. return PRECONDITION_FAILED
  625. if item and etag and item.etag != etag:
  626. # Etag asked but item not matching: item has changed
  627. return PRECONDITION_FAILED
  628. match = environ.get("HTTP_IF_NONE_MATCH", "") == "*"
  629. if item and match:
  630. # Creation asked but item found: item can't be replaced
  631. return PRECONDITION_FAILED
  632. items = list(vobject.readComponents(content or ""))
  633. content_type = environ.get("CONTENT_TYPE", "").split(";")[0]
  634. tags = {value: key for key, value in xmlutils.MIMETYPES.items()}
  635. tag = tags.get(content_type)
  636. if write_whole_collection:
  637. new_item = self.Collection.create_collection(
  638. path, items, {"tag": tag})
  639. else:
  640. if tag:
  641. parent_item.set_meta({"tag": tag})
  642. href = posixpath.basename(path.strip("/"))
  643. new_item = parent_item.upload(href, items[0])
  644. headers = {"ETag": new_item.etag}
  645. return client.CREATED, headers, None
  646. def do_REPORT(self, environ, base_prefix, path, user):
  647. """Manage REPORT request."""
  648. if not self._access(user, path, "r"):
  649. return NOT_ALLOWED
  650. xml_content = self._read_xml_content(environ)
  651. with self.Collection.acquire_lock("r", user):
  652. item = next(self.Collection.discover(path), None)
  653. if not self._access(user, path, "r", item):
  654. return NOT_ALLOWED
  655. if not item:
  656. return NOT_FOUND
  657. if isinstance(item, self.Collection):
  658. collection = item
  659. else:
  660. collection = item.collection
  661. headers = {"Content-Type": "text/xml; charset=%s" % self.encoding}
  662. xml_answer = xmlutils.report(
  663. base_prefix, path, xml_content, collection)
  664. return (client.MULTI_STATUS, headers,
  665. self._write_xml_content(xml_answer))