{-# LANGUAGE CPP #-}
{-# LANGUAGE RankNTypes #-}

-- | A Backend represents a unified way to do IO on different
-- types without burdening our calling API with multiple
-- ways to initialize a new context.
--
-- Typically, a backend provides:
--
-- * a way to read data
-- * a way to write data
-- * a way to close the stream
-- * a way to flush the stream
module Network.TLS.Backend (
    HasBackend (..),
    Backend (..),
    RecvWith (..),
    SendWith (..),
) where

import Control.Concurrent.STM (STM)
import qualified Data.ByteString as B
import qualified Network.Socket as Network
import qualified Network.Socket.ByteString as Network
import System.IO (BufferMode (..), Handle, hClose, hFlush, hSetBuffering)

import Network.TLS.Imports

-- | Connection IO backend
data Backend = Backend
    { Backend -> IO ()
backendFlush :: IO ()
    -- ^ Flush the connection sending buffer, if any.
    , Backend -> IO ()
backendClose :: IO ()
    -- ^ Close the connection.
    , Backend -> ByteString -> IO ()
backendSend :: ByteString -> IO ()
    -- ^ Send a bytestring through the connection.
    , Backend -> Int -> IO ByteString
backendRecv :: Int -> IO ByteString
    -- ^ Receive the specified number of bytes from the connection.
    -- Fewer bytes are returned only at the end of the stream.
    --
    -- An 'Control.Exception.IOException' means a broken connection: the
    -- context is marked EOF and 'Network.TLS.bye' sends nothing.  Other
    -- exceptions, including asynchronous ones, pass through as they are,
    -- and 'Network.TLS.bye' can still send close_notify.  'Network.TLS.recvData'
    -- may be called again only if the exception was thrown before any byte
    -- of a record was taken.  Thrown inside the body of a record, it is
    -- thrown again by later receives (an asynchronous one as a TLS error).
    }

-- | Types which a 'Network.TLS.Context' can be created on.
class HasBackend a where
    -- | Prepare the connection before use.
    initializeBackend :: a -> IO ()

    -- | The IO functions of the connection.
    getBackend :: a -> Backend

    -- | A receive which can give up.  With it, 'Network.TLS.bye' waits for the
    --   peer's last handshake messages without interrupting a receive.
    --
    -- @since 2.6.0
    getBackendRecvWith :: a -> Maybe RecvWith
    getBackendRecvWith a
_ = Maybe RecvWith
forall a. Maybe a
Nothing

    -- | A send which can give up.  With it, 'Network.TLS.bye' gives up on
    --   close_notify when the peer does not read.
    --
    -- @since 2.6.4
    getBackendSendWith :: a -> Maybe SendWith
    getBackendSendWith a
_ = Maybe SendWith
forall a. Maybe a
Nothing

-- | A receive of the specified number of bytes which gives up once the
--   'STM' action succeeds, answering what it gave as 'Left'.  Bytes
--   already received by then are answered instead.
--
-- @since 2.6.0
newtype RecvWith = RecvWith (forall g. Int -> STM g -> IO (Either g ByteString))

-- | A send of all the bytes which gives up once the 'STM' action
--   succeeds, answering what it gave as 'Left'.  Part of the bytes may
--   have been sent by then.
--
-- @since 2.6.4
newtype SendWith = SendWith (forall g. ByteString -> STM g -> IO (Either g ()))

instance HasBackend Backend where
    initializeBackend :: Backend -> IO ()
initializeBackend Backend
_ = () -> IO ()
forall a. a -> IO a
forall (m :: * -> *) a. Monad m => a -> m a
return ()
    getBackend :: Backend -> Backend
getBackend = Backend -> Backend
forall a. a -> a
id

safeRecv :: Network.Socket -> Int -> IO ByteString
safeRecv :: Socket -> Int -> IO ByteString
safeRecv = Socket -> Int -> IO ByteString
Network.recv

instance HasBackend Network.Socket where
    initializeBackend :: Socket -> IO ()
initializeBackend Socket
_ = () -> IO ()
forall a. a -> IO a
forall (m :: * -> *) a. Monad m => a -> m a
return ()
    getBackend :: Socket -> Backend
getBackend Socket
sock =
        Backend
            { backendFlush :: IO ()
backendFlush = () -> IO ()
forall a. a -> IO a
forall (m :: * -> *) a. Monad m => a -> m a
return ()
            , backendClose :: IO ()
backendClose = Socket -> IO ()
Network.close Socket
sock
            , backendSend :: ByteString -> IO ()
backendSend = Socket -> ByteString -> IO ()
Network.sendAll Socket
sock
            , backendRecv :: Int -> IO ByteString
backendRecv = Int -> IO ByteString
recvAll
            }
      where
        recvAll :: Int -> IO ByteString
recvAll Int
n = [ByteString] -> ByteString
B.concat ([ByteString] -> ByteString) -> IO [ByteString] -> IO ByteString
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> Int -> IO [ByteString]
loop Int
n
          where
            loop :: Int -> IO [ByteString]
loop Int
0 = [ByteString] -> IO [ByteString]
forall a. a -> IO a
forall (m :: * -> *) a. Monad m => a -> m a
return []
            loop Int
left = do
                r <- Socket -> Int -> IO ByteString
safeRecv Socket
sock Int
left
                if B.null r
                    then return []
                    else (r :) <$> loop (left - B.length r)
#if MIN_VERSION_network(3,2,12)
    getBackendRecvWith :: Socket -> Maybe RecvWith
getBackendRecvWith Socket
sock = RecvWith -> Maybe RecvWith
forall a. a -> Maybe a
Just (RecvWith -> Maybe RecvWith) -> RecvWith -> Maybe RecvWith
forall a b. (a -> b) -> a -> b
$ (forall g. Int -> STM g -> IO (Either g ByteString)) -> RecvWith
RecvWith Int -> STM g -> IO (Either g ByteString)
forall g. Int -> STM g -> IO (Either g ByteString)
recvAllWith
      where
        recvAllWith :: Int -> STM a -> IO (Either a ByteString)
recvAllWith Int
n STM a
giveUp = Int -> [ByteString] -> IO (Either a ByteString)
loop Int
n []
          where
            done :: [ByteString] -> IO (Either a ByteString)
done = Either a ByteString -> IO (Either a ByteString)
forall a. a -> IO a
forall (m :: * -> *) a. Monad m => a -> m a
return (Either a ByteString -> IO (Either a ByteString))
-> ([ByteString] -> Either a ByteString)
-> [ByteString]
-> IO (Either a ByteString)
forall b c a. (b -> c) -> (a -> b) -> a -> c
. ByteString -> Either a ByteString
forall a b. b -> Either a b
Right (ByteString -> Either a ByteString)
-> ([ByteString] -> ByteString)
-> [ByteString]
-> Either a ByteString
forall b c a. (b -> c) -> (a -> b) -> a -> c
. [ByteString] -> ByteString
B.concat ([ByteString] -> ByteString)
-> ([ByteString] -> [ByteString]) -> [ByteString] -> ByteString
forall b c a. (b -> c) -> (a -> b) -> a -> c
. [ByteString] -> [ByteString]
forall a. [a] -> [a]
reverse
            loop :: Int -> [ByteString] -> IO (Either a ByteString)
loop Int
0 [ByteString]
acc = [ByteString] -> IO (Either a ByteString)
forall {a}. [ByteString] -> IO (Either a ByteString)
done [ByteString]
acc
            loop Int
left [ByteString]
acc = do
                r <- Socket -> Int -> STM a -> IO (Either a ByteString)
forall a. Socket -> Int -> STM a -> IO (Either a ByteString)
Network.recvWith Socket
sock Int
left STM a
giveUp
                case r of
                    -- Bytes already received are answered, not 'Left'.
                    Left a
g
                        | [ByteString] -> Bool
forall a. [a] -> Bool
forall (t :: * -> *) a. Foldable t => t a -> Bool
null [ByteString]
acc -> Either a ByteString -> IO (Either a ByteString)
forall a. a -> IO a
forall (m :: * -> *) a. Monad m => a -> m a
return (Either a ByteString -> IO (Either a ByteString))
-> Either a ByteString -> IO (Either a ByteString)
forall a b. (a -> b) -> a -> b
$ a -> Either a ByteString
forall a b. a -> Either a b
Left a
g
                        | Bool
otherwise -> [ByteString] -> IO (Either a ByteString)
forall {a}. [ByteString] -> IO (Either a ByteString)
done [ByteString]
acc
                    Right ByteString
bs
                        | ByteString -> Bool
B.null ByteString
bs -> [ByteString] -> IO (Either a ByteString)
forall {a}. [ByteString] -> IO (Either a ByteString)
done [ByteString]
acc
                        | Bool
otherwise -> Int -> [ByteString] -> IO (Either a ByteString)
loop (Int
left Int -> Int -> Int
forall a. Num a => a -> a -> a
- ByteString -> Int
B.length ByteString
bs) (ByteString
bs ByteString -> [ByteString] -> [ByteString]
forall a. a -> [a] -> [a]
: [ByteString]
acc)
    getBackendSendWith :: Socket -> Maybe SendWith
getBackendSendWith Socket
sock = SendWith -> Maybe SendWith
forall a. a -> Maybe a
Just (SendWith -> Maybe SendWith) -> SendWith -> Maybe SendWith
forall a b. (a -> b) -> a -> b
$ (forall g. ByteString -> STM g -> IO (Either g ())) -> SendWith
SendWith ((forall g. ByteString -> STM g -> IO (Either g ())) -> SendWith)
-> (forall g. ByteString -> STM g -> IO (Either g ())) -> SendWith
forall a b. (a -> b) -> a -> b
$ Socket -> ByteString -> STM g -> IO (Either g ())
forall a. Socket -> ByteString -> STM a -> IO (Either a ())
Network.sendAllWith Socket
sock
#endif

instance HasBackend Handle where
    initializeBackend :: Handle -> IO ()
initializeBackend Handle
handle = Handle -> BufferMode -> IO ()
hSetBuffering Handle
handle BufferMode
NoBuffering
    getBackend :: Handle -> Backend
getBackend Handle
handle =
        Backend
            { backendFlush :: IO ()
backendFlush = Handle -> IO ()
hFlush Handle
handle
            , backendClose :: IO ()
backendClose = Handle -> IO ()
hClose Handle
handle
            , backendSend :: ByteString -> IO ()
backendSend = Handle -> ByteString -> IO ()
B.hPut Handle
handle
            , backendRecv :: Int -> IO ByteString
backendRecv = Handle -> Int -> IO ByteString
B.hGet Handle
handle
            }