__init__.py 27 KB

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