forked from haskell-distributed/network-transport-tcp
-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathTCP.hs
2204 lines (2070 loc) · 95.2 KB
/
TCP.hs
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
-- | TCP implementation of the transport layer.
--
-- The TCP implementation guarantees that only a single TCP connection (socket)
-- will be used between endpoints, provided that the addresses specified are
-- canonical. If /A/ connects to /B/ and reports its address as
-- @192.168.0.1:8080@ and /B/ subsequently connects tries to connect to /A/ as
-- @client1.local:http-alt@ then the transport layer will not realize that the
-- TCP connection can be reused.
--
-- Applications that use the TCP transport should use
-- 'Network.Socket.withSocketsDo' in their main function for Windows
-- compatibility (see "Network.Socket").
{-# LANGUAGE RecursiveDo #-}
{-# LANGUAGE TupleSections #-}
{-# LANGUAGE RankNTypes #-}
module Network.Transport.TCP
( -- * Main API
createTransport
, TCPAddr(..)
, defaultTCPAddr
, TCPAddrInfo(..)
, TCPParameters(..)
, defaultTCPParameters
-- * Internals (exposed for unit tests)
, createTransportExposeInternals
, TransportInternals(..)
, EndPointId
, ControlHeader(..)
, ConnectionRequestResponse(..)
, firstNonReservedLightweightConnectionId
, firstNonReservedHeavyweightConnectionId
, socketToEndPoint
, LightweightConnectionId
, QDisc(..)
, simpleUnboundedQDisc
, simpleOnePlaceQDisc
-- * Design notes
-- $design
) where
import Prelude hiding
( mapM_
#if ! MIN_VERSION_base(4,6,0)
, catch
#endif
)
import Network.Transport
import Network.Transport.TCP.Internal
( ControlHeader(..)
, encodeControlHeader
, decodeControlHeader
, ConnectionRequestResponse(..)
, encodeConnectionRequestResponse
, decodeConnectionRequestResponse
, forkServer
, recvWithLength
, recvExact
, recvWord32
, encodeWord32
, tryCloseSocket
, tryShutdownSocketBoth
, resolveSockAddr
, EndPointId
, encodeEndPointAddress
, decodeEndPointAddress
, currentProtocolVersion
, randomEndPointAddress
)
import Network.Transport.Internal
( prependLength
, mapIOException
, tryIO
, tryToEnum
, void
, timeoutMaybe
, asyncWhenCancelled
)
#ifdef USE_MOCK_NETWORK
import qualified Network.Transport.TCP.Mock.Socket as N
#else
import qualified Network.Socket as N
#endif
( HostName
, ServiceName
, Socket
, getAddrInfo
, socket
, addrFamily
, addrAddress
, SocketType(Stream)
, defaultProtocol
, setSocketOption
, SocketOption(ReuseAddr, NoDelay, UserTimeout, KeepAlive)
, isSupportedSocketOption
, connect
, sOMAXCONN
, AddrInfo
, SockAddr(..)
)
#ifdef USE_MOCK_NETWORK
import Network.Transport.TCP.Mock.Socket.ByteString (sendMany)
#else
import Network.Socket.ByteString (sendMany)
#endif
import Control.Concurrent
( forkIO
, ThreadId
, killThread
, myThreadId
, threadDelay
, throwTo
)
import Control.Concurrent.Chan (Chan, newChan, readChan, writeChan)
import Control.Concurrent.MVar
( MVar
, newMVar
, modifyMVar
, modifyMVar_
, readMVar
, takeMVar
, putMVar
, newEmptyMVar
, withMVar
)
import Control.Category ((>>>))
import Control.Applicative ((<$>))
import Control.Monad (when, unless, join, mplus, (<=<))
import Control.Exception
( IOException
, SomeException
, AsyncException
, handle
, throw
, throwIO
, try
, bracketOnError
, bracket
, fromException
, finally
, catch
, bracket
, mask_
)
import Data.IORef (IORef, newIORef, writeIORef, readIORef, writeIORef)
import Data.ByteString (ByteString)
import qualified Data.ByteString as BS (concat, length, null)
import qualified Data.ByteString.Char8 as BSC (pack, unpack)
import Data.Bits (shiftL, (.|.))
import Data.Maybe (isJust)
import Data.Word (Word32)
import Data.Set (Set)
import qualified Data.Set as Set
( empty
, insert
, elems
, singleton
, null
, delete
, member
)
import Data.Map (Map)
import qualified Data.Map as Map (empty)
import Data.Traversable (traverse)
import Data.Accessor (Accessor, accessor, (^.), (^=), (^:))
import qualified Data.Accessor.Container as DAC (mapMaybe)
import Data.Foldable (forM_, mapM_)
import qualified System.Timeout (timeout)
-- $design
--
-- [Goals]
--
-- The TCP transport maps multiple logical connections between /A/ and /B/ (in
-- either direction) to a single TCP connection:
--
-- > +-------+ +-------+
-- > | A |==========================| B |
-- > | |>~~~~~~~~~~~~~~~~~~~~~~~~~|~~~\ |
-- > | Q |>~~~~~~~~~~~~~~~~~~~~~~~~~|~~~Q |
-- > | \~~~|~~~~~~~~~~~~~~~~~~~~~~~~~<| |
-- > | |==========================| |
-- > +-------+ +-------+
--
-- Ignoring the complications detailed below, the TCP connection is set up is
-- when the first lightweight connection is created (in either direction), and
-- torn down when the last lightweight connection (in either direction) is
-- closed.
--
-- [Connecting]
--
-- Let /A/, /B/ be two endpoints without any connections. When /A/ wants to
-- connect to /B/, it locally records that it is trying to connect to /B/ and
-- sends a request to /B/. As part of the request /A/ sends its own endpoint
-- address to /B/ (so that /B/ can reuse the connection in the other direction).
--
-- When /B/ receives the connection request it first checks if it did not
-- already initiate a connection request to /A/. If not it will acknowledge the
-- connection request by sending 'ConnectionRequestAccepted' to /A/ and record
-- that it has a TCP connection to /A/.
--
-- The tricky case arises when /A/ sends a connection request to /B/ and /B/
-- finds that it had already sent a connection request to /A/. In this case /B/
-- will accept the connection request from /A/ if /A/s endpoint address is
-- smaller (lexicographically) than /B/s, and reject it otherwise. If it rejects
-- it, it sends a 'ConnectionRequestCrossed' message to /A/. The
-- lexicographical ordering is an arbitrary but convenient way to break the
-- tie. If a connection exists between /A/ and /B/ when /B/ rejects the request,
-- /B/ will probe the connection to make sure it is healthy. If /A/ does not
-- answer timely to the probe, /B/ will discard the connection.
--
-- When it receives a 'ConnectionRequestCrossed' message the /A/ thread that
-- initiated the request just needs to wait until the /A/ thread that is dealing
-- with /B/'s connection request completes, unless there is a network failure.
-- If there is a network failure, the initiator thread would timeout and return
-- an error.
--
-- [Disconnecting]
--
-- The TCP connection is created as soon as the first logical connection from
-- /A/ to /B/ (or /B/ to /A/) is established. At this point a thread (@#@) is
-- spawned that listens for incoming connections from /B/:
--
-- > +-------+ +-------+
-- > | A |==========================| B |
-- > | |>~~~~~~~~~~~~~~~~~~~~~~~~~|~~~\ |
-- > | | | Q |
-- > | #| | |
-- > | |==========================| |
-- > +-------+ +-------+
--
-- The question is when the TCP connection can be closed again. Conceptually,
-- we want to do reference counting: when there are no logical connections left
-- between /A/ and /B/ we want to close the socket (possibly after some
-- timeout).
--
-- However, /A/ and /B/ need to agree that the refcount has reached zero. It
-- might happen that /B/ sends a connection request over the existing socket at
-- the same time that /A/ closes its logical connection to /B/ and closes the
-- socket. This will cause a failure in /B/ (which will have to retry) which is
-- not caused by a network failure, which is unfortunate. (Note that the
-- connection request from /B/ might succeed even if /A/ closes the socket.)
--
-- Instead, when /A/ is ready to close the socket it sends a 'CloseSocket'
-- request to /B/ and records that its connection to /B/ is closing. If /A/
-- receives a new connection request from /B/ after having sent the
-- 'CloseSocket' request it simply forgets that it sent a 'CloseSocket' request
-- and increments the reference count of the connection again.
--
-- When /B/ receives a 'CloseSocket' message and it too is ready to close the
-- connection, it will respond with a reciprocal 'CloseSocket' request to /A/
-- and then actually close the socket. /A/ meanwhile will not send any more
-- requests to /B/ after having sent a 'CloseSocket' request, and will actually
-- close its end of the socket only when receiving the 'CloseSocket' message
-- from /B/. (Since /A/ recorded that its connection to /B/ is in closing state
-- after sending a 'CloseSocket' request to /B/, it knows not to reciprocate /B/
-- reciprocal 'CloseSocket' message.)
--
-- If there is a concurrent thread in /A/ waiting to connect to /B/ after /A/
-- has sent a 'CloseSocket' request then this thread will block until /A/ knows
-- whether to reuse the old socket (if /B/ sends a new connection request
-- instead of acknowledging the 'CloseSocket') or to set up a new socket.
--------------------------------------------------------------------------------
-- Internal datatypes --
--------------------------------------------------------------------------------
-- We use underscores for fields that we might update (using accessors)
--
-- All data types follow the same structure:
--
-- * A top-level data type describing static properties (TCPTransport,
-- LocalEndPoint, RemoteEndPoint)
-- * The 'static' properties include an MVar containing a data structure for
-- the dynamic properties (TransportState, LocalEndPointState,
-- RemoteEndPointState). The state could be invalid/valid/closed,/etc.
-- * For the case of "valid" we use third data structure to give more details
-- about the state (ValidTransportState, ValidLocalEndPointState,
-- ValidRemoteEndPointState).
-- | Information about the network addresses of a transport: the external
-- host/port as well as the bound host/port, which are not necessarily the
-- same.
data TransportAddrInfo = TransportAddrInfo
{ transportHost :: !N.HostName
, transportPort :: !N.ServiceName
, transportBindHost :: !N.HostName
, transportBindPort :: !N.ServiceName
}
data TCPTransport = TCPTransport
{ transportAddrInfo :: !(Maybe TransportAddrInfo)
-- ^ This is 'Nothing' in case the transport is not addressable from the
-- network: peers cannot connect to it unless it has a connection to the
-- peer.
, transportState :: !(MVar TransportState)
, transportParams :: !TCPParameters
}
data TransportState =
TransportValid !ValidTransportState
| TransportClosed
data ValidTransportState = ValidTransportState
{ _localEndPoints :: !(Map EndPointId LocalEndPoint)
, _nextEndPointId :: !EndPointId
}
data LocalEndPoint = LocalEndPoint
{ localAddress :: !EndPointAddress
, localEndPointId :: !EndPointId
, localState :: !(MVar LocalEndPointState)
-- | A 'QDisc' is held here rather than on the 'ValidLocalEndPointState'
-- because even closed 'LocalEndPoint's can have queued input data.
, localQueue :: !(QDisc Event)
}
data LocalEndPointState =
LocalEndPointValid !ValidLocalEndPointState
| LocalEndPointClosed
data ValidLocalEndPointState = ValidLocalEndPointState
{ -- Next available ID for an outgoing lightweight self-connection
-- (see also remoteNextConnOutId)
_localNextConnOutId :: !LightweightConnectionId
-- Next available ID for an incoming heavyweight connection
, _nextConnInId :: !HeavyweightConnectionId
-- Currently active outgoing heavyweight connections
, _localConnections :: !(Map EndPointAddress RemoteEndPoint)
}
-- REMOTE ENDPOINTS
--
-- Remote endpoints (basically, TCP connections) have the following lifecycle:
--
-- Init ---+---> Invalid
-- |
-- +-------------------------------\
-- | |
-- | /----------\ |
-- | | | |
-- | v | v
-- +---> Valid ---> Closing ---> Closed
-- | | | |
-- | | | v
-- \-------+----------+--------> Failed
--
-- Init: There are two places where we create new remote endpoints: in
-- createConnectionTo (in response to an API 'connect' call) and in
-- handleConnectionRequest (when a remote node tries to connect to us).
-- 'Init' carries an MVar () 'resolved' which concurrent threads can use to
-- wait for the remote endpoint to finish initialization. We record who
-- requested the connection (the local endpoint or the remote endpoint).
--
-- Invalid: We put the remote endpoint in invalid state only during
-- createConnectionTo when we fail to connect.
--
-- Valid: This is the "normal" state for a working remote endpoint.
--
-- Closing: When we detect that a remote endpoint is no longer used, we send a
-- CloseSocket request across the connection and put the remote endpoint in
-- closing state. As with Init, 'Closing' carries an MVar () 'resolved' which
-- concurrent threads can use to wait for the remote endpoint to either be
-- closed fully (if the communication parnet responds with another
-- CloseSocket) or be put back in 'Valid' state if the remote endpoint denies
-- the request.
--
-- We also put the endpoint in Closed state, directly from Init, if we our
-- outbound connection request crossed an inbound connection request and we
-- decide to keep the inbound (i.e., the remote endpoint sent us a
-- ConnectionRequestCrossed message).
--
-- Closed: The endpoint is put in Closed state after a successful garbage
-- collection.
--
-- Failed: If the connection to the remote endpoint is lost, or the local
-- endpoint (or the whole transport) is closed manually, the remote endpoint is
-- put in Failed state, and we record the reason.
--
-- Invariants for dealing with remote endpoints:
--
-- INV-SEND: Whenever we send data the remote endpoint must be locked (to avoid
-- interleaving bits of payload).
--
-- INV-CLOSE: Local endpoints should never point to remote endpoint in closed
-- state. Whenever we put an endpoint in Closed state we remove that
-- endpoint from localConnections first, so that if a concurrent thread reads
-- the MVar, finds RemoteEndPointClosed, and then looks up the endpoint in
-- localConnections it is guaranteed to either find a different remote
-- endpoint, or else none at all (if we don't insist in this order some
-- threads might start spinning).
--
-- INV-RESOLVE: We should only signal on 'resolved' while the remote endpoint is
-- locked, and the remote endpoint must be in Valid or Closed state once
-- unlocked. This guarantees that there will not be two threads attempting to
-- both signal on 'resolved'.
--
-- INV-LOST: If a send or recv fails, or a socket is closed unexpectedly, we
-- first put the remote endpoint in Closed state, and then send a
-- EventConnectionLost event. This guarantees that we only send this event
-- once.
--
-- INV-CLOSING: An endpoint in closing state is for all intents and purposes
-- closed; that is, we shouldn't do any 'send's on it (although 'recv' is
-- acceptable, of course -- as we are waiting for the remote endpoint to
-- confirm or deny the request).
--
-- INV-LOCK-ORDER: Remote endpoint must be locked before their local endpoints.
-- In other words: it is okay to call modifyMVar on a local endpoint inside a
-- modifyMVar on a remote endpoint, but not the other way around. In
-- particular, it is okay to call removeRemoteEndPoint inside
-- modifyRemoteState.
data RemoteEndPoint = RemoteEndPoint
{ remoteAddress :: !EndPointAddress
, remoteState :: !(MVar RemoteState)
, remoteId :: !HeavyweightConnectionId
, remoteScheduled :: !(Chan (IO ()))
}
data RequestedBy = RequestedByUs | RequestedByThem
deriving (Eq, Show)
data RemoteState =
-- | Invalid remote endpoint (for example, invalid address)
RemoteEndPointInvalid !(TransportError ConnectErrorCode)
-- | The remote endpoint is being initialized
| RemoteEndPointInit !(MVar ()) !(MVar ()) !RequestedBy
-- | "Normal" working endpoint
| RemoteEndPointValid !ValidRemoteEndPointState
-- | The remote endpoint is being closed (garbage collected)
| RemoteEndPointClosing !(MVar ()) !ValidRemoteEndPointState
-- | The remote endpoint has been closed (garbage collected)
| RemoteEndPointClosed
-- | The remote endpoint has failed, or has been forcefully shutdown
-- using a closeTransport or closeEndPoint API call
| RemoteEndPointFailed !IOException
-- TODO: we might want to replace Set (here and elsewhere) by faster
-- containers
--
-- TODO: we could get rid of 'remoteIncoming' (and maintain less state) if
-- we introduce a new event 'AllConnectionsClosed'
data ValidRemoteEndPointState = ValidRemoteEndPointState
{ _remoteOutgoing :: !Int
, _remoteIncoming :: !(Set LightweightConnectionId)
, _remoteLastIncoming :: !LightweightConnectionId
, _remoteNextConnOutId :: !LightweightConnectionId
, remoteSocket :: !N.Socket
-- | When the connection is being probed, yields an IO action that can be
-- used to release any resources dedicated to the probing.
, remoteProbing :: Maybe (IO ())
, remoteSendLock :: !(MVar ())
-- | An IO which returns when the socket (remoteSocket) has been closed.
-- The program/thread which created the socket is always responsible
-- for closing it, but sometimes other threads need to know when this
-- happens.
, remoteSocketClosed :: !(IO ())
}
-- | Pair of local and a remote endpoint (for conciseness in signatures)
type EndPointPair = (LocalEndPoint, RemoteEndPoint)
-- | Lightweight connection ID (sender allocated)
--
-- A ConnectionId is the concentation of a 'HeavyweightConnectionId' and a
-- 'LightweightConnectionId'.
type LightweightConnectionId = Word32
-- | Heavyweight connection ID (recipient allocated)
--
-- A ConnectionId is the concentation of a 'HeavyweightConnectionId' and a
-- 'LightweightConnectionId'.
type HeavyweightConnectionId = Word32
-- | A transport which is addressable from the network must give a host/port
-- on which to bind/listen, and determine its external address (host/port) from
-- the actual port (which may not be known, in case 0 is used for the bind
-- port).
data TCPAddrInfo = TCPAddrInfo {
tcpBindHost :: N.HostName
, tcpBindPort :: N.ServiceName
, tcpExternalAddress :: N.ServiceName -> (N.HostName, N.ServiceName)
}
-- | Addressability of a transport. If your transport cannot be connected
-- to, for instance because it runs behind NAT, use Unaddressable.
data TCPAddr = Addressable TCPAddrInfo | Unaddressable
-- | The bind and external host/port are the same.
defaultTCPAddr :: N.HostName -> N.ServiceName -> TCPAddr
defaultTCPAddr host port = Addressable $ TCPAddrInfo {
tcpBindHost = host
, tcpBindPort = port
, tcpExternalAddress = (,) host
}
-- | Parameters for setting up the TCP transport
data TCPParameters = TCPParameters {
-- | Backlog for 'listen'.
-- Defaults to SOMAXCONN.
tcpBacklog :: Int
-- | Should we set SO_REUSEADDR on the server socket?
-- Defaults to True.
, tcpReuseServerAddr :: Bool
-- | Should we set SO_REUSEADDR on client sockets?
-- Defaults to True.
, tcpReuseClientAddr :: Bool
-- | Should we set TCP_NODELAY on connection sockets?
-- Defaults to True.
, tcpNoDelay :: Bool
-- | Should we set TCP_KEEPALIVE on connection sockets?
, tcpKeepAlive :: Bool
-- | Value of TCP_USER_TIMEOUT in milliseconds
, tcpUserTimeout :: Maybe Int
-- | A connect timeout for all 'connect' calls of the transport
-- in microseconds
--
-- This can be overriden for each connect call with
-- 'ConnectHints'.'connectTimeout'.
--
-- Connection requests to this transport will also timeout if they don't
-- send the required data before this many microseconds.
, transportConnectTimeout :: Maybe Int
-- | Create a QDisc for an EndPoint.
, tcpNewQDisc :: forall t . IO (QDisc t)
-- | Maximum length (in bytes) for a peer's address.
-- If a peer attempts to send an address of length exceeding the limit,
-- the connection will be refused (socket will close).
, tcpMaxAddressLength :: Word32
-- | Maximum length (in bytes) to receive from a peer.
-- If a peer attempts to send data on a lightweight connection exceeding
-- the limit, the heavyweight connection which carries that lightweight
-- connection will go down. The peer and the local node will get an
-- EventConnectionLost.
, tcpMaxReceiveLength :: Word32
-- | If True, new connections will be accepted only if the socket's host
-- matches the host that the peer claims in its EndPointAddress.
-- This is useful when operating on untrusted networks, because the peer
-- could otherwise deny service to some victim by claiming the victim's
-- address.
, tcpCheckPeerHost :: Bool
-- | What to do if there's an exception when accepting a new TCP
-- connection. Throwing an exception here will cause the server to
-- terminate.
, tcpServerExceptionHandler :: SomeException -> IO ()
}
-- | Internal functionality we expose for unit testing
data TransportInternals = TransportInternals
{ -- | The ID of the thread that listens for new incoming connections
transportThread :: Maybe ThreadId
-- | A variant of newEndPoint in which the QDisc determined by the
-- transport's TCPParameters can be optionally overridden.
, newEndPointInternal :: (forall t . Maybe (QDisc t))
-> IO (Either (TransportError NewEndPointErrorCode) EndPoint)
-- | Find the socket between a local and a remote endpoint
, socketBetween :: EndPointAddress
-> EndPointAddress
-> IO N.Socket
}
--------------------------------------------------------------------------------
-- Top-level functionality --
--------------------------------------------------------------------------------
-- | Create a TCP transport
createTransport
:: TCPAddr
-> TCPParameters
-> IO (Either IOException Transport)
createTransport addr params =
either Left (Right . fst) <$> createTransportExposeInternals addr params
-- | You should probably not use this function (used for unit testing only)
createTransportExposeInternals
:: TCPAddr
-> TCPParameters
-> IO (Either IOException (Transport, TransportInternals))
createTransportExposeInternals addr params = do
state <- newMVar . TransportValid $ ValidTransportState
{ _localEndPoints = Map.empty
, _nextEndPointId = 0
}
case addr of
Unaddressable ->
let transport = TCPTransport { transportState = state
, transportAddrInfo = Nothing
, transportParams = params
}
in fmap Right (mkTransport transport Nothing)
Addressable (TCPAddrInfo bindHost bindPort mkExternal) -> tryIO $ mdo
when ( isJust (tcpUserTimeout params) &&
not (N.isSupportedSocketOption N.UserTimeout)
) $
throwIO $ userError $ "Network.Transport.TCP.createTransport: " ++
"the parameter tcpUserTimeout is unsupported " ++
"in this system."
-- We don't know for sure the actual port 'forkServer' binded until it
-- completes (see description of 'forkServer'), yet we need the port to
-- construct a transport. So we tie a recursive knot.
(port', result) <- do
let (externalHost, externalPort) = mkExternal port'
let addrInfo = TransportAddrInfo { transportHost = externalHost
, transportPort = externalPort
, transportBindHost = bindHost
, transportBindPort = port'
}
let transport = TCPTransport { transportState = state
, transportAddrInfo = Just addrInfo
, transportParams = params
}
bracketOnError (forkServer
bindHost
bindPort
(tcpBacklog params)
(tcpReuseServerAddr params)
(errorHandler transport)
(terminationHandler transport)
(handleConnectionRequest transport (errorHandler transport)))
(\(_port', tid) -> killThread tid)
(\(port'', tid) -> (port'',) <$> mkTransport transport (Just tid))
return result
where
mkTransport :: TCPTransport
-> Maybe ThreadId
-> IO (Transport, TransportInternals)
mkTransport transport mtid = do
return
( Transport
{ newEndPoint = do
qdisc <- tcpNewQDisc params
apiNewEndPoint transport qdisc
, closeTransport = let evs = [ EndPointClosed ]
in apiCloseTransport transport mtid evs
}
, TransportInternals
{ transportThread = mtid
, socketBetween = internalSocketBetween transport
, newEndPointInternal = \mqdisc -> case mqdisc of
Just qdisc -> apiNewEndPoint transport qdisc
Nothing -> do
qdisc <- tcpNewQDisc params
apiNewEndPoint transport qdisc
}
)
errorHandler :: TCPTransport -> SomeException -> IO ()
errorHandler _ = tcpServerExceptionHandler params
terminationHandler :: TCPTransport -> SomeException -> IO ()
terminationHandler transport ex = do
let evs = [ ErrorEvent (TransportError EventTransportFailed (show ex))
, throw $ userError "Transport closed"
]
apiCloseTransport transport Nothing evs
-- | Default TCP parameters
defaultTCPParameters :: TCPParameters
defaultTCPParameters = TCPParameters {
tcpBacklog = N.sOMAXCONN
, tcpReuseServerAddr = True
, tcpReuseClientAddr = True
, tcpNoDelay = False
, tcpKeepAlive = False
, tcpUserTimeout = Nothing
, tcpNewQDisc = simpleUnboundedQDisc
, transportConnectTimeout = Nothing
, tcpMaxAddressLength = maxBound
, tcpMaxReceiveLength = maxBound
, tcpCheckPeerHost = False
, tcpServerExceptionHandler = throwIO
}
--------------------------------------------------------------------------------
-- API functions --
--------------------------------------------------------------------------------
-- | Close the transport
apiCloseTransport :: TCPTransport -> Maybe ThreadId -> [Event] -> IO ()
apiCloseTransport transport mTransportThread evs =
asyncWhenCancelled return $ do
mTSt <- modifyMVar (transportState transport) $ \st -> case st of
TransportValid vst -> return (TransportClosed, Just vst)
TransportClosed -> return (TransportClosed, Nothing)
forM_ mTSt $ mapM_ (apiCloseEndPoint transport evs) . (^. localEndPoints)
-- This will invoke the termination handler, which in turn will call
-- apiCloseTransport again, but then the transport will already be closed
-- and we won't be passed a transport thread, so we terminate immmediate
forM_ mTransportThread killThread
-- | Create a new endpoint
apiNewEndPoint :: TCPTransport
-> QDisc Event
-> IO (Either (TransportError NewEndPointErrorCode) EndPoint)
apiNewEndPoint transport qdisc =
try . asyncWhenCancelled closeEndPoint $ do
ourEndPoint <- createLocalEndPoint transport qdisc
return EndPoint
{ receive = qdiscDequeue (localQueue ourEndPoint)
, address = localAddress ourEndPoint
, connect = apiConnect transport ourEndPoint
, closeEndPoint = let evs = [ EndPointClosed ]
in apiCloseEndPoint transport evs ourEndPoint
, newMulticastGroup = return . Left $ newMulticastGroupError
, resolveMulticastGroup = return . Left . const resolveMulticastGroupError
}
where
newMulticastGroupError =
TransportError NewMulticastGroupUnsupported "Multicast not supported"
resolveMulticastGroupError =
TransportError ResolveMulticastGroupUnsupported "Multicast not supported"
-- | Abstraction of a queue for an 'EndPoint'.
--
-- A value of type @QDisc t@ is a queue of events of an abstract type @t@.
--
-- This specifies which 'Event's will come from
-- 'receive :: EndPoint -> IO Event' and when. It is highly general so that
-- the simple yet potentially very fast implementation backed by a single
-- unbounded channel can be used, without excluding more nuanced policies
-- like class-based queueing with bounded buffers for each peer, which may be
-- faster in certain conditions but probably has lower maximal throughput.
--
-- A 'QDisc' must satisfy some properties in order for the semantics of
-- network-transport to hold true. In general, an event fed with
-- 'qdiscEnqueue' must not be dropped. i.e. provided that no other event in
-- the QDisc has higher priority, the event should eventually be returned by
-- 'qdiscDequeue'. An exception to this are 'Receive' events of unreliable
-- connections.
--
-- Every call to 'receive' is just 'qdiscDequeue' on that 'EndPoint's
-- 'QDisc'. Whenever an event arises from a socket, `qdiscEnqueue` is called
-- with the relevant metadata in the same thread that reads from the socket.
-- You can be clever about when to block here, so as to control network
-- ingress. This applies also to loopback connections (an 'EndPoint' connects
-- to itself), in which case blocking on the enqueue would only block some
-- thread in your program rather than some chatty network peer. The 'Event'
-- which is to be enqueued is given to 'qdiscEnqueue' so that the 'QDisc'
-- can know about open connections, their identifiers and peer addresses, etc.
data QDisc t = QDisc {
-- | Dequeue an event.
qdiscDequeue :: IO t
-- | @qdiscEnqueue ep ev t@ enqueues and event @t@, originated from the
-- given remote endpoint @ep@ and with data @ev@.
--
-- @ep@ might be the local endpoint if it relates to a self-connection.
--
-- @ev@ might be in practice the value given as @t@. It is passed in
-- the abstract form @t@ to enforce it is dequeued unmodified, but the
-- 'QDisc' implementation can still observe the concrete form @ev@ to
-- make prioritization decisions.
, qdiscEnqueue :: EndPointAddress -> Event -> t -> IO ()
}
-- | Post an 'Event' using a 'QDisc'.
qdiscEnqueue' :: QDisc Event -> EndPointAddress -> Event -> IO ()
qdiscEnqueue' qdisc addr event = qdiscEnqueue qdisc addr event event
-- | A very simple QDisc backed by an unbounded channel.
simpleUnboundedQDisc :: forall t . IO (QDisc t)
simpleUnboundedQDisc = do
eventChan <- newChan
return $ QDisc {
qdiscDequeue = readChan eventChan
, qdiscEnqueue = const (const (writeChan eventChan))
}
-- | A very simple QDisc backed by a 1-place queue (MVar).
-- With this QDisc, all threads reading from sockets will try to put their
-- events into the same MVar. That MVar will be cleared by calls to
-- 'receive'. Thus the rate at which data is read from the wire is directly
-- related to the rate at which data is pulled from the EndPoint by
-- 'receive'.
simpleOnePlaceQDisc :: forall t . IO (QDisc t)
simpleOnePlaceQDisc = do
mvar <- newEmptyMVar
return $ QDisc {
qdiscDequeue = takeMVar mvar
, qdiscEnqueue = const (const (putMVar mvar))
}
-- | Connnect to an endpoint
apiConnect :: TCPTransport
-> LocalEndPoint -- ^ Local end point
-> EndPointAddress -- ^ Remote address
-> Reliability -- ^ Reliability (ignored)
-> ConnectHints -- ^ Hints
-> IO (Either (TransportError ConnectErrorCode) Connection)
apiConnect transport ourEndPoint theirAddress _reliability hints =
try . asyncWhenCancelled close $
if localAddress ourEndPoint == theirAddress
then connectToSelf ourEndPoint
else do
resetIfBroken ourEndPoint theirAddress
(theirEndPoint, connId) <-
createConnectionTo transport ourEndPoint theirAddress hints
-- connAlive can be an IORef rather than an MVar because it is protected
-- by the remoteState MVar. We don't need the overhead of locking twice.
connAlive <- newIORef True
return Connection
{ send = apiSend (ourEndPoint, theirEndPoint) connId connAlive
, close = apiClose (ourEndPoint, theirEndPoint) connId connAlive
, bundle = remoteId theirEndPoint
}
where
params = transportParams transport
-- | Close a connection
apiClose :: EndPointPair -> LightweightConnectionId -> IORef Bool -> IO ()
apiClose (ourEndPoint, theirEndPoint) connId connAlive =
void . tryIO . asyncWhenCancelled return $ finally
(withScheduledAction ourEndPoint $ \sched -> do
modifyMVar_ (remoteState theirEndPoint) $ \st -> case st of
RemoteEndPointValid vst -> do
alive <- readIORef connAlive
if alive
then do
writeIORef connAlive False
sched theirEndPoint $
sendOn vst [
encodeWord32 (encodeControlHeader CloseConnection)
, encodeWord32 connId
]
return ( RemoteEndPointValid
. (remoteOutgoing ^: (\x -> x - 1))
$ vst
)
else
return (RemoteEndPointValid vst)
_ ->
return st)
(closeIfUnused (ourEndPoint, theirEndPoint))
-- | Send data across a connection
apiSend :: EndPointPair -- ^ Local and remote endpoint
-> LightweightConnectionId -- ^ Connection ID
-> IORef Bool -- ^ Is the connection still alive?
-> [ByteString] -- ^ Payload
-> IO (Either (TransportError SendErrorCode) ())
apiSend (ourEndPoint, theirEndPoint) connId connAlive payload =
-- We don't need the overhead of asyncWhenCancelled here
try . mapIOException sendFailed $ withScheduledAction ourEndPoint $ \sched -> do
withMVar (remoteState theirEndPoint) $ \st -> case st of
RemoteEndPointInvalid _ ->
relyViolation (ourEndPoint, theirEndPoint) "apiSend"
RemoteEndPointInit _ _ _ ->
relyViolation (ourEndPoint, theirEndPoint) "apiSend"
RemoteEndPointValid vst -> do
alive <- readIORef connAlive
if alive
then sched theirEndPoint $
sendOn vst (encodeWord32 connId : prependLength payload)
else throwIO $ TransportError SendClosed "Connection closed"
RemoteEndPointClosing _ _ -> do
alive <- readIORef connAlive
if alive
-- RemoteEndPointClosing is only entered by 'closeIfUnused',
-- which guarantees that there are no alive connections.
then relyViolation (ourEndPoint, theirEndPoint) "apiSend RemoteEndPointClosing"
else throwIO $ TransportError SendClosed "Connection closed"
RemoteEndPointClosed -> do
alive <- readIORef connAlive
if alive
-- This is normal. If the remote endpoint closes up while we have
-- an outgoing connection (CloseEndPoint or CloseSocket message),
-- we'll post the connection lost event but we won't update these
-- 'connAlive' IORefs.
then throwIO $ TransportError SendFailed "Remote endpoint closed"
else throwIO $ TransportError SendClosed "Connection closed"
RemoteEndPointFailed err -> do
alive <- readIORef connAlive
if alive
then throwIO $ TransportError SendFailed (show err)
else throwIO $ TransportError SendClosed "Connection closed"
where
sendFailed = TransportError SendFailed . show
-- | Force-close the endpoint
apiCloseEndPoint :: TCPTransport -- ^ Transport
-> [Event] -- ^ Events used to report closure
-> LocalEndPoint -- ^ Local endpoint
-> IO ()
apiCloseEndPoint transport evs ourEndPoint =
asyncWhenCancelled return $ do
-- Remove the reference from the transport state
removeLocalEndPoint transport ourEndPoint
-- Close the local endpoint
mOurState <- modifyMVar (localState ourEndPoint) $ \st ->
case st of
LocalEndPointValid vst ->
return (LocalEndPointClosed, Just vst)
LocalEndPointClosed ->
return (LocalEndPointClosed, Nothing)
forM_ mOurState $ \vst -> do
forM_ (vst ^. localConnections) tryCloseRemoteSocket
let qdisc = localQueue ourEndPoint
forM_ evs (qdiscEnqueue' qdisc (localAddress ourEndPoint))
where
-- Close the remote socket and return the set of all incoming connections
tryCloseRemoteSocket :: RemoteEndPoint -> IO ()
tryCloseRemoteSocket theirEndPoint = withScheduledAction ourEndPoint $ \sched -> do
-- We make an attempt to close the connection nicely
-- (by sending a CloseSocket first)
let closed = RemoteEndPointFailed . userError $ "apiCloseEndPoint"
modifyMVar_ (remoteState theirEndPoint) $ \st ->
case st of
RemoteEndPointInvalid _ ->
return st
RemoteEndPointInit resolved _ _ -> do
putMVar resolved ()
return closed
RemoteEndPointValid vst -> do
-- Schedule an action to send a CloseEndPoint message and then
-- wait for the socket to actually close (meaning that this
-- end point is no longer receiving from it).
-- Since we replace the state in this MVar with 'closed', it's
-- guaranteed that no other actions will be scheduled after this
-- one.
sched theirEndPoint $ do
void $ tryIO $ sendOn vst
[ encodeWord32 (encodeControlHeader CloseEndPoint) ]
-- Release probing resources if probing.
forM_ (remoteProbing vst) id
tryShutdownSocketBoth (remoteSocket vst)
remoteSocketClosed vst
return closed
RemoteEndPointClosing resolved vst -> do
-- Release probing resources if probing.
forM_ (remoteProbing vst) id
putMVar resolved ()
-- Schedule an action to wait for the socket to actually close (this
-- end point is no longer receiving from it).
-- Since we replace the state in this MVar with 'closed', it's
-- guaranteed that no other actions will be scheduled after this
-- one.
sched theirEndPoint $ do
tryShutdownSocketBoth (remoteSocket vst)
remoteSocketClosed vst
return closed
RemoteEndPointClosed ->
return st
RemoteEndPointFailed err ->
return (RemoteEndPointFailed err)
--------------------------------------------------------------------------------
-- Incoming requests --
--------------------------------------------------------------------------------
-- | Handle a connection request (that is, a remote endpoint that is trying to
-- establish a TCP connection with us)
--
-- 'handleConnectionRequest' runs in the context of the transport thread, which
-- can be killed asynchronously by 'closeTransport'. We fork a separate thread
-- as soon as we have located the lcoal endpoint that the remote endpoint is
-- interested in. We cannot fork any sooner because then we have no way of
-- storing the thread ID and hence no way of killing the thread when we take
-- the transport down. We must be careful to close the socket when a (possibly
-- asynchronous, ThreadKilled) exception occurs. (If an exception escapes from
-- handleConnectionRequest the transport will be shut down.)
handleConnectionRequest :: TCPTransport
-> (SomeException -> IO ())
-> IO ()
-> (N.Socket, N.SockAddr)
-> IO ()
handleConnectionRequest transport errorHandler socketClosed (sock, sockAddr) = handle handleException $ do
when (tcpNoDelay $ transportParams transport) $
N.setSocketOption sock N.NoDelay 1
when (tcpKeepAlive $ transportParams transport) $
N.setSocketOption sock N.KeepAlive 1
forM_ (tcpUserTimeout $ transportParams transport) $
N.setSocketOption sock N.UserTimeout
let handleVersioned = do
-- Always receive the protocol version and a handshake (content of the
-- handshake is version-dependent, but the length is always sent,
-- regardless of the version).
protocolVersion <- recvWord32 sock
handshakeLength <- recvWord32 sock
-- For now we support only version 0.0.0.0.
case protocolVersion of
0x00000000 -> handleConnectionRequestV0 (sock, sockAddr)
_ -> do
-- Inform the peer that we want version 0x00000000
sendMany sock [
encodeWord32 (encodeConnectionRequestResponse ConnectionRequestUnsupportedVersion)
, encodeWord32 0x00000000
]
-- Clear the socket of the unsupported handshake data.
_ <- recvExact sock handshakeLength
handleVersioned
-- The handshake must complete within the optional timeout duration.