chiark / gitweb /
Merge remote-tracking branch 'python/master' into old-python/
[hippotat.git] / old-python / hippotat
1 #!/usr/bin/python3
2 #
3 # Hippotat - Asinine IP Over HTTP program
4 # ./hippotat - client main program
5 #
6 # Copyright 2017 Ian Jackson
7 #
8 # GPLv3+
9 #
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.
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 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/>.
23
24 #@ import sys; sys.path.append('@PYBUILD_INSTALL_DIR@')
25 from hippotatlib import *
26
27 import twisted.web
28 import twisted.web.client
29 import urllib.parse
30
31 import io
32
33 class GeneralResponseConsumer(twisted.internet.protocol.Protocol):
34   def __init__(self, cl, req, resp, desc):
35     self._cl = cl
36     self._req = req
37     self._resp = resp
38     self._desc = desc
39
40   def _log(self, dflag, msg, **kwargs):
41     self._cl.log(dflag, '%s: %s' % (self._desc, msg), idof=self._req, **kwargs)
42
43   def connectionMade(self):
44     self._log(DBG.HTTP_CTRL, 'connectionMade')
45
46   def connectionLostOK(self, reason):
47     return (reason.check(twisted.web.client.ResponseDone) or
48             reason.check(twisted.web.client.PotentialDataLoss))
49     # twisted.web.client.PotentialDataLoss is an entirely daft
50     # exception.  It will occur every time if the origin server does
51     # not provide a Content-Length.  (hippotatd does, of course, but
52     # the HTTP transaction might be proxied.)
53
54 class ResponseConsumer(GeneralResponseConsumer):
55   def __init__(self, cl, req, resp):
56     super().__init__(cl, req, resp, 'RC')
57     ssddesc = '[%s] %s' % (id(req), self._desc)
58     self._ssd = SlipStreamDecoder(ssddesc, partial(queue_inbound, cl.ipif),
59                                   cl.c.mtu)
60     self._log(DBG.HTTP_CTRL, '__init__')
61
62   def dataReceived(self, data):
63     self._log(DBG.HTTP, 'dataReceived', d=data)
64     try:
65       self._ssd.inputdata(data)
66     except Exception as e:
67       self._handleexception()
68
69   def connectionLost(self, reason):
70     reason_msg = 'connectionLost ' + str(reason)
71     self._log(DBG.HTTP_CTRL, reason_msg)
72     if not self.connectionLostOK(reason):
73       self._latefailure(reason_msg)
74       return
75     try:
76       self._log(DBG.HTTP, 'ResponseDone')
77       self._ssd.flush()
78       self._cl.req_fin(self._req)
79     except Exception as e:
80       self._handleexception()
81     self._cl.report_running()
82
83   def _handleexception(self):
84     self._latefailure(traceback.format_exc())
85
86   def _latefailure(self, reason):
87     self._log(DBG.HTTP_CTRL, '_latefailure ' + str(reason))
88     self._cl.req_err(self._req, reason)
89
90 class ErrorResponseConsumer(GeneralResponseConsumer):
91   def __init__(self, cl, req, resp):
92     super().__init__(cl, req, resp, 'ERROR-RC')
93     self._m = b''
94     try:
95       self._phrase = resp.phrase.decode('utf-8')
96     except Exception:
97       self._phrase = repr(resp.phrase)
98     self._log(DBG.HTTP_CTRL, '__init__ %d %s' % (resp.code, self._phrase))
99
100   def dataReceived(self, data):
101     self._log(DBG.HTTP_CTRL, 'dataReceived ' + repr(data))
102     self._m += data
103
104   def connectionLost(self, reason):
105     try:
106       mbody = self._m.decode('utf-8')
107     except Exception:
108       mbody = repr(self._m)
109     if not self.connectionLostOK(reason):
110       mbody += ' || ' + str(reason)
111     self._cl.req_err(self._req,
112             "FAILED %d %s | %s"
113             % (self._resp.code, self._phrase, mbody))
114
115 class Client():
116   def __init__(cl, c,ss,cs):
117     cl.c = c
118     cl.outstanding = { }
119     cl.desc = '[%s %s] ' % (ss,cs)
120     cl.running_reported = False
121     cl.log_info('setting up')
122
123   def log_info(cl, msg):
124     log.info(cl.desc + msg, dflag=False)
125
126   def report_running(cl):
127     if not cl.running_reported:
128       cl.log_info('running OK')
129       cl.running_reported = True
130
131   def log(cl, dflag, msg, **kwargs):
132     log_debug(dflag, cl.desc + msg, **kwargs)
133
134   def log_outstanding(cl):
135     cl.log(DBG.CTRL_DUMP, 'OS %s' % cl.outstanding)
136
137   def start(cl):
138     cl.queue = PacketQueue('up', cl.c.max_queue_time)
139     cl.agent = twisted.web.client.Agent(
140       reactor, connectTimeout = cl.c.http_timeout)
141
142   def outbound(cl, packet, saddr, daddr):
143     #print('OUT ', saddr, daddr, repr(packet))
144     cl.queue.append(packet)
145     cl.check_outbound()
146
147   def req_ok(cl, req, resp):
148     cl.log(DBG.HTTP_CTRL,
149             'req_ok %d %s %s' % (resp.code, repr(resp.phrase), str(resp)),
150             idof=req)
151     if resp.code == 200:
152       rc = ResponseConsumer(cl, req, resp)
153     else:
154       rc = ErrorResponseConsumer(cl, req, resp)
155
156     resp.deliverBody(rc)
157     # now rc is responsible for calling req_fin
158
159   def req_err(cl, req, err):
160     # called when the Deferred fails, or (if it completes),
161     # later, by ResponsConsumer or ErrorResponsConsumer
162     try:
163       cl.log(DBG.HTTP_CTRL, 'req_err ' + str(err), idof=req)
164       cl.running_reported = False
165       if isinstance(err, twisted.python.failure.Failure):
166         err = err.getTraceback()
167       print('%s[%#x] %s' % (cl.desc, id(req), err.strip('\n').replace('\n',' / ')),
168             file=sys.stderr)
169       if not isinstance(cl.outstanding[req], int):
170         raise RuntimeError('[%#x] previously %s' %
171                            (id(req), cl.outstanding[req]))
172       cl.outstanding[req] = err
173       cl.log_outstanding()
174       reactor.callLater(cl.c.http_retry, partial(cl.req_fin, req))
175     except Exception as e:
176       crash(traceback.format_exc() + '\n----- handling -----\n' + err)
177
178   def req_fin(cl, req):
179     del cl.outstanding[req]
180     cl.log(DBG.HTTP_CTRL, 'req_fin OS=%d' % len(cl.outstanding), idof=req)
181     cl.check_outbound()
182
183   def check_outbound(cl):
184     while True:
185       if len(cl.outstanding) >= cl.c.max_outstanding:
186         break
187
188       if (not cl.queue.nonempty() and
189           len(cl.outstanding) >= cl.c.target_requests_outstanding):
190         break
191
192       d = b''
193       def moredata(s): nonlocal d; d += s
194       cl.queue.process((lambda: len(d)),
195                     moredata,
196                     cl.c.max_batch_up)
197
198       d = mime_translate(d)
199
200       token = authtoken_make(cl.c.secret)
201
202       crlf = b'\r\n'
203       lf   =   b'\n'
204       mime = (b'--b'                                        + crlf +
205               b'Content-Type: text/plain; charset="utf-8"'  + crlf +
206               b'Content-Disposition: form-data; name="m"'   + crlf + crlf +
207               str(cl.c.client)            .encode('ascii')  + crlf +
208               token                                         + crlf +
209               str(cl.c.target_requests_outstanding)
210                                           .encode('ascii')  + crlf +
211               str(cl.c.http_timeout)      .encode('ascii')  + crlf +
212             ((
213               b'--b'                                        + crlf +
214               b'Content-Type: application/octet-stream'     + crlf +
215               b'Content-Disposition: form-data; name="d"'   + crlf + crlf +
216               d                                             + crlf
217              ) if len(d) else b'')                               +
218               b'--b--'                                      + crlf)
219
220       #df = open('data.dump.dbg', mode='wb')
221       #df.write(mime)
222       #df.close()
223       # POST -use -c 'multipart/form-data; boundary="b"' http://localhost:8099/ <data.dump.dbg
224
225       cl.log(DBG.HTTP_FULL, 'requesting: ' + str(mime))
226
227       hh = { 'User-Agent': ['hippotat'],
228              'Content-Type': ['multipart/form-data; boundary="b"'] }
229
230       bytesreader = io.BytesIO(mime)
231       producer = twisted.web.client.FileBodyProducer(bytesreader)
232
233       req = cl.agent.request(b'POST',
234                           cl.c.url,
235                           twisted.web.client.Headers(hh),
236                           producer)
237
238       cl.outstanding[req] = len(d)
239       cl.log(DBG.HTTP_CTRL,
240              'request OS=%d' % len(cl.outstanding),
241              idof=req, d=d)
242       req.addTimeout(cl.c.http_timeout, reactor)
243       req.addCallback(partial(cl.req_ok, req))
244       req.addErrback(partial(cl.req_err, req))
245
246     cl.log_outstanding()
247
248 clients = [ ]
249
250 def encode_url(urlstr):
251   # Oh, this is a disaster.  We're given a URL as a `str', but the underlying
252   # machinery insists on having `bytes'.  Assume we've been given a sensible
253   # URL, with escaping in all of the necessary places, except that it may
254   # contain non-ASCII characters: then encode as UTF-8 and squash the top-
255   # bit-set bytes down to percent escapes.
256   #
257   # This conses like it's going out of fashion, but it gets the job done.
258   return b''.join(bytes([b]) if b < 128 else '%%%02X' % b
259                   for b in urlstr.encode('utf-8'))
260
261 def process_cfg(_opts, putative_servers, putative_clients):
262   global clients
263
264   for ss in putative_servers.values():
265     for (ci,cs) in putative_clients.items():
266       c = ConfigResults()
267
268       sections = cfg_process_client_common(c,ss,cs,ci)
269       if not sections: continue
270
271       log_debug_config('processing client [%s %s]' % (ss, cs))
272
273       def srch(getter,key): return cfg_search(getter,key,sections)
274
275       c.http_timeout   += srch(cfg.getint, 'http_timeout_grace')
276       c.max_outstanding = srch(cfg.getint, 'max_requests_outstanding')
277       c.max_batch_up    = srch(cfg.getint, 'max_batch_up')
278       c.http_retry      = srch(cfg.getint, 'http_retry')
279       c.max_queue_time  = srch(cfg.getint, 'max_queue_time')
280       c.vroutes         = srch(cfg.get,    'vroutes')
281
282       try: c.ifname     = srch(cfg_get_raw, 'ifname_client')
283       except NoOptionError: pass
284
285       try: c.url = encode_url(srch(cfg.get,'url'))
286       except NoOptionError:
287         cfg_process_saddrs(c, ss)
288         c.url = c.saddrs[0].url()
289
290       c.client = ci
291
292       cfg_process_vaddr(c,ss)
293
294       cfg_process_ipif(c,
295                        sections,
296                        (('local','client'),
297                         ('peer', 'vaddr'),
298                         ('rnets','vroutes')))
299
300       clients.append(Client(c,ss,cs))
301
302 common_startup(process_cfg)
303
304 for cl in clients:
305   cl.start()
306   cl.ipif = start_ipif(cl.c.ipif_command, cl.outbound, cl.c.mtu)
307   cl.check_outbound()
308
309 common_run()