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
, desc
):
38 def _log(self
, dflag
, msg
, **kwargs
):
39 self
._cl
.log(dflag
, '%s: %s' %
(self
._desc
, msg
), idof
=self
._req
, **kwargs
)
41 def connectionMade(self
):
42 self
._log(DBG
.HTTP_CTRL
, 'connectionMade')
44 class ResponseConsumer(GeneralResponseConsumer
):
45 def __init__(self
, cl
, req
):
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__')
51 def dataReceived(self
, data
):
52 self
._log(DBG
.HTTP
, 'dataReceived', d
=data
)
54 self
._ssd
.inputdata(data
)
55 except Exception as e
:
56 self
._handleexception()
58 def connectionLost(self
, reason
):
59 self
._log(DBG
.HTTP_CTRL
, 'connectionLost ' + str(reason
))
60 if not reason
.check(twisted
.web
.client
.ResponseDone
):
64 self
._log(DBG
.HTTP
, 'ResponseDone')
66 self
._cl
.req_fin(self
._req
)
67 except Exception as e
:
68 self
._handleexception()
69 self
._cl
.report_running()
71 def _handleexception(self
):
72 self
._latefailure(traceback
.format_exc())
74 def _latefailure(self
, reason
):
75 self
._log(DBG
.HTTP_CTRL
, '_latefailure ' + str(reason
))
76 self
._cl
.req_err(self
._req
, reason
)
78 class ErrorResponseConsumer(GeneralResponseConsumer
):
79 def __init__(self
, cl
, req
, resp
):
80 super().__init__(cl
, req
, 'ERROR-RC')
84 self
._phrase
= resp
.phrase
.decode('utf-8')
86 self
._phrase
= repr(resp
.phrase
)
87 self
._log(DBG
.HTTP_CTRL
, '__init__ %d %s' %
(resp
.code
, self
._phrase
))
89 def dataReceived(self
, data
):
90 self
._log(DBG
.HTTP_CTRL
, 'dataReceived ' + repr(data
))
93 def connectionLost(self
, reason
):
95 mbody
= self
._m
.decode('utf-8')
98 if not reason
.check(twisted
.web
.client
.ResponseDone
):
99 mbody
+= ' || ' + str(reason
)
100 self
._cl
.req_err(self
._req
,
102 %
(self
._resp
.code
, self
._phrase
, mbody
))
105 def __init__(cl
, c
,ss
,cs
):
108 cl
.desc
= '[%s %s] ' %
(ss
,cs
)
109 cl
.running_reported
= False
110 cl
.log_info('setting up')
112 def log_info(cl
, msg
):
113 log
.info(cl
.desc
+ msg
, dflag
=False)
115 def report_running(cl
):
116 if not cl
.running_reported
:
117 cl
.log_info('running OK')
118 cl
.running_reported
= True
120 def log(cl
, dflag
, msg
, **kwargs
):
121 log_debug(dflag
, cl
.desc
+ msg
, **kwargs
)
123 def log_outstanding(cl
):
124 cl
.log(DBG
.CTRL_DUMP
, 'OS %s' % cl
.outstanding
)
127 cl
.queue
= PacketQueue('up', cl
.c
.max_queue_time
)
128 cl
.agent
= twisted
.web
.client
.Agent(
129 reactor
, connectTimeout
= cl
.c
.http_timeout
)
131 def outbound(cl
, packet
, saddr
, daddr
):
132 #print('OUT ', saddr, daddr, repr(packet))
133 cl
.queue
.append(packet
)
136 def req_ok(cl
, req
, resp
):
137 cl
.log(DBG
.HTTP_CTRL
,
138 'req_ok %d %s %s' %
(resp
.code
, repr(resp
.phrase
), str(resp
)),
141 rc
= ResponseConsumer(cl
, req
)
143 rc
= ErrorResponseConsumer(cl
, req
, resp
)
146 # now rc is responsible for calling req_fin
148 def req_err(cl
, req
, err
):
149 # called when the Deferred fails, or (if it completes),
150 # later, by ResponsConsumer or ErrorResponsConsumer
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('%s[%#x] %s' %
(cl
.desc
, id(req
), err
.strip('\n').replace('\n',' / ')),
157 if not isinstance(cl
.outstanding
[req
], int):
158 raise RuntimeError('[%#x] previously %s' %
159 (id(req
), cl
.outstanding
[req
]))
160 cl
.outstanding
[req
] = err
162 reactor
.callLater(cl
.c
.http_retry
, partial(cl
.req_fin
, req
))
163 except Exception as e
:
164 crash(traceback
.format_exc() + '\n----- handling -----\n' + err
)
166 def req_fin(cl
, req
):
167 del cl
.outstanding
[req
]
168 cl
.log(DBG
.HTTP_CTRL
, 'req_fin OS=%d' %
len(cl
.outstanding
), idof
=req
)
171 def check_outbound(cl
):
173 if len(cl
.outstanding
) >= cl
.c
.max_outstanding
:
176 if (not cl
.queue
.nonempty() and
177 len(cl
.outstanding
) >= cl
.c
.target_requests_outstanding
):
181 def moredata(s
): nonlocal d
; d
+= s
182 cl
.queue
.process((lambda: len(d
)),
186 d
= mime_translate(d
)
190 mime
= (b
'--b' + crlf
+
191 b
'Content-Type: text/plain; charset="utf-8"' + crlf
+
192 b
'Content-Disposition: form-data; name="m"' + crlf
+ crlf
+
193 str(cl
.c
.client
) .encode('ascii') + crlf
+
194 cl
.c
.password
+ crlf
+
195 str(cl
.c
.target_requests_outstanding
)
196 .encode('ascii') + crlf
+
197 str(cl
.c
.http_timeout
) .encode('ascii') + crlf
+
200 b
'Content-Type: application/octet-stream' + crlf
+
201 b
'Content-Disposition: form-data; name="d"' + crlf
+ crlf
+
203 ) if len(d
) else b
'') +
206 #df = open('data.dump.dbg', mode='wb')
209 # POST -use -c 'multipart/form-data; boundary="b"' http://localhost:8099/ <data.dump.dbg
211 cl
.log(DBG
.HTTP_FULL
, 'requesting: ' + str(mime
))
213 hh
= { 'User-Agent': ['hippotat'],
214 'Content-Type': ['multipart/form-data; boundary="b"'],
215 'Content-Length': [str(len(mime
))] }
217 bytesreader
= io
.BytesIO(mime
)
218 producer
= twisted
.web
.client
.FileBodyProducer(bytesreader
)
220 req
= cl
.agent
.request(b
'POST',
222 twisted
.web
.client
.Headers(hh
),
225 cl
.outstanding
[req
] = len(d
)
226 cl
.log(DBG
.HTTP_CTRL
,
227 'request OS=%d' %
len(cl
.outstanding
),
229 req
.addTimeout(cl
.c
.http_timeout
, reactor
)
230 req
.addCallback(partial(cl
.req_ok
, req
))
231 req
.addErrback(partial(cl
.req_err
, req
))
237 def process_cfg(_opts
, putative_servers
, putative_clients
):
240 for ss
in putative_servers
.values():
241 for (ci
,cs
) in putative_clients
.items():
244 sections
= cfg_process_client_common(c
,ss
,cs
,ci
)
245 if not sections
: continue
247 log_debug_config('processing client [%s %s]' %
(ss
, cs
))
249 def srch(getter
,key
): return cfg_search(getter
,key
,sections
)
251 c
.http_timeout
+= srch(cfg
.getint
, 'http_timeout_grace')
252 c
.max_outstanding
= srch(cfg
.getint
, 'max_requests_outstanding')
253 c
.max_batch_up
= srch(cfg
.getint
, 'max_batch_up')
254 c
.http_retry
= srch(cfg
.getint
, 'http_retry')
255 c
.max_queue_time
= srch(cfg
.getint
, 'max_queue_time')
256 c
.vroutes
= srch(cfg
.get
, 'vroutes')
258 try: c
.ifname
= srch(cfg_get_raw
, 'ifname_client')
259 except NoOptionError
: pass
261 try: c
.url
= srch(cfg
.get
,'url')
262 except NoOptionError
:
263 cfg_process_saddrs(c
, ss
)
264 c
.url
= c
.saddrs
[0].url()
268 cfg_process_vaddr(c
,ss
)
274 ('rnets','vroutes')))
276 clients
.append(Client(c
,ss
,cs
))
278 common_startup(process_cfg
)
282 cl
.ipif
= start_ipif(cl
.c
.ipif_command
, cl
.outbound
)