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