-- |
-- process handshake message received
module Network.TLS.Handshake.Process (
    processHandshake12,
    processHandshake13,
    startHandshake,
) where

import Control.Concurrent.MVar

import Network.TLS.Context.Internal
import Network.TLS.Handshake.Random
import Network.TLS.Handshake.State
import Network.TLS.Handshake.State13
import Network.TLS.Imports
import Network.TLS.Sending
import Network.TLS.Struct
import Network.TLS.Struct13

processHandshake12 :: Context -> Handshake -> IO ()
processHandshake12 :: Context -> Handshake -> IO ()
processHandshake12 Context
ctx Handshake
hs = do
    Bool -> IO () -> IO ()
forall (f :: * -> *). Applicative f => Bool -> f () -> f ()
when (Handshake -> Bool
isHRR Handshake
hs) (IO () -> IO ()) -> IO () -> IO ()
forall a b. (a -> b) -> a -> b
$ Context -> HandshakeM () -> IO ()
forall (m :: * -> *) a. MonadIO m => Context -> HandshakeM a -> m a
usingHState Context
ctx HandshakeM ()
wrapAsMessageHash13
    IO ByteString -> IO ()
forall (f :: * -> *) a. Functor f => f a -> f ()
void (IO ByteString -> IO ()) -> IO ByteString -> IO ()
forall a b. (a -> b) -> a -> b
$ Context -> Handshake -> IO ByteString
updateHandshake12 Context
ctx Handshake
hs
  where
    isHRR :: Handshake -> Bool
isHRR (ServerHello Version
TLS12 ServerRandom
srand Session
_ CipherID
_ CompressionID
_ [ExtensionRaw]
_) = ServerRandom -> Bool
isHelloRetryRequest ServerRandom
srand
    isHRR Handshake
_ = Bool
False

processHandshake13 :: Context -> Handshake13 -> IO ()
processHandshake13 :: Context -> Handshake13 -> IO ()
processHandshake13 Context
ctx = IO ByteString -> IO ()
forall (f :: * -> *) a. Functor f => f a -> f ()
void (IO ByteString -> IO ())
-> (Handshake13 -> IO ByteString) -> Handshake13 -> IO ()
forall b c a. (b -> c) -> (a -> b) -> a -> c
. Context -> Handshake13 -> IO ByteString
updateHandshake13 Context
ctx

-- initialize a new Handshake context (initial handshake or renegotiations)
startHandshake :: Context -> Version -> ClientRandom -> IO ()
startHandshake :: Context -> Version -> ClientRandom -> IO ()
startHandshake Context
ctx Version
ver ClientRandom
crand =
    let hs :: Maybe HandshakeState
hs = HandshakeState -> Maybe HandshakeState
forall a. a -> Maybe a
Just (HandshakeState -> Maybe HandshakeState)
-> HandshakeState -> Maybe HandshakeState
forall a b. (a -> b) -> a -> b
$ Version -> ClientRandom -> HandshakeState
newEmptyHandshake Version
ver ClientRandom
crand
     in IO (Maybe HandshakeState) -> IO ()
forall (f :: * -> *) a. Functor f => f a -> f ()
void (IO (Maybe HandshakeState) -> IO ())
-> IO (Maybe HandshakeState) -> IO ()
forall a b. (a -> b) -> a -> b
$ MVar (Maybe HandshakeState)
-> Maybe HandshakeState -> IO (Maybe HandshakeState)
forall a. MVar a -> a -> IO a
swapMVar (Context -> MVar (Maybe HandshakeState)
ctxHandshakeState Context
ctx) Maybe HandshakeState
hs