4-- Module : Streamly.Internal.Network.Inet.TCP
5-- Copyright : (c) 2019 Composewell Technologies
8-- Maintainer : streamly@composewell.com
9-- Stability : experimental
12-- Combinators to build Inet/TCP clients and servers.
14module Streamly.Internal.Network.Inet.TCP
32 -- | IP Address based operations.
64 , putBytesWithBufferOf
76 -- These abstractions can be applied to any setting where we need to do a
77 -- sink processing of multiple streams e.g. output from multiple processes
78 -- or data coming from multiple files.
80 -- handle connections concurrently using a specified fold
81 -- , handleConnections
83 -- handle frames concurrently using a specified fold
86 -- merge frames from all connection into a single stream. Frames can be
87 -- created by a specified fold.
97import Control.Exception (onException)
98import Control.Monad.Catch (MonadCatch, MonadMask, bracket)
99import Control.Monad.IO.Class (MonadIO(..))
100import Data.Word (Word8)
102 (Socket, PortNumber, SocketOption(..), Family(..), SockAddr(..),
103 SocketType(..), defaultProtocol, maxListenQueue, tupleToHostAddress,
105import Prelude hiding (read)
107import Streamly.Internal.Control.Concurrent (MonadAsync)
108import Streamly.Internal.Control.ForkLifted (fork)
109import Streamly.Internal.Data.Array.Unboxed.Type (Array(..), writeNUnsafe)
110import Streamly.Internal.Data.Fold.Type (Fold(..))
111import Streamly.Data.Stream (Stream)
112import Streamly.Internal.Data.Tuple.Strict (Tuple'(..))
113import Streamly.Internal.Data.Unfold.Type (Unfold(..))
114import Streamly.Internal.Network.Socket (SockSpec(..), accept, acceptor)
115import Streamly.Internal.System.IO (defaultChunkSize)
117import qualified Control.Monad.Catch as MC
118import qualified Network.Socket as Net
120import qualified Streamly.Data.Array.Unboxed as A
121import qualified Streamly.Data.Fold as FL
122import qualified Streamly.Data.Unfold as UF
123import qualified Streamly.Internal.Data.Unfold as UF (bracket, first)
124import qualified Streamly.Internal.Data.Array.Unboxed.Stream as AS
125import qualified Streamly.Internal.Data.Fold.Type as FL
126 (initialize, snoc, Step(..))
127import qualified Streamly.Internal.Data.Stream.IsStream as S
128import qualified Streamly.Internal.Network.Socket as ISK
130-------------------------------------------------------------------------------
132-------------------------------------------------------------------------------
134{-# INLINE acceptorOnAddrWith #-}
137 => [(SocketOption, Int)]
138 -> Unfold m ((Word8, Word8, Word8, Word8), PortNumber) Socket
139acceptorOnAddrWith opts = UF.lmap f acceptor
144 { sockFamily = AF_INET
146 , sockProto = defaultProtocol -- TCP
149 , SockAddrInet port (tupleToHostAddress addr)
152-- | Unfold a tuple @(ipAddr, port)@ into a stream of connected TCP sockets.
153-- @ipAddr@ is the local IP address and @port@ is the local port on which
154-- connections are accepted.
157{-# INLINE acceptorOnAddr #-}
160 => Unfold m ((Word8, Word8, Word8, Word8), PortNumber) Socket
161acceptorOnAddr = acceptorOnAddrWith []
163{-# INLINE acceptorOnPortWith #-}
164acceptorOnPortWith :: MonadIO m
165 => [(SocketOption, Int)]
166 -> Unfold m PortNumber Socket
167acceptorOnPortWith opts = UF.first (0,0,0,0) (acceptorOnAddrWith opts)
169-- | Like 'acceptorOnAddr' but binds on the IPv4 address @0.0.0.0@ i.e. on all
170-- IPv4 addresses/interfaces of the machine and listens for TCP connections on
171-- the specified port.
173-- > acceptorOnPort = UF.first acceptorOnAddr (0,0,0,0)
176{-# INLINE acceptorOnPort #-}
177acceptorOnPort :: MonadIO m => Unfold m PortNumber Socket
178acceptorOnPort = UF.first (0,0,0,0) acceptorOnAddr
180-- | Like 'acceptorOnAddr' but binds on the localhost IPv4 address @127.0.0.1@.
181-- The server can only be accessed from the local host, it cannot be accessed
182-- from other hosts on the network.
184-- > acceptorOnPortLocal = UF.first acceptorOnAddr (127,0,0,1)
187{-# INLINE acceptorOnPortLocal #-}
188acceptorOnPortLocal :: MonadIO m => Unfold m PortNumber Socket
189acceptorOnPortLocal = UF.first (127,0,0,1) acceptorOnAddr
191-------------------------------------------------------------------------------
193-------------------------------------------------------------------------------
195{-# INLINE acceptOnAddrWith #-}
198 => [(SocketOption, Int)]
199 -> (Word8, Word8, Word8, Word8)
202acceptOnAddrWith opts addr port =
203 accept maxListenQueue SockSpec
204 { sockFamily = AF_INET
206 , sockProto = defaultProtocol
209 (SockAddrInet port (tupleToHostAddress addr))
211-- | Like 'accept' but binds on the specified IPv4 address of the machine
212-- and listens for TCP connections on the specified port.
215{-# INLINE acceptOnAddr #-}
218 => (Word8, Word8, Word8, Word8)
221acceptOnAddr = acceptOnAddrWith []
223-- | Like 'accept' but binds on the IPv4 address @0.0.0.0@ i.e. on all
224-- IPv4 addresses/interfaces of the machine and listens for TCP connections on
225-- the specified port.
227-- > acceptOnPort = acceptOnAddr (0,0,0,0)
230{-# INLINE acceptOnPort #-}
231acceptOnPort :: MonadIO m => PortNumber -> Stream m Socket
232acceptOnPort = acceptOnAddr (0,0,0,0)
234-- | Like 'accept' but binds on the localhost IPv4 address @127.0.0.1@.
235-- The server can only be accessed from the local host, it cannot be accessed
236-- from other hosts on the network.
238-- > acceptOnPortLocal = acceptOnAddr (127,0,0,1)
241{-# INLINE acceptOnPortLocal #-}
242acceptOnPortLocal :: MonadIO m => PortNumber -> Stream m Socket
243acceptOnPortLocal = acceptOnAddr (127,0,0,1)
245-------------------------------------------------------------------------------
247-------------------------------------------------------------------------------
249-- | Connect to the specified IP address and port number. Returns a connected
250-- socket or throws an exception.
253connect :: (Word8, Word8, Word8, Word8) -> PortNumber -> IO Socket
254connect addr port = do
255 sock <- socket AF_INET Stream defaultProtocol
256 Net.connect sock (SockAddrInet port (Net.tupleToHostAddress addr))
257 `onException` Net.close sock
260-- | Connect to a remote host using IP address and port and run the supplied
261-- action on the resulting socket. 'withConnectionM' makes sure that the
262-- socket is closed on normal termination or in case of an exception. If
263-- closing the socket raises an exception, then this exception will be raised
264-- by 'withConnectionM'.
267{-# INLINABLE withConnectionM #-}
268withConnectionM :: (MonadMask m, MonadIO m)
269 => (Word8, Word8, Word8, Word8) -> PortNumber -> (Socket -> m ()) -> m ()
270withConnectionM addr port =
271 bracket (liftIO $ connect addr port) (liftIO . Net.close)
273-------------------------------------------------------------------------------
275-------------------------------------------------------------------------------
277-- | Transform an 'Unfold' from a 'Socket' to an unfold from a remote IP
278-- address and port. The resulting unfold opens a socket, uses it using the
279-- supplied unfold and then makes sure that the socket is closed on normal
280-- termination or in case of an exception. If closing the socket raises an
281-- exception, then this exception will be raised by 'usingConnection'.
284{-# INLINE usingConnection #-}
285usingConnection :: (MonadCatch m, MonadAsync m)
287 -> Unfold m ((Word8, Word8, Word8, Word8), PortNumber) a
289 UF.bracket (\(addr, port) -> liftIO $ connect addr port)
292-------------------------------------------------------------------------------
294-------------------------------------------------------------------------------
296-- | @'withConnection' addr port act@ opens a connection to the specified IPv4
297-- host address and port and passes the resulting socket handle to the
298-- computation @act@. The handle will be closed on exit from 'withConnection',
299-- whether by normal termination or by raising an exception. If closing the
300-- handle raises an exception, then this exception will be raised by
301-- 'withConnection' rather than any exception raised by 'act'.
304{-# INLINE withConnection #-}
305withConnection :: (MonadCatch m, MonadAsync m)
306 => (Word8, Word8, Word8, Word8)
308 -> (Socket -> Stream m a)
310withConnection addr port =
311 S.bracket (liftIO $ connect addr port) (liftIO . Net.close)
313-------------------------------------------------------------------------------
314-- Read Addr to Stream
315-------------------------------------------------------------------------------
317-- | Read a stream from the supplied IPv4 host address and port number.
321reader :: (MonadCatch m, MonadAsync m)
322 => Unfold m ((Word8, Word8, Word8, Word8), PortNumber) Word8
323reader = UF.many A.read (usingConnection ISK.chunkReader)
325-- | Read a stream from the supplied IPv4 host address and port number.
329read :: (MonadCatch m, MonadAsync m)
330 => (Word8, Word8, Word8, Word8) -> PortNumber -> Stream m Word8
331read addr port = AS.concat $ withConnection addr port ISK.readChunks
333-------------------------------------------------------------------------------
335-------------------------------------------------------------------------------
337-- | Write a stream of arrays to the supplied IPv4 host address and port
341{-# INLINE putChunks #-}
343 :: (MonadCatch m, MonadAsync m)
344 => (Word8, Word8, Word8, Word8)
346 -> Stream m (Array Word8)
348putChunks addr port xs =
349 S.drain $ withConnection addr port (\sk -> S.fromEffect $ ISK.putChunks sk xs)
351-- | Write a stream of arrays to the supplied IPv4 host address and port
355{-# INLINE writeChunks #-}
357 :: (MonadIO m, MonadCatch m)
358 => (Word8, Word8, Word8, Word8)
360 -> Fold m (Array Word8) ()
361writeChunks addr port = Fold step initial extract
364 skt <- liftIO (connect addr port)
365 fld <- FL.initialize (ISK.writeChunks skt)
366 `MC.onException` liftIO (Net.close skt)
367 return $ FL.Partial (Tuple' fld skt)
368 step (Tuple' fld skt) x = do
369 r <- FL.snoc fld x `MC.onException` liftIO (Net.close skt)
370 return $ FL.Partial (Tuple' r skt)
371 extract (Tuple' (Fold _ initial1 extract1) skt) = do
372 liftIO $ Net.close skt
375 FL.Partial fs -> extract1 fs
376 FL.Done fb -> return fb
378-- | Like 'write' but provides control over the write buffer. Output will
379-- be written to the IO device as soon as we collect the specified number of
383{-# INLINE putBytesWithBufferOf #-}
385 :: (MonadCatch m, MonadAsync m)
387 -> (Word8, Word8, Word8, Word8)
391putBytesWithBufferOf n addr port m = putChunks addr port $ AS.arraysOf n m
393-- | Like 'write' but provides control over the write buffer. Output will
394-- be written to the IO device as soon as we collect the specified number of
398{-# INLINE writeWithBufferOf #-}
400 :: (MonadIO m, MonadCatch m)
402 -> (Word8, Word8, Word8, Word8)
405writeWithBufferOf n addr port =
406 FL.chunksOf n (writeNUnsafe n) (writeChunks addr port)
408-- | Write a stream to the supplied IPv4 host address and port number.
411{-# INLINE putBytes #-}
412putBytes :: (MonadCatch m, MonadAsync m)
413 => (Word8, Word8, Word8, Word8) -> PortNumber -> Stream m Word8 -> m ()
414putBytes = putBytesWithBufferOf defaultChunkSize
416-- | Write a stream to the supplied IPv4 host address and port number.
420write :: (MonadIO m, MonadCatch m)
421 => (Word8, Word8, Word8, Word8) -> PortNumber -> Fold m Word8 ()
422write = writeWithBufferOf defaultChunkSize
424-------------------------------------------------------------------------------
426-------------------------------------------------------------------------------
428{-# INLINE withInputConnect #-}
430 :: (MonadCatch m, MonadAsync m)
431 => (Word8, Word8, Word8, Word8)
434 -> (Socket -> Stream m a)
436withInputConnect addr port input f = S.bracket pre post handler
441 sk <- liftIO $ connect addr port
442 tid <- fork (ISK.putBytes sk input)
445 handler (sk, _) = f sk
447 -- XXX kill the thread immediately?
448 post (sk, _) = liftIO $ Net.close sk
450-- | Send an input stream to a remote host and produce the output stream from
451-- the host. The server host just acts as a transformation function on the
452-- input stream. Both sending and receiving happen asynchronously.
456{-# INLINE pipeBytes #-}
458 :: (MonadAsync m, MonadCatch m)
459 => (Word8, Word8, Word8, Word8)
463pipeBytes addr port input = withInputConnect addr port input ISK.read
keysesc to close
- j k
- move down, up
- enter
- open
- esc
- back, or up a level
- 1 2 3 4
- readme, files, commits, refs
- /
- filter
- y
- copy the clone command
- c
- compare the chosen commit with another (or shift-click both)
- ?
- show or hide this list