4-- Module : Streamly.Internal.Network.Socket
5-- Copyright : (c) 2018 Composewell Technologies
8-- Maintainer : streamly@composewell.com
9-- Stability : experimental
12module Streamly.Internal.Network.Socket
19 -- * Accept connections
27 -- * Read from connection
42 -- * Write to connection
57 -- reading/writing datagrams
61 , readChunksWithBufferOf
63 , writeChunksWithBufferOf
67import Control.Concurrent (threadWaitWrite, rtsSupportsBoundThreads)
68import Control.Exception (onException)
69import Control.Monad (forM_, when)
70import Control.Monad.Catch (MonadCatch, finally, MonadMask)
71import Control.Monad.IO.Class (MonadIO(..))
72import Data.Maybe (isNothing, fromJust)
73import Data.Word (Word8)
74import Foreign.Ptr (plusPtr, Ptr, castPtr)
75import Streamly.Internal.Data.Unboxed (Unbox)
77 (Socket, SocketOption(..), Family(..), SockAddr(..),
78 ProtocolNumber, withSocketsDo, SocketType(..), socket, bind,
79 setSocketOption, sendBuf, recvBuf)
80#if MIN_VERSION_network(3,1,0)
81import Network.Socket (withFdSocket)
83import Network.Socket (fdSocket)
85import Prelude hiding (read)
87import qualified Network.Socket as Net
89import Streamly.Internal.Data.Array.Type (Array(..))
90import Streamly.Internal.Data.Stream.Chunked (lpackArraysChunksOf)
91import Streamly.Internal.Data.Fold (Fold)
92import Streamly.Internal.Data.Stream.Type (Stream)
93import Streamly.Internal.Data.Unfold.Type (Unfold(..))
94-- import Streamly.String (encodeUtf8, decodeUtf8, foldLines)
95import Streamly.Internal.System.IO (defaultChunkSize)
97import qualified Streamly.Data.Array as A (reader, length, writeN)
98import qualified Streamly.Data.Fold as FL
99import qualified Streamly.Internal.Data.Array.Type as A
100 (unsafeFreeze, asPtrUnsafe, byteLength, writeNUnsafe)
101import qualified Streamly.Internal.Data.Array.Mut as MArray
102 (Array(..), newPinnedBytes, asPtrUnsafe)
103import qualified Streamly.Internal.Data.Stream.Chunked as AS
104import qualified Streamly.Internal.Data.Stream as S
105import qualified Streamly.Internal.Data.Stream.StreamD.Type as D
106 (Stream(..), Step(..))
107import qualified Streamly.Data.Unfold as UF
108import qualified Streamly.Internal.Data.Unfold as UF (first, map)
109import qualified Streamly.Internal.Data.Stream.StreamK.Type as K (mkStream)
113-- >>> import Streamly.Internal.System.IO (defaultChunkSize)
114-- >>> import qualified Streamly.Internal.Network.Socket as Socket
116-- | @'forSocketM' action socket@ runs the monadic computation @action@ passing
117-- the socket handle to it. The handle will be closed on exit from
118-- 'forSocketM', whether by normal termination or by raising an exception. If
119-- closing the handle raises an exception, then this exception will be raised
120-- by 'forSocketM' rather than any exception raised by 'action'.
122{-# INLINE forSocketM #-}
123forSocketM :: (MonadMask m, MonadIO m) => (Socket -> m ()) -> Socket -> m ()
124forSocketM f sk = finally (f sk) (liftIO (Net.close sk))
126-- | Like 'forSocketM' but runs a streaming computation instead of a monadic
129-- /Inhibits stream fusion/
132{-# INLINE withSocket #-}
133withSocket :: (MonadIO m, MonadCatch m) =>
134 Socket -> (Socket -> Stream m a) -> Stream m a
135withSocket sk f = S.finallyIO (Net.close sk) (f sk)
137-------------------------------------------------------------------------------
139-------------------------------------------------------------------------------
141-- XXX Protocol specific socket options should be separated from socket level
144-- | Specify the socket protocol details.
145data SockSpec = SockSpec
147 sockFamily :: !Family
148 , sockType :: !SocketType
149 , sockProto :: !ProtocolNumber
150 , sockOpts :: ![(SocketOption, Int)]
153initListener :: Int -> SockSpec -> SockAddr -> IO Socket
154initListener listenQLen SockSpec{..} addr =
156 sock <- socket sockFamily sockType sockProto
157 use sock `onException` Net.close sock
163 mapM_ (\(opt, val) -> setSocketOption sock opt val) sockOpts
165 Net.listen sock listenQLen
167{-# INLINE listenTuples #-}
168listenTuples :: MonadIO m
169 => Unfold m (Int, SockSpec, SockAddr) (Socket, SockAddr)
170listenTuples = Unfold step inject
172 inject (listenQLen, spec, addr) =
173 liftIO $ initListener listenQLen spec addr
176 r <- liftIO (Net.accept listener `onException` Net.close listener)
177 return $ D.Yield r listener
179-- | Unfold a three tuple @(listenQLen, spec, addr)@ into a stream of connected
180-- protocol sockets corresponding to incoming connections. @listenQLen@ is the
181-- maximum number of pending connections in the backlog. @spec@ is the socket
182-- protocol and options specification and @addr@ is the protocol address where
183-- the server listens for incoming connections.
185{-# INLINE acceptor #-}
186acceptor :: MonadIO m => Unfold m (Int, SockSpec, SockAddr) Socket
187acceptor = UF.map fst listenTuples
189{-# INLINE connectCommon #-}
190connectCommon :: SockSpec -> Maybe SockAddr -> SockAddr -> IO Socket
191connectCommon SockSpec{..} local remote = withSocketsDo $ do
192 sock <- socket sockFamily sockType sockProto
193 use sock `onException` Net.close sock
199 mapM_ (\(opt, val) -> setSocketOption sock opt val) sockOpts
200 forM_ local (bind sock)
201 Net.connect sock remote
203-- | Connect to a remote host using the given socket specification and remote
204-- address. Returns a connected socket or throws an exception.
208{-# INLINE connect #-}
209connect :: SockSpec -> SockAddr -> IO Socket
210connect spec = connectCommon spec Nothing
212-- | Connect to a remote host using the given socket specification, a local
213-- address to bind to and a remote address to connect to. Returns a connected
214-- socket or throws an exception.
218{-# INLINE connectFrom #-}
219connectFrom :: SockSpec -> SockAddr -> SockAddr -> IO Socket
220connectFrom spec local = connectCommon spec (Just local)
222-------------------------------------------------------------------------------
224-------------------------------------------------------------------------------
226{-# INLINE recvConnectionTuplesWith #-}
227recvConnectionTuplesWith :: MonadIO m
228 => Int -> SockSpec -> SockAddr -> Stream m (Socket, SockAddr)
229recvConnectionTuplesWith tcpListenQ spec addr = S.unfoldrM step Nothing
232 listener <- liftIO $ initListener tcpListenQ spec addr
233 r <- liftIO (Net.accept listener `onException` Net.close listener)
234 return $ Just (r, Just listener)
236 step (Just listener) = do
237 r <- liftIO (Net.accept listener `onException` Net.close listener)
238 return $ Just (r, Just listener)
240-- | Start a TCP stream server that listens for connections on the supplied
241-- server address specification (address family, local interface IP address and
242-- port). The server generates a stream of connected sockets. The first
243-- argument is the maximum number of pending connections in the backlog.
247accept :: MonadIO m => Int -> SockSpec -> SockAddr -> Stream m Socket
248accept tcpListenQ spec addr =
249 fst <$> recvConnectionTuplesWith tcpListenQ spec addr
251-------------------------------------------------------------------------------
253-------------------------------------------------------------------------------
255{-# INLINABLE readArrayUptoWith #-}
257 :: (h -> Ptr Word8 -> Int -> IO Int)
261readArrayUptoWith f size h = do
262 arr <- MArray.newPinnedBytes size
263 -- ptr <- mallocPlainForeignPtrAlignedBytes size (alignment (undefined :: Word8))
264 MArray.asPtrUnsafe arr $ \p -> do
266 let v = A.unsafeFreeze
267 $ arr { MArray.arrEnd = n, MArray.arrBound = size }
269 -- XXX shrink only if the diff is significant
273-- | Read a byte array from a file handle up to a maximum of the requested
274-- size. If no data is available on the handle it blocks until some data
275-- becomes available. If data is available then it immediately returns that
276-- data without blocking.
278{-# INLINABLE getChunk #-}
279getChunk :: Int -> Socket -> IO (Array Word8)
280getChunk = readArrayUptoWith recvBuf
282-------------------------------------------------------------------------------
284-------------------------------------------------------------------------------
286waitWhen0 :: Int -> Socket -> IO ()
287waitWhen0 0 s = when rtsSupportsBoundThreads $
288#if MIN_VERSION_network(3,1,0)
289 withFdSocket s $ \fd -> threadWaitWrite $ fromIntegral fd
290#elif MIN_VERSION_network(3,0,0)
291 fdSocket s >>= threadWaitWrite . fromIntegral
293 let fd = fdSocket s in threadWaitWrite $ fromIntegral fd
295waitWhen0 _ _ = return ()
297sendAll :: Socket -> Ptr Word8 -> Int -> IO ()
298sendAll _ _ len | len <= 0 = return ()
300 sent <- sendBuf s p len
302 -- assert (sent <= len)
303 when (sent >= 0) $ sendAll s (p `plusPtr` sent) (len - sent)
305{-# INLINABLE writeArrayWith #-}
306writeArrayWith :: Unbox a
307 => (h -> Ptr Word8 -> Int -> IO ())
311writeArrayWith _ _ arr | A.length arr == 0 = return ()
312writeArrayWith f h arr = A.asPtrUnsafe arr $ \ptr -> f h (castPtr ptr) aLen
316 aLen = A.byteLength arr
318-- | Write an Array to a socket.
320{-# INLINABLE putChunk #-}
321putChunk :: Unbox a => Socket -> Array a -> IO ()
322putChunk = writeArrayWith sendAll
324-------------------------------------------------------------------------------
325-- Stream of Arrays IO
326-------------------------------------------------------------------------------
328{-# INLINE _readChunksUptoWith #-}
329_readChunksUptoWith :: (MonadIO m)
330 => (Int -> h -> IO (Array Word8))
331 -> Int -> h -> Stream m (Array Word8)
332_readChunksUptoWith f size h = S.fromStreamK go
334 -- XXX use cons/nil instead
335 go = K.mkStream $ \_ yld _ stp -> do
336 arr <- liftIO $ f size h
341-- | @readChunksWith bufsize socket@ reads a stream of arrays from @socket@.
342-- The maximum size of a single array is limited to @bufsize@.
345{-# INLINE_NORMAL readChunksWith #-}
346readChunksWith :: MonadIO m => Int -> Socket -> Stream m (Array Word8)
347-- readChunksWith = _readChunksUptoWith readChunk
348readChunksWith size h = S.fromStreamD (D.Stream step ())
350 {-# INLINE_LATE step #-}
352 arr <- liftIO $ getChunk size h
358-- | Read a stream of byte arrays from a socket. The maximum size of a single
359-- array is limited to @defaultChunkSize@.
361-- >>> readChunks = Socket.readChunksWith defaultChunkSize
364{-# INLINE readChunks #-}
365readChunks :: MonadIO m => Socket -> Stream m (Array Word8)
366readChunks = readChunksWith defaultChunkSize
368-- | Unfold the tuple @(bufsize, socket)@ into a stream of 'Word8' arrays.
369-- Read requests to the socket are performed using a buffer of size @bufsize@.
370-- The size of an array in the resulting stream is always less than or equal to
373{-# INLINE_NORMAL chunkReaderWith #-}
374chunkReaderWith :: MonadIO m => Unfold m (Int, Socket) (Array Word8)
375chunkReaderWith = Unfold step return
377 {-# INLINE_LATE step #-}
379 arr <- liftIO $ getChunk size h
383 _ -> D.Yield arr (size, h)
385-- | Same as 'chunkReaderWith'
387{-# DEPRECATED readChunksWithBufferOf "Please use 'chunkReaderWith' instead" #-}
388{-# INLINE_NORMAL readChunksWithBufferOf #-}
389readChunksWithBufferOf :: MonadIO m => Unfold m (Int, Socket) (Array Word8)
390readChunksWithBufferOf = chunkReaderWith
392-- | Unfolds a socket into a stream of 'Word8' arrays. Requests to the socket
393-- are performed using a buffer of size
394-- 'Streamly.Internal.Data.Array.Type.defaultChunkSize'. The
395-- size of arrays in the resulting stream are therefore less than or equal to
396-- 'Streamly.Internal.Data.Array.Type.defaultChunkSize'.
398{-# INLINE chunkReader #-}
399chunkReader :: MonadIO m => Unfold m Socket (Array Word8)
400chunkReader = UF.first defaultChunkSize chunkReaderWith
402-------------------------------------------------------------------------------
403-- Read File to Stream
404-------------------------------------------------------------------------------
406-- | Generate a byte stream from a socket using a buffer of the given size.
409{-# INLINE readWith #-}
410readWith :: MonadIO m => Int -> Socket -> Stream m Word8
411readWith size = AS.concat . readChunksWith size
413-- | Generate a byte stream from a socket.
415-- >>> read = Socket.readWith defaultChunkSize
419read :: MonadIO m => Socket -> Stream m Word8
420read = readWith defaultChunkSize
422-- | Unfolds the tuple @(bufsize, socket)@ into a byte stream, read requests
423-- to the socket are performed using buffers of @bufsize@.
425{-# INLINE readerWith #-}
426readerWith :: MonadIO m => Unfold m (Int, Socket) Word8
427readerWith = UF.many A.reader chunkReaderWith
429-- | Same as 'readWith'
431{-# DEPRECATED readWithBufferOf "Please use 'readerWith' instead" #-}
432{-# INLINE readWithBufferOf #-}
433readWithBufferOf :: MonadIO m => Unfold m (Int, Socket) Word8
434readWithBufferOf = readerWith
436-- | Unfolds a 'Socket' into a byte stream. IO requests to the socket are
437-- performed in sizes of
438-- 'Streamly.Internal.Data.Array.Type.defaultChunkSize'.
441reader :: MonadIO m => Unfold m Socket Word8
442reader = UF.first defaultChunkSize readerWith
444-------------------------------------------------------------------------------
446-------------------------------------------------------------------------------
448-- | Write a stream of arrays to a handle.
450{-# INLINE putChunks #-}
451putChunks :: (MonadIO m, Unbox a)
452 => Socket -> Stream m (Array a) -> m ()
453putChunks h = S.fold (FL.drainMapM (liftIO . putChunk h))
455-- | Write a stream of arrays to a socket. Each array in the stream is written
456-- to the socket as a separate IO request.
458{-# INLINE writeChunks #-}
459writeChunks :: (MonadIO m, Unbox a) => Socket -> Fold m (Array a) ()
460writeChunks h = FL.drainMapM (liftIO . putChunk h)
462-- | @writeChunksWith bufsize socket@ writes a stream of arrays to
463-- @socket@ after coalescing the adjacent arrays in chunks of @bufsize@.
464-- Multiple arrays are coalesed as long as the total size remains below the
465-- specified size. It never splits an array, if a single array is bigger than
466-- the specified size it emitted as it is.
468{-# INLINE writeChunksWith #-}
469writeChunksWith :: (MonadIO m, Unbox a)
470 => Int -> Socket -> Fold m (Array a) ()
471writeChunksWith n h = lpackArraysChunksOf n (writeChunks h)
473-- | Same as 'writeChunksWith'
475{-# DEPRECATED writeChunksWithBufferOf "Please use 'writeChunksWith' instead" #-}
476{-# INLINE writeChunksWithBufferOf #-}
477writeChunksWithBufferOf :: (MonadIO m, Unbox a)
478 => Int -> Socket -> Fold m (Array a) ()
479writeChunksWithBufferOf = writeChunksWith
481-- GHC buffer size dEFAULT_FD_BUFFER_SIZE=8192 bytes.
484-- Note that if you use a chunk size less than 8K (GHC's default buffer
485-- size) then you are advised to use 'NOBuffering' mode on the 'Handle' in case you
486-- do not want buffering to occur at GHC level as well. Same thing applies to
489-- | Like 'write' but provides control over the write buffer. Output will
490-- be written to the IO device as soon as we collect the specified number of
493{-# INLINE putBytesWith #-}
494putBytesWith :: MonadIO m => Int -> Socket -> Stream m Word8 -> m ()
495putBytesWith n h m = putChunks h $ AS.arraysOf n m
497-- | Write a byte stream to a socket. Accumulates the input in chunks of
498-- specified number of bytes before writing.
500{-# INLINE writeWith #-}
501writeWith :: MonadIO m => Int -> Socket -> Fold m Word8 ()
502writeWith n h = FL.chunksOf n (A.writeNUnsafe n) (writeChunks h)
504-- | Same as 'writeWith'
506{-# DEPRECATED writeWithBufferOf "Please use 'writeWith' instead" #-}
507{-# INLINE writeWithBufferOf #-}
508writeWithBufferOf :: MonadIO m => Int -> Socket -> Fold m Word8 ()
509writeWithBufferOf = writeWith
511-- | Write a stream of 'Maybe' values. Keep buffering the 'Just' values in an
512-- array. Write the array to the 'Handle' as soon as a 'Nothing' is encountered
513-- or the buffer size exceeds the specified limit.
516{-# INLINE writeMaybesWith #-}
517writeMaybesWith :: (MonadIO m )
518 => Int -> Socket -> Fold m (Maybe Word8) ()
520 let writeNJusts = FL.lmap fromJust $ A.writeN n
521 writeOnNothing = FL.takeEndBy_ isNothing writeNJusts
522 in FL.many writeOnNothing (writeChunks h)
524-- | Write a byte stream to a file handle. Combines the bytes in chunks of size
525-- up to 'defaultChunkSize' before writing. Note that the write behavior
526-- depends on the 'IOMode' and the current seek position of the handle.
528{-# INLINE putBytes #-}
529putBytes :: MonadIO m => Socket -> Stream m Word8 -> m ()
530putBytes = putBytesWith defaultChunkSize
532-- | Write a byte stream to a socket. Accumulates the input in chunks of
533-- up to 'defaultChunkSize' bytes before writing.
535-- >>> write = Socket.writeWith defaultChunkSize
538write :: MonadIO m => Socket -> Fold m Word8 ()
539write = writeWith defaultChunkSize
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