Show More
@@ -1,297 +1,291 | |||
|
1 | 1 | # hgweb/server.py - The standalone hg web server. |
|
2 | 2 | # |
|
3 | 3 | # Copyright 21 May 2005 - (c) 2005 Jake Edge <jake@edge2.net> |
|
4 | 4 | # Copyright 2005-2007 Matt Mackall <mpm@selenic.com> |
|
5 | 5 | # |
|
6 | 6 | # This software may be used and distributed according to the terms of the |
|
7 | 7 | # GNU General Public License version 2 or any later version. |
|
8 | 8 | |
|
9 | 9 | import os, sys, errno, urllib, BaseHTTPServer, socket, SocketServer, traceback |
|
10 | 10 | from mercurial import hg, util, error |
|
11 | 11 | from hgweb_mod import hgweb |
|
12 | 12 | from hgwebdir_mod import hgwebdir |
|
13 | 13 | from mercurial.i18n import _ |
|
14 | 14 | |
|
15 | 15 | def _splitURI(uri): |
|
16 | 16 | """ Return path and query splited from uri |
|
17 | 17 | |
|
18 | 18 | Just like CGI environment, the path is unquoted, the query is |
|
19 | 19 | not. |
|
20 | 20 | """ |
|
21 | 21 | if '?' in uri: |
|
22 | 22 | path, query = uri.split('?', 1) |
|
23 | 23 | else: |
|
24 | 24 | path, query = uri, '' |
|
25 | 25 | return urllib.unquote(path), query |
|
26 | 26 | |
|
27 | 27 | class _error_logger(object): |
|
28 | 28 | def __init__(self, handler): |
|
29 | 29 | self.handler = handler |
|
30 | 30 | def flush(self): |
|
31 | 31 | pass |
|
32 | 32 | def write(self, str): |
|
33 | 33 | self.writelines(str.split('\n')) |
|
34 | 34 | def writelines(self, seq): |
|
35 | 35 | for msg in seq: |
|
36 | 36 | self.handler.log_error("HG error: %s", msg) |
|
37 | 37 | |
|
38 | 38 | class _hgwebhandler(BaseHTTPServer.BaseHTTPRequestHandler): |
|
39 | 39 | |
|
40 | 40 | url_scheme = 'http' |
|
41 | 41 | |
|
42 | 42 | def __init__(self, *args, **kargs): |
|
43 | 43 | self.protocol_version = 'HTTP/1.1' |
|
44 | 44 | BaseHTTPServer.BaseHTTPRequestHandler.__init__(self, *args, **kargs) |
|
45 | 45 | |
|
46 | 46 | def _log_any(self, fp, format, *args): |
|
47 | 47 | fp.write("%s - - [%s] %s\n" % (self.client_address[0], |
|
48 | 48 | self.log_date_time_string(), |
|
49 | 49 | format % args)) |
|
50 | 50 | fp.flush() |
|
51 | 51 | |
|
52 | 52 | def log_error(self, format, *args): |
|
53 | 53 | self._log_any(self.server.errorlog, format, *args) |
|
54 | 54 | |
|
55 | 55 | def log_message(self, format, *args): |
|
56 | 56 | self._log_any(self.server.accesslog, format, *args) |
|
57 | 57 | |
|
58 | 58 | def do_write(self): |
|
59 | 59 | try: |
|
60 | 60 | self.do_hgweb() |
|
61 | 61 | except socket.error, inst: |
|
62 | 62 | if inst[0] != errno.EPIPE: |
|
63 | 63 | raise |
|
64 | 64 | |
|
65 | 65 | def do_POST(self): |
|
66 | 66 | try: |
|
67 | 67 | self.do_write() |
|
68 | 68 | except StandardError: |
|
69 | 69 | self._start_response("500 Internal Server Error", []) |
|
70 | 70 | self._write("Internal Server Error") |
|
71 | 71 | tb = "".join(traceback.format_exception(*sys.exc_info())) |
|
72 | 72 | self.log_error("Exception happened during processing " |
|
73 | 73 | "request '%s':\n%s", self.path, tb) |
|
74 | 74 | |
|
75 | 75 | def do_GET(self): |
|
76 | 76 | self.do_POST() |
|
77 | 77 | |
|
78 | 78 | def do_hgweb(self): |
|
79 | 79 | path, query = _splitURI(self.path) |
|
80 | 80 | |
|
81 | 81 | env = {} |
|
82 | 82 | env['GATEWAY_INTERFACE'] = 'CGI/1.1' |
|
83 | 83 | env['REQUEST_METHOD'] = self.command |
|
84 | 84 | env['SERVER_NAME'] = self.server.server_name |
|
85 | 85 | env['SERVER_PORT'] = str(self.server.server_port) |
|
86 | 86 | env['REQUEST_URI'] = self.path |
|
87 | 87 | env['SCRIPT_NAME'] = self.server.prefix |
|
88 | 88 | env['PATH_INFO'] = path[len(self.server.prefix):] |
|
89 | 89 | env['REMOTE_HOST'] = self.client_address[0] |
|
90 | 90 | env['REMOTE_ADDR'] = self.client_address[0] |
|
91 | 91 | if query: |
|
92 | 92 | env['QUERY_STRING'] = query |
|
93 | 93 | |
|
94 | 94 | if self.headers.typeheader is None: |
|
95 | 95 | env['CONTENT_TYPE'] = self.headers.type |
|
96 | 96 | else: |
|
97 | 97 | env['CONTENT_TYPE'] = self.headers.typeheader |
|
98 | 98 | length = self.headers.getheader('content-length') |
|
99 | 99 | if length: |
|
100 | 100 | env['CONTENT_LENGTH'] = length |
|
101 | 101 | for header in [h for h in self.headers.keys() |
|
102 | 102 | if h not in ('content-type', 'content-length')]: |
|
103 | 103 | hkey = 'HTTP_' + header.replace('-', '_').upper() |
|
104 | 104 | hval = self.headers.getheader(header) |
|
105 | 105 | hval = hval.replace('\n', '').strip() |
|
106 | 106 | if hval: |
|
107 | 107 | env[hkey] = hval |
|
108 | 108 | env['SERVER_PROTOCOL'] = self.request_version |
|
109 | 109 | env['wsgi.version'] = (1, 0) |
|
110 | 110 | env['wsgi.url_scheme'] = self.url_scheme |
|
111 | 111 | env['wsgi.input'] = self.rfile |
|
112 | 112 | env['wsgi.errors'] = _error_logger(self) |
|
113 | 113 | env['wsgi.multithread'] = isinstance(self.server, |
|
114 | 114 | SocketServer.ThreadingMixIn) |
|
115 | 115 | env['wsgi.multiprocess'] = isinstance(self.server, |
|
116 | 116 | SocketServer.ForkingMixIn) |
|
117 | 117 | env['wsgi.run_once'] = 0 |
|
118 | 118 | |
|
119 | 119 | self.close_connection = True |
|
120 | 120 | self.saved_status = None |
|
121 | 121 | self.saved_headers = [] |
|
122 | 122 | self.sent_headers = False |
|
123 | 123 | self.length = None |
|
124 | 124 | for chunk in self.server.application(env, self._start_response): |
|
125 | 125 | self._write(chunk) |
|
126 | 126 | |
|
127 | 127 | def send_headers(self): |
|
128 | 128 | if not self.saved_status: |
|
129 | 129 | raise AssertionError("Sending headers before " |
|
130 | 130 | "start_response() called") |
|
131 | 131 | saved_status = self.saved_status.split(None, 1) |
|
132 | 132 | saved_status[0] = int(saved_status[0]) |
|
133 | 133 | self.send_response(*saved_status) |
|
134 | 134 | should_close = True |
|
135 | 135 | for h in self.saved_headers: |
|
136 | 136 | self.send_header(*h) |
|
137 | 137 | if h[0].lower() == 'content-length': |
|
138 | 138 | should_close = False |
|
139 | 139 | self.length = int(h[1]) |
|
140 | 140 | # The value of the Connection header is a list of case-insensitive |
|
141 | 141 | # tokens separated by commas and optional whitespace. |
|
142 | 142 | if 'close' in [token.strip().lower() for token in |
|
143 | 143 | self.headers.get('connection', '').split(',')]: |
|
144 | 144 | should_close = True |
|
145 | 145 | if should_close: |
|
146 | 146 | self.send_header('Connection', 'close') |
|
147 | 147 | self.close_connection = should_close |
|
148 | 148 | self.end_headers() |
|
149 | 149 | self.sent_headers = True |
|
150 | 150 | |
|
151 | 151 | def _start_response(self, http_status, headers, exc_info=None): |
|
152 | 152 | code, msg = http_status.split(None, 1) |
|
153 | 153 | code = int(code) |
|
154 | 154 | self.saved_status = http_status |
|
155 | 155 | bad_headers = ('connection', 'transfer-encoding') |
|
156 | 156 | self.saved_headers = [h for h in headers |
|
157 | 157 | if h[0].lower() not in bad_headers] |
|
158 | 158 | return self._write |
|
159 | 159 | |
|
160 | 160 | def _write(self, data): |
|
161 | 161 | if not self.saved_status: |
|
162 | 162 | raise AssertionError("data written before start_response() called") |
|
163 | 163 | elif not self.sent_headers: |
|
164 | 164 | self.send_headers() |
|
165 | 165 | if self.length is not None: |
|
166 | 166 | if len(data) > self.length: |
|
167 | 167 | raise AssertionError("Content-length header sent, but more " |
|
168 | 168 | "bytes than specified are being written.") |
|
169 | 169 | self.length = self.length - len(data) |
|
170 | 170 | self.wfile.write(data) |
|
171 | 171 | self.wfile.flush() |
|
172 | 172 | |
|
173 | 173 | class _shgwebhandler(_hgwebhandler): |
|
174 | 174 | |
|
175 | 175 | url_scheme = 'https' |
|
176 | 176 | |
|
177 | 177 | def setup(self): |
|
178 | 178 | self.connection = self.request |
|
179 | 179 | self.rfile = socket._fileobject(self.request, "rb", self.rbufsize) |
|
180 | 180 | self.wfile = socket._fileobject(self.request, "wb", self.wbufsize) |
|
181 | 181 | |
|
182 | 182 | def do_write(self): |
|
183 | 183 | from OpenSSL.SSL import SysCallError |
|
184 | 184 | try: |
|
185 | 185 | super(_shgwebhandler, self).do_write() |
|
186 | 186 | except SysCallError, inst: |
|
187 | 187 | if inst.args[0] != errno.EPIPE: |
|
188 | 188 | raise |
|
189 | 189 | |
|
190 | 190 | def handle_one_request(self): |
|
191 | 191 | from OpenSSL.SSL import SysCallError, ZeroReturnError |
|
192 | 192 | try: |
|
193 | 193 | super(_shgwebhandler, self).handle_one_request() |
|
194 | 194 | except (SysCallError, ZeroReturnError): |
|
195 | 195 | self.close_connection = True |
|
196 | 196 | pass |
|
197 | 197 | |
|
198 | try: | |
|
199 | from threading import activeCount | |
|
200 | _mixin = SocketServer.ThreadingMixIn | |
|
201 | except ImportError: | |
|
202 | if hasattr(os, "fork"): | |
|
203 | _mixin = SocketServer.ForkingMixIn | |
|
204 | else: | |
|
205 | class _mixin: | |
|
206 | pass | |
|
207 | ||
|
198 | 208 | def create_server(ui, repo): |
|
199 | use_threads = True | |
|
200 | 209 | |
|
201 | 210 | def openlog(opt, default): |
|
202 | 211 | if opt and opt != '-': |
|
203 | 212 | return open(opt, 'a') |
|
204 | 213 | return default |
|
205 | 214 | |
|
206 | 215 | if repo is None: |
|
207 | 216 | myui = ui |
|
208 | 217 | else: |
|
209 | 218 | myui = repo.ui |
|
210 | 219 | address = myui.config("web", "address", "") |
|
211 | 220 | port = int(myui.config("web", "port", 8000)) |
|
212 | 221 | prefix = myui.config("web", "prefix", "") |
|
213 | 222 | if prefix: |
|
214 | 223 | prefix = "/" + prefix.strip("/") |
|
215 | 224 | use_ipv6 = myui.configbool("web", "ipv6") |
|
216 | 225 | webdir_conf = myui.config("web", "webdir_conf") |
|
217 | 226 | ssl_cert = myui.config("web", "certificate") |
|
218 | 227 | accesslog = openlog(myui.config("web", "accesslog", "-"), sys.stdout) |
|
219 | 228 | errorlog = openlog(myui.config("web", "errorlog", "-"), sys.stderr) |
|
220 | 229 | |
|
221 | if use_threads: | |
|
222 | try: | |
|
223 | from threading import activeCount | |
|
224 | except ImportError: | |
|
225 | use_threads = False | |
|
226 | ||
|
227 | if use_threads: | |
|
228 | _mixin = SocketServer.ThreadingMixIn | |
|
229 | else: | |
|
230 | if hasattr(os, "fork"): | |
|
231 | _mixin = SocketServer.ForkingMixIn | |
|
232 | else: | |
|
233 | class _mixin: | |
|
234 | pass | |
|
235 | ||
|
236 | 230 | if webdir_conf: |
|
237 | 231 | hgwebobj = hgwebdir(webdir_conf, ui) |
|
238 | 232 | elif repo is not None: |
|
239 | 233 | hgwebobj = hgweb(hg.repository(repo.ui, repo.root)) |
|
240 | 234 | else: |
|
241 | 235 | raise error.RepoError(_("There is no Mercurial repository" |
|
242 | 236 | " here (.hg not found)")) |
|
243 | 237 | |
|
244 | 238 | class MercurialHTTPServer(object, _mixin, BaseHTTPServer.HTTPServer): |
|
245 | 239 | |
|
246 | 240 | # SO_REUSEADDR has broken semantics on windows |
|
247 | 241 | if os.name == 'nt': |
|
248 | 242 | allow_reuse_address = 0 |
|
249 | 243 | |
|
250 | 244 | def __init__(self, *args, **kargs): |
|
251 | 245 | BaseHTTPServer.HTTPServer.__init__(self, *args, **kargs) |
|
252 | 246 | self.accesslog = accesslog |
|
253 | 247 | self.errorlog = errorlog |
|
254 | 248 | self.daemon_threads = True |
|
255 | 249 | self.application = hgwebobj |
|
256 | 250 | |
|
257 | 251 | if ssl_cert: |
|
258 | 252 | try: |
|
259 | 253 | from OpenSSL import SSL |
|
260 | 254 | ctx = SSL.Context(SSL.SSLv23_METHOD) |
|
261 | 255 | except ImportError: |
|
262 | 256 | raise util.Abort(_("SSL support is unavailable")) |
|
263 | 257 | ctx.use_privatekey_file(ssl_cert) |
|
264 | 258 | ctx.use_certificate_file(ssl_cert) |
|
265 | 259 | sock = socket.socket(self.address_family, self.socket_type) |
|
266 | 260 | self.socket = SSL.Connection(ctx, sock) |
|
267 | 261 | self.server_bind() |
|
268 | 262 | self.server_activate() |
|
269 | 263 | |
|
270 | 264 | self.addr, self.port = self.socket.getsockname()[0:2] |
|
271 | 265 | self.prefix = prefix |
|
272 | 266 | self.fqaddr = socket.getfqdn(address) |
|
273 | 267 | |
|
274 | 268 | class IPv6HTTPServer(MercurialHTTPServer): |
|
275 | 269 | address_family = getattr(socket, 'AF_INET6', None) |
|
276 | 270 | |
|
277 | 271 | def __init__(self, *args, **kwargs): |
|
278 | 272 | if self.address_family is None: |
|
279 | 273 | raise error.RepoError(_('IPv6 is not available on this system')) |
|
280 | 274 | super(IPv6HTTPServer, self).__init__(*args, **kwargs) |
|
281 | 275 | |
|
282 | 276 | if ssl_cert: |
|
283 | 277 | handler = _shgwebhandler |
|
284 | 278 | else: |
|
285 | 279 | handler = _hgwebhandler |
|
286 | 280 | |
|
287 | 281 | # ugly hack due to python issue5853 (for threaded use) |
|
288 | 282 | import mimetypes; mimetypes.init() |
|
289 | 283 | |
|
290 | 284 | try: |
|
291 | 285 | if use_ipv6: |
|
292 | 286 | return IPv6HTTPServer((address, port), handler) |
|
293 | 287 | else: |
|
294 | 288 | return MercurialHTTPServer((address, port), handler) |
|
295 | 289 | except socket.error, inst: |
|
296 | 290 | raise util.Abort(_("cannot start server at '%s:%d': %s") |
|
297 | 291 | % (address, port, inst.args[1])) |
General Comments 0
You need to be logged in to leave comments.
Login now