chiark / gitweb /
a56dde2fbc0f92ec5321c0ba80465aed373184eb
[hippotat.git] / client
1 #!/usr/bin/python3
2
3 from hippotat import *
4
5 import twisted.web
6 import twisted.web.client
7
8 import io
9
10 class GeneralResponseConsumer(twisted.internet.protocol.Protocol):
11   def __init__(self, cl, req, desc):
12     self._cl = cl
13     self._req = req
14     self._desc = desc
15
16   def _log(self, dflag, msg, **kwargs):
17     self.cl.log(dflag, '%s: %s' % (self._desc, msg), idof=self._req, **kwargs)
18
19   def connectionMade(self):
20     self._log(DBG.HTTP_CTRL, 'connectionMade')
21
22 class ResponseConsumer(GeneralResponseConsumer):
23   def __init__(self, cl, req):
24     super().__init__(cl, req, 'RC')
25     ssddesc = '[%s] %s' % (id(req), self._desc)
26     self._ssd = SlipStreamDecoder(ssddesc, cl.queue_inbound)
27     self._log(DBG.HTTP_CTRL, '__init__')
28
29   def dataReceived(self, data):
30     self._log(DBG.HTTP, 'dataReceived', d=data)
31     try:
32       self._ssd.inputdata(data)
33     except Exception as e:
34       self._handleexception()
35
36   def connectionLost(self, reason):
37     self._log(DBG.HTTP_CTRL, 'connectionLost ' + str(reason))
38     if not reason.check(twisted.web.client.ResponseDone):
39       self.latefailure()
40       return
41     try:
42       self._log(DBG.HTTP, 'ResponseDone')
43       self._ssd.flush()
44       self.cl.req_fin(self._req)
45     except Exception as e:
46       self._handleexception()
47
48   def _handleexception(self):
49     self._latefailure(traceback.format_exc())
50
51   def _latefailure(self, reason):
52     self._log(DBG.HTTP_CTRL, '_latefailure ' + str(reason))
53     self.cl.req_err(self._req, reason)
54
55 class ErrorResponseConsumer(twisted.internet.protocol.Protocol):
56   def __init__(self, cl, req, resp):
57     super().__init__(cl, req, 'ERROR-RC')
58     self._resp = resp
59     self._m = b''
60     try:
61       self._phrase = resp.phrase.decode('utf-8')
62     except Exception:
63       self._phrase = repr(resp.phrase)
64     self._log(DBG.HTTP_CTRL, '__init__ %d %s' % (resp.code, self._phrase))
65
66   def dataReceived(self, data):
67     self._log(DBG.HTTP_CTRL, 'dataReceived ' + repr(data))
68     self._m += data
69
70   def connectionLost(self, reason):
71     try:
72       mbody = self._m.decode('utf-8')
73     except Exception:
74       mbody = repr(self._m)
75     if not reason.check(twisted.web.client.ResponseDone):
76       mbody += ' || ' + str(reason)
77     self.cl.req_err(self._req,
78             "FAILED %d %s | %s"
79             % (self._resp.code, self._phrase, mbody))
80
81 class Client():
82   def __init__(cl, c,ss,cs):
83     cl.c = c
84     cl.outstanding = { }
85     cl.desc = '[%s %s] ' % (ss,cs)
86
87   def log(cl, dflag, msg, **kwargs):
88     log_debug(dflag, cl.desc + msg, **kwargs)
89
90   def log_outstanding(cl):
91     cl.log(DBG.CTRL_DUMP, 'OS %s' % outstanding)
92
93   def start(cl):
94     cl.queue = PacketQueue('up', cl.c.max_queue_time)
95     cl.agent = twisted.web.client.Agent(
96       reactor, connectTimeout = cl.c.http_timeout)
97
98   def outbound(cl, packet, saddr, daddr):
99     #print('OUT ', saddr, daddr, repr(packet))
100     cl.queue.append(packet)
101     cl.check_outbound()
102
103   def req_ok(cl, req, resp):
104     cl.log(DBG.HTTP_CTRL,
105             'req_ok %d %s %s' % (resp.code, repr(resp.phrase), str(resp)),
106             idof=req)
107     if resp.code == 200:
108       rc = ResponseConsumer(cl, req)
109     else:
110       rc = ErrorResponseConsumer(cl, req, resp)
111
112     resp.deliverBody(rc)
113     # now rc is responsible for calling req_fin
114
115   def req_err(cl, req, err):
116     # called when the Deferred fails, or (if it completes),
117     # later, by ResponsConsumer or ErrorResponsConsumer
118     try:
119       cl.log(DBG.HTTP_CTRL, 'req_err ' + str(err), idof=req)
120       if isinstance(err, twisted.python.failure.Failure):
121         err = err.getTraceback()
122       print('[%#x] %s' % (id(req), err), file=sys.stderr)
123       if not isinstance(outstanding[req], int):
124         raise RuntimeError('[%#x] previously %s' % (id(req), outstanding[req]))
125       cl.outstanding[req] = err
126       cl.log_outstanding()
127       reactor.callLater(cl.c.http_retry, partial(cl.req_fin, req))
128     except Exception as e:
129       crash(traceback.format_exc() + '\n----- handling -----\n' + err)
130
131   def req_fin(cl, req):
132     del cl.outstanding[req]
133     cl.log(DBG.HTTP_CTRL, 'req_fin OS=%d' % len(outstanding), idof=req)
134     cl.check_outbound()
135
136   def check_outbound(cl):
137     while True:
138       if len(cl.outstanding) >= cl.c.max_outstanding:
139         break
140
141       if (not queue.nonempty() and
142           len(cl.outstanding) >= cl.c.target_outstanding):
143         break
144
145       d = b''
146       def moredata(s): nonlocal d; d += s
147       queue.process((lambda: len(d)),
148                     moredata,
149                     cl.c.max_batch_up)
150
151       d = mime_translate(d)
152
153       crlf = b'\r\n'
154       lf   =   b'\n'
155       mime = (b'--b'                                        + crlf +
156               b'Content-Type: text/plain; charset="utf-8"'  + crlf +
157               b'Content-Disposition: form-data; name="m"'   + crlf + crlf +
158               str(cl.c.client)            .encode('ascii')  + crlf +
159               cl.c.password                                 + crlf +
160               str(cl.c.target_outstanding).encode('ascii')  + crlf +
161               str(cl.c.http_timeout)      .encode('ascii')  + crlf +
162             ((
163               b'--b'                                        + crlf +
164               b'Content-Type: application/octet-stream'     + crlf +
165               b'Content-Disposition: form-data; name="d"'   + crlf + crlf +
166               d                                             + crlf
167              ) if len(d) else b'')                               +
168               b'--b--'                                      + crlf)
169
170       #df = open('data.dump.dbg', mode='wb')
171       #df.write(mime)
172       #df.close()
173       # POST -use -c 'multipart/form-data; boundary="b"' http://localhost:8099/ <data.dump.dbg
174
175       cl.log(DBG.HTTP_FULL, 'requesting: ' + str(mime))
176
177       hh = { 'User-Agent': ['hippotat'],
178              'Content-Type': ['multipart/form-data; boundary="b"'],
179              'Content-Length': [str(len(mime))] }
180
181       bytesreader = io.BytesIO(mime)
182       producer = twisted.web.client.FileBodyProducer(bytesreader)
183
184       req = agent.request(b'POST',
185                           cl.c.url,
186                           twisted.web.client.Headers(hh),
187                           producer)
188
189       cl.outstanding[req] = len(d)
190       cl.log(DBG.HTTP_CTRL,
191              'request OS=%d' % len(cl.outstanding),
192              idof=req, d=d)
193       req.addTimeout(cl.c.http_timeout, reactor)
194       req.addCallback(partial(cl.req_ok, req))
195       req.addErrback(partial(cl.req_err, req))
196
197     cl.log_outstanding()
198
199 clients = [ ]
200
201 def process_cfg(putative_servers, putative_clients):
202   global clients
203
204   for ss in putative_servers.values():
205     for (ci,cs) in putative_clients.items():
206       c = ConfigResults()
207
208       sections = cfg_process_client_common(c,ss,cs,ci)
209       if not sections: continue
210
211       def srch(getter,key): return cfg_search(getter,key,sections)
212
213       c.http_timeout   += srch(cfg.getint, 'http_timeout_grace')
214       c.max_outstanding = srch(cfg.getint, 'max_requests_outstanding')
215       c.max_batch_up    = srch(cfg.getint, 'max_batch_up')
216       c.http_retry      = srch(cfg.getint, 'http_retry')
217       c.max_queue_time  = srch(cfg.getint, 'max_queue_time')
218       c.vroutes         = srch(cfg.get,    'vroutes')
219
220       try: c.url = srch(cfg.get,'url')
221       except NoOptionError:
222         cfg_process_saddrs(c, ss)
223         c.url = c.saddrs[0].url()
224
225       c.client = ci
226
227       cfg_process_vaddr(c,ss)
228
229       cfg_process_ipif(c,
230                        sections,
231                        (('local','client'),
232                         ('peer', 'vaddr'),
233                         ('rnets','vroutes')))
234
235       clients.append(Client(c,ss,cs))
236
237 common_startup(process_cfg)
238
239 for cl in clients:
240   cl.start()
241   start_ipif(cl.c.ipif_command, cl.outbound)
242   cl.check_outbound()
243
244 common_run()