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.Unbox (PinnedState(..), 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.StreamD.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)
98import qualified Streamly.Data.Fold as FL
99import qualified Streamly.Internal.Data.Array.Type as A
100 ( unsafeFreeze, asPtrUnsafe, byteLength, writeNUnsafeAs, chunksOfAs
103import qualified Streamly.Internal.Data.Array.Mut as MArray
104 (MutArray(..), newPinnedBytes, asPtrUnsafe)
105import qualified Streamly.Internal.Data.Stream as S
106import qualified Streamly.Internal.Data.Stream.StreamD.Type as D
107 (Stream(..), Step(..))
108import qualified Streamly.Data.Unfold as UF
109import qualified Streamly.Internal.Data.Unfold as UF (first, map)
110import qualified Streamly.Internal.Data.Stream.StreamK.Type as K (mkStream)
114-- >>> import Streamly.Internal.System.IO (defaultChunkSize)
115-- >>> import qualified Streamly.Internal.Network.Socket as Socket
117-- | @'forSocketM' action socket@ runs the monadic computation @action@ passing
118-- the socket handle to it. The handle will be closed on exit from
119-- 'forSocketM', whether by normal termination or by raising an exception. If
120-- closing the handle raises an exception, then this exception will be raised
121-- by 'forSocketM' rather than any exception raised by 'action'.
123{-# INLINE forSocketM #-}
124forSocketM :: (MonadMask m, MonadIO m) => (Socket -> m ()) -> Socket -> m ()
125forSocketM f sk = finally (f sk) (liftIO (Net.close sk))
127-- | Like 'forSocketM' but runs a streaming computation instead of a monadic
130-- /Inhibits stream fusion/
133{-# INLINE withSocket #-}
134withSocket :: (MonadIO m, MonadCatch m) =>
135 Socket -> (Socket -> Stream m a) -> Stream m a
136withSocket sk f = S.finallyIO (Net.close sk) (f sk)
138-------------------------------------------------------------------------------
140-------------------------------------------------------------------------------
142-- XXX Protocol specific socket options should be separated from socket level
145-- | Specify the socket protocol details.
146data SockSpec = SockSpec
148 sockFamily :: !Family
149 , sockType :: !SocketType
150 , sockProto :: !ProtocolNumber
151 , sockOpts :: ![(SocketOption, Int)]
154initListener :: Int -> SockSpec -> SockAddr -> IO Socket
155initListener listenQLen SockSpec{..} addr =
157 sock <- socket sockFamily sockType sockProto
158 use sock `onException` Net.close sock
164 mapM_ (\(opt, val) -> setSocketOption sock opt val) sockOpts
166 Net.listen sock listenQLen
168{-# INLINE listenTuples #-}
169listenTuples :: MonadIO m
170 => Unfold m (Int, SockSpec, SockAddr) (Socket, SockAddr)
171listenTuples = Unfold step inject
173 inject (listenQLen, spec, addr) =
174 liftIO $ initListener listenQLen spec addr
177 r <- liftIO (Net.accept listener `onException` Net.close listener)
178 return $ D.Yield r listener
180-- | Unfold a three tuple @(listenQLen, spec, addr)@ into a stream of connected
181-- protocol sockets corresponding to incoming connections. @listenQLen@ is the
182-- maximum number of pending connections in the backlog. @spec@ is the socket
183-- protocol and options specification and @addr@ is the protocol address where
184-- the server listens for incoming connections.
186{-# INLINE acceptor #-}
187acceptor :: MonadIO m => Unfold m (Int, SockSpec, SockAddr) Socket
188acceptor = UF.map fst listenTuples
190{-# INLINE connectCommon #-}
191connectCommon :: SockSpec -> Maybe SockAddr -> SockAddr -> IO Socket
192connectCommon SockSpec{..} local remote = withSocketsDo $ do
193 sock <- socket sockFamily sockType sockProto
194 use sock `onException` Net.close sock
200 mapM_ (\(opt, val) -> setSocketOption sock opt val) sockOpts
201 forM_ local (bind sock)
202 Net.connect sock remote
204-- | Connect to a remote host using the given socket specification and remote
205-- address. Returns a connected socket or throws an exception.
209{-# INLINE connect #-}
210connect :: SockSpec -> SockAddr -> IO Socket
211connect spec = connectCommon spec Nothing
213-- | Connect to a remote host using the given socket specification, a local
214-- address to bind to and a remote address to connect to. Returns a connected
215-- socket or throws an exception.
219{-# INLINE connectFrom #-}
220connectFrom :: SockSpec -> SockAddr -> SockAddr -> IO Socket
221connectFrom spec local = connectCommon spec (Just local)
223-------------------------------------------------------------------------------
225-------------------------------------------------------------------------------
227{-# INLINE recvConnectionTuplesWith #-}
228recvConnectionTuplesWith :: MonadIO m
229 => Int -> SockSpec -> SockAddr -> Stream m (Socket, SockAddr)
230recvConnectionTuplesWith tcpListenQ spec addr = S.unfoldrM step Nothing
233 listener <- liftIO $ initListener tcpListenQ spec addr
234 r <- liftIO (Net.accept listener `onException` Net.close listener)
235 return $ Just (r, Just listener)
237 step (Just listener) = do
238 r <- liftIO (Net.accept listener `onException` Net.close listener)
239 return $ Just (r, Just listener)
241-- | Start a TCP stream server that listens for connections on the supplied
242-- server address specification (address family, local interface IP address and
243-- port). The server generates a stream of connected sockets. The first
244-- argument is the maximum number of pending connections in the backlog.
248accept :: MonadIO m => Int -> SockSpec -> SockAddr -> Stream m Socket
249accept tcpListenQ spec addr =
250 fst <$> recvConnectionTuplesWith tcpListenQ spec addr
252-------------------------------------------------------------------------------
254-------------------------------------------------------------------------------
256{-# INLINABLE readArrayUptoWith #-}
258 :: (h -> Ptr Word8 -> Int -> IO Int)
262readArrayUptoWith f size h = do
263 arr <- MArray.newPinnedBytes size
264 -- ptr <- mallocPlainForeignPtrAlignedBytes size (alignment (undefined :: Word8))
265 MArray.asPtrUnsafe arr $ \p -> do
267 let v = A.unsafeFreeze
268 $ arr { MArray.arrEnd = n, MArray.arrBound = size }
270 -- XXX shrink only if the diff is significant
274-- | Read a byte array from a file handle up to a maximum of the requested
275-- size. If no data is available on the handle it blocks until some data
276-- becomes available. If data is available then it immediately returns that
277-- data without blocking.
279{-# INLINABLE getChunk #-}
280getChunk :: Int -> Socket -> IO (Array Word8)
281getChunk = readArrayUptoWith recvBuf
283-------------------------------------------------------------------------------
285-------------------------------------------------------------------------------
287waitWhen0 :: Int -> Socket -> IO ()
288waitWhen0 0 s = when rtsSupportsBoundThreads $
289#if MIN_VERSION_network(3,1,0)
290 withFdSocket s $ \fd -> threadWaitWrite $ fromIntegral fd
291#elif MIN_VERSION_network(3,0,0)
292 fdSocket s >>= threadWaitWrite . fromIntegral
294 let fd = fdSocket s in threadWaitWrite $ fromIntegral fd
296waitWhen0 _ _ = return ()
298sendAll :: Socket -> Ptr Word8 -> Int -> IO ()
299sendAll _ _ len | len <= 0 = return ()
301 sent <- sendBuf s p len
303 -- assert (sent <= len)
304 when (sent >= 0) $ sendAll s (p `plusPtr` sent) (len - sent)
306{-# INLINABLE writeArrayWith #-}
307writeArrayWith :: Unbox a
308 => (h -> Ptr Word8 -> Int -> IO ())
312writeArrayWith _ _ arr | A.length arr == 0 = return ()
313writeArrayWith f h arr = A.asPtrUnsafe arr $ \ptr -> f h (castPtr ptr) aLen
317 aLen = A.byteLength arr
319-- | Write an Array to a socket.
321{-# INLINABLE putChunk #-}
322putChunk :: Unbox a => Socket -> Array a -> IO ()
323putChunk = writeArrayWith sendAll
325-------------------------------------------------------------------------------
326-- Stream of Arrays IO
327-------------------------------------------------------------------------------
329{-# INLINE _readChunksUptoWith #-}
330_readChunksUptoWith :: (MonadIO m)
331 => (Int -> h -> IO (Array Word8))
332 -> Int -> h -> Stream m (Array Word8)
333_readChunksUptoWith f size h = S.fromStreamK go
335 -- XXX use cons/nil instead
336 go = K.mkStream $ \_ yld _ stp -> do
337 arr <- liftIO $ f size h
342-- | @readChunksWith bufsize socket@ reads a stream of arrays from @socket@.
343-- The maximum size of a single array is limited to @bufsize@.
346{-# INLINE_NORMAL readChunksWith #-}
347readChunksWith :: MonadIO m => Int -> Socket -> Stream m (Array Word8)
348-- readChunksWith = _readChunksUptoWith readChunk
349readChunksWith size h = D.Stream step ()
351 {-# INLINE_LATE step #-}
353 arr <- liftIO $ getChunk size h
359-- | Read a stream of byte arrays from a socket. The maximum size of a single
360-- array is limited to @defaultChunkSize@.
362-- >>> readChunks = Socket.readChunksWith defaultChunkSize
365{-# INLINE readChunks #-}
366readChunks :: MonadIO m => Socket -> Stream m (Array Word8)
367readChunks = readChunksWith defaultChunkSize
369-- | Unfold the tuple @(bufsize, socket)@ into a stream of 'Word8' arrays.
370-- Read requests to the socket are performed using a buffer of size @bufsize@.
371-- The size of an array in the resulting stream is always less than or equal to
374{-# INLINE_NORMAL chunkReaderWith #-}
375chunkReaderWith :: MonadIO m => Unfold m (Int, Socket) (Array Word8)
376chunkReaderWith = Unfold step return
378 {-# INLINE_LATE step #-}
380 arr <- liftIO $ getChunk size h
384 _ -> D.Yield arr (size, h)
386-- | Same as 'chunkReaderWith'
388{-# DEPRECATED readChunksWithBufferOf "Please use 'chunkReaderWith' instead" #-}
389{-# INLINE_NORMAL readChunksWithBufferOf #-}
390readChunksWithBufferOf :: MonadIO m => Unfold m (Int, Socket) (Array Word8)
391readChunksWithBufferOf = chunkReaderWith
393-- | Unfolds a socket into a stream of 'Word8' arrays. Requests to the socket
394-- are performed using a buffer of size
395-- 'Streamly.Internal.Data.Array.Type.defaultChunkSize'. The
396-- size of arrays in the resulting stream are therefore less than or equal to
397-- 'Streamly.Internal.Data.Array.Type.defaultChunkSize'.
399{-# INLINE chunkReader #-}
400chunkReader :: MonadIO m => Unfold m Socket (Array Word8)
401chunkReader = UF.first defaultChunkSize chunkReaderWith
403-------------------------------------------------------------------------------
404-- Read File to Stream
405-------------------------------------------------------------------------------
407{-# INLINE concatChunks #-}
408concatChunks :: (Monad m, Unbox a) => Stream m (Array a) -> Stream m a
409concatChunks = S.unfoldMany A.reader
411-- | Generate a byte stream from a socket using a buffer of the given size.
414{-# INLINE readWith #-}
415readWith :: MonadIO m => Int -> Socket -> Stream m Word8
416readWith size = concatChunks . readChunksWith size
418-- | Generate a byte stream from a socket.
420-- >>> read = Socket.readWith defaultChunkSize
424read :: MonadIO m => Socket -> Stream m Word8
425read = readWith defaultChunkSize
427-- | Unfolds the tuple @(bufsize, socket)@ into a byte stream, read requests
428-- to the socket are performed using buffers of @bufsize@.
430{-# INLINE readerWith #-}
431readerWith :: MonadIO m => Unfold m (Int, Socket) Word8
432readerWith = UF.many A.reader chunkReaderWith
434-- | Same as 'readWith'
436{-# DEPRECATED readWithBufferOf "Please use 'readerWith' instead" #-}
437{-# INLINE readWithBufferOf #-}
438readWithBufferOf :: MonadIO m => Unfold m (Int, Socket) Word8
439readWithBufferOf = readerWith
441-- | Unfolds a 'Socket' into a byte stream. IO requests to the socket are
442-- performed in sizes of
443-- 'Streamly.Internal.Data.Array.Type.defaultChunkSize'.
446reader :: MonadIO m => Unfold m Socket Word8
447reader = UF.first defaultChunkSize readerWith
449-------------------------------------------------------------------------------
451-------------------------------------------------------------------------------
453-- | Write a stream of arrays to a handle.
455{-# INLINE putChunks #-}
456putChunks :: (MonadIO m, Unbox a)
457 => Socket -> Stream m (Array a) -> m ()
458putChunks h = S.fold (FL.drainMapM (liftIO . putChunk h))
460-- | Write a stream of arrays to a socket. Each array in the stream is written
461-- to the socket as a separate IO request.
463{-# INLINE writeChunks #-}
464writeChunks :: (MonadIO m, Unbox a) => Socket -> Fold m (Array a) ()
465writeChunks h = FL.drainMapM (liftIO . putChunk h)
467-- | @writeChunksWith bufsize socket@ writes a stream of arrays to
468-- @socket@ after coalescing the adjacent arrays in chunks of @bufsize@.
469-- Multiple arrays are coalesed as long as the total size remains below the
470-- specified size. It never splits an array, if a single array is bigger than
471-- the specified size it emitted as it is.
473{-# INLINE writeChunksWith #-}
474writeChunksWith :: (MonadIO m, Unbox a)
475 => Int -> Socket -> Fold m (Array a) ()
476writeChunksWith n h = lpackArraysChunksOf n (writeChunks h)
478-- | Same as 'writeChunksWith'
480{-# DEPRECATED writeChunksWithBufferOf "Please use 'writeChunksWith' instead" #-}
481{-# INLINE writeChunksWithBufferOf #-}
482writeChunksWithBufferOf :: (MonadIO m, Unbox a)
483 => Int -> Socket -> Fold m (Array a) ()
484writeChunksWithBufferOf = writeChunksWith
486-- GHC buffer size dEFAULT_FD_BUFFER_SIZE=8192 bytes.
489-- Note that if you use a chunk size less than 8K (GHC's default buffer
490-- size) then you are advised to use 'NOBuffering' mode on the 'Handle' in case you
491-- do not want buffering to occur at GHC level as well. Same thing applies to
494-- | Like 'write' but provides control over the write buffer. Output will
495-- be written to the IO device as soon as we collect the specified number of
498{-# INLINE putBytesWith #-}
499putBytesWith :: MonadIO m => Int -> Socket -> Stream m Word8 -> m ()
500putBytesWith n h m = putChunks h $ A.chunksOfAs Pinned n m
502-- | Write a byte stream to a socket. Accumulates the input in chunks of
503-- specified number of bytes before writing.
505{-# INLINE writeWith #-}
506writeWith :: MonadIO m => Int -> Socket -> Fold m Word8 ()
507writeWith n h = FL.groupsOf n (A.writeNUnsafeAs Pinned n) (writeChunks h)
509-- | Same as 'writeWith'
511{-# DEPRECATED writeWithBufferOf "Please use 'writeWith' instead" #-}
512{-# INLINE writeWithBufferOf #-}
513writeWithBufferOf :: MonadIO m => Int -> Socket -> Fold m Word8 ()
514writeWithBufferOf = writeWith
516-- | Write a stream of 'Maybe' values. Keep buffering the 'Just' values in an
517-- array. Write the array to the 'Handle' as soon as a 'Nothing' is encountered
518-- or the buffer size exceeds the specified limit.
521{-# INLINE writeMaybesWith #-}
522writeMaybesWith :: (MonadIO m )
523 => Int -> Socket -> Fold m (Maybe Word8) ()
525 let writeNJusts = FL.lmap fromJust $ A.writeNAs Pinned n
526 writeOnNothing = FL.takeEndBy_ isNothing writeNJusts
527 in FL.many writeOnNothing (writeChunks h)
529-- | Write a byte stream to a file handle. Combines the bytes in chunks of size
530-- up to 'defaultChunkSize' before writing. Note that the write behavior
531-- depends on the 'IOMode' and the current seek position of the handle.
533{-# INLINE putBytes #-}
534putBytes :: MonadIO m => Socket -> Stream m Word8 -> m ()
535putBytes = putBytesWith defaultChunkSize
537-- | Write a byte stream to a socket. Accumulates the input in chunks of
538-- up to 'defaultChunkSize' bytes before writing.
540-- >>> write = Socket.writeWith defaultChunkSize
543write :: MonadIO m => Socket -> Fold m Word8 ()
544write = 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