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