Show More
@@ -1,487 +1,483 | |||||
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 | import os, re |
|
9 | import os, re | |
10 | from mercurial import ui, hg, hook, error, encoding, templater, util, repoview |
|
10 | from mercurial import ui, hg, hook, error, encoding, templater, util, repoview | |
11 | from mercurial.templatefilters import websub |
|
11 | from mercurial.templatefilters import websub | |
12 | from mercurial.i18n import _ |
|
12 | from mercurial.i18n import _ | |
13 | from common import get_stat, ErrorResponse, permhooks, caching |
|
13 | from common import get_stat, ErrorResponse, permhooks, caching | |
14 | from common import HTTP_OK, HTTP_NOT_MODIFIED, HTTP_BAD_REQUEST |
|
14 | from common import HTTP_OK, HTTP_NOT_MODIFIED, HTTP_BAD_REQUEST | |
15 | from common import HTTP_NOT_FOUND, HTTP_SERVER_ERROR |
|
15 | from common import HTTP_NOT_FOUND, HTTP_SERVER_ERROR | |
16 | from request import wsgirequest |
|
16 | from request import wsgirequest | |
17 | import webcommands, protocol, webutil |
|
17 | import webcommands, protocol, webutil | |
18 |
|
18 | |||
19 | perms = { |
|
19 | perms = { | |
20 | 'changegroup': 'pull', |
|
20 | 'changegroup': 'pull', | |
21 | 'changegroupsubset': 'pull', |
|
21 | 'changegroupsubset': 'pull', | |
22 | 'getbundle': 'pull', |
|
22 | 'getbundle': 'pull', | |
23 | 'stream_out': 'pull', |
|
23 | 'stream_out': 'pull', | |
24 | 'listkeys': 'pull', |
|
24 | 'listkeys': 'pull', | |
25 | 'unbundle': 'push', |
|
25 | 'unbundle': 'push', | |
26 | 'pushkey': 'push', |
|
26 | 'pushkey': 'push', | |
27 | } |
|
27 | } | |
28 |
|
28 | |||
29 | ## Files of interest |
|
29 | ## Files of interest | |
30 | # Used to check if the repository has changed looking at mtime and size of |
|
30 | # Used to check if the repository has changed looking at mtime and size of | |
31 | # theses files. This should probably be relocated a bit higher in core. |
|
31 | # theses files. This should probably be relocated a bit higher in core. | |
32 | foi = [('spath', '00changelog.i'), |
|
32 | foi = [('spath', '00changelog.i'), | |
33 | ('spath', 'phaseroots'), # ! phase can change content at the same size |
|
33 | ('spath', 'phaseroots'), # ! phase can change content at the same size | |
34 | ('spath', 'obsstore'), |
|
34 | ('spath', 'obsstore'), | |
35 | ('path', 'bookmarks'), # ! bookmark can change content at the same size |
|
35 | ('path', 'bookmarks'), # ! bookmark can change content at the same size | |
36 | ] |
|
36 | ] | |
37 |
|
37 | |||
38 | def makebreadcrumb(url, prefix=''): |
|
38 | def makebreadcrumb(url, prefix=''): | |
39 | '''Return a 'URL breadcrumb' list |
|
39 | '''Return a 'URL breadcrumb' list | |
40 |
|
40 | |||
41 | A 'URL breadcrumb' is a list of URL-name pairs, |
|
41 | A 'URL breadcrumb' is a list of URL-name pairs, | |
42 | corresponding to each of the path items on a URL. |
|
42 | corresponding to each of the path items on a URL. | |
43 | This can be used to create path navigation entries. |
|
43 | This can be used to create path navigation entries. | |
44 | ''' |
|
44 | ''' | |
45 | if url.endswith('/'): |
|
45 | if url.endswith('/'): | |
46 | url = url[:-1] |
|
46 | url = url[:-1] | |
47 | if prefix: |
|
47 | if prefix: | |
48 | url = '/' + prefix + url |
|
48 | url = '/' + prefix + url | |
49 | relpath = url |
|
49 | relpath = url | |
50 | if relpath.startswith('/'): |
|
50 | if relpath.startswith('/'): | |
51 | relpath = relpath[1:] |
|
51 | relpath = relpath[1:] | |
52 |
|
52 | |||
53 | breadcrumb = [] |
|
53 | breadcrumb = [] | |
54 | urlel = url |
|
54 | urlel = url | |
55 | pathitems = [''] + relpath.split('/') |
|
55 | pathitems = [''] + relpath.split('/') | |
56 | for pathel in reversed(pathitems): |
|
56 | for pathel in reversed(pathitems): | |
57 | if not pathel or not urlel: |
|
57 | if not pathel or not urlel: | |
58 | break |
|
58 | break | |
59 | breadcrumb.append({'url': urlel, 'name': pathel}) |
|
59 | breadcrumb.append({'url': urlel, 'name': pathel}) | |
60 | urlel = os.path.dirname(urlel) |
|
60 | urlel = os.path.dirname(urlel) | |
61 | return reversed(breadcrumb) |
|
61 | return reversed(breadcrumb) | |
62 |
|
62 | |||
63 |
|
63 | |||
64 | class requestcontext(object): |
|
64 | class requestcontext(object): | |
65 | """Holds state/context for an individual request. |
|
65 | """Holds state/context for an individual request. | |
66 |
|
66 | |||
67 | Servers can be multi-threaded. Holding state on the WSGI application |
|
67 | Servers can be multi-threaded. Holding state on the WSGI application | |
68 | is prone to race conditions. Instances of this class exist to hold |
|
68 | is prone to race conditions. Instances of this class exist to hold | |
69 | mutable and race-free state for requests. |
|
69 | mutable and race-free state for requests. | |
70 | """ |
|
70 | """ | |
71 | def __init__(self, app): |
|
71 | def __init__(self, app): | |
72 | object.__setattr__(self, 'app', app) |
|
72 | object.__setattr__(self, 'app', app) | |
73 | object.__setattr__(self, 'repo', app.repo) |
|
73 | object.__setattr__(self, 'repo', app.repo) | |
74 |
|
74 | |||
75 | object.__setattr__(self, 'archives', ('zip', 'gz', 'bz2')) |
|
75 | object.__setattr__(self, 'archives', ('zip', 'gz', 'bz2')) | |
76 |
|
76 | |||
77 | object.__setattr__(self, 'maxchanges', |
|
77 | object.__setattr__(self, 'maxchanges', | |
78 | self.configint('web', 'maxchanges', 10)) |
|
78 | self.configint('web', 'maxchanges', 10)) | |
79 | object.__setattr__(self, 'stripecount', |
|
79 | object.__setattr__(self, 'stripecount', | |
80 | self.configint('web', 'stripes', 1)) |
|
80 | self.configint('web', 'stripes', 1)) | |
81 | object.__setattr__(self, 'maxshortchanges', |
|
81 | object.__setattr__(self, 'maxshortchanges', | |
82 | self.configint('web', 'maxshortchanges', 60)) |
|
82 | self.configint('web', 'maxshortchanges', 60)) | |
83 | object.__setattr__(self, 'maxfiles', |
|
83 | object.__setattr__(self, 'maxfiles', | |
84 | self.configint('web', 'maxfiles', 10)) |
|
84 | self.configint('web', 'maxfiles', 10)) | |
85 | object.__setattr__(self, 'allowpull', |
|
85 | object.__setattr__(self, 'allowpull', | |
86 | self.configbool('web', 'allowpull', True)) |
|
86 | self.configbool('web', 'allowpull', True)) | |
87 |
|
87 | |||
88 | # Proxy unknown reads and writes to the application instance |
|
88 | # Proxy unknown reads and writes to the application instance | |
89 | # until everything is moved to us. |
|
89 | # until everything is moved to us. | |
90 | def __getattr__(self, name): |
|
90 | def __getattr__(self, name): | |
91 | return getattr(self.app, name) |
|
91 | return getattr(self.app, name) | |
92 |
|
92 | |||
93 | def __setattr__(self, name, value): |
|
93 | def __setattr__(self, name, value): | |
94 | return setattr(self.app, name, value) |
|
94 | return setattr(self.app, name, value) | |
95 |
|
95 | |||
96 | # Servers are often run by a user different from the repo owner. |
|
96 | # Servers are often run by a user different from the repo owner. | |
97 | # Trust the settings from the .hg/hgrc files by default. |
|
97 | # Trust the settings from the .hg/hgrc files by default. | |
98 | def config(self, section, name, default=None, untrusted=True): |
|
98 | def config(self, section, name, default=None, untrusted=True): | |
99 | return self.repo.ui.config(section, name, default, |
|
99 | return self.repo.ui.config(section, name, default, | |
100 | untrusted=untrusted) |
|
100 | untrusted=untrusted) | |
101 |
|
101 | |||
102 | def configbool(self, section, name, default=False, untrusted=True): |
|
102 | def configbool(self, section, name, default=False, untrusted=True): | |
103 | return self.repo.ui.configbool(section, name, default, |
|
103 | return self.repo.ui.configbool(section, name, default, | |
104 | untrusted=untrusted) |
|
104 | untrusted=untrusted) | |
105 |
|
105 | |||
106 | def configint(self, section, name, default=None, untrusted=True): |
|
106 | def configint(self, section, name, default=None, untrusted=True): | |
107 | return self.repo.ui.configint(section, name, default, |
|
107 | return self.repo.ui.configint(section, name, default, | |
108 | untrusted=untrusted) |
|
108 | untrusted=untrusted) | |
109 |
|
109 | |||
110 | def configlist(self, section, name, default=None, untrusted=True): |
|
110 | def configlist(self, section, name, default=None, untrusted=True): | |
111 | return self.repo.ui.configlist(section, name, default, |
|
111 | return self.repo.ui.configlist(section, name, default, | |
112 | untrusted=untrusted) |
|
112 | untrusted=untrusted) | |
113 |
|
113 | |||
114 | archivespecs = { |
|
114 | archivespecs = { | |
115 | 'bz2': ('application/x-bzip2', 'tbz2', '.tar.bz2', None), |
|
115 | 'bz2': ('application/x-bzip2', 'tbz2', '.tar.bz2', None), | |
116 | 'gz': ('application/x-gzip', 'tgz', '.tar.gz', None), |
|
116 | 'gz': ('application/x-gzip', 'tgz', '.tar.gz', None), | |
117 | 'zip': ('application/zip', 'zip', '.zip', None), |
|
117 | 'zip': ('application/zip', 'zip', '.zip', None), | |
118 | } |
|
118 | } | |
119 |
|
119 | |||
120 | def archivelist(self, nodeid): |
|
120 | def archivelist(self, nodeid): | |
121 | allowed = self.configlist('web', 'allow_archive') |
|
121 | allowed = self.configlist('web', 'allow_archive') | |
122 | for typ, spec in self.archivespecs.iteritems(): |
|
122 | for typ, spec in self.archivespecs.iteritems(): | |
123 | if typ in allowed or self.configbool('web', 'allow%s' % typ): |
|
123 | if typ in allowed or self.configbool('web', 'allow%s' % typ): | |
124 | yield {'type': typ, 'extension': spec[2], 'node': nodeid} |
|
124 | yield {'type': typ, 'extension': spec[2], 'node': nodeid} | |
125 |
|
125 | |||
126 | class hgweb(object): |
|
126 | class hgweb(object): | |
127 | """HTTP server for individual repositories. |
|
127 | """HTTP server for individual repositories. | |
128 |
|
128 | |||
129 | Instances of this class serve HTTP responses for a particular |
|
129 | Instances of this class serve HTTP responses for a particular | |
130 | repository. |
|
130 | repository. | |
131 |
|
131 | |||
132 | Instances are typically used as WSGI applications. |
|
132 | Instances are typically used as WSGI applications. | |
133 |
|
133 | |||
134 | Some servers are multi-threaded. On these servers, there may |
|
134 | Some servers are multi-threaded. On these servers, there may | |
135 | be multiple active threads inside __call__. |
|
135 | be multiple active threads inside __call__. | |
136 | """ |
|
136 | """ | |
137 | def __init__(self, repo, name=None, baseui=None): |
|
137 | def __init__(self, repo, name=None, baseui=None): | |
138 | if isinstance(repo, str): |
|
138 | if isinstance(repo, str): | |
139 | if baseui: |
|
139 | if baseui: | |
140 | u = baseui.copy() |
|
140 | u = baseui.copy() | |
141 | else: |
|
141 | else: | |
142 | u = ui.ui() |
|
142 | u = ui.ui() | |
143 | r = hg.repository(u, repo) |
|
143 | r = hg.repository(u, repo) | |
144 | else: |
|
144 | else: | |
145 | # we trust caller to give us a private copy |
|
145 | # we trust caller to give us a private copy | |
146 | r = repo |
|
146 | r = repo | |
147 |
|
147 | |||
148 | r = self._getview(r) |
|
148 | r = self._getview(r) | |
149 | r.ui.setconfig('ui', 'report_untrusted', 'off', 'hgweb') |
|
149 | r.ui.setconfig('ui', 'report_untrusted', 'off', 'hgweb') | |
150 | r.baseui.setconfig('ui', 'report_untrusted', 'off', 'hgweb') |
|
150 | r.baseui.setconfig('ui', 'report_untrusted', 'off', 'hgweb') | |
151 | r.ui.setconfig('ui', 'nontty', 'true', 'hgweb') |
|
151 | r.ui.setconfig('ui', 'nontty', 'true', 'hgweb') | |
152 | r.baseui.setconfig('ui', 'nontty', 'true', 'hgweb') |
|
152 | r.baseui.setconfig('ui', 'nontty', 'true', 'hgweb') | |
153 | # displaying bundling progress bar while serving feel wrong and may |
|
153 | # displaying bundling progress bar while serving feel wrong and may | |
154 | # break some wsgi implementation. |
|
154 | # break some wsgi implementation. | |
155 | r.ui.setconfig('progress', 'disable', 'true', 'hgweb') |
|
155 | r.ui.setconfig('progress', 'disable', 'true', 'hgweb') | |
156 | r.baseui.setconfig('progress', 'disable', 'true', 'hgweb') |
|
156 | r.baseui.setconfig('progress', 'disable', 'true', 'hgweb') | |
157 | self.repo = r |
|
157 | self.repo = r | |
158 | hook.redirect(True) |
|
158 | hook.redirect(True) | |
159 | self.repostate = None |
|
159 | self.repostate = None | |
160 | self.mtime = -1 |
|
160 | self.mtime = -1 | |
161 | self.reponame = name |
|
161 | self.reponame = name | |
162 | # we use untrusted=False to prevent a repo owner from using |
|
162 | # we use untrusted=False to prevent a repo owner from using | |
163 | # web.templates in .hg/hgrc to get access to any file readable |
|
163 | # web.templates in .hg/hgrc to get access to any file readable | |
164 | # by the user running the CGI script |
|
164 | # by the user running the CGI script | |
165 | self.templatepath = self.config('web', 'templates', untrusted=False) |
|
165 | self.templatepath = self.config('web', 'templates', untrusted=False) | |
166 | self.websubtable = self.loadwebsub() |
|
166 | self.websubtable = self.loadwebsub() | |
167 |
|
167 | |||
168 | # The CGI scripts are often run by a user different from the repo owner. |
|
168 | # The CGI scripts are often run by a user different from the repo owner. | |
169 | # Trust the settings from the .hg/hgrc files by default. |
|
169 | # Trust the settings from the .hg/hgrc files by default. | |
170 | def config(self, section, name, default=None, untrusted=True): |
|
170 | def config(self, section, name, default=None, untrusted=True): | |
171 | return self.repo.ui.config(section, name, default, |
|
171 | return self.repo.ui.config(section, name, default, | |
172 | untrusted=untrusted) |
|
172 | untrusted=untrusted) | |
173 |
|
173 | |||
174 | def configbool(self, section, name, default=False, untrusted=True): |
|
|||
175 | return self.repo.ui.configbool(section, name, default, |
|
|||
176 | untrusted=untrusted) |
|
|||
177 |
|
||||
178 | def _getview(self, repo): |
|
174 | def _getview(self, repo): | |
179 | """The 'web.view' config controls changeset filter to hgweb. Possible |
|
175 | """The 'web.view' config controls changeset filter to hgweb. Possible | |
180 | values are ``served``, ``visible`` and ``all``. Default is ``served``. |
|
176 | values are ``served``, ``visible`` and ``all``. Default is ``served``. | |
181 | The ``served`` filter only shows changesets that can be pulled from the |
|
177 | The ``served`` filter only shows changesets that can be pulled from the | |
182 | hgweb instance. The``visible`` filter includes secret changesets but |
|
178 | hgweb instance. The``visible`` filter includes secret changesets but | |
183 | still excludes "hidden" one. |
|
179 | still excludes "hidden" one. | |
184 |
|
180 | |||
185 | See the repoview module for details. |
|
181 | See the repoview module for details. | |
186 |
|
182 | |||
187 | The option has been around undocumented since Mercurial 2.5, but no |
|
183 | The option has been around undocumented since Mercurial 2.5, but no | |
188 | user ever asked about it. So we better keep it undocumented for now.""" |
|
184 | user ever asked about it. So we better keep it undocumented for now.""" | |
189 | viewconfig = repo.ui.config('web', 'view', 'served', |
|
185 | viewconfig = repo.ui.config('web', 'view', 'served', | |
190 | untrusted=True) |
|
186 | untrusted=True) | |
191 | if viewconfig == 'all': |
|
187 | if viewconfig == 'all': | |
192 | return repo.unfiltered() |
|
188 | return repo.unfiltered() | |
193 | elif viewconfig in repoview.filtertable: |
|
189 | elif viewconfig in repoview.filtertable: | |
194 | return repo.filtered(viewconfig) |
|
190 | return repo.filtered(viewconfig) | |
195 | else: |
|
191 | else: | |
196 | return repo.filtered('served') |
|
192 | return repo.filtered('served') | |
197 |
|
193 | |||
198 | def refresh(self): |
|
194 | def refresh(self): | |
199 | repostate = [] |
|
195 | repostate = [] | |
200 | # file of interrests mtime and size |
|
196 | # file of interrests mtime and size | |
201 | for meth, fname in foi: |
|
197 | for meth, fname in foi: | |
202 | prefix = getattr(self.repo, meth) |
|
198 | prefix = getattr(self.repo, meth) | |
203 | st = get_stat(prefix, fname) |
|
199 | st = get_stat(prefix, fname) | |
204 | repostate.append((st.st_mtime, st.st_size)) |
|
200 | repostate.append((st.st_mtime, st.st_size)) | |
205 | repostate = tuple(repostate) |
|
201 | repostate = tuple(repostate) | |
206 | # we need to compare file size in addition to mtime to catch |
|
202 | # we need to compare file size in addition to mtime to catch | |
207 | # changes made less than a second ago |
|
203 | # changes made less than a second ago | |
208 | if repostate != self.repostate: |
|
204 | if repostate != self.repostate: | |
209 | r = hg.repository(self.repo.baseui, self.repo.url()) |
|
205 | r = hg.repository(self.repo.baseui, self.repo.url()) | |
210 | self.repo = self._getview(r) |
|
206 | self.repo = self._getview(r) | |
211 | # update these last to avoid threads seeing empty settings |
|
207 | # update these last to avoid threads seeing empty settings | |
212 | self.repostate = repostate |
|
208 | self.repostate = repostate | |
213 | # mtime is needed for ETag |
|
209 | # mtime is needed for ETag | |
214 | self.mtime = st.st_mtime |
|
210 | self.mtime = st.st_mtime | |
215 |
|
211 | |||
216 | def run(self): |
|
212 | def run(self): | |
217 | """Start a server from CGI environment. |
|
213 | """Start a server from CGI environment. | |
218 |
|
214 | |||
219 | Modern servers should be using WSGI and should avoid this |
|
215 | Modern servers should be using WSGI and should avoid this | |
220 | method, if possible. |
|
216 | method, if possible. | |
221 | """ |
|
217 | """ | |
222 | if not os.environ.get('GATEWAY_INTERFACE', '').startswith("CGI/1."): |
|
218 | if not os.environ.get('GATEWAY_INTERFACE', '').startswith("CGI/1."): | |
223 | raise RuntimeError("This function is only intended to be " |
|
219 | raise RuntimeError("This function is only intended to be " | |
224 | "called while running as a CGI script.") |
|
220 | "called while running as a CGI script.") | |
225 | import mercurial.hgweb.wsgicgi as wsgicgi |
|
221 | import mercurial.hgweb.wsgicgi as wsgicgi | |
226 | wsgicgi.launch(self) |
|
222 | wsgicgi.launch(self) | |
227 |
|
223 | |||
228 | def __call__(self, env, respond): |
|
224 | def __call__(self, env, respond): | |
229 | """Run the WSGI application. |
|
225 | """Run the WSGI application. | |
230 |
|
226 | |||
231 | This may be called by multiple threads. |
|
227 | This may be called by multiple threads. | |
232 | """ |
|
228 | """ | |
233 | req = wsgirequest(env, respond) |
|
229 | req = wsgirequest(env, respond) | |
234 | return self.run_wsgi(req) |
|
230 | return self.run_wsgi(req) | |
235 |
|
231 | |||
236 | def run_wsgi(self, req): |
|
232 | def run_wsgi(self, req): | |
237 | """Internal method to run the WSGI application. |
|
233 | """Internal method to run the WSGI application. | |
238 |
|
234 | |||
239 | This is typically only called by Mercurial. External consumers |
|
235 | This is typically only called by Mercurial. External consumers | |
240 | should be using instances of this class as the WSGI application. |
|
236 | should be using instances of this class as the WSGI application. | |
241 | """ |
|
237 | """ | |
242 | self.refresh() |
|
238 | self.refresh() | |
243 | rctx = requestcontext(self) |
|
239 | rctx = requestcontext(self) | |
244 |
|
240 | |||
245 | # This state is global across all threads. |
|
241 | # This state is global across all threads. | |
246 | encoding.encoding = rctx.config('web', 'encoding', encoding.encoding) |
|
242 | encoding.encoding = rctx.config('web', 'encoding', encoding.encoding) | |
247 | rctx.repo.ui.environ = req.env |
|
243 | rctx.repo.ui.environ = req.env | |
248 |
|
244 | |||
249 | # work with CGI variables to create coherent structure |
|
245 | # work with CGI variables to create coherent structure | |
250 | # use SCRIPT_NAME, PATH_INFO and QUERY_STRING as well as our REPO_NAME |
|
246 | # use SCRIPT_NAME, PATH_INFO and QUERY_STRING as well as our REPO_NAME | |
251 |
|
247 | |||
252 | req.url = req.env['SCRIPT_NAME'] |
|
248 | req.url = req.env['SCRIPT_NAME'] | |
253 | if not req.url.endswith('/'): |
|
249 | if not req.url.endswith('/'): | |
254 | req.url += '/' |
|
250 | req.url += '/' | |
255 | if 'REPO_NAME' in req.env: |
|
251 | if 'REPO_NAME' in req.env: | |
256 | req.url += req.env['REPO_NAME'] + '/' |
|
252 | req.url += req.env['REPO_NAME'] + '/' | |
257 |
|
253 | |||
258 | if 'PATH_INFO' in req.env: |
|
254 | if 'PATH_INFO' in req.env: | |
259 | parts = req.env['PATH_INFO'].strip('/').split('/') |
|
255 | parts = req.env['PATH_INFO'].strip('/').split('/') | |
260 | repo_parts = req.env.get('REPO_NAME', '').split('/') |
|
256 | repo_parts = req.env.get('REPO_NAME', '').split('/') | |
261 | if parts[:len(repo_parts)] == repo_parts: |
|
257 | if parts[:len(repo_parts)] == repo_parts: | |
262 | parts = parts[len(repo_parts):] |
|
258 | parts = parts[len(repo_parts):] | |
263 | query = '/'.join(parts) |
|
259 | query = '/'.join(parts) | |
264 | else: |
|
260 | else: | |
265 | query = req.env['QUERY_STRING'].split('&', 1)[0] |
|
261 | query = req.env['QUERY_STRING'].split('&', 1)[0] | |
266 | query = query.split(';', 1)[0] |
|
262 | query = query.split(';', 1)[0] | |
267 |
|
263 | |||
268 | # process this if it's a protocol request |
|
264 | # process this if it's a protocol request | |
269 | # protocol bits don't need to create any URLs |
|
265 | # protocol bits don't need to create any URLs | |
270 | # and the clients always use the old URL structure |
|
266 | # and the clients always use the old URL structure | |
271 |
|
267 | |||
272 | cmd = req.form.get('cmd', [''])[0] |
|
268 | cmd = req.form.get('cmd', [''])[0] | |
273 | if protocol.iscmd(cmd): |
|
269 | if protocol.iscmd(cmd): | |
274 | try: |
|
270 | try: | |
275 | if query: |
|
271 | if query: | |
276 | raise ErrorResponse(HTTP_NOT_FOUND) |
|
272 | raise ErrorResponse(HTTP_NOT_FOUND) | |
277 | if cmd in perms: |
|
273 | if cmd in perms: | |
278 | self.check_perm(rctx, req, perms[cmd]) |
|
274 | self.check_perm(rctx, req, perms[cmd]) | |
279 | return protocol.call(self.repo, req, cmd) |
|
275 | return protocol.call(self.repo, req, cmd) | |
280 | except ErrorResponse as inst: |
|
276 | except ErrorResponse as inst: | |
281 | # A client that sends unbundle without 100-continue will |
|
277 | # A client that sends unbundle without 100-continue will | |
282 | # break if we respond early. |
|
278 | # break if we respond early. | |
283 | if (cmd == 'unbundle' and |
|
279 | if (cmd == 'unbundle' and | |
284 | (req.env.get('HTTP_EXPECT', |
|
280 | (req.env.get('HTTP_EXPECT', | |
285 | '').lower() != '100-continue') or |
|
281 | '').lower() != '100-continue') or | |
286 | req.env.get('X-HgHttp2', '')): |
|
282 | req.env.get('X-HgHttp2', '')): | |
287 | req.drain() |
|
283 | req.drain() | |
288 | else: |
|
284 | else: | |
289 | req.headers.append(('Connection', 'Close')) |
|
285 | req.headers.append(('Connection', 'Close')) | |
290 | req.respond(inst, protocol.HGTYPE, |
|
286 | req.respond(inst, protocol.HGTYPE, | |
291 | body='0\n%s\n' % inst.message) |
|
287 | body='0\n%s\n' % inst.message) | |
292 | return '' |
|
288 | return '' | |
293 |
|
289 | |||
294 | # translate user-visible url structure to internal structure |
|
290 | # translate user-visible url structure to internal structure | |
295 |
|
291 | |||
296 | args = query.split('/', 2) |
|
292 | args = query.split('/', 2) | |
297 | if 'cmd' not in req.form and args and args[0]: |
|
293 | if 'cmd' not in req.form and args and args[0]: | |
298 |
|
294 | |||
299 | cmd = args.pop(0) |
|
295 | cmd = args.pop(0) | |
300 | style = cmd.rfind('-') |
|
296 | style = cmd.rfind('-') | |
301 | if style != -1: |
|
297 | if style != -1: | |
302 | req.form['style'] = [cmd[:style]] |
|
298 | req.form['style'] = [cmd[:style]] | |
303 | cmd = cmd[style + 1:] |
|
299 | cmd = cmd[style + 1:] | |
304 |
|
300 | |||
305 | # avoid accepting e.g. style parameter as command |
|
301 | # avoid accepting e.g. style parameter as command | |
306 | if util.safehasattr(webcommands, cmd): |
|
302 | if util.safehasattr(webcommands, cmd): | |
307 | req.form['cmd'] = [cmd] |
|
303 | req.form['cmd'] = [cmd] | |
308 |
|
304 | |||
309 | if cmd == 'static': |
|
305 | if cmd == 'static': | |
310 | req.form['file'] = ['/'.join(args)] |
|
306 | req.form['file'] = ['/'.join(args)] | |
311 | else: |
|
307 | else: | |
312 | if args and args[0]: |
|
308 | if args and args[0]: | |
313 | node = args.pop(0).replace('%2F', '/') |
|
309 | node = args.pop(0).replace('%2F', '/') | |
314 | req.form['node'] = [node] |
|
310 | req.form['node'] = [node] | |
315 | if args: |
|
311 | if args: | |
316 | req.form['file'] = args |
|
312 | req.form['file'] = args | |
317 |
|
313 | |||
318 | ua = req.env.get('HTTP_USER_AGENT', '') |
|
314 | ua = req.env.get('HTTP_USER_AGENT', '') | |
319 | if cmd == 'rev' and 'mercurial' in ua: |
|
315 | if cmd == 'rev' and 'mercurial' in ua: | |
320 | req.form['style'] = ['raw'] |
|
316 | req.form['style'] = ['raw'] | |
321 |
|
317 | |||
322 | if cmd == 'archive': |
|
318 | if cmd == 'archive': | |
323 | fn = req.form['node'][0] |
|
319 | fn = req.form['node'][0] | |
324 | for type_, spec in rctx.archivespecs.iteritems(): |
|
320 | for type_, spec in rctx.archivespecs.iteritems(): | |
325 | ext = spec[2] |
|
321 | ext = spec[2] | |
326 | if fn.endswith(ext): |
|
322 | if fn.endswith(ext): | |
327 | req.form['node'] = [fn[:-len(ext)]] |
|
323 | req.form['node'] = [fn[:-len(ext)]] | |
328 | req.form['type'] = [type_] |
|
324 | req.form['type'] = [type_] | |
329 |
|
325 | |||
330 | # process the web interface request |
|
326 | # process the web interface request | |
331 |
|
327 | |||
332 | try: |
|
328 | try: | |
333 | tmpl = self.templater(req) |
|
329 | tmpl = self.templater(req) | |
334 | ctype = tmpl('mimetype', encoding=encoding.encoding) |
|
330 | ctype = tmpl('mimetype', encoding=encoding.encoding) | |
335 | ctype = templater.stringify(ctype) |
|
331 | ctype = templater.stringify(ctype) | |
336 |
|
332 | |||
337 | # check read permissions non-static content |
|
333 | # check read permissions non-static content | |
338 | if cmd != 'static': |
|
334 | if cmd != 'static': | |
339 | self.check_perm(rctx, req, None) |
|
335 | self.check_perm(rctx, req, None) | |
340 |
|
336 | |||
341 | if cmd == '': |
|
337 | if cmd == '': | |
342 | req.form['cmd'] = [tmpl.cache['default']] |
|
338 | req.form['cmd'] = [tmpl.cache['default']] | |
343 | cmd = req.form['cmd'][0] |
|
339 | cmd = req.form['cmd'][0] | |
344 |
|
340 | |||
345 |
if |
|
341 | if rctx.configbool('web', 'cache', True): | |
346 | caching(self, req) # sets ETag header or raises NOT_MODIFIED |
|
342 | caching(self, req) # sets ETag header or raises NOT_MODIFIED | |
347 | if cmd not in webcommands.__all__: |
|
343 | if cmd not in webcommands.__all__: | |
348 | msg = 'no such method: %s' % cmd |
|
344 | msg = 'no such method: %s' % cmd | |
349 | raise ErrorResponse(HTTP_BAD_REQUEST, msg) |
|
345 | raise ErrorResponse(HTTP_BAD_REQUEST, msg) | |
350 | elif cmd == 'file' and 'raw' in req.form.get('style', []): |
|
346 | elif cmd == 'file' and 'raw' in req.form.get('style', []): | |
351 | self.ctype = ctype |
|
347 | self.ctype = ctype | |
352 | content = webcommands.rawfile(rctx, req, tmpl) |
|
348 | content = webcommands.rawfile(rctx, req, tmpl) | |
353 | else: |
|
349 | else: | |
354 | content = getattr(webcommands, cmd)(rctx, req, tmpl) |
|
350 | content = getattr(webcommands, cmd)(rctx, req, tmpl) | |
355 | req.respond(HTTP_OK, ctype) |
|
351 | req.respond(HTTP_OK, ctype) | |
356 |
|
352 | |||
357 | return content |
|
353 | return content | |
358 |
|
354 | |||
359 | except (error.LookupError, error.RepoLookupError) as err: |
|
355 | except (error.LookupError, error.RepoLookupError) as err: | |
360 | req.respond(HTTP_NOT_FOUND, ctype) |
|
356 | req.respond(HTTP_NOT_FOUND, ctype) | |
361 | msg = str(err) |
|
357 | msg = str(err) | |
362 | if (util.safehasattr(err, 'name') and |
|
358 | if (util.safehasattr(err, 'name') and | |
363 | not isinstance(err, error.ManifestLookupError)): |
|
359 | not isinstance(err, error.ManifestLookupError)): | |
364 | msg = 'revision not found: %s' % err.name |
|
360 | msg = 'revision not found: %s' % err.name | |
365 | return tmpl('error', error=msg) |
|
361 | return tmpl('error', error=msg) | |
366 | except (error.RepoError, error.RevlogError) as inst: |
|
362 | except (error.RepoError, error.RevlogError) as inst: | |
367 | req.respond(HTTP_SERVER_ERROR, ctype) |
|
363 | req.respond(HTTP_SERVER_ERROR, ctype) | |
368 | return tmpl('error', error=str(inst)) |
|
364 | return tmpl('error', error=str(inst)) | |
369 | except ErrorResponse as inst: |
|
365 | except ErrorResponse as inst: | |
370 | req.respond(inst, ctype) |
|
366 | req.respond(inst, ctype) | |
371 | if inst.code == HTTP_NOT_MODIFIED: |
|
367 | if inst.code == HTTP_NOT_MODIFIED: | |
372 | # Not allowed to return a body on a 304 |
|
368 | # Not allowed to return a body on a 304 | |
373 | return [''] |
|
369 | return [''] | |
374 | return tmpl('error', error=inst.message) |
|
370 | return tmpl('error', error=inst.message) | |
375 |
|
371 | |||
376 | def loadwebsub(self): |
|
372 | def loadwebsub(self): | |
377 | websubtable = [] |
|
373 | websubtable = [] | |
378 | websubdefs = self.repo.ui.configitems('websub') |
|
374 | websubdefs = self.repo.ui.configitems('websub') | |
379 | # we must maintain interhg backwards compatibility |
|
375 | # we must maintain interhg backwards compatibility | |
380 | websubdefs += self.repo.ui.configitems('interhg') |
|
376 | websubdefs += self.repo.ui.configitems('interhg') | |
381 | for key, pattern in websubdefs: |
|
377 | for key, pattern in websubdefs: | |
382 | # grab the delimiter from the character after the "s" |
|
378 | # grab the delimiter from the character after the "s" | |
383 | unesc = pattern[1] |
|
379 | unesc = pattern[1] | |
384 | delim = re.escape(unesc) |
|
380 | delim = re.escape(unesc) | |
385 |
|
381 | |||
386 | # identify portions of the pattern, taking care to avoid escaped |
|
382 | # identify portions of the pattern, taking care to avoid escaped | |
387 | # delimiters. the replace format and flags are optional, but |
|
383 | # delimiters. the replace format and flags are optional, but | |
388 | # delimiters are required. |
|
384 | # delimiters are required. | |
389 | match = re.match( |
|
385 | match = re.match( | |
390 | r'^s%s(.+)(?:(?<=\\\\)|(?<!\\))%s(.*)%s([ilmsux])*$' |
|
386 | r'^s%s(.+)(?:(?<=\\\\)|(?<!\\))%s(.*)%s([ilmsux])*$' | |
391 | % (delim, delim, delim), pattern) |
|
387 | % (delim, delim, delim), pattern) | |
392 | if not match: |
|
388 | if not match: | |
393 | self.repo.ui.warn(_("websub: invalid pattern for %s: %s\n") |
|
389 | self.repo.ui.warn(_("websub: invalid pattern for %s: %s\n") | |
394 | % (key, pattern)) |
|
390 | % (key, pattern)) | |
395 | continue |
|
391 | continue | |
396 |
|
392 | |||
397 | # we need to unescape the delimiter for regexp and format |
|
393 | # we need to unescape the delimiter for regexp and format | |
398 | delim_re = re.compile(r'(?<!\\)\\%s' % delim) |
|
394 | delim_re = re.compile(r'(?<!\\)\\%s' % delim) | |
399 | regexp = delim_re.sub(unesc, match.group(1)) |
|
395 | regexp = delim_re.sub(unesc, match.group(1)) | |
400 | format = delim_re.sub(unesc, match.group(2)) |
|
396 | format = delim_re.sub(unesc, match.group(2)) | |
401 |
|
397 | |||
402 | # the pattern allows for 6 regexp flags, so set them if necessary |
|
398 | # the pattern allows for 6 regexp flags, so set them if necessary | |
403 | flagin = match.group(3) |
|
399 | flagin = match.group(3) | |
404 | flags = 0 |
|
400 | flags = 0 | |
405 | if flagin: |
|
401 | if flagin: | |
406 | for flag in flagin.upper(): |
|
402 | for flag in flagin.upper(): | |
407 | flags |= re.__dict__[flag] |
|
403 | flags |= re.__dict__[flag] | |
408 |
|
404 | |||
409 | try: |
|
405 | try: | |
410 | regexp = re.compile(regexp, flags) |
|
406 | regexp = re.compile(regexp, flags) | |
411 | websubtable.append((regexp, format)) |
|
407 | websubtable.append((regexp, format)) | |
412 | except re.error: |
|
408 | except re.error: | |
413 | self.repo.ui.warn(_("websub: invalid regexp for %s: %s\n") |
|
409 | self.repo.ui.warn(_("websub: invalid regexp for %s: %s\n") | |
414 | % (key, regexp)) |
|
410 | % (key, regexp)) | |
415 | return websubtable |
|
411 | return websubtable | |
416 |
|
412 | |||
417 | def templater(self, req): |
|
413 | def templater(self, req): | |
418 |
|
414 | |||
419 | # determine scheme, port and server name |
|
415 | # determine scheme, port and server name | |
420 | # this is needed to create absolute urls |
|
416 | # this is needed to create absolute urls | |
421 |
|
417 | |||
422 | proto = req.env.get('wsgi.url_scheme') |
|
418 | proto = req.env.get('wsgi.url_scheme') | |
423 | if proto == 'https': |
|
419 | if proto == 'https': | |
424 | proto = 'https' |
|
420 | proto = 'https' | |
425 | default_port = "443" |
|
421 | default_port = "443" | |
426 | else: |
|
422 | else: | |
427 | proto = 'http' |
|
423 | proto = 'http' | |
428 | default_port = "80" |
|
424 | default_port = "80" | |
429 |
|
425 | |||
430 | port = req.env["SERVER_PORT"] |
|
426 | port = req.env["SERVER_PORT"] | |
431 | port = port != default_port and (":" + port) or "" |
|
427 | port = port != default_port and (":" + port) or "" | |
432 | urlbase = '%s://%s%s' % (proto, req.env['SERVER_NAME'], port) |
|
428 | urlbase = '%s://%s%s' % (proto, req.env['SERVER_NAME'], port) | |
433 | logourl = self.config("web", "logourl", "http://mercurial.selenic.com/") |
|
429 | logourl = self.config("web", "logourl", "http://mercurial.selenic.com/") | |
434 | logoimg = self.config("web", "logoimg", "hglogo.png") |
|
430 | logoimg = self.config("web", "logoimg", "hglogo.png") | |
435 | staticurl = self.config("web", "staticurl") or req.url + 'static/' |
|
431 | staticurl = self.config("web", "staticurl") or req.url + 'static/' | |
436 | if not staticurl.endswith('/'): |
|
432 | if not staticurl.endswith('/'): | |
437 | staticurl += '/' |
|
433 | staticurl += '/' | |
438 |
|
434 | |||
439 | # some functions for the templater |
|
435 | # some functions for the templater | |
440 |
|
436 | |||
441 | def motd(**map): |
|
437 | def motd(**map): | |
442 | yield self.config("web", "motd", "") |
|
438 | yield self.config("web", "motd", "") | |
443 |
|
439 | |||
444 | # figure out which style to use |
|
440 | # figure out which style to use | |
445 |
|
441 | |||
446 | vars = {} |
|
442 | vars = {} | |
447 | styles = ( |
|
443 | styles = ( | |
448 | req.form.get('style', [None])[0], |
|
444 | req.form.get('style', [None])[0], | |
449 | self.config('web', 'style'), |
|
445 | self.config('web', 'style'), | |
450 | 'paper', |
|
446 | 'paper', | |
451 | ) |
|
447 | ) | |
452 | style, mapfile = templater.stylemap(styles, self.templatepath) |
|
448 | style, mapfile = templater.stylemap(styles, self.templatepath) | |
453 | if style == styles[0]: |
|
449 | if style == styles[0]: | |
454 | vars['style'] = style |
|
450 | vars['style'] = style | |
455 |
|
451 | |||
456 | start = req.url[-1] == '?' and '&' or '?' |
|
452 | start = req.url[-1] == '?' and '&' or '?' | |
457 | sessionvars = webutil.sessionvars(vars, start) |
|
453 | sessionvars = webutil.sessionvars(vars, start) | |
458 |
|
454 | |||
459 | if not self.reponame: |
|
455 | if not self.reponame: | |
460 | self.reponame = (self.config("web", "name") |
|
456 | self.reponame = (self.config("web", "name") | |
461 | or req.env.get('REPO_NAME') |
|
457 | or req.env.get('REPO_NAME') | |
462 | or req.url.strip('/') or self.repo.root) |
|
458 | or req.url.strip('/') or self.repo.root) | |
463 |
|
459 | |||
464 | def websubfilter(text): |
|
460 | def websubfilter(text): | |
465 | return websub(text, self.websubtable) |
|
461 | return websub(text, self.websubtable) | |
466 |
|
462 | |||
467 | # create the templater |
|
463 | # create the templater | |
468 |
|
464 | |||
469 | tmpl = templater.templater(mapfile, |
|
465 | tmpl = templater.templater(mapfile, | |
470 | filters={"websub": websubfilter}, |
|
466 | filters={"websub": websubfilter}, | |
471 | defaults={"url": req.url, |
|
467 | defaults={"url": req.url, | |
472 | "logourl": logourl, |
|
468 | "logourl": logourl, | |
473 | "logoimg": logoimg, |
|
469 | "logoimg": logoimg, | |
474 | "staticurl": staticurl, |
|
470 | "staticurl": staticurl, | |
475 | "urlbase": urlbase, |
|
471 | "urlbase": urlbase, | |
476 | "repo": self.reponame, |
|
472 | "repo": self.reponame, | |
477 | "encoding": encoding.encoding, |
|
473 | "encoding": encoding.encoding, | |
478 | "motd": motd, |
|
474 | "motd": motd, | |
479 | "sessionvars": sessionvars, |
|
475 | "sessionvars": sessionvars, | |
480 | "pathdef": makebreadcrumb(req.url), |
|
476 | "pathdef": makebreadcrumb(req.url), | |
481 | "style": style, |
|
477 | "style": style, | |
482 | }) |
|
478 | }) | |
483 | return tmpl |
|
479 | return tmpl | |
484 |
|
480 | |||
485 | def check_perm(self, rctx, req, op): |
|
481 | def check_perm(self, rctx, req, op): | |
486 | for permhook in permhooks: |
|
482 | for permhook in permhooks: | |
487 | permhook(rctx, req, op) |
|
483 | permhook(rctx, req, op) |
General Comments 0
You need to be logged in to leave comments.
Login now