##// END OF EJS Templates
hgweb: more "headers are native strs" cleanup...
Augie Fackler -
r34744:dc2bf707 default
parent child Browse files
Show More
@@ -1,207 +1,207 b''
1 #
1 #
2 # Copyright 21 May 2005 - (c) 2005 Jake Edge <jake@edge2.net>
2 # Copyright 21 May 2005 - (c) 2005 Jake Edge <jake@edge2.net>
3 # Copyright 2005-2007 Matt Mackall <mpm@selenic.com>
3 # Copyright 2005-2007 Matt Mackall <mpm@selenic.com>
4 #
4 #
5 # This software may be used and distributed according to the terms of the
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.
6 # GNU General Public License version 2 or any later version.
7
7
8 from __future__ import absolute_import
8 from __future__ import absolute_import
9
9
10 import cgi
10 import cgi
11 import struct
11 import struct
12
12
13 from .common import (
13 from .common import (
14 HTTP_OK,
14 HTTP_OK,
15 )
15 )
16
16
17 from .. import (
17 from .. import (
18 error,
18 error,
19 pycompat,
19 pycompat,
20 util,
20 util,
21 wireproto,
21 wireproto,
22 )
22 )
23 stringio = util.stringio
23 stringio = util.stringio
24
24
25 urlerr = util.urlerr
25 urlerr = util.urlerr
26 urlreq = util.urlreq
26 urlreq = util.urlreq
27
27
28 HGTYPE = 'application/mercurial-0.1'
28 HGTYPE = 'application/mercurial-0.1'
29 HGTYPE2 = 'application/mercurial-0.2'
29 HGTYPE2 = 'application/mercurial-0.2'
30 HGERRTYPE = 'application/hg-error'
30 HGERRTYPE = 'application/hg-error'
31
31
32 def decodevaluefromheaders(req, headerprefix):
32 def decodevaluefromheaders(req, headerprefix):
33 """Decode a long value from multiple HTTP request headers."""
33 """Decode a long value from multiple HTTP request headers."""
34 chunks = []
34 chunks = []
35 i = 1
35 i = 1
36 while True:
36 while True:
37 v = req.env.get('HTTP_%s_%d' % (
37 v = req.env.get('HTTP_%s_%d' % (
38 headerprefix.upper().replace('-', '_'), i))
38 headerprefix.upper().replace('-', '_'), i))
39 if v is None:
39 if v is None:
40 break
40 break
41 chunks.append(v)
41 chunks.append(v)
42 i += 1
42 i += 1
43
43
44 return ''.join(chunks)
44 return ''.join(chunks)
45
45
46 class webproto(wireproto.abstractserverproto):
46 class webproto(wireproto.abstractserverproto):
47 def __init__(self, req, ui):
47 def __init__(self, req, ui):
48 self.req = req
48 self.req = req
49 self.response = ''
49 self.response = ''
50 self.ui = ui
50 self.ui = ui
51 self.name = 'http'
51 self.name = 'http'
52
52
53 def getargs(self, args):
53 def getargs(self, args):
54 knownargs = self._args()
54 knownargs = self._args()
55 data = {}
55 data = {}
56 keys = args.split()
56 keys = args.split()
57 for k in keys:
57 for k in keys:
58 if k == '*':
58 if k == '*':
59 star = {}
59 star = {}
60 for key in knownargs.keys():
60 for key in knownargs.keys():
61 if key != 'cmd' and key not in keys:
61 if key != 'cmd' and key not in keys:
62 star[key] = knownargs[key][0]
62 star[key] = knownargs[key][0]
63 data['*'] = star
63 data['*'] = star
64 else:
64 else:
65 data[k] = knownargs[k][0]
65 data[k] = knownargs[k][0]
66 return [data[k] for k in keys]
66 return [data[k] for k in keys]
67 def _args(self):
67 def _args(self):
68 args = self.req.form.copy()
68 args = self.req.form.copy()
69 if pycompat.ispy3:
69 if pycompat.ispy3:
70 args = {k.encode('ascii'): [v.encode('ascii') for v in vs]
70 args = {k.encode('ascii'): [v.encode('ascii') for v in vs]
71 for k, vs in args.items()}
71 for k, vs in args.items()}
72 postlen = int(self.req.env.get('HTTP_X_HGARGS_POST', 0))
72 postlen = int(self.req.env.get(r'HTTP_X_HGARGS_POST', 0))
73 if postlen:
73 if postlen:
74 args.update(cgi.parse_qs(
74 args.update(cgi.parse_qs(
75 self.req.read(postlen), keep_blank_values=True))
75 self.req.read(postlen), keep_blank_values=True))
76 return args
76 return args
77
77
78 argvalue = decodevaluefromheaders(self.req, 'X-HgArg')
78 argvalue = decodevaluefromheaders(self.req, r'X-HgArg')
79 args.update(cgi.parse_qs(argvalue, keep_blank_values=True))
79 args.update(cgi.parse_qs(argvalue, keep_blank_values=True))
80 return args
80 return args
81 def getfile(self, fp):
81 def getfile(self, fp):
82 length = int(self.req.env[r'CONTENT_LENGTH'])
82 length = int(self.req.env[r'CONTENT_LENGTH'])
83 # If httppostargs is used, we need to read Content-Length
83 # If httppostargs is used, we need to read Content-Length
84 # minus the amount that was consumed by args.
84 # minus the amount that was consumed by args.
85 length -= int(self.req.env.get(r'HTTP_X_HGARGS_POST', 0))
85 length -= int(self.req.env.get(r'HTTP_X_HGARGS_POST', 0))
86 for s in util.filechunkiter(self.req, limit=length):
86 for s in util.filechunkiter(self.req, limit=length):
87 fp.write(s)
87 fp.write(s)
88 def redirect(self):
88 def redirect(self):
89 self.oldio = self.ui.fout, self.ui.ferr
89 self.oldio = self.ui.fout, self.ui.ferr
90 self.ui.ferr = self.ui.fout = stringio()
90 self.ui.ferr = self.ui.fout = stringio()
91 def restore(self):
91 def restore(self):
92 val = self.ui.fout.getvalue()
92 val = self.ui.fout.getvalue()
93 self.ui.ferr, self.ui.fout = self.oldio
93 self.ui.ferr, self.ui.fout = self.oldio
94 return val
94 return val
95
95
96 def _client(self):
96 def _client(self):
97 return 'remote:%s:%s:%s' % (
97 return 'remote:%s:%s:%s' % (
98 self.req.env.get('wsgi.url_scheme') or 'http',
98 self.req.env.get('wsgi.url_scheme') or 'http',
99 urlreq.quote(self.req.env.get('REMOTE_HOST', '')),
99 urlreq.quote(self.req.env.get('REMOTE_HOST', '')),
100 urlreq.quote(self.req.env.get('REMOTE_USER', '')))
100 urlreq.quote(self.req.env.get('REMOTE_USER', '')))
101
101
102 def responsetype(self, v1compressible=False):
102 def responsetype(self, v1compressible=False):
103 """Determine the appropriate response type and compression settings.
103 """Determine the appropriate response type and compression settings.
104
104
105 The ``v1compressible`` argument states whether the response with
105 The ``v1compressible`` argument states whether the response with
106 application/mercurial-0.1 media types should be zlib compressed.
106 application/mercurial-0.1 media types should be zlib compressed.
107
107
108 Returns a tuple of (mediatype, compengine, engineopts).
108 Returns a tuple of (mediatype, compengine, engineopts).
109 """
109 """
110 # For now, if it isn't compressible in the old world, it's never
110 # For now, if it isn't compressible in the old world, it's never
111 # compressible. We can change this to send uncompressed 0.2 payloads
111 # compressible. We can change this to send uncompressed 0.2 payloads
112 # later.
112 # later.
113 if not v1compressible:
113 if not v1compressible:
114 return HGTYPE, None, None
114 return HGTYPE, None, None
115
115
116 # Determine the response media type and compression engine based
116 # Determine the response media type and compression engine based
117 # on the request parameters.
117 # on the request parameters.
118 protocaps = decodevaluefromheaders(self.req, 'X-HgProto').split(' ')
118 protocaps = decodevaluefromheaders(self.req, r'X-HgProto').split(' ')
119
119
120 if '0.2' in protocaps:
120 if '0.2' in protocaps:
121 # Default as defined by wire protocol spec.
121 # Default as defined by wire protocol spec.
122 compformats = ['zlib', 'none']
122 compformats = ['zlib', 'none']
123 for cap in protocaps:
123 for cap in protocaps:
124 if cap.startswith('comp='):
124 if cap.startswith('comp='):
125 compformats = cap[5:].split(',')
125 compformats = cap[5:].split(',')
126 break
126 break
127
127
128 # Now find an agreed upon compression format.
128 # Now find an agreed upon compression format.
129 for engine in wireproto.supportedcompengines(self.ui, self,
129 for engine in wireproto.supportedcompengines(self.ui, self,
130 util.SERVERROLE):
130 util.SERVERROLE):
131 if engine.wireprotosupport().name in compformats:
131 if engine.wireprotosupport().name in compformats:
132 opts = {}
132 opts = {}
133 level = self.ui.configint('server',
133 level = self.ui.configint('server',
134 '%slevel' % engine.name())
134 '%slevel' % engine.name())
135 if level is not None:
135 if level is not None:
136 opts['level'] = level
136 opts['level'] = level
137
137
138 return HGTYPE2, engine, opts
138 return HGTYPE2, engine, opts
139
139
140 # No mutually supported compression format. Fall back to the
140 # No mutually supported compression format. Fall back to the
141 # legacy protocol.
141 # legacy protocol.
142
142
143 # Don't allow untrusted settings because disabling compression or
143 # Don't allow untrusted settings because disabling compression or
144 # setting a very high compression level could lead to flooding
144 # setting a very high compression level could lead to flooding
145 # the server's network or CPU.
145 # the server's network or CPU.
146 opts = {'level': self.ui.configint('server', 'zliblevel')}
146 opts = {'level': self.ui.configint('server', 'zliblevel')}
147 return HGTYPE, util.compengines['zlib'], opts
147 return HGTYPE, util.compengines['zlib'], opts
148
148
149 def iscmd(cmd):
149 def iscmd(cmd):
150 return cmd in wireproto.commands
150 return cmd in wireproto.commands
151
151
152 def call(repo, req, cmd):
152 def call(repo, req, cmd):
153 p = webproto(req, repo.ui)
153 p = webproto(req, repo.ui)
154
154
155 def genversion2(gen, compress, engine, engineopts):
155 def genversion2(gen, compress, engine, engineopts):
156 # application/mercurial-0.2 always sends a payload header
156 # application/mercurial-0.2 always sends a payload header
157 # identifying the compression engine.
157 # identifying the compression engine.
158 name = engine.wireprotosupport().name
158 name = engine.wireprotosupport().name
159 assert 0 < len(name) < 256
159 assert 0 < len(name) < 256
160 yield struct.pack('B', len(name))
160 yield struct.pack('B', len(name))
161 yield name
161 yield name
162
162
163 if compress:
163 if compress:
164 for chunk in engine.compressstream(gen, opts=engineopts):
164 for chunk in engine.compressstream(gen, opts=engineopts):
165 yield chunk
165 yield chunk
166 else:
166 else:
167 for chunk in gen:
167 for chunk in gen:
168 yield chunk
168 yield chunk
169
169
170 rsp = wireproto.dispatch(repo, p, cmd)
170 rsp = wireproto.dispatch(repo, p, cmd)
171 if isinstance(rsp, bytes):
171 if isinstance(rsp, bytes):
172 req.respond(HTTP_OK, HGTYPE, body=rsp)
172 req.respond(HTTP_OK, HGTYPE, body=rsp)
173 return []
173 return []
174 elif isinstance(rsp, wireproto.streamres):
174 elif isinstance(rsp, wireproto.streamres):
175 if rsp.reader:
175 if rsp.reader:
176 gen = iter(lambda: rsp.reader.read(32768), '')
176 gen = iter(lambda: rsp.reader.read(32768), '')
177 else:
177 else:
178 gen = rsp.gen
178 gen = rsp.gen
179
179
180 # This code for compression should not be streamres specific. It
180 # This code for compression should not be streamres specific. It
181 # is here because we only compress streamres at the moment.
181 # is here because we only compress streamres at the moment.
182 mediatype, engine, engineopts = p.responsetype(rsp.v1compressible)
182 mediatype, engine, engineopts = p.responsetype(rsp.v1compressible)
183
183
184 if mediatype == HGTYPE and rsp.v1compressible:
184 if mediatype == HGTYPE and rsp.v1compressible:
185 gen = engine.compressstream(gen, engineopts)
185 gen = engine.compressstream(gen, engineopts)
186 elif mediatype == HGTYPE2:
186 elif mediatype == HGTYPE2:
187 gen = genversion2(gen, rsp.v1compressible, engine, engineopts)
187 gen = genversion2(gen, rsp.v1compressible, engine, engineopts)
188
188
189 req.respond(HTTP_OK, mediatype)
189 req.respond(HTTP_OK, mediatype)
190 return gen
190 return gen
191 elif isinstance(rsp, wireproto.pushres):
191 elif isinstance(rsp, wireproto.pushres):
192 val = p.restore()
192 val = p.restore()
193 rsp = '%d\n%s' % (rsp.res, val)
193 rsp = '%d\n%s' % (rsp.res, val)
194 req.respond(HTTP_OK, HGTYPE, body=rsp)
194 req.respond(HTTP_OK, HGTYPE, body=rsp)
195 return []
195 return []
196 elif isinstance(rsp, wireproto.pusherr):
196 elif isinstance(rsp, wireproto.pusherr):
197 # drain the incoming bundle
197 # drain the incoming bundle
198 req.drain()
198 req.drain()
199 p.restore()
199 p.restore()
200 rsp = '0\n%s\n' % rsp.res
200 rsp = '0\n%s\n' % rsp.res
201 req.respond(HTTP_OK, HGTYPE, body=rsp)
201 req.respond(HTTP_OK, HGTYPE, body=rsp)
202 return []
202 return []
203 elif isinstance(rsp, wireproto.ooberror):
203 elif isinstance(rsp, wireproto.ooberror):
204 rsp = rsp.message
204 rsp = rsp.message
205 req.respond(HTTP_OK, HGERRTYPE, body=rsp)
205 req.respond(HTTP_OK, HGERRTYPE, body=rsp)
206 return []
206 return []
207 raise error.ProgrammingError('hgweb.protocol internal failure', rsp)
207 raise error.ProgrammingError('hgweb.protocol internal failure', rsp)
General Comments 0
You need to be logged in to leave comments. Login now