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