__init__.py 27 KB

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