ldp.py 30 KB

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