ldp.py 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905
  1. import hashlib
  2. import logging
  3. import pdb
  4. from base64 import b64encode
  5. from collections import defaultdict
  6. from io import BytesIO
  7. from pprint import pformat
  8. from uuid import uuid4
  9. import arrow
  10. from flask import (
  11. Blueprint, Response, g, make_response, render_template,
  12. request, send_file)
  13. from rdflib import Graph, plugin, parser#, serializer
  14. from werkzeug.http import parse_date
  15. from lakesuperior import env
  16. from lakesuperior.api import resource as rsrc_api
  17. from lakesuperior.dictionaries.namespaces import ns_collection as nsc
  18. from lakesuperior.dictionaries.namespaces import ns_mgr as nsm
  19. from lakesuperior.exceptions import (
  20. ChecksumValidationError, ResourceNotExistsError, TombstoneError,
  21. ServerManagedTermError, InvalidResourceError, SingleSubjectError,
  22. ResourceExistsError, IncompatibleLdpTypeError)
  23. from lakesuperior.globals import RES_CREATED
  24. from lakesuperior.model.ldp.ldp_factory import LdpFactory
  25. from lakesuperior.model.ldp.ldp_nr import LdpNr
  26. from lakesuperior.model.ldp.ldp_rs import LdpRs
  27. from lakesuperior.model.ldp.ldpr import Ldpr
  28. from lakesuperior.util import toolbox
  29. from lakesuperior.util.toolbox import RequestUtils
  30. DEFAULT_RDF_MIMETYPE = 'text/turtle'
  31. """
  32. Fallback serialization format used when no acceptable formats are specified.
  33. """
  34. logger = logging.getLogger(__name__)
  35. rdf_parsable_mimetypes = {
  36. mt.name for mt in plugin.plugins()
  37. if mt.kind is parser.Parser and '/' in mt.name
  38. }
  39. """MIMEtypes that can be parsed into RDF."""
  40. store = env.app_globals.rdf_store
  41. rdf_serializable_mimetypes = {
  42. #mt.name for mt in plugin.plugins()
  43. #if mt.kind is serializer.Serializer and '/' in mt.name
  44. 'application/ld+json',
  45. 'application/n-triples',
  46. 'application/rdf+xml',
  47. 'text/turtle',
  48. 'text/n3',
  49. }
  50. """
  51. MIMEtypes that RDF can be serialized into.
  52. These are not automatically derived from RDFLib because only triple
  53. (not quad) serializations are applicable.
  54. """
  55. accept_patch = (
  56. 'application/sparql-update',
  57. )
  58. std_headers = {
  59. 'Accept-Patch' : ','.join(accept_patch),
  60. 'Accept-Post' : ','.join(rdf_parsable_mimetypes),
  61. }
  62. """Predicates excluded by view."""
  63. vw_blacklist = {
  64. }
  65. ldp = Blueprint(
  66. 'ldp', __name__, template_folder='templates',
  67. static_url_path='/static', static_folder='templates/static')
  68. """
  69. Blueprint for LDP REST API. This is what is usually found under ``/rest/`` in
  70. standard fcrepo4. Here, it is under ``/ldp`` but initially ``/rest`` will be
  71. kept for backward compatibility.
  72. """
  73. ## ROUTE PRE- & POST-PROCESSING ##
  74. @ldp.url_defaults
  75. def bp_url_defaults(endpoint, values):
  76. url_prefix = getattr(g, 'url_prefix', None)
  77. if url_prefix is not None:
  78. values.setdefault('url_prefix', url_prefix)
  79. @ldp.url_value_preprocessor
  80. def bp_url_value_preprocessor(endpoint, values):
  81. g.url_prefix = values.pop('url_prefix')
  82. g.webroot = request.host_url + g.url_prefix
  83. # Normalize leading slashes for UID.
  84. if 'uid' in values:
  85. values['uid'] = '/' + values['uid'].lstrip('/')
  86. if 'parent_uid' in values:
  87. values['parent_uid'] = '/' + values['parent_uid'].lstrip('/')
  88. @ldp.before_request
  89. def log_request_start():
  90. logger.info('** Start {} {} **'.format(request.method, request.url))
  91. @ldp.before_request
  92. def instantiate_req_vars():
  93. g.tbox = RequestUtils()
  94. @ldp.after_request
  95. def log_request_end(rsp):
  96. logger.info('** End {} {} **'.format(request.method, request.url))
  97. return rsp
  98. ## REST SERVICES ##
  99. @ldp.route('/<path:uid>', methods=['GET'], strict_slashes=False)
  100. @ldp.route('/', defaults={'uid': '/'}, methods=['GET'], strict_slashes=False)
  101. @ldp.route('/<path:uid>/fcr:metadata', defaults={'out_fmt' : 'rdf'},
  102. methods=['GET'])
  103. @ldp.route('/<path:uid>/fcr:content', defaults={'out_fmt' : 'non_rdf'},
  104. methods=['GET'])
  105. def get_resource(uid, out_fmt=None):
  106. r"""
  107. https://www.w3.org/TR/ldp/#ldpr-HTTP_GET
  108. Retrieve RDF or binary content.
  109. :param str uid: UID of resource to retrieve. The repository root has
  110. an empty string for UID.
  111. :param str out_fmt: Force output to RDF or non-RDF if the resource is
  112. a LDP-NR. This is not available in the API but is used e.g. by the
  113. ``\*/fcr:metadata`` and ``\*/fcr:content`` endpoints. The default is
  114. False.
  115. """
  116. out_headers = std_headers.copy()
  117. repr_options = defaultdict(dict)
  118. # Fist check if it's not a 404 or a 410.
  119. try:
  120. if not rsrc_api.exists(uid):
  121. return '', 404
  122. except TombstoneError as e:
  123. return _tombstone_response(e, uid)
  124. # Then process the condition headers.
  125. cond_ret = _process_cond_headers(uid, request.headers)
  126. if cond_ret:
  127. return cond_ret
  128. # Then, business as usual.
  129. # Evaluate which representation is requested.
  130. if 'prefer' in request.headers:
  131. prefer = toolbox.parse_rfc7240(request.headers['prefer'])
  132. logger.debug('Parsed Prefer header: {}'.format(pformat(prefer)))
  133. if 'return' in prefer:
  134. repr_options = parse_repr_options(prefer['return'])
  135. rsrc = rsrc_api.get(uid, repr_options)
  136. with store.txn_ctx():
  137. if out_fmt is None:
  138. rdf_mimetype = _best_rdf_mimetype()
  139. out_fmt = (
  140. 'rdf'
  141. if isinstance(rsrc, LdpRs) or rdf_mimetype is not None
  142. else 'non_rdf')
  143. out_headers.update(_headers_from_metadata(rsrc, out_fmt))
  144. uri = g.tbox.uid_to_uri(uid)
  145. # RDF output.
  146. if out_fmt == 'rdf':
  147. if locals().get('rdf_mimetype', None) is None:
  148. rdf_mimetype = DEFAULT_RDF_MIMETYPE
  149. ggr = g.tbox.globalize_imr(rsrc.out_graph)
  150. ggr.namespace_manager = nsm
  151. return _negotiate_content(
  152. ggr, rdf_mimetype, out_headers, uid=uid, uri=uri)
  153. # Datastream.
  154. else:
  155. if not getattr(rsrc, 'local_path', False):
  156. return ('{} has no binary content.'.format(rsrc.uid), 404)
  157. logger.debug('Streaming out binary content.')
  158. if request.range and request.range.units == 'bytes':
  159. # Stream partial response.
  160. # This is only true if the header is well-formed. Thanks, Werkzeug.
  161. rsp = _parse_range_header(
  162. request.range.ranges, rsrc, out_headers
  163. )
  164. else:
  165. rsp = make_response(send_file(
  166. rsrc.local_path, as_attachment=True,
  167. attachment_filename=rsrc.filename,
  168. mimetype=rsrc.mimetype), 200, out_headers)
  169. # This seems necessary to prevent Flask from setting an
  170. # additional ETag.
  171. if 'ETag' in out_headers:
  172. rsp.set_etag(out_headers['ETag'])
  173. rsp.headers.add('Link', f'<{uri}/fcr:metadata>; rel="describedby"')
  174. return rsp
  175. @ldp.route('/<path:uid>/fcr:versions', methods=['GET'])
  176. def get_version_info(uid):
  177. """
  178. Get version info (`fcr:versions`).
  179. :param str uid: UID of resource to retrieve versions for.
  180. """
  181. rdf_mimetype = _best_rdf_mimetype() or DEFAULT_RDF_MIMETYPE
  182. try:
  183. imr = rsrc_api.get_version_info(uid)
  184. except ResourceNotExistsError as e:
  185. return str(e), 404
  186. except InvalidResourceError as e:
  187. return str(e), 409
  188. except TombstoneError as e:
  189. return _tombstone_response(e, uid)
  190. else:
  191. with store.txn_ctx():
  192. return _negotiate_content(g.tbox.globalize_imr(imr), rdf_mimetype)
  193. @ldp.route('/<path:uid>/fcr:versions/<ver_uid>', methods=['GET'])
  194. def get_version(uid, ver_uid):
  195. """
  196. Get an individual resource version.
  197. :param str uid: Resource UID.
  198. :param str ver_uid: Version UID.
  199. """
  200. rdf_mimetype = _best_rdf_mimetype() or DEFAULT_RDF_MIMETYPE
  201. try:
  202. imr = rsrc_api.get_version(uid, ver_uid)
  203. except ResourceNotExistsError as e:
  204. return str(e), 404
  205. except InvalidResourceError as e:
  206. return str(e), 409
  207. except TombstoneError as e:
  208. return _tombstone_response(e, uid)
  209. else:
  210. with store.txn_ctx():
  211. return _negotiate_content(g.tbox.globalize_imr(imr), rdf_mimetype)
  212. @ldp.route('/<path:parent_uid>', methods=['POST'], strict_slashes=False)
  213. @ldp.route('/', defaults={'parent_uid': '/'}, methods=['POST'],
  214. strict_slashes=False)
  215. def post_resource(parent_uid):
  216. """
  217. https://www.w3.org/TR/ldp/#ldpr-HTTP_POST
  218. Add a new resource in a new URI.
  219. """
  220. rsp_headers = std_headers.copy()
  221. slug = request.headers.get('Slug')
  222. kwargs = {}
  223. kwargs['handling'], kwargs['disposition'] = set_post_put_params()
  224. stream, mimetype = _bistream_from_req()
  225. if mimetype in rdf_parsable_mimetypes:
  226. # If the content is RDF, localize in-repo URIs.
  227. global_rdf = stream.read()
  228. kwargs['rdf_data'] = g.tbox.localize_payload(global_rdf)
  229. kwargs['rdf_fmt'] = mimetype
  230. else:
  231. kwargs['stream'] = stream
  232. kwargs['mimetype'] = mimetype
  233. # Check digest if requested.
  234. if 'digest' in request.headers:
  235. kwargs['prov_cksum_algo'], kwargs['prov_cksum'] = \
  236. request.headers['digest'].split('=')
  237. try:
  238. rsrc = rsrc_api.create(parent_uid, slug, **kwargs)
  239. except ResourceNotExistsError as e:
  240. return str(e), 404
  241. except (InvalidResourceError, ChecksumValidationError) as e:
  242. return str(e), 409
  243. except TombstoneError as e:
  244. return _tombstone_response(e, uid)
  245. except ServerManagedTermError as e:
  246. return str(e), 412
  247. uri = g.tbox.uid_to_uri(rsrc.uid)
  248. with store.txn_ctx():
  249. rsp_headers.update(_headers_from_metadata(rsrc))
  250. rsp_headers['Location'] = uri
  251. if mimetype and kwargs.get('rdf_fmt') is None:
  252. rsp_headers['Link'] = (f'<{uri}/fcr:metadata>; rel="describedby"; '
  253. f'anchor="{uri}"')
  254. return uri, 201, rsp_headers
  255. @ldp.route('/<path:uid>', methods=['PUT'], strict_slashes=False)
  256. @ldp.route('/<path:uid>/fcr:metadata', defaults={'force_rdf' : True},
  257. methods=['PUT'])
  258. def put_resource(uid):
  259. """
  260. https://www.w3.org/TR/ldp/#ldpr-HTTP_PUT
  261. Add or replace a new resource at a specified URI.
  262. """
  263. # Parse headers.
  264. logger.debug('Request headers: {}'.format(request.headers))
  265. cond_ret = _process_cond_headers(uid, request.headers, False)
  266. if cond_ret:
  267. return cond_ret
  268. kwargs = {}
  269. kwargs['handling'], kwargs['disposition'] = set_post_put_params()
  270. stream, mimetype = _bistream_from_req()
  271. if mimetype in rdf_parsable_mimetypes:
  272. # If the content is RDF, localize in-repo URIs.
  273. global_rdf = stream.read()
  274. kwargs['rdf_data'] = g.tbox.localize_payload(global_rdf)
  275. kwargs['rdf_fmt'] = mimetype
  276. else:
  277. kwargs['stream'] = stream
  278. kwargs['mimetype'] = mimetype
  279. # Check digest if requested.
  280. if 'digest' in request.headers:
  281. kwargs['prov_cksum_algo'], kwargs['prov_cksum'] = \
  282. request.headers['digest'].split('=')
  283. try:
  284. evt, rsrc = rsrc_api.create_or_replace(uid, **kwargs)
  285. except (
  286. InvalidResourceError, ChecksumValidationError,
  287. ResourceExistsError) as e:
  288. return str(e), 409
  289. except (ServerManagedTermError, SingleSubjectError) as e:
  290. return str(e), 412
  291. except IncompatibleLdpTypeError as e:
  292. return str(e), 415
  293. except TombstoneError as e:
  294. return _tombstone_response(e, uid)
  295. with store.txn_ctx():
  296. rsp_headers = _headers_from_metadata(rsrc)
  297. rsp_headers['Content-Type'] = 'text/plain; charset=utf-8'
  298. uri = g.tbox.uid_to_uri(uid)
  299. if evt == RES_CREATED:
  300. rsp_code = 201
  301. rsp_headers['Location'] = rsp_body = uri
  302. if mimetype and not kwargs.get('rdf_data'):
  303. rsp_headers['Link'] = f'<{uri}/fcr:metadata>; rel="describedby"'
  304. else:
  305. rsp_code = 204
  306. rsp_body = ''
  307. return rsp_body, rsp_code, rsp_headers
  308. @ldp.route('/<path:uid>', methods=['PATCH'], strict_slashes=False)
  309. @ldp.route('/', defaults={'uid': '/'}, methods=['PATCH'],
  310. strict_slashes=False)
  311. def patch_resource(uid, is_metadata=False):
  312. """
  313. https://www.w3.org/TR/ldp/#ldpr-HTTP_PATCH
  314. Update an existing resource with a SPARQL-UPDATE payload.
  315. """
  316. # Fist check if it's not a 404 or a 410.
  317. try:
  318. if not rsrc_api.exists(uid):
  319. return '', 404
  320. except TombstoneError as e:
  321. return _tombstone_response(e, uid)
  322. # Then process the condition headers.
  323. cond_ret = _process_cond_headers(uid, request.headers, False)
  324. if cond_ret:
  325. return cond_ret
  326. rsp_headers = {'Content-Type' : 'text/plain; charset=utf-8'}
  327. if request.mimetype != 'application/sparql-update':
  328. return 'Provided content type is not a valid parsable format: {}'\
  329. .format(request.mimetype), 415
  330. update_str = request.get_data().decode('utf-8')
  331. local_update_str = g.tbox.localize_ext_str(update_str, nsc['fcres'][uid])
  332. try:
  333. rsrc = rsrc_api.update(uid, local_update_str, is_metadata)
  334. except (ServerManagedTermError, SingleSubjectError) as e:
  335. return str(e), 412
  336. except InvalidResourceError as e:
  337. return str(e), 415
  338. else:
  339. with store.txn_ctx():
  340. rsp_headers.update(_headers_from_metadata(rsrc))
  341. return '', 204, rsp_headers
  342. @ldp.route('/<path:uid>/fcr:metadata', methods=['PATCH'])
  343. def patch_resource_metadata(uid):
  344. return patch_resource(uid, True)
  345. @ldp.route('/<path:uid>', methods=['DELETE'])
  346. def delete_resource(uid):
  347. """
  348. Delete a resource and optionally leave a tombstone.
  349. This behaves differently from FCREPO. A tombstone indicated that the
  350. resource is no longer available at its current location, but its historic
  351. snapshots still are. Also, deleting a resource with a tombstone creates
  352. one more version snapshot of the resource prior to being deleted.
  353. In order to completely wipe out all traces of a resource, the tombstone
  354. must be deleted as well, or the ``Prefer:no-tombstone`` header can be used.
  355. The latter will forget (completely delete) the resource immediately.
  356. """
  357. # Fist check if it's not a 404 or a 410.
  358. try:
  359. if not rsrc_api.exists(uid):
  360. return '', 404
  361. except TombstoneError as e:
  362. return _tombstone_response(e, uid)
  363. # Then process the condition headers.
  364. cond_ret = _process_cond_headers(uid, request.headers, False)
  365. if cond_ret:
  366. return cond_ret
  367. headers = std_headers.copy()
  368. if 'prefer' in request.headers:
  369. prefer = toolbox.parse_rfc7240(request.headers['prefer'])
  370. leave_tstone = 'no-tombstone' not in prefer
  371. else:
  372. leave_tstone = True
  373. rsrc_api.delete(uid, leave_tstone)
  374. return '', 204, headers
  375. @ldp.route('/<path:uid>/fcr:tombstone', methods=['GET', 'POST', 'PUT',
  376. 'PATCH', 'DELETE'])
  377. def tombstone(uid):
  378. """
  379. Handle all tombstone operations.
  380. The only allowed methods are POST and DELETE; any other verb will return a
  381. 405.
  382. """
  383. try:
  384. rsrc_api.get(uid)
  385. except TombstoneError as e:
  386. if request.method == 'DELETE':
  387. if e.uid == uid:
  388. rsrc_api.delete(uid, False)
  389. return '', 204
  390. else:
  391. return _tombstone_response(e, uid)
  392. elif request.method == 'POST':
  393. if e.uid == uid:
  394. rsrc_uri = rsrc_api.resurrect(uid)
  395. headers = {'Location' : rsrc_uri}
  396. return rsrc_uri, 201, headers
  397. else:
  398. return _tombstone_response(e, uid)
  399. else:
  400. return 'Method Not Allowed.', 405
  401. except ResourceNotExistsError as e:
  402. return str(e), 404
  403. else:
  404. return '', 404
  405. @ldp.route('/<path:uid>/fcr:versions', methods=['POST', 'PUT'])
  406. def post_version(uid):
  407. """
  408. Create a new resource version.
  409. """
  410. if request.method == 'PUT':
  411. return 'Method not allowed.', 405
  412. ver_uid = request.headers.get('slug', None)
  413. try:
  414. ver_uid = rsrc_api.create_version(uid, ver_uid)
  415. except ResourceNotExistsError as e:
  416. return str(e), 404
  417. except InvalidResourceError as e:
  418. return str(e), 409
  419. except TombstoneError as e:
  420. return _tombstone_response(e, uid)
  421. else:
  422. return '', 201, {'Location': g.tbox.uid_to_uri(ver_uid)}
  423. @ldp.route('/<path:uid>/fcr:versions/<ver_uid>', methods=['PATCH'])
  424. def patch_version(uid, ver_uid):
  425. """
  426. Revert to a previous version.
  427. NOTE: This creates a new version snapshot.
  428. :param str uid: Resource UID.
  429. :param str ver_uid: Version UID.
  430. """
  431. try:
  432. rsrc_api.revert_to_version(uid, ver_uid)
  433. except ResourceNotExistsError as e:
  434. return str(e), 404
  435. except InvalidResourceError as e:
  436. return str(e), 409
  437. except TombstoneError as e:
  438. return _tombstone_response(e, uid)
  439. else:
  440. return '', 204
  441. ## PRIVATE METHODS ##
  442. def _best_rdf_mimetype():
  443. """
  444. Check if any of the 'Accept' header values provided is a RDF parsable
  445. format.
  446. """
  447. for accept in request.accept_mimetypes:
  448. mimetype = accept[0]
  449. if mimetype in rdf_parsable_mimetypes:
  450. return mimetype
  451. return None
  452. def _negotiate_content(gr, rdf_mimetype, headers=None, **vw_kwargs):
  453. """
  454. Return HTML or serialized RDF depending on accept headers.
  455. """
  456. if request.accept_mimetypes.best == 'text/html':
  457. return render_template(
  458. 'resource.html', gr=gr, nsc=nsc, nsm=nsm,
  459. blacklist=vw_blacklist, arrow=arrow, **vw_kwargs)
  460. else:
  461. for p in vw_blacklist:
  462. gr.remove((None, p, None))
  463. return Response(
  464. gr.serialize(format=rdf_mimetype), 200, headers,
  465. mimetype=rdf_mimetype)
  466. def _bistream_from_req():
  467. """
  468. Find how a binary file and its MIMEtype were uploaded in the request.
  469. """
  470. #logger.debug('Content type: {}'.format(request.mimetype))
  471. #logger.debug('files: {}'.format(request.files))
  472. #logger.debug('stream: {}'.format(request.stream))
  473. if request.mimetype == 'multipart/form-data':
  474. # This seems the "right" way to upload a binary file, with a
  475. # multipart/form-data MIME type and the file in the `file`
  476. # field. This however is not supported by FCREPO4.
  477. stream = request.files.get('file').stream
  478. mimetype = request.files.get('file').content_type
  479. # @TODO This will turn out useful to provide metadata
  480. # with the binary.
  481. #metadata = request.files.get('metadata').stream
  482. else:
  483. # This is a less clean way, with the file in the form body and
  484. # the request as application/x-www-form-urlencoded.
  485. # This is how FCREPO4 accepts binary uploads.
  486. stream = request.stream
  487. # @FIXME Must decide what to do with this.
  488. mimetype = request.mimetype
  489. if mimetype == '' or mimetype == 'application/x-www-form-urlencoded':
  490. if getattr(stream, 'limit', 0) == 0:
  491. stream = mimetype = None
  492. else:
  493. mimetype = 'application/octet-stream'
  494. return stream, mimetype
  495. def _tombstone_response(e, uid):
  496. headers = {
  497. 'Link': '<{}/fcr:tombstone>; rel="hasTombstone"'.format(request.url),
  498. } if e.uid == uid else {}
  499. return str(e), 410, headers
  500. def set_post_put_params():
  501. """
  502. Sets handling and content disposition for POST and PUT by parsing headers.
  503. """
  504. handling = 'strict'
  505. if 'prefer' in request.headers:
  506. prefer = toolbox.parse_rfc7240(request.headers['prefer'])
  507. logger.debug('Parsed Prefer header: {}'.format(prefer))
  508. if 'handling' in prefer:
  509. handling = prefer['handling']['value']
  510. try:
  511. disposition = toolbox.parse_rfc7240(
  512. request.headers['content-disposition'])
  513. except KeyError:
  514. disposition = None
  515. return handling, disposition
  516. def parse_repr_options(retr_opts):
  517. """
  518. Set options to retrieve IMR.
  519. Ideally, IMR retrieval is done once per request, so all the options
  520. are set once in the `imr()` property.
  521. :param dict retr_opts:: Options parsed from `Prefer` header.
  522. """
  523. logger.debug('Parsing retrieval options: {}'.format(retr_opts))
  524. imr_options = {}
  525. if retr_opts.get('value') == 'minimal':
  526. imr_options = {
  527. 'embed_children' : False,
  528. 'incl_children' : False,
  529. 'incl_inbound' : False,
  530. 'incl_srv_mgd' : False,
  531. }
  532. else:
  533. # Default.
  534. imr_options = {
  535. 'embed_children' : False,
  536. 'incl_children' : True,
  537. 'incl_inbound' : False,
  538. 'incl_srv_mgd' : True,
  539. }
  540. # Override defaults.
  541. if 'parameters' in retr_opts:
  542. include = retr_opts['parameters']['include'].split(' ') \
  543. if 'include' in retr_opts['parameters'] else []
  544. omit = retr_opts['parameters']['omit'].split(' ') \
  545. if 'omit' in retr_opts['parameters'] else []
  546. logger.debug('Include: {}'.format(include))
  547. logger.debug('Omit: {}'.format(omit))
  548. if str(Ldpr.EMBED_CHILD_RES_URI) in include:
  549. imr_options['embed_children'] = True
  550. if str(Ldpr.RETURN_CHILD_RES_URI) in omit:
  551. imr_options['incl_children'] = False
  552. if str(Ldpr.RETURN_INBOUND_REF_URI) in include:
  553. imr_options['incl_inbound'] = True
  554. if str(Ldpr.RETURN_SRV_MGD_RES_URI) in omit:
  555. imr_options['incl_srv_mgd'] = False
  556. logger.debug('Retrieval options: {}'.format(pformat(imr_options)))
  557. return imr_options
  558. def _headers_from_metadata(rsrc, out_fmt='text/turtle'):
  559. """
  560. Create a dict of headers from a metadata graph.
  561. :param lakesuperior.model.ldp.ldpr.Ldpr rsrc: Resource to extract metadata
  562. from.
  563. """
  564. rsp_headers = defaultdict(list)
  565. digest_p = rsrc.metadata.value(nsc['premis'].hasMessageDigest)
  566. # Only add ETag and digest if output is not RDF.
  567. if digest_p:
  568. rsp_headers['ETag'], rsp_headers['Digest'] = (
  569. _digest_headers(digest_p))
  570. last_updated_term = rsrc.metadata.value(nsc['fcrepo'].lastModified)
  571. if last_updated_term:
  572. rsp_headers['Last-Modified'] = arrow.get(last_updated_term)\
  573. .format('ddd, D MMM YYYY HH:mm:ss Z')
  574. for t in rsrc.ldp_types:
  575. rsp_headers['Link'].append('{};rel="type"'.format(t.n3()))
  576. if rsrc.mimetype:
  577. rsp_headers['Content-Type'] = rsrc.mimetype
  578. return rsp_headers
  579. def _digest_headers(digest):
  580. """
  581. Format ETag and Digest headers from resource checksum.
  582. :param str digest: Resource digest. For an extracted IMR, this is the
  583. value of the ``premis:hasMessageDigest`` property.
  584. """
  585. digest_components = digest.split(':')
  586. cksum_hex = digest_components[-1]
  587. cksum = bytearray.fromhex(cksum_hex)
  588. digest_algo = digest_components[-2]
  589. etag_str = cksum_hex
  590. digest_str = '{}={}'.format(
  591. digest_algo.upper(), b64encode(cksum).decode('ascii'))
  592. return etag_str, digest_str
  593. def _condition_hdr_match(uid, headers, safe=True):
  594. """
  595. Conditional header evaluation for HEAD, GET, PUT and DELETE requests.
  596. Determine whether any conditional headers, and which, is/are imposed in the
  597. request (``If-Match``, ``If-None-Match``, ``If-Modified-Since``,
  598. ``If-Unmodified-Since``, or none) and what the most relevant condition
  599. evaluates to (``True`` or ``False``).
  600. `RFC 7232 <https://tools.ietf.org/html/rfc7232#section-3.1>`__ does not
  601. indicate an exact condition precedence, except that the ETag
  602. matching conditions void the timestamp-based ones. This function
  603. adopts the following precedence:
  604. - ``If-Match`` is evaluated first if present;
  605. - Else, ``If-None-Match`` is evaluated if present;
  606. - Else, ``If-Modified-Since`` and ``If-Unmodified-Since``
  607. are evaluated if present. If both conditions are present they are
  608. both returned so they can be furher evaluated, e.g. using a logical AND
  609. to allow time-range conditions, where the two terms indicate the early
  610. and late boundary, respectively.
  611. Note that the above mentioned RFC mentions several cases in which these
  612. conditions are ignored, e.g. for a 404 in some cases, or for certain
  613. HTTP methods for ``If-Modified-Since``. This must be implemented by the
  614. calling function.
  615. :param str uid: UID of the resource requested.
  616. :param werkzeug.datastructures.EnvironHeaders headers: Incoming request
  617. headers.
  618. :param bool safe: Whether a "safe" method is being processed. Defaults to
  619. True.
  620. :rtype: dict (str, bool)
  621. :return: Dictionary whose keys are the conditional header names that
  622. have been evaluated, and whose boolean values indicate whether each
  623. condition is met. If no valid conditional header is found, an empty
  624. dict is returned.
  625. """
  626. # ETag-based conditions.
  627. # This ignores headers with empty values.
  628. if headers.get('if-match') or headers.get('if-none-match'):
  629. cond_hdr = 'if-match' if headers.get('if-match') else 'if-none-match'
  630. # Wildcard matching for unsafe methods. Cannot be part of a list of
  631. # ETags nor be enclosed in quotes.
  632. if not safe and headers.get(cond_hdr) == '*':
  633. return {cond_hdr: (cond_hdr == 'if-match') == rsrc_api.exists(uid)}
  634. req_etags = [
  635. et.strip('\'" ') for et in headers.get(cond_hdr).split(',')]
  636. with store.txn_ctx():
  637. try:
  638. rsrc_meta = rsrc_api.get_metadata(uid)
  639. except ResourceNotExistsError:
  640. rsrc_meta = Graph(uri=nsc['fcres'][uid])
  641. digest_prop = rsrc_meta.value(nsc['premis'].hasMessageDigest)
  642. if digest_prop:
  643. etag, _ = _digest_headers(digest_prop)
  644. if cond_hdr == 'if-match':
  645. is_match = etag in req_etags
  646. else:
  647. is_match = etag not in req_etags
  648. else:
  649. is_match = cond_hdr == 'if-none-match'
  650. return {cond_hdr: is_match}
  651. # Timestmp-based conditions.
  652. ret = {}
  653. if headers.get('if-modified-since') or headers.get('if-unmodified-since'):
  654. try:
  655. rsrc_meta = rsrc_api.get_metadata(uid)
  656. except ResourceNotExistsError:
  657. return {
  658. 'if-modified-since': False,
  659. 'if-unmodified-since': False
  660. }
  661. with store.txn_ctx():
  662. lastmod_str = rsrc_meta.value(nsc['fcrepo'].lastModified)
  663. lastmod_ts = arrow.get(lastmod_str)
  664. # If date is not in a RFC 5322 format
  665. # (https://tools.ietf.org/html/rfc5322#section-3.3) parse_date
  666. # evaluates to None.
  667. mod_since_date = parse_date(headers.get('if-modified-since'))
  668. if mod_since_date:
  669. cond_hdr = 'if-modified-since'
  670. ret[cond_hdr] = lastmod_ts > arrow.get(mod_since_date)
  671. unmod_since_date = parse_date(headers.get('if-unmodified-since'))
  672. if unmod_since_date:
  673. cond_hdr = 'if-unmodified-since'
  674. ret[cond_hdr] = lastmod_ts < arrow.get(unmod_since_date)
  675. return ret
  676. def _process_cond_headers(uid, headers, safe=True):
  677. """
  678. Process the outcome of the evaluation of conditional headers.
  679. This yields different response between safe methods (``HEAD``, ``GET``,
  680. etc.) and unsafe ones (``PUT``, ``DELETE``, etc.
  681. :param str uid: Resource UID.
  682. :param werkzeug.datastructures.EnvironHeaders headers: Incoming request
  683. headers.
  684. :param bool safe: Whether a "safe" method is being processed. Defaults to
  685. True.
  686. """
  687. try:
  688. cond_match = _condition_hdr_match(uid, headers, safe)
  689. except TombstoneError as e:
  690. return _tombstone_response(e, uid)
  691. if cond_match:
  692. if safe:
  693. if 'if-match' in cond_match or 'if-none-match' in cond_match:
  694. # If an expected list of tags is not matched, the response is
  695. # "Precondition Failed". For all other cases, it's "Not Modified".
  696. if not cond_match.get('if-match', True):
  697. return '', 412
  698. if not cond_match.get('if-none-match', True):
  699. return '', 304
  700. # The presence of an Etag-based condition, whether satisfied or not,
  701. # voids the timestamp-based conditions.
  702. elif (
  703. not cond_match.get('if-modified-since', True) or
  704. not cond_match.get('if-unmodified-since', True)):
  705. return '', 304
  706. else:
  707. # Note that If-Modified-Since is only evaluated for safe methods.
  708. if 'if-match' in cond_match or 'if-none-match' in cond_match:
  709. if (
  710. not cond_match.get('if-match', True) or
  711. not cond_match.get('if-none-match', True)):
  712. return '', 412
  713. # The presence of an Etag-based condition, whether satisfied or not,
  714. # voids the timestamp-based conditions.
  715. elif not cond_match.get('if-unmodified-since', True):
  716. return '', 412
  717. def _parse_range_header(ranges, rsrc, headers):
  718. """
  719. Parse a ``Range`` header and return the appropriate response.
  720. """
  721. if len(ranges) == 1:
  722. # Single range.
  723. rng = ranges[0]
  724. logger.debug('Streaming contiguous partial content.')
  725. with open(rsrc.local_path, 'rb') as fh:
  726. size = None if rng[1] is None else rng[1] - rng[0]
  727. hdr_endbyte = (
  728. rsrc.content_size - 1 if rng[1] is None else rng[1] - 1)
  729. fh.seek(rng[0])
  730. out = fh.read(size)
  731. headers['Content-Range'] = \
  732. f'bytes {rng[0]}-{hdr_endbyte} / {rsrc.content_size}'
  733. else:
  734. return make_response('Multiple ranges are not yet supported.', 501)
  735. # TODO Format the response as multipart/byteranges:
  736. # https://tools.ietf.org/html/rfc7233#section-4.1
  737. #out = []
  738. #with open(rsrc.local_path, 'rb') as fh:
  739. # for rng in rng_header.ranges:
  740. # fh.seek(rng[0])
  741. # size = None if rng[1] is None else rng[1] - rng[0]
  742. # out.extend(fh.read(size))
  743. return make_response(out, 206, headers)