on d29030f help sign in
544 lines 19 kB history raw
1#include "inline.hs"
3-- |
4-- Module : Streamly.Internal.Network.Socket
5-- Copyright : (c) 2018 Composewell Technologies
6--
7-- License : BSD3
8-- Maintainer : streamly@composewell.com
9-- Stability : experimental
10-- Portability : GHC
11--
12module Streamly.Internal.Network.Socket
13 (
14 SockSpec (..)
15 -- * Use a socket
16 , forSocketM
17 , withSocket
19 -- * Accept connections
20 , accept
21 , acceptor
23 -- * Connect
24 , connect
25 , connectFrom
27 -- * Read from connection
28 , getChunk
30 -- ** Streams
31 , read
32 , readWith
33 , readChunks
34 , readChunksWith
36 -- ** Unfolds
37 , reader
38 , readerWith
39 , chunkReader
40 , chunkReaderWith
42 -- * Write to connection
43 , putChunk
45 -- ** Folds
46 , write
47 , writeWith
48 , writeChunks
49 , writeChunksWith
50 , writeMaybesWith
52 -- ** Stream writes
53 , putChunks
54 , putBytesWith
55 , putBytes
57 -- reading/writing datagrams
59 -- * Deprecated
60 , readWithBufferOf
61 , readChunksWithBufferOf
62 , writeWithBufferOf
63 , writeChunksWithBufferOf
64 )
65where
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)
76import Network.Socket
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)
82#else
83import Network.Socket (fdSocket)
84#endif
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
101 , writeNAs
102 )
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)
112-- $setup
113-- >>> :m
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'.
122--
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
128-- computation.
129--
130-- /Inhibits stream fusion/
131--
132-- /Internal/
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-------------------------------------------------------------------------------
139-- Accept (Unfolds)
140-------------------------------------------------------------------------------
142-- XXX Protocol specific socket options should be separated from socket level
143-- options.
144--
145-- | Specify the socket protocol details.
146data SockSpec = SockSpec
147 {
148 sockFamily :: !Family
149 , sockType :: !SocketType
150 , sockProto :: !ProtocolNumber
151 , sockOpts :: ![(SocketOption, Int)]
152 }
154initListener :: Int -> SockSpec -> SockAddr -> IO Socket
155initListener listenQLen SockSpec{..} addr =
156 withSocketsDo $ do
157 sock <- socket sockFamily sockType sockProto
158 use sock `onException` Net.close sock
159 return sock
161 where
163 use sock = do
164 mapM_ (\(opt, val) -> setSocketOption sock opt val) sockOpts
165 bind sock addr
166 Net.listen sock listenQLen
168{-# INLINE listenTuples #-}
169listenTuples :: MonadIO m
170 => Unfold m (Int, SockSpec, SockAddr) (Socket, SockAddr)
171listenTuples = Unfold step inject
172 where
173 inject (listenQLen, spec, addr) =
174 liftIO $ initListener listenQLen spec addr
176 step listener = do
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.
185--
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
195 return sock
197 where
199 use sock = do
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.
206--
207-- /Pre-release/
208--
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.
216--
217-- /Pre-release/
218--
219{-# INLINE connectFrom #-}
220connectFrom :: SockSpec -> SockAddr -> SockAddr -> IO Socket
221connectFrom spec local = connectCommon spec (Just local)
223-------------------------------------------------------------------------------
224-- Listen (Streams)
225-------------------------------------------------------------------------------
227{-# INLINE recvConnectionTuplesWith #-}
228recvConnectionTuplesWith :: MonadIO m
229 => Int -> SockSpec -> SockAddr -> Stream m (Socket, SockAddr)
230recvConnectionTuplesWith tcpListenQ spec addr = S.unfoldrM step Nothing
231 where
232 step Nothing = do
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.
245--
246-- /Pre-release/
247{-# INLINE accept #-}
248accept :: MonadIO m => Int -> SockSpec -> SockAddr -> Stream m Socket
249accept tcpListenQ spec addr =
250 fst <$> recvConnectionTuplesWith tcpListenQ spec addr
252-------------------------------------------------------------------------------
253-- Array IO (Input)
254-------------------------------------------------------------------------------
256{-# INLINABLE readArrayUptoWith #-}
257readArrayUptoWith
258 :: (h -> Ptr Word8 -> Int -> IO Int)
259 -> Int
260 -> h
261 -> IO (Array Word8)
262readArrayUptoWith f size h = do
263 arr <- MArray.newPinnedBytes size
264 -- ptr <- mallocPlainForeignPtrAlignedBytes size (alignment (undefined :: Word8))
265 MArray.asPtrUnsafe arr $ \p -> do
266 n <- f h p size
267 let v = A.unsafeFreeze
268 $ arr { MArray.arrEnd = n, MArray.arrBound = size }
270 -- XXX shrink only if the diff is significant
271 -- A.shrinkToFit v
272 return v
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.
278--
279{-# INLINABLE getChunk #-}
280getChunk :: Int -> Socket -> IO (Array Word8)
281getChunk = readArrayUptoWith recvBuf
283-------------------------------------------------------------------------------
284-- Array IO (output)
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
293#else
294 let fd = fdSocket s in threadWaitWrite $ fromIntegral fd
295#endif
296waitWhen0 _ _ = return ()
298sendAll :: Socket -> Ptr Word8 -> Int -> IO ()
299sendAll _ _ len | len <= 0 = return ()
300sendAll s p len = do
301 sent <- sendBuf s p len
302 waitWhen0 sent s
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 ())
309 -> h
310 -> Array a
311 -> IO ()
312writeArrayWith _ _ arr | A.length arr == 0 = return ()
313writeArrayWith f h arr = A.asPtrUnsafe arr $ \ptr -> f h (castPtr ptr) aLen
315 where
317 aLen = A.byteLength arr
319-- | Write an Array to a socket.
320--
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
334 where
335 -- XXX use cons/nil instead
336 go = K.mkStream $ \_ yld _ stp -> do
337 arr <- liftIO $ f size h
338 if A.length arr == 0
339 then stp
340 else yld arr go
342-- | @readChunksWith bufsize socket@ reads a stream of arrays from @socket@.
343-- The maximum size of a single array is limited to @bufsize@.
344--
345-- /Pre-release/
346{-# INLINE_NORMAL readChunksWith #-}
347readChunksWith :: MonadIO m => Int -> Socket -> Stream m (Array Word8)
348-- readChunksWith = _readChunksUptoWith readChunk
349readChunksWith size h = D.Stream step ()
350 where
351 {-# INLINE_LATE step #-}
352 step _ _ = do
353 arr <- liftIO $ getChunk size h
354 return $
355 case A.length arr of
356 0 -> D.Stop
357 _ -> D.Yield arr ()
359-- | Read a stream of byte arrays from a socket. The maximum size of a single
360-- array is limited to @defaultChunkSize@.
361--
362-- >>> readChunks = Socket.readChunksWith defaultChunkSize
363--
364-- /Pre-release/
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
372-- @bufsize@.
373--
374{-# INLINE_NORMAL chunkReaderWith #-}
375chunkReaderWith :: MonadIO m => Unfold m (Int, Socket) (Array Word8)
376chunkReaderWith = Unfold step return
377 where
378 {-# INLINE_LATE step #-}
379 step (size, h) = do
380 arr <- liftIO $ getChunk size h
381 return $
382 case A.length arr of
383 0 -> D.Stop
384 _ -> D.Yield arr (size, h)
386-- | Same as 'chunkReaderWith'
387--
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'.
398--
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.
412--
413-- /Pre-release/
414{-# INLINE readWith #-}
415readWith :: MonadIO m => Int -> Socket -> Stream m Word8
416readWith size = concatChunks . readChunksWith size
418-- | Generate a byte stream from a socket.
419--
420-- >>> read = Socket.readWith defaultChunkSize
421--
422-- /Pre-release/
423{-# INLINE read #-}
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@.
429--
430{-# INLINE readerWith #-}
431readerWith :: MonadIO m => Unfold m (Int, Socket) Word8
432readerWith = UF.many A.reader chunkReaderWith
434-- | Same as 'readWith'
435--
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'.
444--
445{-# INLINE reader #-}
446reader :: MonadIO m => Unfold m Socket Word8
447reader = UF.first defaultChunkSize readerWith
449-------------------------------------------------------------------------------
450-- Writing
451-------------------------------------------------------------------------------
453-- | Write a stream of arrays to a handle.
454--
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.
462--
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.
472--
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'
479--
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.
487--
488-- XXX test this
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
492-- writes as well.
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
496-- input elements.
497--
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.
504--
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'
510--
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.
519--
520-- /Pre-release/
521{-# INLINE writeMaybesWith #-}
522writeMaybesWith :: (MonadIO m )
523 => Int -> Socket -> Fold m (Maybe Word8) ()
524writeMaybesWith n h =
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.
532--
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.
539--
540-- >>> write = Socket.writeWith defaultChunkSize
541--
542{-# INLINE write #-}
543write :: MonadIO m => Socket -> Fold m Word8 ()
544write = writeWith defaultChunkSize