chiark / gitweb /
ResponseConsumer: pass resp to constructor (nfc)
[hippotat.git] / 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
30 import io
31
32 class GeneralResponseConsumer(twisted.internet.protocol.Protocol):
33   def __init__(self, cl, req, desc):
34     self._cl = cl
35     self._req = req
36     self._desc = desc
37
38   def _log(self, dflag, msg, **kwargs):
39     self._cl.log(dflag, '%s: %s' % (self._desc, msg), idof=self._req, **kwargs)
40
41   def connectionMade(self):
42     self._log(DBG.HTTP_CTRL, 'connectionMade')
43
44 class ResponseConsumer(GeneralResponseConsumer):
45   def __init__(self, cl, req, resp):
46     super().__init__(cl, req, 'RC')
47     ssddesc = '[%s] %s' % (id(req), self._desc)
48     self._ssd = SlipStreamDecoder(ssddesc, partial(queue_inbound, cl.ipif))
49     self._log(DBG.HTTP_CTRL, '__init__')
50
51   def dataReceived(self, data):
52     self._log(DBG.HTTP, 'dataReceived', d=data)
53     try:
54       self._ssd.inputdata(data)
55     except Exception as e:
56       self._handleexception()
57
58   def connectionLost(self, reason):
59     reason_msg = 'connectionLost ' + str(reason)
60     self._log(DBG.HTTP_CTRL, reason_msg)
61     if not reason.check(twisted.web.client.ResponseDone):
62       self._latefailure(reason_msg)
63       return
64     try:
65       self._log(DBG.HTTP, 'ResponseDone')
66       self._ssd.flush()
67       self._cl.req_fin(self._req)
68     except Exception as e:
69       self._handleexception()
70     self._cl.report_running()
71
72   def _handleexception(self):
73     self._latefailure(traceback.format_exc())
74
75   def _latefailure(self, reason):
76     self._log(DBG.HTTP_CTRL, '_latefailure ' + str(reason))
77     self._cl.req_err(self._req, reason)
78
79 class ErrorResponseConsumer(GeneralResponseConsumer):
80   def __init__(self, cl, req, resp):
81     super().__init__(cl, req, 'ERROR-RC')
82     self._resp = resp
83     self._m = b''
84     try:
85       self._phrase = resp.phrase.decode('utf-8')
86     except Exception:
87       self._phrase = repr(resp.phrase)
88     self._log(DBG.HTTP_CTRL, '__init__ %d %s' % (resp.code, self._phrase))
89
90   def dataReceived(self, data):
91     self._log(DBG.HTTP_CTRL, 'dataReceived ' + repr(data))
92     self._m += data
93
94   def connectionLost(self, reason):
95     try:
96       mbody = self._m.decode('utf-8')
97     except Exception:
98       mbody = repr(self._m)
99     if not reason.check(twisted.web.client.ResponseDone):
100       mbody += ' || ' + str(reason)
101     self._cl.req_err(self._req,
102             "FAILED %d %s | %s"
103             % (self._resp.code, self._phrase, mbody))
104
105 class Client():
106   def __init__(cl, c,ss,cs):
107     cl.c = c
108     cl.outstanding = { }
109     cl.desc = '[%s %s] ' % (ss,cs)
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
120
121   def log(cl, dflag, msg, **kwargs):
122     log_debug(dflag, cl.desc + msg, **kwargs)
123
124   def log_outstanding(cl):
125     cl.log(DBG.CTRL_DUMP, 'OS %s' % cl.outstanding)
126
127   def start(cl):
128     cl.queue = PacketQueue('up', cl.c.max_queue_time)
129     cl.agent = twisted.web.client.Agent(
130       reactor, connectTimeout = cl.c.http_timeout)
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,
139             'req_ok %d %s %s' % (resp.code, repr(resp.phrase), str(resp)),
140             idof=req)
141     if resp.code == 200:
142       rc = ResponseConsumer(cl, req, resp)
143     else:
144       rc = ErrorResponseConsumer(cl, req, resp)
145
146     resp.deliverBody(rc)
147     # now rc is responsible for calling req_fin
148
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       cl.running_reported = False
155       if isinstance(err, twisted.python.failure.Failure):
156         err = err.getTraceback()
157       print('%s[%#x] %s' % (cl.desc, id(req), err.strip('\n').replace('\n',' / ')),
158             file=sys.stderr)
159       if not isinstance(cl.outstanding[req], int):
160         raise RuntimeError('[%#x] previously %s' %
161                            (id(req), cl.outstanding[req]))
162       cl.outstanding[req] = err
163       cl.log_outstanding()
164       reactor.callLater(cl.c.http_retry, partial(cl.req_fin, req))
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]
170     cl.log(DBG.HTTP_CTRL, 'req_fin OS=%d' % len(cl.outstanding), idof=req)
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
178       if (not cl.queue.nonempty() and
179           len(cl.outstanding) >= cl.c.target_requests_outstanding):
180         break
181
182       d = b''
183       def moredata(s): nonlocal d; d += s
184       cl.queue.process((lambda: len(d)),
185                     moredata,
186                     cl.c.max_batch_up)
187
188       d = mime_translate(d)
189
190       token = authtoken_make(cl.c.secret)
191
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 +
198               token                                         + crlf +
199               str(cl.c.target_requests_outstanding)
200                                           .encode('ascii')  + crlf +
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
224       req = cl.agent.request(b'POST',
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
241 def process_cfg(_opts, putative_servers, putative_clients):
242   global clients
243
244   for ss in putative_servers.values():
245     for (ci,cs) in putative_clients.items():
246       c = ConfigResults()
247
248       sections = cfg_process_client_common(c,ss,cs,ci)
249       if not sections: continue
250
251       log_debug_config('processing client [%s %s]' % (ss, cs))
252
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')
259       c.max_queue_time  = srch(cfg.getint, 'max_queue_time')
260       c.vroutes         = srch(cfg.get,    'vroutes')
261
262       try: c.ifname     = srch(cfg_get_raw, 'ifname_client')
263       except NoOptionError: pass
264
265       try: c.url = srch(cfg.get,'url')
266       except NoOptionError:
267         cfg_process_saddrs(c, ss)
268         c.url = c.saddrs[0].url()
269
270       c.client = ci
271
272       cfg_process_vaddr(c,ss)
273
274       cfg_process_ipif(c,
275                        sections,
276                        (('local','client'),
277                         ('peer', 'vaddr'),
278                         ('rnets','vroutes')))
279
280       clients.append(Client(c,ss,cs))
281
282 common_startup(process_cfg)
283
284 for cl in clients:
285   cl.start()
286   cl.ipif = start_ipif(cl.c.ipif_command, cl.outbound)
287   cl.check_outbound()
288
289 common_run()