Debian Codegraph @

hgext/lfs/wireprotolfsserver.py

raw
1 # wireprotolfsserver.py - lfs protocol server side implementation
2 #
3 # Copyright 2018 Matt Harbison <[email protected]>
4 #
5 # This software may be used and distributed according to the terms of the
6 # GNU General Public License version 2 or any later version.
7
8 from __future__ import annotations
9
10 import datetime
11 import errno
12 import json
13 import traceback
14
15 from mercurial.hgweb import common as hgwebcommon
16
17 from mercurial import (
18 exthelper,
19 pycompat,
20 wireprotoserver,
21 )
22
23 from . import blobstore
24
25 HTTP_OK = hgwebcommon.HTTP_OK
26 HTTP_CREATED = hgwebcommon.HTTP_CREATED
27 HTTP_BAD_REQUEST = hgwebcommon.HTTP_BAD_REQUEST
28 HTTP_NOT_FOUND = hgwebcommon.HTTP_NOT_FOUND
29 HTTP_METHOD_NOT_ALLOWED = hgwebcommon.HTTP_METHOD_NOT_ALLOWED
30 HTTP_NOT_ACCEPTABLE = hgwebcommon.HTTP_NOT_ACCEPTABLE
31 HTTP_UNSUPPORTED_MEDIA_TYPE = hgwebcommon.HTTP_UNSUPPORTED_MEDIA_TYPE
32
33 eh = exthelper.exthelper()
34
35
36 @eh.wrapfunction(wireprotoserver, 'handlewsgirequest')
37 def handlewsgirequest(orig, rctx, req, res, checkperm):
38 """Wrap wireprotoserver.handlewsgirequest() to possibly process an LFS
39 request if it is left unprocessed by the wrapped method.
40 """
41 if orig(rctx, req, res, checkperm):
42 return True
43
44 if not rctx.repo.ui.configbool(b'experimental', b'lfs.serve'):
45 return False
46
47 if not hasattr(rctx.repo.svfs, 'lfslocalblobstore'):
48 return False
49
50 if not req.dispatchpath:
51 return False
52
53 try:
54 if req.dispatchpath == b'.git/info/lfs/objects/batch':
55 checkperm(rctx, req, b'pull')
56 return _processbatchrequest(rctx.repo, req, res)
57 # TODO: reserve and use a path in the proposed http wireprotocol /api/
58 # namespace?
59 elif req.dispatchpath.startswith(b'.hg/lfs/objects'):
60 return _processbasictransfer(
61 rctx.repo, req, res, lambda perm: checkperm(rctx, req, perm)
62 )
63 return False
64 except hgwebcommon.ErrorResponse as e:
65 # XXX: copied from the handler surrounding wireprotoserver._callhttp()
66 # in the wrapped function. Should this be moved back to hgweb to
67 # be a common handler?
68 for k, v in e.headers:
69 res.headers[k] = v
70 res.status = hgwebcommon.statusmessage(e.code, pycompat.bytestr(e))
71 res.setbodybytes(b'0\n%s\n' % pycompat.bytestr(e))
72 return True
73
74
75 def _sethttperror(res, code, message=None):
76 res.status = hgwebcommon.statusmessage(code, message=message)
77 res.headers[b'Content-Type'] = b'text/plain; charset=utf-8'
78 res.setbodybytes(b'')
79
80
81 def _logexception(req):
82 """Write information about the current exception to wsgi.errors."""
83 tb = pycompat.sysbytes(traceback.format_exc())
84 errorlog = req.rawenv[b'wsgi.errors']
85
86 uri = b''
87 if req.apppath:
88 uri += req.apppath
89 uri += b'/' + req.dispatchpath
90
91 errorlog.write(
92 b"Exception happened while processing request '%s':\n%s" % (uri, tb)
93 )
94
95
96 def _processbatchrequest(repo, req, res):
97 """Handle a request for the Batch API, which is the gateway to granting file
98 access.
99
100 https://github.com/git-lfs/git-lfs/blob/master/docs/api/batch.md
101 """
102
103 # Mercurial client request:
104 #
105 # HOST: localhost:$HGPORT
106 # ACCEPT: application/vnd.git-lfs+json
107 # ACCEPT-ENCODING: identity
108 # USER-AGENT: git-lfs/2.3.4 (Mercurial 4.5.2+1114-f48b9754f04c+20180316)
109 # Content-Length: 125
110 # Content-Type: application/vnd.git-lfs+json
111 #
112 # {
113 # "objects": [
114 # {
115 # "oid": "31cf...8e5b"
116 # "size": 12
117 # }
118 # ]
119 # "operation": "upload"
120 # }
121
122 if req.method != b'POST':
123 _sethttperror(res, HTTP_METHOD_NOT_ALLOWED)
124 return True
125
126 if req.headers[b'Content-Type'] != b'application/vnd.git-lfs+json':
127 _sethttperror(res, HTTP_UNSUPPORTED_MEDIA_TYPE)
128 return True
129
130 if req.headers[b'Accept'] != b'application/vnd.git-lfs+json':
131 _sethttperror(res, HTTP_NOT_ACCEPTABLE)
132 return True
133
134 # XXX: specify an encoding?
135 lfsreq = pycompat.json_loads(req.bodyfh.read())
136
137 # If no transfer handlers are explicitly requested, 'basic' is assumed.
138 if 'basic' not in lfsreq.get('transfers', ['basic']):
139 _sethttperror(
140 res,
141 HTTP_BAD_REQUEST,
142 b'Only the basic LFS transfer handler is supported',
143 )
144 return True
145
146 operation = lfsreq.get('operation')
147 operation = pycompat.bytestr(operation)
148
149 if operation not in (b'upload', b'download'):
150 _sethttperror(
151 res,
152 HTTP_BAD_REQUEST,
153 b'Unsupported LFS transfer operation: %s' % operation,
154 )
155 return True
156
157 localstore = repo.svfs.lfslocalblobstore
158
159 objects = [
160 p
161 for p in _batchresponseobjects(
162 req, lfsreq.get('objects', []), operation, localstore
163 )
164 ]
165
166 rsp = {
167 'transfer': 'basic',
168 'objects': objects,
169 }
170
171 res.status = hgwebcommon.statusmessage(HTTP_OK)
172 res.headers[b'Content-Type'] = b'application/vnd.git-lfs+json'
173 res.setbodybytes(pycompat.bytestr(json.dumps(rsp)))
174
175 return True
176
177
178 def _batchresponseobjects(req, objects, action, store):
179 """Yield one dictionary of attributes for the Batch API response for each
180 object in the list.
181
182 req: The parsedrequest for the Batch API request
183 objects: The list of objects in the Batch API object request list
184 action: 'upload' or 'download'
185 store: The local blob store for servicing requests"""
186
187 # Successful lfs-test-server response to solict an upload:
188 # {
189 # u'objects': [{
190 # u'size': 12,
191 # u'oid': u'31cf...8e5b',
192 # u'actions': {
193 # u'upload': {
194 # u'href': u'http://localhost:$HGPORT/objects/31cf...8e5b',
195 # u'expires_at': u'0001-01-01T00:00:00Z',
196 # u'header': {
197 # u'Accept': u'application/vnd.git-lfs'
198 # }
199 # }
200 # }
201 # }]
202 # }
203
204 # TODO: Sort out the expires_at/expires_in/authenticated keys.
205
206 for obj in objects:
207 # Convert unicode to ASCII to create a filesystem path
208 soid = obj.get('oid')
209 oid = soid.encode('ascii')
210 rsp = {
211 'oid': soid,
212 'size': obj.get('size'), # XXX: should this check the local size?
213 # 'authenticated': True,
214 }
215
216 exists = True
217 verifies = False
218
219 # Verify an existing file on the upload request, so that the client is
220 # solicited to re-upload if it corrupt locally. Download requests are
221 # also verified, so the error can be flagged in the Batch API response.
222 # (Maybe we can use this to short circuit the download for `hg verify`,
223 # IFF the client can assert that the remote end is an hg server.)
224 # Otherwise, it's potentially overkill on download, since it is also
225 # verified as the file is streamed to the caller.
226 try:
227 verifies = store.verify(oid)
228 if verifies and action == b'upload':
229 # The client will skip this upload, but make sure it remains
230 # available locally.
231 store.linkfromusercache(oid)
232 except OSError as inst:
233 if inst.errno != errno.ENOENT:
234 _logexception(req)
235
236 rsp['error'] = {
237 'code': 500,
238 'message': inst.strerror or 'Internal Server Server',
239 }
240 yield rsp
241 continue
242
243 exists = False
244
245 # Items are always listed for downloads. They are dropped for uploads
246 # IFF they already exist locally.
247 if action == b'download':
248 if not exists:
249 rsp['error'] = {
250 'code': 404,
251 'message': "The object does not exist",
252 }
253 yield rsp
254 continue
255
256 elif not verifies:
257 rsp['error'] = {
258 'code': 422, # XXX: is this the right code?
259 'message': "The object is corrupt",
260 }
261 yield rsp
262 continue
263
264 elif verifies:
265 yield rsp # Skip 'actions': already uploaded
266 continue
267
268 expiresat = datetime.datetime.now() + datetime.timedelta(minutes=10)
269
270 def _buildheader():
271 # The spec doesn't mention the Accept header here, but avoid
272 # a gratuitous deviation from lfs-test-server in the test
273 # output.
274 hdr = {'Accept': 'application/vnd.git-lfs'}
275
276 auth = req.headers.get(b'Authorization', b'')
277 if auth.startswith(b'Basic '):
278 hdr['Authorization'] = pycompat.strurl(auth)
279
280 return hdr
281
282 rsp['actions'] = {
283 '%s'
284 % pycompat.strurl(action): {
285 'href': pycompat.strurl(
286 b'%s%s/.hg/lfs/objects/%s' % (req.baseurl, req.apppath, oid)
287 ),
288 # datetime.isoformat() doesn't include the 'Z' suffix
289 "expires_at": expiresat.strftime('%Y-%m-%dT%H:%M:%SZ'),
290 'header': _buildheader(),
291 }
292 }
293
294 yield rsp
295
296
297 def _processbasictransfer(repo, req, res, checkperm):
298 """Handle a single file upload (PUT) or download (GET) action for the Basic
299 Transfer Adapter.
300
301 After determining if the request is for an upload or download, the access
302 must be checked by calling ``checkperm()`` with either 'pull' or 'upload'
303 before accessing the files.
304
305 https://github.com/git-lfs/git-lfs/blob/master/docs/api/basic-transfers.md
306 """
307
308 method = req.method
309 oid = req.dispatchparts[-1]
310 localstore = repo.svfs.lfslocalblobstore
311
312 if len(req.dispatchparts) != 4:
313 _sethttperror(res, HTTP_NOT_FOUND)
314 return True
315
316 if method == b'PUT':
317 checkperm(b'upload')
318
319 # TODO: verify Content-Type?
320
321 existed = localstore.has(oid)
322
323 # TODO: how to handle timeouts? The body proxy handles limiting to
324 # Content-Length, but what happens if a client sends less than it
325 # says it will?
326
327 statusmessage = hgwebcommon.statusmessage
328 try:
329 localstore.download(oid, req.bodyfh, req.headers[b'Content-Length'])
330 res.status = statusmessage(HTTP_OK if existed else HTTP_CREATED)
331 except blobstore.LfsCorruptionError:
332 _logexception(req)
333
334 # XXX: Is this the right code?
335 res.status = statusmessage(422, b'corrupt blob')
336
337 # There's no payload here, but this is the header that lfs-test-server
338 # sends back. This eliminates some gratuitous test output conditionals.
339 res.headers[b'Content-Type'] = b'text/plain; charset=utf-8'
340 res.setbodybytes(b'')
341
342 return True
343 elif method == b'GET':
344 checkperm(b'pull')
345
346 res.status = hgwebcommon.statusmessage(HTTP_OK)
347 res.headers[b'Content-Type'] = b'application/octet-stream'
348
349 try:
350 # TODO: figure out how to send back the file in chunks, instead of
351 # reading the whole thing. (Also figure out how to send back
352 # an error status if an IOError occurs after a partial write
353 # in that case. Here, everything is read before starting.)
354 res.setbodybytes(localstore.read(oid))
355 except blobstore.LfsCorruptionError:
356 _logexception(req)
357
358 # XXX: Is this the right code?
359 res.status = hgwebcommon.statusmessage(422, b'corrupt blob')
360 res.setbodybytes(b'')
361
362 return True
363 else:
364 _sethttperror(
365 res,
366 HTTP_METHOD_NOT_ALLOWED,
367 message=b'Unsupported LFS transfer method: %s' % method,
368 )
369 return True