##// END OF EJS Templates
hgweb: move call to protocol handler outside of try..except...
Gregory Szorc -
r36003:e69e65b2 default
parent child Browse files
Show More
@@ -1,493 +1,494 b''
1 # hgweb/hgweb_mod.py - Web interface for a repository.
1 # hgweb/hgweb_mod.py - Web interface for a repository.
2 #
2 #
3 # Copyright 21 May 2005 - (c) 2005 Jake Edge <jake@edge2.net>
3 # Copyright 21 May 2005 - (c) 2005 Jake Edge <jake@edge2.net>
4 # Copyright 2005-2007 Matt Mackall <mpm@selenic.com>
4 # Copyright 2005-2007 Matt Mackall <mpm@selenic.com>
5 #
5 #
6 # This software may be used and distributed according to the terms of the
6 # This software may be used and distributed according to the terms of the
7 # GNU General Public License version 2 or any later version.
7 # GNU General Public License version 2 or any later version.
8
8
9 from __future__ import absolute_import
9 from __future__ import absolute_import
10
10
11 import contextlib
11 import contextlib
12 import os
12 import os
13
13
14 from .common import (
14 from .common import (
15 ErrorResponse,
15 ErrorResponse,
16 HTTP_BAD_REQUEST,
16 HTTP_BAD_REQUEST,
17 HTTP_NOT_FOUND,
17 HTTP_NOT_FOUND,
18 HTTP_NOT_MODIFIED,
18 HTTP_NOT_MODIFIED,
19 HTTP_OK,
19 HTTP_OK,
20 HTTP_SERVER_ERROR,
20 HTTP_SERVER_ERROR,
21 caching,
21 caching,
22 cspvalues,
22 cspvalues,
23 permhooks,
23 permhooks,
24 )
24 )
25 from .request import wsgirequest
25 from .request import wsgirequest
26
26
27 from .. import (
27 from .. import (
28 encoding,
28 encoding,
29 error,
29 error,
30 hg,
30 hg,
31 hook,
31 hook,
32 profiling,
32 profiling,
33 pycompat,
33 pycompat,
34 repoview,
34 repoview,
35 templatefilters,
35 templatefilters,
36 templater,
36 templater,
37 ui as uimod,
37 ui as uimod,
38 util,
38 util,
39 wireprotoserver,
39 wireprotoserver,
40 )
40 )
41
41
42 from . import (
42 from . import (
43 webcommands,
43 webcommands,
44 webutil,
44 webutil,
45 wsgicgi,
45 wsgicgi,
46 )
46 )
47
47
48 perms = {
48 perms = {
49 'changegroup': 'pull',
49 'changegroup': 'pull',
50 'changegroupsubset': 'pull',
50 'changegroupsubset': 'pull',
51 'getbundle': 'pull',
51 'getbundle': 'pull',
52 'stream_out': 'pull',
52 'stream_out': 'pull',
53 'listkeys': 'pull',
53 'listkeys': 'pull',
54 'unbundle': 'push',
54 'unbundle': 'push',
55 'pushkey': 'push',
55 'pushkey': 'push',
56 }
56 }
57
57
58 archivespecs = util.sortdict((
58 archivespecs = util.sortdict((
59 ('zip', ('application/zip', 'zip', '.zip', None)),
59 ('zip', ('application/zip', 'zip', '.zip', None)),
60 ('gz', ('application/x-gzip', 'tgz', '.tar.gz', None)),
60 ('gz', ('application/x-gzip', 'tgz', '.tar.gz', None)),
61 ('bz2', ('application/x-bzip2', 'tbz2', '.tar.bz2', None)),
61 ('bz2', ('application/x-bzip2', 'tbz2', '.tar.bz2', None)),
62 ))
62 ))
63
63
64 def getstyle(req, configfn, templatepath):
64 def getstyle(req, configfn, templatepath):
65 fromreq = req.form.get('style', [None])[0]
65 fromreq = req.form.get('style', [None])[0]
66 if fromreq is not None:
66 if fromreq is not None:
67 fromreq = pycompat.sysbytes(fromreq)
67 fromreq = pycompat.sysbytes(fromreq)
68 styles = (
68 styles = (
69 fromreq,
69 fromreq,
70 configfn('web', 'style'),
70 configfn('web', 'style'),
71 'paper',
71 'paper',
72 )
72 )
73 return styles, templater.stylemap(styles, templatepath)
73 return styles, templater.stylemap(styles, templatepath)
74
74
75 def makebreadcrumb(url, prefix=''):
75 def makebreadcrumb(url, prefix=''):
76 '''Return a 'URL breadcrumb' list
76 '''Return a 'URL breadcrumb' list
77
77
78 A 'URL breadcrumb' is a list of URL-name pairs,
78 A 'URL breadcrumb' is a list of URL-name pairs,
79 corresponding to each of the path items on a URL.
79 corresponding to each of the path items on a URL.
80 This can be used to create path navigation entries.
80 This can be used to create path navigation entries.
81 '''
81 '''
82 if url.endswith('/'):
82 if url.endswith('/'):
83 url = url[:-1]
83 url = url[:-1]
84 if prefix:
84 if prefix:
85 url = '/' + prefix + url
85 url = '/' + prefix + url
86 relpath = url
86 relpath = url
87 if relpath.startswith('/'):
87 if relpath.startswith('/'):
88 relpath = relpath[1:]
88 relpath = relpath[1:]
89
89
90 breadcrumb = []
90 breadcrumb = []
91 urlel = url
91 urlel = url
92 pathitems = [''] + relpath.split('/')
92 pathitems = [''] + relpath.split('/')
93 for pathel in reversed(pathitems):
93 for pathel in reversed(pathitems):
94 if not pathel or not urlel:
94 if not pathel or not urlel:
95 break
95 break
96 breadcrumb.append({'url': urlel, 'name': pathel})
96 breadcrumb.append({'url': urlel, 'name': pathel})
97 urlel = os.path.dirname(urlel)
97 urlel = os.path.dirname(urlel)
98 return reversed(breadcrumb)
98 return reversed(breadcrumb)
99
99
100 class requestcontext(object):
100 class requestcontext(object):
101 """Holds state/context for an individual request.
101 """Holds state/context for an individual request.
102
102
103 Servers can be multi-threaded. Holding state on the WSGI application
103 Servers can be multi-threaded. Holding state on the WSGI application
104 is prone to race conditions. Instances of this class exist to hold
104 is prone to race conditions. Instances of this class exist to hold
105 mutable and race-free state for requests.
105 mutable and race-free state for requests.
106 """
106 """
107 def __init__(self, app, repo):
107 def __init__(self, app, repo):
108 self.repo = repo
108 self.repo = repo
109 self.reponame = app.reponame
109 self.reponame = app.reponame
110
110
111 self.archivespecs = archivespecs
111 self.archivespecs = archivespecs
112
112
113 self.maxchanges = self.configint('web', 'maxchanges')
113 self.maxchanges = self.configint('web', 'maxchanges')
114 self.stripecount = self.configint('web', 'stripes')
114 self.stripecount = self.configint('web', 'stripes')
115 self.maxshortchanges = self.configint('web', 'maxshortchanges')
115 self.maxshortchanges = self.configint('web', 'maxshortchanges')
116 self.maxfiles = self.configint('web', 'maxfiles')
116 self.maxfiles = self.configint('web', 'maxfiles')
117 self.allowpull = self.configbool('web', 'allow-pull')
117 self.allowpull = self.configbool('web', 'allow-pull')
118
118
119 # we use untrusted=False to prevent a repo owner from using
119 # we use untrusted=False to prevent a repo owner from using
120 # web.templates in .hg/hgrc to get access to any file readable
120 # web.templates in .hg/hgrc to get access to any file readable
121 # by the user running the CGI script
121 # by the user running the CGI script
122 self.templatepath = self.config('web', 'templates', untrusted=False)
122 self.templatepath = self.config('web', 'templates', untrusted=False)
123
123
124 # This object is more expensive to build than simple config values.
124 # This object is more expensive to build than simple config values.
125 # It is shared across requests. The app will replace the object
125 # It is shared across requests. The app will replace the object
126 # if it is updated. Since this is a reference and nothing should
126 # if it is updated. Since this is a reference and nothing should
127 # modify the underlying object, it should be constant for the lifetime
127 # modify the underlying object, it should be constant for the lifetime
128 # of the request.
128 # of the request.
129 self.websubtable = app.websubtable
129 self.websubtable = app.websubtable
130
130
131 self.csp, self.nonce = cspvalues(self.repo.ui)
131 self.csp, self.nonce = cspvalues(self.repo.ui)
132
132
133 # Trust the settings from the .hg/hgrc files by default.
133 # Trust the settings from the .hg/hgrc files by default.
134 def config(self, section, name, default=uimod._unset, untrusted=True):
134 def config(self, section, name, default=uimod._unset, untrusted=True):
135 return self.repo.ui.config(section, name, default,
135 return self.repo.ui.config(section, name, default,
136 untrusted=untrusted)
136 untrusted=untrusted)
137
137
138 def configbool(self, section, name, default=uimod._unset, untrusted=True):
138 def configbool(self, section, name, default=uimod._unset, untrusted=True):
139 return self.repo.ui.configbool(section, name, default,
139 return self.repo.ui.configbool(section, name, default,
140 untrusted=untrusted)
140 untrusted=untrusted)
141
141
142 def configint(self, section, name, default=uimod._unset, untrusted=True):
142 def configint(self, section, name, default=uimod._unset, untrusted=True):
143 return self.repo.ui.configint(section, name, default,
143 return self.repo.ui.configint(section, name, default,
144 untrusted=untrusted)
144 untrusted=untrusted)
145
145
146 def configlist(self, section, name, default=uimod._unset, untrusted=True):
146 def configlist(self, section, name, default=uimod._unset, untrusted=True):
147 return self.repo.ui.configlist(section, name, default,
147 return self.repo.ui.configlist(section, name, default,
148 untrusted=untrusted)
148 untrusted=untrusted)
149
149
150 def archivelist(self, nodeid):
150 def archivelist(self, nodeid):
151 allowed = self.configlist('web', 'allow_archive')
151 allowed = self.configlist('web', 'allow_archive')
152 for typ, spec in self.archivespecs.iteritems():
152 for typ, spec in self.archivespecs.iteritems():
153 if typ in allowed or self.configbool('web', 'allow%s' % typ):
153 if typ in allowed or self.configbool('web', 'allow%s' % typ):
154 yield {'type': typ, 'extension': spec[2], 'node': nodeid}
154 yield {'type': typ, 'extension': spec[2], 'node': nodeid}
155
155
156 def templater(self, req):
156 def templater(self, req):
157 # determine scheme, port and server name
157 # determine scheme, port and server name
158 # this is needed to create absolute urls
158 # this is needed to create absolute urls
159
159
160 proto = req.env.get('wsgi.url_scheme')
160 proto = req.env.get('wsgi.url_scheme')
161 if proto == 'https':
161 if proto == 'https':
162 proto = 'https'
162 proto = 'https'
163 default_port = '443'
163 default_port = '443'
164 else:
164 else:
165 proto = 'http'
165 proto = 'http'
166 default_port = '80'
166 default_port = '80'
167
167
168 port = req.env[r'SERVER_PORT']
168 port = req.env[r'SERVER_PORT']
169 port = port != default_port and (r':' + port) or r''
169 port = port != default_port and (r':' + port) or r''
170 urlbase = r'%s://%s%s' % (proto, req.env[r'SERVER_NAME'], port)
170 urlbase = r'%s://%s%s' % (proto, req.env[r'SERVER_NAME'], port)
171 logourl = self.config('web', 'logourl')
171 logourl = self.config('web', 'logourl')
172 logoimg = self.config('web', 'logoimg')
172 logoimg = self.config('web', 'logoimg')
173 staticurl = self.config('web', 'staticurl') or req.url + 'static/'
173 staticurl = self.config('web', 'staticurl') or req.url + 'static/'
174 if not staticurl.endswith('/'):
174 if not staticurl.endswith('/'):
175 staticurl += '/'
175 staticurl += '/'
176
176
177 # some functions for the templater
177 # some functions for the templater
178
178
179 def motd(**map):
179 def motd(**map):
180 yield self.config('web', 'motd')
180 yield self.config('web', 'motd')
181
181
182 # figure out which style to use
182 # figure out which style to use
183
183
184 vars = {}
184 vars = {}
185 styles, (style, mapfile) = getstyle(req, self.config,
185 styles, (style, mapfile) = getstyle(req, self.config,
186 self.templatepath)
186 self.templatepath)
187 if style == styles[0]:
187 if style == styles[0]:
188 vars['style'] = style
188 vars['style'] = style
189
189
190 start = '&' if req.url[-1] == r'?' else '?'
190 start = '&' if req.url[-1] == r'?' else '?'
191 sessionvars = webutil.sessionvars(vars, start)
191 sessionvars = webutil.sessionvars(vars, start)
192
192
193 if not self.reponame:
193 if not self.reponame:
194 self.reponame = (self.config('web', 'name', '')
194 self.reponame = (self.config('web', 'name', '')
195 or req.env.get('REPO_NAME')
195 or req.env.get('REPO_NAME')
196 or req.url.strip('/') or self.repo.root)
196 or req.url.strip('/') or self.repo.root)
197
197
198 def websubfilter(text):
198 def websubfilter(text):
199 return templatefilters.websub(text, self.websubtable)
199 return templatefilters.websub(text, self.websubtable)
200
200
201 # create the templater
201 # create the templater
202
202
203 defaults = {
203 defaults = {
204 'url': req.url,
204 'url': req.url,
205 'logourl': logourl,
205 'logourl': logourl,
206 'logoimg': logoimg,
206 'logoimg': logoimg,
207 'staticurl': staticurl,
207 'staticurl': staticurl,
208 'urlbase': urlbase,
208 'urlbase': urlbase,
209 'repo': self.reponame,
209 'repo': self.reponame,
210 'encoding': encoding.encoding,
210 'encoding': encoding.encoding,
211 'motd': motd,
211 'motd': motd,
212 'sessionvars': sessionvars,
212 'sessionvars': sessionvars,
213 'pathdef': makebreadcrumb(req.url),
213 'pathdef': makebreadcrumb(req.url),
214 'style': style,
214 'style': style,
215 'nonce': self.nonce,
215 'nonce': self.nonce,
216 }
216 }
217 tmpl = templater.templater.frommapfile(mapfile,
217 tmpl = templater.templater.frommapfile(mapfile,
218 filters={'websub': websubfilter},
218 filters={'websub': websubfilter},
219 defaults=defaults)
219 defaults=defaults)
220 return tmpl
220 return tmpl
221
221
222
222
223 class hgweb(object):
223 class hgweb(object):
224 """HTTP server for individual repositories.
224 """HTTP server for individual repositories.
225
225
226 Instances of this class serve HTTP responses for a particular
226 Instances of this class serve HTTP responses for a particular
227 repository.
227 repository.
228
228
229 Instances are typically used as WSGI applications.
229 Instances are typically used as WSGI applications.
230
230
231 Some servers are multi-threaded. On these servers, there may
231 Some servers are multi-threaded. On these servers, there may
232 be multiple active threads inside __call__.
232 be multiple active threads inside __call__.
233 """
233 """
234 def __init__(self, repo, name=None, baseui=None):
234 def __init__(self, repo, name=None, baseui=None):
235 if isinstance(repo, str):
235 if isinstance(repo, str):
236 if baseui:
236 if baseui:
237 u = baseui.copy()
237 u = baseui.copy()
238 else:
238 else:
239 u = uimod.ui.load()
239 u = uimod.ui.load()
240 r = hg.repository(u, repo)
240 r = hg.repository(u, repo)
241 else:
241 else:
242 # we trust caller to give us a private copy
242 # we trust caller to give us a private copy
243 r = repo
243 r = repo
244
244
245 r.ui.setconfig('ui', 'report_untrusted', 'off', 'hgweb')
245 r.ui.setconfig('ui', 'report_untrusted', 'off', 'hgweb')
246 r.baseui.setconfig('ui', 'report_untrusted', 'off', 'hgweb')
246 r.baseui.setconfig('ui', 'report_untrusted', 'off', 'hgweb')
247 r.ui.setconfig('ui', 'nontty', 'true', 'hgweb')
247 r.ui.setconfig('ui', 'nontty', 'true', 'hgweb')
248 r.baseui.setconfig('ui', 'nontty', 'true', 'hgweb')
248 r.baseui.setconfig('ui', 'nontty', 'true', 'hgweb')
249 # resolve file patterns relative to repo root
249 # resolve file patterns relative to repo root
250 r.ui.setconfig('ui', 'forcecwd', r.root, 'hgweb')
250 r.ui.setconfig('ui', 'forcecwd', r.root, 'hgweb')
251 r.baseui.setconfig('ui', 'forcecwd', r.root, 'hgweb')
251 r.baseui.setconfig('ui', 'forcecwd', r.root, 'hgweb')
252 # displaying bundling progress bar while serving feel wrong and may
252 # displaying bundling progress bar while serving feel wrong and may
253 # break some wsgi implementation.
253 # break some wsgi implementation.
254 r.ui.setconfig('progress', 'disable', 'true', 'hgweb')
254 r.ui.setconfig('progress', 'disable', 'true', 'hgweb')
255 r.baseui.setconfig('progress', 'disable', 'true', 'hgweb')
255 r.baseui.setconfig('progress', 'disable', 'true', 'hgweb')
256 self._repos = [hg.cachedlocalrepo(self._webifyrepo(r))]
256 self._repos = [hg.cachedlocalrepo(self._webifyrepo(r))]
257 self._lastrepo = self._repos[0]
257 self._lastrepo = self._repos[0]
258 hook.redirect(True)
258 hook.redirect(True)
259 self.reponame = name
259 self.reponame = name
260
260
261 def _webifyrepo(self, repo):
261 def _webifyrepo(self, repo):
262 repo = getwebview(repo)
262 repo = getwebview(repo)
263 self.websubtable = webutil.getwebsubs(repo)
263 self.websubtable = webutil.getwebsubs(repo)
264 return repo
264 return repo
265
265
266 @contextlib.contextmanager
266 @contextlib.contextmanager
267 def _obtainrepo(self):
267 def _obtainrepo(self):
268 """Obtain a repo unique to the caller.
268 """Obtain a repo unique to the caller.
269
269
270 Internally we maintain a stack of cachedlocalrepo instances
270 Internally we maintain a stack of cachedlocalrepo instances
271 to be handed out. If one is available, we pop it and return it,
271 to be handed out. If one is available, we pop it and return it,
272 ensuring it is up to date in the process. If one is not available,
272 ensuring it is up to date in the process. If one is not available,
273 we clone the most recently used repo instance and return it.
273 we clone the most recently used repo instance and return it.
274
274
275 It is currently possible for the stack to grow without bounds
275 It is currently possible for the stack to grow without bounds
276 if the server allows infinite threads. However, servers should
276 if the server allows infinite threads. However, servers should
277 have a thread limit, thus establishing our limit.
277 have a thread limit, thus establishing our limit.
278 """
278 """
279 if self._repos:
279 if self._repos:
280 cached = self._repos.pop()
280 cached = self._repos.pop()
281 r, created = cached.fetch()
281 r, created = cached.fetch()
282 else:
282 else:
283 cached = self._lastrepo.copy()
283 cached = self._lastrepo.copy()
284 r, created = cached.fetch()
284 r, created = cached.fetch()
285 if created:
285 if created:
286 r = self._webifyrepo(r)
286 r = self._webifyrepo(r)
287
287
288 self._lastrepo = cached
288 self._lastrepo = cached
289 self.mtime = cached.mtime
289 self.mtime = cached.mtime
290 try:
290 try:
291 yield r
291 yield r
292 finally:
292 finally:
293 self._repos.append(cached)
293 self._repos.append(cached)
294
294
295 def run(self):
295 def run(self):
296 """Start a server from CGI environment.
296 """Start a server from CGI environment.
297
297
298 Modern servers should be using WSGI and should avoid this
298 Modern servers should be using WSGI and should avoid this
299 method, if possible.
299 method, if possible.
300 """
300 """
301 if not encoding.environ.get('GATEWAY_INTERFACE',
301 if not encoding.environ.get('GATEWAY_INTERFACE',
302 '').startswith("CGI/1."):
302 '').startswith("CGI/1."):
303 raise RuntimeError("This function is only intended to be "
303 raise RuntimeError("This function is only intended to be "
304 "called while running as a CGI script.")
304 "called while running as a CGI script.")
305 wsgicgi.launch(self)
305 wsgicgi.launch(self)
306
306
307 def __call__(self, env, respond):
307 def __call__(self, env, respond):
308 """Run the WSGI application.
308 """Run the WSGI application.
309
309
310 This may be called by multiple threads.
310 This may be called by multiple threads.
311 """
311 """
312 req = wsgirequest(env, respond)
312 req = wsgirequest(env, respond)
313 return self.run_wsgi(req)
313 return self.run_wsgi(req)
314
314
315 def run_wsgi(self, req):
315 def run_wsgi(self, req):
316 """Internal method to run the WSGI application.
316 """Internal method to run the WSGI application.
317
317
318 This is typically only called by Mercurial. External consumers
318 This is typically only called by Mercurial. External consumers
319 should be using instances of this class as the WSGI application.
319 should be using instances of this class as the WSGI application.
320 """
320 """
321 with self._obtainrepo() as repo:
321 with self._obtainrepo() as repo:
322 profile = repo.ui.configbool('profiling', 'enabled')
322 profile = repo.ui.configbool('profiling', 'enabled')
323 with profiling.profile(repo.ui, enabled=profile):
323 with profiling.profile(repo.ui, enabled=profile):
324 for r in self._runwsgi(req, repo):
324 for r in self._runwsgi(req, repo):
325 yield r
325 yield r
326
326
327 def _runwsgi(self, req, repo):
327 def _runwsgi(self, req, repo):
328 rctx = requestcontext(self, repo)
328 rctx = requestcontext(self, repo)
329
329
330 # This state is global across all threads.
330 # This state is global across all threads.
331 encoding.encoding = rctx.config('web', 'encoding')
331 encoding.encoding = rctx.config('web', 'encoding')
332 rctx.repo.ui.environ = req.env
332 rctx.repo.ui.environ = req.env
333
333
334 if rctx.csp:
334 if rctx.csp:
335 # hgwebdir may have added CSP header. Since we generate our own,
335 # hgwebdir may have added CSP header. Since we generate our own,
336 # replace it.
336 # replace it.
337 req.headers = [h for h in req.headers
337 req.headers = [h for h in req.headers
338 if h[0] != 'Content-Security-Policy']
338 if h[0] != 'Content-Security-Policy']
339 req.headers.append(('Content-Security-Policy', rctx.csp))
339 req.headers.append(('Content-Security-Policy', rctx.csp))
340
340
341 # work with CGI variables to create coherent structure
341 # work with CGI variables to create coherent structure
342 # use SCRIPT_NAME, PATH_INFO and QUERY_STRING as well as our REPO_NAME
342 # use SCRIPT_NAME, PATH_INFO and QUERY_STRING as well as our REPO_NAME
343
343
344 req.url = req.env[r'SCRIPT_NAME']
344 req.url = req.env[r'SCRIPT_NAME']
345 if not req.url.endswith('/'):
345 if not req.url.endswith('/'):
346 req.url += '/'
346 req.url += '/'
347 if req.env.get('REPO_NAME'):
347 if req.env.get('REPO_NAME'):
348 req.url += req.env[r'REPO_NAME'] + r'/'
348 req.url += req.env[r'REPO_NAME'] + r'/'
349
349
350 if r'PATH_INFO' in req.env:
350 if r'PATH_INFO' in req.env:
351 parts = req.env[r'PATH_INFO'].strip('/').split('/')
351 parts = req.env[r'PATH_INFO'].strip('/').split('/')
352 repo_parts = req.env.get(r'REPO_NAME', r'').split(r'/')
352 repo_parts = req.env.get(r'REPO_NAME', r'').split(r'/')
353 if parts[:len(repo_parts)] == repo_parts:
353 if parts[:len(repo_parts)] == repo_parts:
354 parts = parts[len(repo_parts):]
354 parts = parts[len(repo_parts):]
355 query = '/'.join(parts)
355 query = '/'.join(parts)
356 else:
356 else:
357 query = req.env[r'QUERY_STRING'].partition(r'&')[0]
357 query = req.env[r'QUERY_STRING'].partition(r'&')[0]
358 query = query.partition(r';')[0]
358 query = query.partition(r';')[0]
359
359
360 # Route it to a wire protocol handler if it looks like a wire protocol
360 # Route it to a wire protocol handler if it looks like a wire protocol
361 # request.
361 # request.
362 protohandler = wireprotoserver.parsehttprequest(rctx.repo, req, query)
362 protohandler = wireprotoserver.parsehttprequest(rctx.repo, req, query)
363
363
364 if protohandler:
364 if protohandler:
365 cmd = protohandler['cmd']
365 cmd = protohandler['cmd']
366 try:
366 try:
367 if query:
367 if query:
368 raise ErrorResponse(HTTP_NOT_FOUND)
368 raise ErrorResponse(HTTP_NOT_FOUND)
369 if cmd in perms:
369 if cmd in perms:
370 self.check_perm(rctx, req, perms[cmd])
370 self.check_perm(rctx, req, perms[cmd])
371 return protohandler['dispatch']()
372 except ErrorResponse as inst:
371 except ErrorResponse as inst:
373 # A client that sends unbundle without 100-continue will
372 # A client that sends unbundle without 100-continue will
374 # break if we respond early.
373 # break if we respond early.
375 if (cmd == 'unbundle' and
374 if (cmd == 'unbundle' and
376 (req.env.get('HTTP_EXPECT',
375 (req.env.get('HTTP_EXPECT',
377 '').lower() != '100-continue') or
376 '').lower() != '100-continue') or
378 req.env.get('X-HgHttp2', '')):
377 req.env.get('X-HgHttp2', '')):
379 req.drain()
378 req.drain()
380 else:
379 else:
381 req.headers.append((r'Connection', r'Close'))
380 req.headers.append((r'Connection', r'Close'))
382 req.respond(inst, wireprotoserver.HGTYPE,
381 req.respond(inst, wireprotoserver.HGTYPE,
383 body='0\n%s\n' % inst)
382 body='0\n%s\n' % inst)
384 return ''
383 return ''
385
384
385 return protohandler['dispatch']()
386
386 # translate user-visible url structure to internal structure
387 # translate user-visible url structure to internal structure
387
388
388 args = query.split('/', 2)
389 args = query.split('/', 2)
389 if r'cmd' not in req.form and args and args[0]:
390 if r'cmd' not in req.form and args and args[0]:
390 cmd = args.pop(0)
391 cmd = args.pop(0)
391 style = cmd.rfind('-')
392 style = cmd.rfind('-')
392 if style != -1:
393 if style != -1:
393 req.form['style'] = [cmd[:style]]
394 req.form['style'] = [cmd[:style]]
394 cmd = cmd[style + 1:]
395 cmd = cmd[style + 1:]
395
396
396 # avoid accepting e.g. style parameter as command
397 # avoid accepting e.g. style parameter as command
397 if util.safehasattr(webcommands, cmd):
398 if util.safehasattr(webcommands, cmd):
398 req.form[r'cmd'] = [cmd]
399 req.form[r'cmd'] = [cmd]
399
400
400 if cmd == 'static':
401 if cmd == 'static':
401 req.form['file'] = ['/'.join(args)]
402 req.form['file'] = ['/'.join(args)]
402 else:
403 else:
403 if args and args[0]:
404 if args and args[0]:
404 node = args.pop(0).replace('%2F', '/')
405 node = args.pop(0).replace('%2F', '/')
405 req.form['node'] = [node]
406 req.form['node'] = [node]
406 if args:
407 if args:
407 req.form['file'] = args
408 req.form['file'] = args
408
409
409 ua = req.env.get('HTTP_USER_AGENT', '')
410 ua = req.env.get('HTTP_USER_AGENT', '')
410 if cmd == 'rev' and 'mercurial' in ua:
411 if cmd == 'rev' and 'mercurial' in ua:
411 req.form['style'] = ['raw']
412 req.form['style'] = ['raw']
412
413
413 if cmd == 'archive':
414 if cmd == 'archive':
414 fn = req.form['node'][0]
415 fn = req.form['node'][0]
415 for type_, spec in rctx.archivespecs.iteritems():
416 for type_, spec in rctx.archivespecs.iteritems():
416 ext = spec[2]
417 ext = spec[2]
417 if fn.endswith(ext):
418 if fn.endswith(ext):
418 req.form['node'] = [fn[:-len(ext)]]
419 req.form['node'] = [fn[:-len(ext)]]
419 req.form['type'] = [type_]
420 req.form['type'] = [type_]
420 else:
421 else:
421 cmd = pycompat.sysbytes(req.form.get(r'cmd', [r''])[0])
422 cmd = pycompat.sysbytes(req.form.get(r'cmd', [r''])[0])
422
423
423 # process the web interface request
424 # process the web interface request
424
425
425 try:
426 try:
426 tmpl = rctx.templater(req)
427 tmpl = rctx.templater(req)
427 ctype = tmpl('mimetype', encoding=encoding.encoding)
428 ctype = tmpl('mimetype', encoding=encoding.encoding)
428 ctype = templater.stringify(ctype)
429 ctype = templater.stringify(ctype)
429
430
430 # check read permissions non-static content
431 # check read permissions non-static content
431 if cmd != 'static':
432 if cmd != 'static':
432 self.check_perm(rctx, req, None)
433 self.check_perm(rctx, req, None)
433
434
434 if cmd == '':
435 if cmd == '':
435 req.form[r'cmd'] = [tmpl.cache['default']]
436 req.form[r'cmd'] = [tmpl.cache['default']]
436 cmd = req.form[r'cmd'][0]
437 cmd = req.form[r'cmd'][0]
437
438
438 # Don't enable caching if using a CSP nonce because then it wouldn't
439 # Don't enable caching if using a CSP nonce because then it wouldn't
439 # be a nonce.
440 # be a nonce.
440 if rctx.configbool('web', 'cache') and not rctx.nonce:
441 if rctx.configbool('web', 'cache') and not rctx.nonce:
441 caching(self, req) # sets ETag header or raises NOT_MODIFIED
442 caching(self, req) # sets ETag header or raises NOT_MODIFIED
442 if cmd not in webcommands.__all__:
443 if cmd not in webcommands.__all__:
443 msg = 'no such method: %s' % cmd
444 msg = 'no such method: %s' % cmd
444 raise ErrorResponse(HTTP_BAD_REQUEST, msg)
445 raise ErrorResponse(HTTP_BAD_REQUEST, msg)
445 elif cmd == 'file' and r'raw' in req.form.get(r'style', []):
446 elif cmd == 'file' and r'raw' in req.form.get(r'style', []):
446 rctx.ctype = ctype
447 rctx.ctype = ctype
447 content = webcommands.rawfile(rctx, req, tmpl)
448 content = webcommands.rawfile(rctx, req, tmpl)
448 else:
449 else:
449 content = getattr(webcommands, cmd)(rctx, req, tmpl)
450 content = getattr(webcommands, cmd)(rctx, req, tmpl)
450 req.respond(HTTP_OK, ctype)
451 req.respond(HTTP_OK, ctype)
451
452
452 return content
453 return content
453
454
454 except (error.LookupError, error.RepoLookupError) as err:
455 except (error.LookupError, error.RepoLookupError) as err:
455 req.respond(HTTP_NOT_FOUND, ctype)
456 req.respond(HTTP_NOT_FOUND, ctype)
456 msg = str(err)
457 msg = str(err)
457 if (util.safehasattr(err, 'name') and
458 if (util.safehasattr(err, 'name') and
458 not isinstance(err, error.ManifestLookupError)):
459 not isinstance(err, error.ManifestLookupError)):
459 msg = 'revision not found: %s' % err.name
460 msg = 'revision not found: %s' % err.name
460 return tmpl('error', error=msg)
461 return tmpl('error', error=msg)
461 except (error.RepoError, error.RevlogError) as inst:
462 except (error.RepoError, error.RevlogError) as inst:
462 req.respond(HTTP_SERVER_ERROR, ctype)
463 req.respond(HTTP_SERVER_ERROR, ctype)
463 return tmpl('error', error=str(inst))
464 return tmpl('error', error=str(inst))
464 except ErrorResponse as inst:
465 except ErrorResponse as inst:
465 req.respond(inst, ctype)
466 req.respond(inst, ctype)
466 if inst.code == HTTP_NOT_MODIFIED:
467 if inst.code == HTTP_NOT_MODIFIED:
467 # Not allowed to return a body on a 304
468 # Not allowed to return a body on a 304
468 return ['']
469 return ['']
469 return tmpl('error', error=str(inst))
470 return tmpl('error', error=str(inst))
470
471
471 def check_perm(self, rctx, req, op):
472 def check_perm(self, rctx, req, op):
472 for permhook in permhooks:
473 for permhook in permhooks:
473 permhook(rctx, req, op)
474 permhook(rctx, req, op)
474
475
475 def getwebview(repo):
476 def getwebview(repo):
476 """The 'web.view' config controls changeset filter to hgweb. Possible
477 """The 'web.view' config controls changeset filter to hgweb. Possible
477 values are ``served``, ``visible`` and ``all``. Default is ``served``.
478 values are ``served``, ``visible`` and ``all``. Default is ``served``.
478 The ``served`` filter only shows changesets that can be pulled from the
479 The ``served`` filter only shows changesets that can be pulled from the
479 hgweb instance. The``visible`` filter includes secret changesets but
480 hgweb instance. The``visible`` filter includes secret changesets but
480 still excludes "hidden" one.
481 still excludes "hidden" one.
481
482
482 See the repoview module for details.
483 See the repoview module for details.
483
484
484 The option has been around undocumented since Mercurial 2.5, but no
485 The option has been around undocumented since Mercurial 2.5, but no
485 user ever asked about it. So we better keep it undocumented for now."""
486 user ever asked about it. So we better keep it undocumented for now."""
486 # experimental config: web.view
487 # experimental config: web.view
487 viewconfig = repo.ui.config('web', 'view', untrusted=True)
488 viewconfig = repo.ui.config('web', 'view', untrusted=True)
488 if viewconfig == 'all':
489 if viewconfig == 'all':
489 return repo.unfiltered()
490 return repo.unfiltered()
490 elif viewconfig in repoview.filtertable:
491 elif viewconfig in repoview.filtertable:
491 return repo.filtered(viewconfig)
492 return repo.filtered(viewconfig)
492 else:
493 else:
493 return repo.filtered('served')
494 return repo.filtered('served')
General Comments 0
You need to be logged in to leave comments. Login now