Commit | Line | Data |
---|---|---|
c55f394e | 1 | #!/usr/bin/python3 |
6b926141 IJ |
2 | # |
3 | # Hippotat - Asinine IP Over HTTP program | |
4 | # ./hippotat - client main program | |
5 | # | |
6 | # Copyright 2017 Ian Jackson | |
7 | # | |
f85d143f | 8 | # GPLv3+ |
6b926141 | 9 | # |
f85d143f IJ |
10 | # This program is free software: you can redistribute it and/or modify |
11 | # it under the terms of the GNU General Public License as published by | |
12 | # the Free Software Foundation, either version 3 of the License, or | |
13 | # (at your option) any later version. | |
6b926141 | 14 | # |
f85d143f IJ |
15 | # This program is distributed in the hope that it will be useful, |
16 | # but WITHOUT ANY WARRANTY; without even the implied warranty of | |
17 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the | |
18 | # GNU General Public License for more details. | |
19 | # | |
20 | # You should have received a copy of the GNU General Public License | |
21 | # along with this program, in the file GPLv3. If not, | |
22 | # see <http://www.gnu.org/licenses/>. | |
6b926141 | 23 | |
1d33eef3 | 24 | #@ import sys; sys.path.append('@PYBUILD_INSTALL_DIR@') |
5a37bac8 | 25 | from hippotatlib import * |
c55f394e | 26 | |
c0c90673 IJ |
27 | import twisted.web |
28 | import twisted.web.client | |
29 | ||
dd6665ee IJ |
30 | import io |
31 | ||
0accf0d3 | 32 | class GeneralResponseConsumer(twisted.internet.protocol.Protocol): |
c7fb640e IJ |
33 | def __init__(self, cl, req, desc): |
34 | self._cl = cl | |
8b62cd2c | 35 | self._req = req |
0accf0d3 | 36 | self._desc = desc |
14c6d55c IJ |
37 | |
38 | def _log(self, dflag, msg, **kwargs): | |
74934d63 | 39 | self._cl.log(dflag, '%s: %s' % (self._desc, msg), idof=self._req, **kwargs) |
0accf0d3 IJ |
40 | |
41 | def connectionMade(self): | |
42 | self._log(DBG.HTTP_CTRL, 'connectionMade') | |
43 | ||
44 | class ResponseConsumer(GeneralResponseConsumer): | |
c7fb640e IJ |
45 | def __init__(self, cl, req): |
46 | super().__init__(cl, req, 'RC') | |
0accf0d3 | 47 | ssddesc = '[%s] %s' % (id(req), self._desc) |
909e0ff3 | 48 | self._ssd = SlipStreamDecoder(ssddesc, partial(queue_inbound, cl.ipif)) |
0accf0d3 | 49 | self._log(DBG.HTTP_CTRL, '__init__') |
bd9e77fb | 50 | |
62b51bcf | 51 | def dataReceived(self, data): |
380ed56c | 52 | self._log(DBG.HTTP, 'dataReceived', d=data) |
9b65cdd4 | 53 | try: |
02cdcb52 | 54 | self._ssd.inputdata(data) |
9b65cdd4 | 55 | except Exception as e: |
eedc8b30 | 56 | self._handleexception() |
ccd371b3 | 57 | |
62b51bcf | 58 | def connectionLost(self, reason): |
d5008b7c IJ |
59 | reason_msg = 'connectionLost ' + str(reason) |
60 | self._log(DBG.HTTP_CTRL, reason_msg) | |
765aba55 | 61 | if not reason.check(twisted.web.client.ResponseDone): |
d5008b7c | 62 | self._latefailure(reason_msg) |
765aba55 IJ |
63 | return |
64 | try: | |
380ed56c | 65 | self._log(DBG.HTTP, 'ResponseDone') |
765aba55 | 66 | self._ssd.flush() |
74934d63 | 67 | self._cl.req_fin(self._req) |
765aba55 | 68 | except Exception as e: |
eedc8b30 | 69 | self._handleexception() |
909e0ff3 | 70 | self._cl.report_running() |
eedc8b30 IJ |
71 | |
72 | def _handleexception(self): | |
0accf0d3 | 73 | self._latefailure(traceback.format_exc()) |
33932420 | 74 | |
0accf0d3 | 75 | def _latefailure(self, reason): |
380ed56c | 76 | self._log(DBG.HTTP_CTRL, '_latefailure ' + str(reason)) |
74934d63 | 77 | self._cl.req_err(self._req, reason) |
bd9e77fb | 78 | |
74934d63 | 79 | class ErrorResponseConsumer(GeneralResponseConsumer): |
c7fb640e IJ |
80 | def __init__(self, cl, req, resp): |
81 | super().__init__(cl, req, 'ERROR-RC') | |
6e4af0a2 | 82 | self._resp = resp |
0accf0d3 | 83 | self._m = b'' |
6e4af0a2 IJ |
84 | try: |
85 | self._phrase = resp.phrase.decode('utf-8') | |
86 | except Exception: | |
87 | self._phrase = repr(resp.phrase) | |
6e4af0a2 IJ |
88 | self._log(DBG.HTTP_CTRL, '__init__ %d %s' % (resp.code, self._phrase)) |
89 | ||
765aba55 IJ |
90 | def dataReceived(self, data): |
91 | self._log(DBG.HTTP_CTRL, 'dataReceived ' + repr(data)) | |
92 | self._m += data | |
93 | ||
6e4af0a2 IJ |
94 | def connectionLost(self, reason): |
95 | try: | |
96 | mbody = self._m.decode('utf-8') | |
97 | except Exception: | |
98 | mbody = repr(self._m) | |
765aba55 IJ |
99 | if not reason.check(twisted.web.client.ResponseDone): |
100 | mbody += ' || ' + str(reason) | |
74934d63 | 101 | self._cl.req_err(self._req, |
765aba55 IJ |
102 | "FAILED %d %s | %s" |
103 | % (self._resp.code, self._phrase, mbody)) | |
6e4af0a2 | 104 | |
c7fb640e IJ |
105 | class Client(): |
106 | def __init__(cl, c,ss,cs): | |
107 | cl.c = c | |
108 | cl.outstanding = { } | |
109 | cl.desc = '[%s %s] ' % (ss,cs) | |
909e0ff3 IJ |
110 | cl.running_reported = False |
111 | cl.log_info('setting up') | |
112 | ||
113 | def log_info(cl, msg): | |
114 | log.info(cl.desc + msg, dflag=False) | |
115 | ||
116 | def report_running(cl): | |
117 | if not cl.running_reported: | |
118 | cl.log_info('running OK') | |
119 | cl.running_reported = True | |
c7fb640e IJ |
120 | |
121 | def log(cl, dflag, msg, **kwargs): | |
122 | log_debug(dflag, cl.desc + msg, **kwargs) | |
123 | ||
124 | def log_outstanding(cl): | |
c7f134ce | 125 | cl.log(DBG.CTRL_DUMP, 'OS %s' % cl.outstanding) |
c7fb640e IJ |
126 | |
127 | def start(cl): | |
8d374606 | 128 | cl.queue = PacketQueue('up', cl.c.max_queue_time) |
c7fb640e | 129 | cl.agent = twisted.web.client.Agent( |
8d374606 | 130 | reactor, connectTimeout = cl.c.http_timeout) |
c7fb640e IJ |
131 | |
132 | def outbound(cl, packet, saddr, daddr): | |
133 | #print('OUT ', saddr, daddr, repr(packet)) | |
134 | cl.queue.append(packet) | |
135 | cl.check_outbound() | |
136 | ||
137 | def req_ok(cl, req, resp): | |
138 | cl.log(DBG.HTTP_CTRL, | |
5dd3275b IJ |
139 | 'req_ok %d %s %s' % (resp.code, repr(resp.phrase), str(resp)), |
140 | idof=req) | |
8d374606 IJ |
141 | if resp.code == 200: |
142 | rc = ResponseConsumer(cl, req) | |
143 | else: | |
144 | rc = ErrorResponseConsumer(cl, req, resp) | |
5dd3275b | 145 | |
8d374606 IJ |
146 | resp.deliverBody(rc) |
147 | # now rc is responsible for calling req_fin | |
7b07f0b5 | 148 | |
c7fb640e IJ |
149 | def req_err(cl, req, err): |
150 | # called when the Deferred fails, or (if it completes), | |
151 | # later, by ResponsConsumer or ErrorResponsConsumer | |
152 | try: | |
153 | cl.log(DBG.HTTP_CTRL, 'req_err ' + str(err), idof=req) | |
1a691ffd | 154 | cl.running_reported = False |
c7fb640e IJ |
155 | if isinstance(err, twisted.python.failure.Failure): |
156 | err = err.getTraceback() | |
7ec61cc0 IJ |
157 | print('%s[%#x] %s' % (cl.desc, id(req), err.strip('\n').replace('\n',' / ')), |
158 | file=sys.stderr) | |
c7f134ce IJ |
159 | if not isinstance(cl.outstanding[req], int): |
160 | raise RuntimeError('[%#x] previously %s' % | |
161 | (id(req), cl.outstanding[req])) | |
c7fb640e IJ |
162 | cl.outstanding[req] = err |
163 | cl.log_outstanding() | |
8d374606 | 164 | reactor.callLater(cl.c.http_retry, partial(cl.req_fin, req)) |
c7fb640e IJ |
165 | except Exception as e: |
166 | crash(traceback.format_exc() + '\n----- handling -----\n' + err) | |
167 | ||
168 | def req_fin(cl, req): | |
169 | del cl.outstanding[req] | |
c7f134ce | 170 | cl.log(DBG.HTTP_CTRL, 'req_fin OS=%d' % len(cl.outstanding), idof=req) |
c7fb640e IJ |
171 | cl.check_outbound() |
172 | ||
173 | def check_outbound(cl): | |
174 | while True: | |
175 | if len(cl.outstanding) >= cl.c.max_outstanding: | |
176 | break | |
177 | ||
c7f134ce IJ |
178 | if (not cl.queue.nonempty() and |
179 | len(cl.outstanding) >= cl.c.target_requests_outstanding): | |
c7fb640e IJ |
180 | break |
181 | ||
182 | d = b'' | |
183 | def moredata(s): nonlocal d; d += s | |
c7f134ce | 184 | cl.queue.process((lambda: len(d)), |
c7fb640e IJ |
185 | moredata, |
186 | cl.c.max_batch_up) | |
187 | ||
188 | d = mime_translate(d) | |
189 | ||
ef041033 IJ |
190 | token = authtoken_make(cl.c.secret) |
191 | ||
c7fb640e IJ |
192 | crlf = b'\r\n' |
193 | lf = b'\n' | |
194 | mime = (b'--b' + crlf + | |
195 | b'Content-Type: text/plain; charset="utf-8"' + crlf + | |
196 | b'Content-Disposition: form-data; name="m"' + crlf + crlf + | |
197 | str(cl.c.client) .encode('ascii') + crlf + | |
ef041033 | 198 | token + crlf + |
c7f134ce IJ |
199 | str(cl.c.target_requests_outstanding) |
200 | .encode('ascii') + crlf + | |
c7fb640e IJ |
201 | str(cl.c.http_timeout) .encode('ascii') + crlf + |
202 | (( | |
203 | b'--b' + crlf + | |
204 | b'Content-Type: application/octet-stream' + crlf + | |
205 | b'Content-Disposition: form-data; name="d"' + crlf + crlf + | |
206 | d + crlf | |
207 | ) if len(d) else b'') + | |
208 | b'--b--' + crlf) | |
209 | ||
210 | #df = open('data.dump.dbg', mode='wb') | |
211 | #df.write(mime) | |
212 | #df.close() | |
213 | # POST -use -c 'multipart/form-data; boundary="b"' http://localhost:8099/ <data.dump.dbg | |
214 | ||
215 | cl.log(DBG.HTTP_FULL, 'requesting: ' + str(mime)) | |
216 | ||
217 | hh = { 'User-Agent': ['hippotat'], | |
218 | 'Content-Type': ['multipart/form-data; boundary="b"'], | |
219 | 'Content-Length': [str(len(mime))] } | |
220 | ||
221 | bytesreader = io.BytesIO(mime) | |
222 | producer = twisted.web.client.FileBodyProducer(bytesreader) | |
223 | ||
c7f134ce | 224 | req = cl.agent.request(b'POST', |
c7fb640e IJ |
225 | cl.c.url, |
226 | twisted.web.client.Headers(hh), | |
227 | producer) | |
228 | ||
229 | cl.outstanding[req] = len(d) | |
230 | cl.log(DBG.HTTP_CTRL, | |
231 | 'request OS=%d' % len(cl.outstanding), | |
232 | idof=req, d=d) | |
233 | req.addTimeout(cl.c.http_timeout, reactor) | |
234 | req.addCallback(partial(cl.req_ok, req)) | |
235 | req.addErrback(partial(cl.req_err, req)) | |
236 | ||
237 | cl.log_outstanding() | |
238 | ||
239 | clients = [ ] | |
240 | ||
1cc6968f | 241 | def process_cfg(_opts, putative_servers, putative_clients): |
c7fb640e IJ |
242 | global clients |
243 | ||
244 | for ss in putative_servers.values(): | |
245 | for (ci,cs) in putative_clients.items(): | |
246 | c = ConfigResults() | |
247 | ||
8d374606 | 248 | sections = cfg_process_client_common(c,ss,cs,ci) |
c7fb640e IJ |
249 | if not sections: continue |
250 | ||
8c771381 IJ |
251 | log_debug_config('processing client [%s %s]' % (ss, cs)) |
252 | ||
c7fb640e IJ |
253 | def srch(getter,key): return cfg_search(getter,key,sections) |
254 | ||
255 | c.http_timeout += srch(cfg.getint, 'http_timeout_grace') | |
256 | c.max_outstanding = srch(cfg.getint, 'max_requests_outstanding') | |
257 | c.max_batch_up = srch(cfg.getint, 'max_batch_up') | |
258 | c.http_retry = srch(cfg.getint, 'http_retry') | |
f754eec4 | 259 | c.max_queue_time = srch(cfg.getint, 'max_queue_time') |
c7fb640e IJ |
260 | c.vroutes = srch(cfg.get, 'vroutes') |
261 | ||
d72f8360 IJ |
262 | try: c.ifname = srch(cfg_get_raw, 'ifname_client') |
263 | except NoOptionError: pass | |
264 | ||
c7fb640e IJ |
265 | try: c.url = srch(cfg.get,'url') |
266 | except NoOptionError: | |
8d374606 | 267 | cfg_process_saddrs(c, ss) |
c7fb640e IJ |
268 | c.url = c.saddrs[0].url() |
269 | ||
8d374606 IJ |
270 | c.client = ci |
271 | ||
272 | cfg_process_vaddr(c,ss) | |
273 | ||
274 | cfg_process_ipif(c, | |
c7fb640e IJ |
275 | sections, |
276 | (('local','client'), | |
277 | ('peer', 'vaddr'), | |
278 | ('rnets','vroutes'))) | |
279 | ||
280 | clients.append(Client(c,ss,cs)) | |
0accf0d3 | 281 | |
5510890e | 282 | common_startup(process_cfg) |
c7fb640e IJ |
283 | |
284 | for cl in clients: | |
285 | cl.start() | |
909e0ff3 | 286 | cl.ipif = start_ipif(cl.c.ipif_command, cl.outbound) |
c7fb640e IJ |
287 | cl.check_outbound() |
288 | ||
034284c3 | 289 | common_run() |