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 | # | |
8 | # This program is free software: you can redistribute it and/or modify | |
9 | # it under the terms of the GNU Affero General Public License as | |
10 | # published by the Free Software Foundation, either version 3 of the | |
11 | # License, or (at your option) any later version, with the "CAF Login | |
12 | # Exception" as published by Ian Jackson (version 2, or at your option | |
13 | # any later version) as an Additional Permission. | |
14 | # | |
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 Affero General Public License for more details. | |
19 | # | |
20 | # You should have received a copy of the GNU Affero General Public | |
21 | # License and the CAF Login Exception along with this program, in the | |
22 | # file AGPLv3+CAFv2. If not, email Ian Jackson | |
23 | # <ijackson@chiark.greenend.org.uk>. | |
24 | ||
c55f394e | 25 | |
5a37bac8 | 26 | from hippotatlib import * |
c55f394e | 27 | |
c0c90673 IJ |
28 | import twisted.web |
29 | import twisted.web.client | |
30 | ||
dd6665ee IJ |
31 | import io |
32 | ||
0accf0d3 | 33 | class GeneralResponseConsumer(twisted.internet.protocol.Protocol): |
c7fb640e IJ |
34 | def __init__(self, cl, req, desc): |
35 | self._cl = cl | |
8b62cd2c | 36 | self._req = req |
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 | ||
45 | class ResponseConsumer(GeneralResponseConsumer): | |
c7fb640e IJ |
46 | def __init__(self, cl, req): |
47 | super().__init__(cl, req, 'RC') | |
0accf0d3 | 48 | ssddesc = '[%s] %s' % (id(req), self._desc) |
909e0ff3 | 49 | self._ssd = SlipStreamDecoder(ssddesc, partial(queue_inbound, cl.ipif)) |
0accf0d3 | 50 | self._log(DBG.HTTP_CTRL, '__init__') |
bd9e77fb | 51 | |
62b51bcf | 52 | def dataReceived(self, data): |
380ed56c | 53 | self._log(DBG.HTTP, 'dataReceived', d=data) |
9b65cdd4 | 54 | try: |
02cdcb52 | 55 | self._ssd.inputdata(data) |
9b65cdd4 | 56 | except Exception as e: |
eedc8b30 | 57 | self._handleexception() |
ccd371b3 | 58 | |
62b51bcf | 59 | def connectionLost(self, reason): |
15407d80 | 60 | self._log(DBG.HTTP_CTRL, 'connectionLost ' + str(reason)) |
765aba55 | 61 | if not reason.check(twisted.web.client.ResponseDone): |
0accf0d3 | 62 | self.latefailure() |
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) | |
154 | if isinstance(err, twisted.python.failure.Failure): | |
155 | err = err.getTraceback() | |
156 | print('[%#x] %s' % (id(req), err), file=sys.stderr) | |
c7f134ce IJ |
157 | if not isinstance(cl.outstanding[req], int): |
158 | raise RuntimeError('[%#x] previously %s' % | |
159 | (id(req), cl.outstanding[req])) | |
c7fb640e IJ |
160 | cl.outstanding[req] = err |
161 | cl.log_outstanding() | |
8d374606 | 162 | reactor.callLater(cl.c.http_retry, partial(cl.req_fin, req)) |
c7fb640e IJ |
163 | except Exception as e: |
164 | crash(traceback.format_exc() + '\n----- handling -----\n' + err) | |
165 | ||
166 | def req_fin(cl, req): | |
167 | del cl.outstanding[req] | |
c7f134ce | 168 | cl.log(DBG.HTTP_CTRL, 'req_fin OS=%d' % len(cl.outstanding), idof=req) |
c7fb640e IJ |
169 | cl.check_outbound() |
170 | ||
171 | def check_outbound(cl): | |
172 | while True: | |
173 | if len(cl.outstanding) >= cl.c.max_outstanding: | |
174 | break | |
175 | ||
c7f134ce IJ |
176 | if (not cl.queue.nonempty() and |
177 | len(cl.outstanding) >= cl.c.target_requests_outstanding): | |
c7fb640e IJ |
178 | break |
179 | ||
180 | d = b'' | |
181 | def moredata(s): nonlocal d; d += s | |
c7f134ce | 182 | cl.queue.process((lambda: len(d)), |
c7fb640e IJ |
183 | moredata, |
184 | cl.c.max_batch_up) | |
185 | ||
186 | d = mime_translate(d) | |
187 | ||
188 | crlf = b'\r\n' | |
189 | lf = b'\n' | |
190 | mime = (b'--b' + crlf + | |
191 | b'Content-Type: text/plain; charset="utf-8"' + crlf + | |
192 | b'Content-Disposition: form-data; name="m"' + crlf + crlf + | |
193 | str(cl.c.client) .encode('ascii') + crlf + | |
194 | cl.c.password + crlf + | |
c7f134ce IJ |
195 | str(cl.c.target_requests_outstanding) |
196 | .encode('ascii') + crlf + | |
c7fb640e IJ |
197 | str(cl.c.http_timeout) .encode('ascii') + crlf + |
198 | (( | |
199 | b'--b' + crlf + | |
200 | b'Content-Type: application/octet-stream' + crlf + | |
201 | b'Content-Disposition: form-data; name="d"' + crlf + crlf + | |
202 | d + crlf | |
203 | ) if len(d) else b'') + | |
204 | b'--b--' + crlf) | |
205 | ||
206 | #df = open('data.dump.dbg', mode='wb') | |
207 | #df.write(mime) | |
208 | #df.close() | |
209 | # POST -use -c 'multipart/form-data; boundary="b"' http://localhost:8099/ <data.dump.dbg | |
210 | ||
211 | cl.log(DBG.HTTP_FULL, 'requesting: ' + str(mime)) | |
212 | ||
213 | hh = { 'User-Agent': ['hippotat'], | |
214 | 'Content-Type': ['multipart/form-data; boundary="b"'], | |
215 | 'Content-Length': [str(len(mime))] } | |
216 | ||
217 | bytesreader = io.BytesIO(mime) | |
218 | producer = twisted.web.client.FileBodyProducer(bytesreader) | |
219 | ||
c7f134ce | 220 | req = cl.agent.request(b'POST', |
c7fb640e IJ |
221 | cl.c.url, |
222 | twisted.web.client.Headers(hh), | |
223 | producer) | |
224 | ||
225 | cl.outstanding[req] = len(d) | |
226 | cl.log(DBG.HTTP_CTRL, | |
227 | 'request OS=%d' % len(cl.outstanding), | |
228 | idof=req, d=d) | |
229 | req.addTimeout(cl.c.http_timeout, reactor) | |
230 | req.addCallback(partial(cl.req_ok, req)) | |
231 | req.addErrback(partial(cl.req_err, req)) | |
232 | ||
233 | cl.log_outstanding() | |
234 | ||
235 | clients = [ ] | |
236 | ||
237 | def process_cfg(putative_servers, putative_clients): | |
238 | global clients | |
239 | ||
240 | for ss in putative_servers.values(): | |
241 | for (ci,cs) in putative_clients.items(): | |
242 | c = ConfigResults() | |
243 | ||
8d374606 | 244 | sections = cfg_process_client_common(c,ss,cs,ci) |
c7fb640e IJ |
245 | if not sections: continue |
246 | ||
247 | def srch(getter,key): return cfg_search(getter,key,sections) | |
248 | ||
249 | c.http_timeout += srch(cfg.getint, 'http_timeout_grace') | |
250 | c.max_outstanding = srch(cfg.getint, 'max_requests_outstanding') | |
251 | c.max_batch_up = srch(cfg.getint, 'max_batch_up') | |
252 | c.http_retry = srch(cfg.getint, 'http_retry') | |
f754eec4 | 253 | c.max_queue_time = srch(cfg.getint, 'max_queue_time') |
c7fb640e IJ |
254 | c.vroutes = srch(cfg.get, 'vroutes') |
255 | ||
c7fb640e IJ |
256 | try: c.url = srch(cfg.get,'url') |
257 | except NoOptionError: | |
8d374606 | 258 | cfg_process_saddrs(c, ss) |
c7fb640e IJ |
259 | c.url = c.saddrs[0].url() |
260 | ||
8d374606 IJ |
261 | c.client = ci |
262 | ||
263 | cfg_process_vaddr(c,ss) | |
264 | ||
265 | cfg_process_ipif(c, | |
c7fb640e IJ |
266 | sections, |
267 | (('local','client'), | |
268 | ('peer', 'vaddr'), | |
269 | ('rnets','vroutes'))) | |
270 | ||
271 | clients.append(Client(c,ss,cs)) | |
0accf0d3 | 272 | |
5510890e | 273 | common_startup(process_cfg) |
c7fb640e IJ |
274 | |
275 | for cl in clients: | |
276 | cl.start() | |
909e0ff3 | 277 | cl.ipif = start_ipif(cl.c.ipif_command, cl.outbound) |
c7fb640e IJ |
278 | cl.check_outbound() |
279 | ||
034284c3 | 280 | common_run() |