3 # Hippotat - Asinine IP Over HTTP program
4 # ./hippotat - client main program
6 # Copyright 2017 Ian Jackson
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.
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.
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/>.
24 #@ import sys; sys.path.append('@PYBUILD_INSTALL_DIR@')
25 from hippotatlib
import *
28 import twisted
.web
.client
32 class GeneralResponseConsumer(twisted
.internet
.protocol
.Protocol
):
33 def __init__(self
, cl
, req
, resp
, desc
):
39 def _log(self
, dflag
, msg
, **kwargs
):
40 self
._cl
.log(dflag
, '%s: %s' %
(self
._desc
, msg
), idof
=self
._req
, **kwargs
)
42 def connectionMade(self
):
43 self
._log(DBG
.HTTP_CTRL
, 'connectionMade')
45 class ResponseConsumer(GeneralResponseConsumer
):
46 def __init__(self
, cl
, req
, resp
):
47 super().__init__(cl
, req
, resp
, 'RC')
48 ssddesc
= '[%s] %s' %
(id(req
), self
._desc
)
49 self
._ssd
= SlipStreamDecoder(ssddesc
, partial(queue_inbound
, cl
.ipif
))
50 self
._log(DBG
.HTTP_CTRL
, '__init__')
52 def dataReceived(self
, data
):
53 self
._log(DBG
.HTTP
, 'dataReceived', d
=data
)
55 self
._ssd
.inputdata(data
)
56 except Exception as e
:
57 self
._handleexception()
59 def connectionLost(self
, reason
):
60 reason_msg
= 'connectionLost ' + str(reason
)
61 self
._log(DBG
.HTTP_CTRL
, reason_msg
)
62 if not reason
.check(twisted
.web
.client
.ResponseDone
):
63 self
._latefailure(reason_msg
)
66 self
._log(DBG
.HTTP
, 'ResponseDone')
68 self
._cl
.req_fin(self
._req
)
69 except Exception as e
:
70 self
._handleexception()
71 self
._cl
.report_running()
73 def _handleexception(self
):
74 self
._latefailure(traceback
.format_exc())
76 def _latefailure(self
, reason
):
77 self
._log(DBG
.HTTP_CTRL
, '_latefailure ' + str(reason
))
78 self
._cl
.req_err(self
._req
, reason
)
80 class ErrorResponseConsumer(GeneralResponseConsumer
):
81 def __init__(self
, cl
, req
, resp
):
82 super().__init__(cl
, req
, resp
, 'ERROR-RC')
85 self
._phrase
= resp
.phrase
.decode('utf-8')
87 self
._phrase
= repr(resp
.phrase
)
88 self
._log(DBG
.HTTP_CTRL
, '__init__ %d %s' %
(resp
.code
, self
._phrase
))
90 def dataReceived(self
, data
):
91 self
._log(DBG
.HTTP_CTRL
, 'dataReceived ' + repr(data
))
94 def connectionLost(self
, reason
):
96 mbody
= self
._m
.decode('utf-8')
99 if not reason
.check(twisted
.web
.client
.ResponseDone
):
100 mbody
+= ' || ' + str(reason
)
101 self
._cl
.req_err(self
._req
,
103 %
(self
._resp
.code
, self
._phrase
, mbody
))
106 def __init__(cl
, c
,ss
,cs
):
109 cl
.desc
= '[%s %s] ' %
(ss
,cs
)
110 cl
.running_reported
= False
111 cl
.log_info('setting up')
113 def log_info(cl
, msg
):
114 log
.info(cl
.desc
+ msg
, dflag
=False)
116 def report_running(cl
):
117 if not cl
.running_reported
:
118 cl
.log_info('running OK')
119 cl
.running_reported
= True
121 def log(cl
, dflag
, msg
, **kwargs
):
122 log_debug(dflag
, cl
.desc
+ msg
, **kwargs
)
124 def log_outstanding(cl
):
125 cl
.log(DBG
.CTRL_DUMP
, 'OS %s' % cl
.outstanding
)
128 cl
.queue
= PacketQueue('up', cl
.c
.max_queue_time
)
129 cl
.agent
= twisted
.web
.client
.Agent(
130 reactor
, connectTimeout
= cl
.c
.http_timeout
)
132 def outbound(cl
, packet
, saddr
, daddr
):
133 #print('OUT ', saddr, daddr, repr(packet))
134 cl
.queue
.append(packet
)
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
)),
142 rc
= ResponseConsumer(cl
, req
, resp
)
144 rc
= ErrorResponseConsumer(cl
, req
, resp
)
147 # now rc is responsible for calling req_fin
149 def req_err(cl
, req
, err
):
150 # called when the Deferred fails, or (if it completes),
151 # later, by ResponsConsumer or ErrorResponsConsumer
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',' / ')),
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
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
)
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
)
173 def check_outbound(cl
):
175 if len(cl
.outstanding
) >= cl
.c
.max_outstanding
:
178 if (not cl
.queue
.nonempty() and
179 len(cl
.outstanding
) >= cl
.c
.target_requests_outstanding
):
183 def moredata(s
): nonlocal d
; d
+= s
184 cl
.queue
.process((lambda: len(d
)),
188 d
= mime_translate(d
)
190 token
= authtoken_make(cl
.c
.secret
)
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
+
199 str(cl
.c
.target_requests_outstanding
)
200 .encode('ascii') + crlf
+
201 str(cl
.c
.http_timeout
) .encode('ascii') + crlf
+
204 b
'Content-Type: application/octet-stream' + crlf
+
205 b
'Content-Disposition: form-data; name="d"' + crlf
+ crlf
+
207 ) if len(d
) else b
'') +
210 #df = open('data.dump.dbg', mode='wb')
213 # POST -use -c 'multipart/form-data; boundary="b"' http://localhost:8099/ <data.dump.dbg
215 cl
.log(DBG
.HTTP_FULL
, 'requesting: ' + str(mime
))
217 hh
= { 'User-Agent': ['hippotat'],
218 'Content-Type': ['multipart/form-data; boundary="b"'],
219 'Content-Length': [str(len(mime
))] }
221 bytesreader
= io
.BytesIO(mime
)
222 producer
= twisted
.web
.client
.FileBodyProducer(bytesreader
)
224 req
= cl
.agent
.request(b
'POST',
226 twisted
.web
.client
.Headers(hh
),
229 cl
.outstanding
[req
] = len(d
)
230 cl
.log(DBG
.HTTP_CTRL
,
231 'request OS=%d' %
len(cl
.outstanding
),
233 req
.addTimeout(cl
.c
.http_timeout
, reactor
)
234 req
.addCallback(partial(cl
.req_ok
, req
))
235 req
.addErrback(partial(cl
.req_err
, req
))
241 def process_cfg(_opts
, putative_servers
, putative_clients
):
244 for ss
in putative_servers
.values():
245 for (ci
,cs
) in putative_clients
.items():
248 sections
= cfg_process_client_common(c
,ss
,cs
,ci
)
249 if not sections
: continue
251 log_debug_config('processing client [%s %s]' %
(ss
, cs
))
253 def srch(getter
,key
): return cfg_search(getter
,key
,sections
)
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')
262 try: c
.ifname
= srch(cfg_get_raw
, 'ifname_client')
263 except NoOptionError
: pass
265 try: c
.url
= srch(cfg
.get
,'url')
266 except NoOptionError
:
267 cfg_process_saddrs(c
, ss
)
268 c
.url
= c
.saddrs
[0].url()
272 cfg_process_vaddr(c
,ss
)
278 ('rnets','vroutes')))
280 clients
.append(Client(c
,ss
,cs
))
282 common_startup(process_cfg
)
286 cl
.ipif
= start_ipif(cl
.c
.ipif_command
, cl
.outbound
)