-
Notifications
You must be signed in to change notification settings - Fork 13
Expand file tree
/
Copy path_proto.py
More file actions
2091 lines (1782 loc) · 65.6 KB
/
_proto.py
File metadata and controls
2091 lines (1782 loc) · 65.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
from __future__ import print_function
import sys
import json
import binascii
import functools
import struct
import signal
from typing import IO, Callable, TextIO
from functools import partial
import click
import humanize
from attrs import frozen, define, asdict, Factory as AttrFactory
from rich.live import Live
import msgpack
import automat
from twisted.internet import reactor
from twisted.internet.defer import Deferred, ensureDeferred, DeferredList, race, CancelledError, TimeoutError
from twisted.internet.task import deferLater
from twisted.internet.protocol import Factory, Protocol
from twisted.internet.error import ConnectionDone
from twisted.internet.stdio import StandardIO
from twisted.protocols.basic import LineReceiver
from twisted.python.failure import Failure
from zope.interface import directlyProvides
from wormhole.cli.public_relay import RENDEZVOUS_RELAY as PUBLIC_MAILBOX_URL, TRANSIT_RELAY
import wormhole.errors as wormhole_errors
from .observer import When, Next
from .messages import (
SetCode,
AllocateCode,
RemoteListener,
LocalListener,
SessionClose,
Welcome,
Listening,
ListeningFailed,
AwaitingConnect,
RemoteConnectFailed,
PeerConnected,
CodeAllocated,
BytesOut,
BytesIn,
IncomingConnection,
IncomingDone,
IncomingLost,
OutgoingConnection,
OutgoingDone,
OutgoingLost,
WormholeClosed,
WormholeError,
Ping,
Pong,
FowlOutputMessage,
FowlCommandMessage,
PleaseCloseWormhole,
)
from .status import _StatusTracker
from .visual import render_status
APPID = u"meejah.ca/wormhole/forward"
WELL_KNOWN_MAILBOXES = {
"default": PUBLIC_MAILBOX_URL,
"local": "ws://localhost:4000/v1",
"winden": "wss://mailbox.mw.leastauthority.com/v1",
# Do YOU run a public mailbox service? Contact the project to
# consider having it listed here
}
SUPPORTED_FEATURES = [
"core-v1", # the only version of the protocol so far
]
def _sequential_id():
"""
Yield a stream of IDs, starting at 1
"""
next_id = 0
while True:
next_id += 1
yield next_id
allocate_connection_id = partial(next, _sequential_id())
class _TimestampedWriter:
"""
Wrap a writable stream and prefix each line with elapsed time.
"""
def __init__(self, reactor, writable, start_time):
self._reactor = reactor
self._writable = writable
self._start_time = start_time
self._at_line_start = True
def write(self, data):
written = 0
for chunk in data.splitlines(keepends=True):
if self._at_line_start:
elapsed = self._reactor.seconds() - self._start_time
written += self._writable.write(f"{elapsed:.3f} ")
written += self._writable.write(chunk)
self._at_line_start = chunk.endswith("\n")
return written
def flush(self):
return self._writable.flush()
def __getattr__(self, name):
return getattr(self._writable, name)
#@frozen
@define ## could be @frozen, but for "policy" ... hmmm
class _Config:
"""
Represents a set of validated configuration
"""
relay_url: str = PUBLIC_MAILBOX_URL
code: str = None
code_length: int = 2
use_tor: bool = False
appid: str = APPID
debug_state: bool = False
stdout: IO = sys.stdout
stderr: IO = sys.stderr
create_stdio: Callable = None # returns a StandardIO work-alike, for testing
debug_file: IO = None # for state-machine transitions
commands: list[FowlCommandMessage] = AttrFactory(list)
output_debug_messages: TextIO = None # Option<Writable>
output_status: TextIO = None # Option<Readable>
no_logo: bool = False
async def wormhole_from_config(reactor, config, on_status, wormhole_create=None):
"""
Create a suitable wormhole for the given configuration.
:returns DeferredWormhole: a wormhole API
"""
if wormhole_create is None:
from wormhole import create as wormhole_create
tor = None
if config.use_tor:
tor = await get_tor(reactor)
# XXX use a Message
print(
json.dumps({
"kind": "tor",
"version": tor.version,
}),
file=config.stdout,
flush=True,
)
w = wormhole_create(
config.appid or APPID,
config.relay_url,
reactor,
tor=tor,
timing=None, # args.timing,
dilation=True,
versions={
"fowl": {
"features": SUPPORTED_FEATURES,
}
},
on_status_update=on_status,
)
if config.debug_state:
w.debug_set_trace("forward", file=config.stdout)
return w
@frozen
class Connection:
endpoint: str
i: int = 0
o: int = 0
unique_name: str = "unknown"
async def frontend_accept_or_invite(reactor, config):
"""
This runs the core of the default 'fowl' behavior:
- creates a code (or: consumes a code)
- creates any local listeners
- creates any remote listeners
- await incoming subchannels:
- attempt local connection (if permitted by policy)
- forward traffic until one side closes
- await connects on local listeners:
- open subchannel
- request far-side connection
- forward traffic until one side closes
"""
status_tracker = _StatusTracker()
fowl_wh = await create_fowl(config, status_tracker, True)
fowl_wh.start()
# testing a TUI style output UI, maybe optional?
def render():
return render_status(
status_tracker.current_status,
reactor.seconds(),
show_logo=not config.no_logo
)
from rich.console import Console
console = Console(force_terminal=True)
live = Live(get_renderable=render, console=console)
### XXX use PleaseCloseWormhole, approximately
reactor.addSystemEventTrigger("before", "shutdown", lambda: ensureDeferred(fowl_wh.disconnect_session()))
if config.code is not None:
fowl_wh.command(
SetCode(config.code)
)
else:
fowl_wh.command(
AllocateCode(config.code_length)
)
async def issue_commands():
await fowl_wh.when_connected()
for command in config.commands:
fowl_wh.command(command)
d = ensureDeferred(issue_commands())
@d.addErrback
def command_issue_failed(f):
print(f"Failed to issue command: {f}")
done_d = fowl_wh.when_done()
# debugging: "rich" is decent at showing you stuff printed out,
# but for reasons unknown to me it doesn't show "unhandled error"
# from Twisted -- replace "with live:" here with "if 1:" to see
# more error stuff (but of course no TUI)
#if 1:
with live:
while not done_d.called:
await deferLater(reactor, 0.25, lambda: None)
class FowlNearToFar(Protocol):
"""
This is the side of the protocol that was listening .. so a local
connection has come in, creating an instance of this protocol.
In ``connectionMade`` we send the initial message. So the
state-machine here is waiting for the reply before forwarding
data.
Forwards data to the `.other_protocol` from the Factory.
"""
m = automat.MethodicalMachine()
@m.state(initial=True)
def await_confirmation(self):
"""
Waiting for the reply from the other side.
"""
@m.state()
def evaluating(self):
"""
Making the local connection.
"""
@m.state()
def forwarding_bytes(self):
"""
All bytes go to the other side.
"""
@m.state()
def finished(self):
"""
We are done (something went wrong or the wormhole session has been
closed)
"""
@m.input()
def got_bytes(self, data):
"""
received some number of bytes
"""
@m.input()
def no_confirmation(self):
"""
Don't need to wait for a message
"""
@m.input()
def got_reply(self, msg):
"""
Got a complete message (without length prefix)
"""
@m.input()
def remote_connected(self):
"""
The reply message was positive
"""
@m.input()
def remote_not_connected(self, reason):
"""
The reply message was negative
"""
@m.input()
def too_much_data(self, reason):
"""
Too many bytes sent in the reply.
"""
# XXX is this really an error in this direction? i think only
# on the other side...
@m.input()
def subchannel_closed(self, reason):
"""
Our subchannel has closed
"""
@m.output()
def find_message(self, data):
"""
Buffer 'data' and determine if a complete message exists; if so,
inject that input.
"""
self._buffer += data
bsize = len(self._buffer)
if bsize >= 2:
msgsize, = struct.unpack("!H", self._buffer[:2])
if bsize > msgsize + 2:
self.too_much_data()
return
elif bsize == msgsize + 2:
msg = msgpack.unpackb(self._buffer[2:2 + msgsize])
# this used to have a callLater(0, ..) for the
# got_reply -- not sure this can happen "in practice",
# but in testing at least the server can start sending
# bytes _immediately_ so we must call synchronously..
return self.got_reply(msg)
return
@m.output()
def check_message(self, msg):
"""
Initiate the local connection
"""
if msg.get("connected", False):
self.remote_connected()
else:
self.remote_not_connected(msg.get("reason", "Unknown"))
@m.output()
def send_queued_data(self):
"""
Confirm to the other side that we've connected.
"""
self.factory.other_proto.transport.resumeProducing()
# we _had_ a queue in this, but nothing ever put anything into
# it ..
# self.factory.other_proto._maybe_drain_queue()
@m.output()
def emit_remote_failed(self, reason):
# print("bad", reason)
self.factory.coop._status_tracker.outgoing_lost(
self.factory.conn_id,
reason,
)
@m.output()
def close_connection(self):
"""
Shut down this subchannel.
"""
self.transport.loseConnection()
@m.output()
def close_other_connection(self):
"""
Shut down this subchannel.
"""
self.factory.other_proto.transport.loseConnection()
@m.output()
def forward_bytes(self, data):
"""
Send bytes to the other side
"""
self.factory.other_proto.transport.write(data)
self.factory.coop._status_tracker.bytes_out(
self.factory.conn_id,
len(data),
)
# @m.output()
# def emit_incoming_lost(self):
# # do we need a like "OutgoingLost"?
# self.factory.message_out(IncomingLost(self.factory.conn_id, "Unknown"))
await_confirmation.upon(
no_confirmation,
enter=forwarding_bytes,
outputs=[]
)
await_confirmation.upon(
got_bytes,
enter=await_confirmation,
outputs=[find_message]
)
await_confirmation.upon(
too_much_data,
enter=finished,
outputs=[close_connection]
)
await_confirmation.upon(
got_reply,
enter=evaluating,
outputs=[check_message]
)
await_confirmation.upon(
subchannel_closed,
enter=finished,
outputs=[], # used to emit_incoming_lost, do we need to handle something here?
)
evaluating.upon(
remote_connected,
enter=forwarding_bytes,
outputs=[send_queued_data]
)
evaluating.upon(
remote_not_connected,
enter=evaluating,
outputs=[emit_remote_failed, close_connection]
)
evaluating.upon(
subchannel_closed,
enter=finished,
outputs=[]
)
forwarding_bytes.upon(
got_bytes,
enter=forwarding_bytes,
outputs=[forward_bytes]
)
forwarding_bytes.upon(
subchannel_closed,
enter=finished,
outputs=[close_other_connection]
)
finished.upon(
got_reply,
enter=finished,
outputs=[]
)
do_trace = m._setTrace
def connectionMade(self):
# might be "better state-machine" to do the message-sending in
# an @output and use this method to send "connected()" @input
# or similar?
self.transport.registerProducer(self, True)
self._buffer = b""
# self.do_trace(lambda o, i, n: print("{} --[ {} ]--> {}".format(o, i, n)))
self.local = self.factory.other_proto
self.factory.other_proto.remote = self
self.transport.write(
_pack_netstring(
msgpack.packb({
"unique-name": self.factory.unique_name,
})
)
)
self.factory.coop._status_tracker.outgoing_connection(
self.factory.unique_name,
self.factory.conn_id,
)
# MUST wait for reply first -- queueing all data until
# then
self.factory.other_proto.transport.pauseProducing()
def pauseProducing(self):
##print(f"{type(self)} -> pauseProducing")
# remove ourselves from the reactor
self.factory.coop._reactor.removeReader(self.factory.other_proto.transport)
self.factory.coop._reactor.removeWriter(self.factory.other_proto.transport)
def resumeProducing(self):
##print(f"{type(self)} -> resumeProducing")
# add back to the reactor
self.factory.coop._reactor.addReader(self.factory.other_proto.transport)
self.factory.coop._reactor.addWriter(self.factory.other_proto.transport)
def dataReceived(self, data):
self.got_bytes(data)
def connectionLost(self, reason):
# XXX we get exception if we do this (keyerror) so I don't
# think we need to? todo: double-check what happens in this
# path
##self.transport.unregisterProducer()
self.subchannel_closed(str(reason))
if self.factory.other_proto:
self.factory.other_proto.transport.loseConnection()
if isinstance(reason, ConnectionDone):
self.factory.coop._status_tracker.outgoing_done(
self.factory.conn_id,
)
else:
self.factory.coop._status_tracker.outgoing_lost(
self.factory.conn_id,
str(reason),
)
class ConnectionForward(Protocol):
"""
The protocol we speak on connections _we_ make to local
servers. So this basically _just_ forwards bytes.
"""
m = automat.MethodicalMachine()
@m.state(initial=True)
def forwarding_bytes(self):
"""
All bytes go to the other side.
"""
@m.state()
def finished(self):
"""
We are done (something went wrong or the wormhole session has been
closed)
"""
@m.input()
def got_bytes(self, data):
"""
received some number of bytes
"""
@m.input()
def stream_closed(self, reason):
"""
The local server has closed our connection
"""
@m.output()
def forward_bytes(self, data):
"""
Send bytes to the other side.
This will be from the 'actual server' side to our local client
"""
self.factory.other_proto.transport.write(data)
self.factory.coop._status_tracker.bytes_in(
self.factory.conn_id,
len(data),
)
@m.output()
def close_other_side(self, reason):
try:
if self.factory.other_proto:
self.factory.other_proto.transport.loseConnection()
except Exception:
pass
forwarding_bytes.upon(
got_bytes,
enter=forwarding_bytes,
outputs=[forward_bytes]
)
forwarding_bytes.upon(
stream_closed,
enter=finished,
outputs=[close_other_side]
)
def connectionMade(self):
pass
def dataReceived(self, data):
self.got_bytes(data)
def connectionLost(self, reason):
self.stream_closed(reason)
class LocalServerFarSide(Protocol):
"""
"""
def connectionMade(self):
self.remote = None
self.conn_id = allocate_connection_id()
# XXX do we need registerProducer somewhere here?
# XXX make a real Factory subclass instead
factory = Factory.forProtocol(FowlNearToFar)
factory.other_proto = self
factory.conn_id = self.conn_id
factory.unique_name = self.factory.unique_name
factory.coop = self.factory.coop
connect_ep = self.factory.coop.subchannel_connector()
#XXXX we want "a local connection" endpoint
d = ensureDeferred(connect_ep.connect(factory))
def err(f):
self.factory.coop._status_tracker.error(
str(f.value),
)
d.addErrback(err)
return d
def connectionLost(self, reason):
# XXX causes duplice local_close 'errors' in magic-wormhole ... do we not want to do this?)
if self.remote is not None and self.remote.transport:
self.remote.transport.loseConnection()
def dataReceived(self, data):
self.factory.coop._status_tracker.bytes_in(
self.conn_id,
len(data),
)
self.remote.transport.write(data)
class FowlSubprotocolListener(Factory):
def __init__(self, reactor, coop, status):
self.reactor = reactor
self.coop = coop
self.status = status
super(FowlSubprotocolListener, self).__init__()
def buildProtocol(self, addr):
# 'addr' is a SubchannelAddress
assert addr.subprotocol == "fowl", f"unknown subprotocol name: {addr}"
p = FowlFarToNear() # XXX cross-the-road joke in the naming? plz??
p.factory = self
return p
def _pack_netstring(data):
"""
:param bytes data: data to length-prefix
:returns: a binary 'netstring' with a length prefix encoded as a
unsigned 16-bit integer.
"""
if len(data) >= 2**16:
raise ValueError("Too many bytes to encode in 16-bit integer")
prefix = struct.pack("!H", len(data))
return prefix + data
class FowlFarToNear(Protocol):
"""
Handle an incoming Dilation subchannel. This will be from a
listener on the other end of the wormhole.
There is an opening message, and then we forward bytes.
The opening message is a length-prefixed blob; the first 2
bytes of the stream indicate the length (an unsigned short in
network byte order).
The message itself is msgpack-encoded.
A single reply is produced, following the same format: 2-byte
length prefix followed by a msgpack-encoded payload.
The opening message contains a dict like::
{
"local-desination": "tcp:localhost:1234",
}
The "forwarding" side (i.e the one that opened the subchannel)
MUST NOT send any data except the opening message until it
receives a reply from this side. This side (the connecting
side) may deny the connection for any reason (e.g. it might
not even try, if policy says not to).
"""
m = automat.MethodicalMachine()
set_trace = m._setTrace
@m.state(initial=True)
def await_message(self):
"""
The other side must send us a message
"""
@m.state()
def local_policy_check(self):
"""
A connection has come in; we must check our policy
"""
@m.state()
def local_connect(self):
"""
The initial message tells us where to connect locally
"""
@m.state()
def forwarding_bytes(self):
"""
We are connected and have done the proper information exchange;
now we merely forward bytes.
"""
@m.state()
def finished(self):
"""
Completed the task of forwarding (e.g. client closed connection,
subchannel closed, fatal error, etc)
"""
@m.input()
def policy_bad(self, msg):
"""
The local policy check has failed (not allowed)
"""
@m.input()
def policy_ok(self, msg):
"""
The local policy check has succeeded (allowed)
"""
@m.input()
def got_bytes(self, data):
"""
We received some bytes
"""
@m.input()
def too_much_data(self, reason):
"""
We received too many bytes (for the first message).
"""
@m.input()
def got_initial_message(self, msg):
"""
The entire initial message is received (`msg` excludes the
length-prefix but it is not yet parsed)
"""
@m.input()
def subchannel_closed(self, reason):
"""
This subchannel has been closed
"""
@m.input()
def connection_made(self):
"""
We successfully made the local connection
"""
@m.input()
def connection_failed(self, reason):
"""
Making the local connection failed
"""
@m.output()
def close_connection(self, reason):
"""
We wish to close this subchannel
"""
# there isn't currently a great way to pass on "why" we closed
# to the Subchannel -- this will end up with "exited
# normally", approximately, but it would be ideal if we could
# pass along this reason somehow.
self.transport.loseConnection()
@m.output()
def close_local_connection(self):
"""
We wish to close this subchannel
"""
if self._local_connection and self._local_connection.transport:
self._local_connection.transport.loseConnection()
@m.output()
def forward_data(self, data):
assert self._buffer is None, "Internal error: still buffering"
assert self._local_connection is not None, "expected local connection by now"
self._local_connection.transport.write(data)
self.factory.coop._status_tracker.bytes_out(
self.conn_id,
len(data),
)
@m.output()
def find_message(self, data):
"""
Buffer this data and determine if we have a single message yet
"""
# state-machine shouldn't allow this, but just to be sure
assert self._buffer is not None, "Internal error: buffer is gone"
self._buffer += data
bsize = len(self._buffer)
if bsize >= 2:
expected_size, = struct.unpack("!H", self._buffer[:2])
if bsize >= expected_size + 2:
first_msg = self._buffer[2:2 + expected_size]
self._buffer = None
# there should be no "leftover" data
if bsize > 2 + expected_size:
self.too_much_data("Too many bytes sent")
return
# warning: recursive state-machine message
self.got_initial_message(msgpack.unpackb(first_msg))
@m.output()
def send_negative_reply(self, reason):
"""
Tell our peer why we're closing them
"""
self._negative(reason)
self.factory.coop._status_tracker.incoming_lost(
self.conn_id,
reason,
)
def _negative(self, reason):
self.transport.write(
_pack_netstring(
msgpack.packb({
"connected": False,
"reason": reason,
})
)
)
@m.output()
def send_positive_reply(self):
"""
Reply to the other side that we've connected properly
"""
self.transport.write(
_pack_netstring(
msgpack.packb({
"connected": True,
})
)
)
@m.output()
def emit_incoming_connection(self, msg):
self.factory.coop._status_tracker.incoming_connection(
msg.get("unique-name", None),
self.conn_id,
)
@m.output()
def do_policy_check(self, msg):
# note: do this policy check after the IncomingConnection
# message is emitted (otherwise there will be cases where we
# emit _just_ a IncomingLost which is confusing)
name = msg.get("unique-name", None)
if name is None or name not in self.factory.coop._services:
self.policy_bad(f'No service "{name}"')
return
channel = self.factory.coop._services[name]
port = msg.get("listen-port", None)
if port is not None:
if channel.listen_port != port:
self.policy_bad(
f'Remote specified {port} for service {name} but '
'we have {channel.listen_port} here.'
)
return
self.policy_ok(msg)
@m.output()
def local_disconnect(self):
self._negative("Against local policy")
self.transport.loseConnection()
@m.output()
def emit_incoming_lost(self, msg):
self.factory.coop._status_tracker.incoming_lost(
self.conn_id,
f"Incoming connection against local policy: {msg}",
)
@m.output()
def emit_incoming_done(self, reason):
if isinstance(reason, ConnectionDone):
self.factory.coop._status_tracker.incoming_done(
self.conn_id,
)
else:
self.factory.coop._status_tracker.incoming_lost(
self.conn_id,
str(reason),
)
@m.output()
def establish_local_connection(self, msg):
"""
For a given service, establish our outgoing local connection
"""
ep = self.factory.coop.local_connect_endpoint(msg["unique-name"])
factory = Factory.forProtocol(ConnectionForward)
factory.other_proto = self
factory.coop = self.factory.coop
factory.conn_id = self.conn_id
d = ep.connect(factory)
def bad(fail):
reactor.callLater(0, lambda: self.connection_failed(fail.getErrorMessage()))
return None
def assign(proto):
# if we hit the error-case above, we "handled" it so want
# to return None -- but this pushes us into the "success"
# / callback side, albiet with "None" as the value
self._local_connection = proto
if self._local_connection is not None:
reactor.callLater(0, lambda: self.connection_made())
return proto
d.addErrback(bad)
d.addCallback(assign)
await_message.upon(
got_bytes,
enter=await_message,
outputs=[find_message]
)
await_message.upon(
too_much_data,
enter=finished,
outputs=[close_connection]
)
await_message.upon(
got_initial_message,
enter=local_policy_check,
outputs=[emit_incoming_connection, do_policy_check]
)
local_policy_check.upon(
policy_ok,
enter=local_connect,
outputs=[establish_local_connection]
)
local_policy_check.upon(
policy_bad,
enter=finished,
outputs=[local_disconnect, emit_incoming_lost]
)
await_message.upon(
subchannel_closed,
enter=finished,
outputs=[emit_incoming_done],
)