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