{-# LANGUAGE OverloadedStrings #-}
{-# OPTIONS_HADDOCK hide #-}
module Cometa.Provider.Blockfrost.Internal.Connection (managerSettings, managerSettingsWithStore, socketBackend) where
import Control.Concurrent (forkFinally, newEmptyMVar, putMVar, takeMVar, threadDelay)
import Control.Concurrent.Async (forConcurrently, withAsync)
import Control.Concurrent.MVar (tryPutMVar, tryTakeMVar)
import Control.Concurrent.STM (retry)
import Control.Exception (IOException, bracketOnError, mask, onException, throwIO, try)
import Control.Monad (unless, void)
import Data.ByteString (ByteString)
import qualified Data.ByteString as B
import qualified Data.ByteString.Char8 as C
import qualified Data.ByteString.Lazy as Lazy
import Data.List (find)
import Data.Void (Void, absurd)
import Data.X509.CertificateStore (CertificateStore)
import qualified Network.HTTP.Client as Http
import qualified Network.HTTP.Client.Internal as HttpConnection
import qualified Network.HTTP.Client.TLS as TLS
import qualified Network.Socket as Socket
import qualified Network.Socket.ByteString as Socket
import qualified Network.TLS as Tls
import qualified Network.TLS.Extra.Cipher as Cipher
import System.X509 (getSystemCertificateStore)
managerSettings :: IO Http.ManagerSettings
managerSettings :: IO ManagerSettings
managerSettings = CertificateStore -> ManagerSettings
managerSettingsWithStore (CertificateStore -> ManagerSettings)
-> IO CertificateStore -> IO ManagerSettings
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> IO CertificateStore
getSystemCertificateStore
managerSettingsWithStore :: CertificateStore -> Http.ManagerSettings
managerSettingsWithStore :: CertificateStore -> ManagerSettings
managerSettingsWithStore CertificateStore
certificates =
let parameters :: String -> Int -> Tls.ClientParams
parameters :: String -> Int -> ClientParams
parameters String
host Int
port =
let defaults :: ClientParams
defaults = String -> ByteString -> ClientParams
Tls.defaultParamsClient (String -> String
Http.strippedHostName String
host) (String -> ByteString
C.pack (Int -> String
forall a. Show a => a -> String
show Int
port))
in ClientParams
defaults
{ Tls.clientSupported = Tls.defaultSupported {Tls.supportedCiphers = Cipher.ciphersuite_default},
Tls.clientShared = (Tls.clientShared defaults) {Tls.sharedCAStore = certificates}
}
secure :: Maybe HostAddress -> String -> Int -> IO Connection
secure Maybe HostAddress
address String
host Int
port =
IO Connection
-> (Connection -> IO ())
-> (Connection -> IO Connection)
-> IO Connection
forall a b c. IO a -> (a -> IO b) -> (a -> IO c) -> IO c
bracketOnError (Maybe HostAddress -> String -> Int -> IO Connection
rawConnection Maybe HostAddress
address String
host Int
port) Connection -> IO ()
HttpConnection.connectionClose (ClientParams -> Connection -> IO Connection
secureConnection (String -> Int -> ClientParams
parameters String
host Int
port))
proxy :: ByteString
-> (Connection -> IO a)
-> String
-> Maybe HostAddress
-> String
-> Int
-> IO Connection
proxy ByteString
connectBytes Connection -> IO a
checkConnection String
serverName Maybe HostAddress
address String
host Int
port =
IO Connection
-> (Connection -> IO ())
-> (Connection -> IO Connection)
-> IO Connection
forall a b c. IO a -> (a -> IO b) -> (a -> IO c) -> IO c
bracketOnError (Maybe HostAddress -> String -> Int -> IO Connection
rawConnection Maybe HostAddress
address String
host Int
port) Connection -> IO ()
HttpConnection.connectionClose ((Connection -> IO Connection) -> IO Connection)
-> (Connection -> IO Connection) -> IO Connection
forall a b. (a -> b) -> a -> b
$ \Connection
connection -> do
Connection -> ByteString -> IO ()
HttpConnection.connectionWrite Connection
connection ByteString
connectBytes
IO a -> IO ()
forall (f :: * -> *) a. Functor f => f a -> f ()
void (Connection -> IO a
checkConnection Connection
connection)
Int
targetPort <- ByteString -> IO Int
proxyTargetPort ByteString
connectBytes
ClientParams -> Connection -> IO Connection
secureConnection (String -> Int -> ClientParams
parameters String
serverName Int
targetPort) Connection
connection
in ManagerSettings
TLS.tlsManagerSettings
{ Http.managerRawConnection = pure rawConnection,
Http.managerTlsConnection = pure secure,
HttpConnection.managerTlsProxyConnection = pure proxy,
Http.managerRetryableException = const False,
Http.managerIdleConnectionCount = 0
}
rawConnection :: Maybe Socket.HostAddress -> String -> Int -> IO HttpConnection.Connection
rawConnection :: Maybe HostAddress -> String -> Int -> IO Connection
rawConnection Maybe HostAddress
address String
host Int
port =
IO Socket
-> (Socket -> IO ()) -> (Socket -> IO Connection) -> IO Connection
forall a b c. IO a -> (a -> IO b) -> (a -> IO c) -> IO c
bracketOnError (Maybe HostAddress -> String -> Int -> IO Socket
connectSocket Maybe HostAddress
address String
host Int
port) Socket -> IO ()
Socket.close Socket -> IO Connection
socketConnection
socketConnection :: Socket.Socket -> IO HttpConnection.Connection
socketConnection :: Socket -> IO Connection
socketConnection Socket
socket =
IO ByteString -> (ByteString -> IO ()) -> IO () -> IO Connection
Http.makeConnection
(IO (Either Void ByteString) -> IO ByteString
forall a. IO (Either Void a) -> IO a
completed (Socket -> Int -> STM Void -> IO (Either Void ByteString)
forall a. Socket -> Int -> STM a -> IO (Either a ByteString)
Socket.recvWith Socket
socket Int
8192 STM Void
forall a. STM a
retry))
(\ByteString
bytes -> IO (Either Void ()) -> IO ()
forall a. IO (Either Void a) -> IO a
completed (Socket -> ByteString -> STM Void -> IO (Either Void ())
forall a. Socket -> ByteString -> STM a -> IO (Either a ())
Socket.sendAllWith Socket
socket ByteString
bytes STM Void
forall a. STM a
retry))
(Socket -> IO ()
Socket.close Socket
socket)
connectSocket :: Maybe Socket.HostAddress -> String -> Int -> IO Socket.Socket
connectSocket :: Maybe HostAddress -> String -> Int -> IO Socket
connectSocket Maybe HostAddress
address String
host Int
port = do
[AddrInfo]
addresses <- case Maybe HostAddress
address of
Just HostAddress
ipv4 -> [AddrInfo] -> IO [AddrInfo]
forall a. a -> IO a
forall (f :: * -> *) a. Applicative f => a -> f a
pure [AddrInfo
Socket.defaultHints {Socket.addrFamily = Socket.AF_INET, Socket.addrSocketType = Socket.Stream, Socket.addrAddress = Socket.SockAddrInet (fromIntegral port) ipv4}]
Maybe HostAddress
Nothing -> String -> Int -> IO [AddrInfo]
resolve String
host Int
port
((forall a. IO a -> IO a) -> IO Socket) -> IO Socket
forall b. ((forall a. IO a -> IO a) -> IO b) -> IO b
mask (((forall a. IO a -> IO a) -> IO Socket) -> IO Socket)
-> ((forall a. IO a -> IO a) -> IO Socket) -> IO Socket
forall a b. (a -> b) -> a -> b
$ \forall a. IO a -> IO a
restore -> do
MVar (Either IOException Socket)
result <- IO (MVar (Either IOException Socket))
forall a. IO (MVar a)
newEmptyMVar
let attempt :: (AddrInfo, Int) -> IO (Maybe IOException)
attempt (AddrInfo
info, Int
delay) = ((forall a. IO a -> IO a) -> IO (Maybe IOException))
-> IO (Maybe IOException)
forall b. ((forall a. IO a -> IO a) -> IO b) -> IO b
mask (((forall a. IO a -> IO a) -> IO (Maybe IOException))
-> IO (Maybe IOException))
-> ((forall a. IO a -> IO a) -> IO (Maybe IOException))
-> IO (Maybe IOException)
forall a b. (a -> b) -> a -> b
$ \forall a. IO a -> IO a
restoreAttempt -> do
Either IOException Socket
socket <- IO Socket -> IO (Either IOException Socket)
forall e a. Exception e => IO a -> IO (Either e a)
try (Int -> IO ()
threadDelay Int
delay IO () -> IO Socket -> IO Socket
forall a b. IO a -> IO b -> IO b
forall (m :: * -> *) a b. Monad m => m a -> m b -> m b
>> (IO () -> IO ()) -> AddrInfo -> IO Socket
forall {a}. (IO () -> IO a) -> AddrInfo -> IO Socket
open IO () -> IO ()
forall a. IO a -> IO a
restoreAttempt AddrInfo
info)
case Either IOException Socket
socket of
Left IOException
failure -> Maybe IOException -> IO (Maybe IOException)
forall a. a -> IO a
forall (f :: * -> *) a. Applicative f => a -> f a
pure (IOException -> Maybe IOException
forall a. a -> Maybe a
Just (IOException
failure :: IOException))
Right Socket
connected -> do
Bool
published <- MVar (Either IOException Socket)
-> Either IOException Socket -> IO Bool
forall a. MVar a -> a -> IO Bool
tryPutMVar MVar (Either IOException Socket)
result (Socket -> Either IOException Socket
forall a b. b -> Either a b
Right Socket
connected)
Bool -> IO () -> IO ()
forall (f :: * -> *). Applicative f => Bool -> f () -> f ()
unless Bool
published (Socket -> IO ()
Socket.close Socket
connected)
Maybe IOException -> IO (Maybe IOException)
forall a. a -> IO a
forall (f :: * -> *) a. Applicative f => a -> f a
pure Maybe IOException
forall a. Maybe a
Nothing
run :: IO ()
run = do
[Maybe IOException]
failures <- [(AddrInfo, Int)]
-> ((AddrInfo, Int) -> IO (Maybe IOException))
-> IO [Maybe IOException]
forall (t :: * -> *) a b.
Traversable t =>
t a -> (a -> IO b) -> IO (t b)
forConcurrently ([AddrInfo] -> [Int] -> [(AddrInfo, Int)]
forall a b. [a] -> [b] -> [(a, b)]
zip [AddrInfo]
addresses [Int
0, Int
250000 ..]) (AddrInfo, Int) -> IO (Maybe IOException)
attempt
case (Maybe IOException -> Bool)
-> [Maybe IOException] -> Maybe (Maybe IOException)
forall (t :: * -> *) a. Foldable t => (a -> Bool) -> t a -> Maybe a
find Maybe IOException -> Bool
forall {a}. Maybe a -> Bool
isFailure [Maybe IOException]
failures of
Just (Just IOException
failure) -> IO Bool -> IO ()
forall (f :: * -> *) a. Functor f => f a -> f ()
void (MVar (Either IOException Socket)
-> Either IOException Socket -> IO Bool
forall a. MVar a -> a -> IO Bool
tryPutMVar MVar (Either IOException Socket)
result (IOException -> Either IOException Socket
forall a b. a -> Either a b
Left IOException
failure))
Maybe (Maybe IOException)
_ -> () -> IO ()
forall a. a -> IO a
forall (f :: * -> *) a. Applicative f => a -> f a
pure ()
abandon :: IO ()
abandon = do
Maybe (Either IOException Socket)
pending <- MVar (Either IOException Socket)
-> IO (Maybe (Either IOException Socket))
forall a. MVar a -> IO (Maybe a)
tryTakeMVar MVar (Either IOException Socket)
result
case Maybe (Either IOException Socket)
pending of
Just (Right Socket
socket) -> Socket -> IO ()
Socket.close Socket
socket
Maybe (Either IOException Socket)
_ -> () -> IO ()
forall a. a -> IO a
forall (f :: * -> *) a. Applicative f => a -> f a
pure ()
Either IOException Socket
winner <- IO ()
-> (Async () -> IO (Either IOException Socket))
-> IO (Either IOException Socket)
forall a b. IO a -> (Async a -> IO b) -> IO b
withAsync (IO () -> IO ()
forall a. IO a -> IO a
restore IO ()
run) (IO (Either IOException Socket)
-> Async () -> IO (Either IOException Socket)
forall a b. a -> b -> a
const (MVar (Either IOException Socket) -> IO (Either IOException Socket)
forall a. MVar a -> IO a
takeMVar MVar (Either IOException Socket)
result)) IO (Either IOException Socket)
-> IO () -> IO (Either IOException Socket)
forall a b. IO a -> IO b -> IO a
`onException` IO ()
abandon
(IOException -> IO Socket)
-> (Socket -> IO Socket) -> Either IOException Socket -> IO Socket
forall a c b. (a -> c) -> (b -> c) -> Either a b -> c
either IOException -> IO Socket
forall e a. Exception e => e -> IO a
throwIO Socket -> IO Socket
forall a. a -> IO a
forall (f :: * -> *) a. Applicative f => a -> f a
pure Either IOException Socket
winner
where
isFailure :: Maybe a -> Bool
isFailure Maybe a
Nothing = Bool
False
isFailure (Just a
_) = Bool
True
open :: (IO () -> IO a) -> AddrInfo -> IO Socket
open IO () -> IO a
restoreConnect AddrInfo
info = IO Socket
-> (Socket -> IO ()) -> (Socket -> IO Socket) -> IO Socket
forall a b c. IO a -> (a -> IO b) -> (a -> IO c) -> IO c
bracketOnError (Family -> SocketType -> ProtocolNumber -> IO Socket
Socket.socket (AddrInfo -> Family
Socket.addrFamily AddrInfo
info) SocketType
Socket.Stream (AddrInfo -> ProtocolNumber
Socket.addrProtocol AddrInfo
info)) Socket -> IO ()
Socket.close ((Socket -> IO Socket) -> IO Socket)
-> (Socket -> IO Socket) -> IO Socket
forall a b. (a -> b) -> a -> b
$ \Socket
socket -> do
a
_ <- IO () -> IO a
restoreConnect (IO () -> IO a) -> IO () -> IO a
forall a b. (a -> b) -> a -> b
$ do
Socket -> SocketOption -> Int -> IO ()
Socket.setSocketOption Socket
socket SocketOption
Socket.NoDelay Int
1
IO (Either Void ()) -> IO ()
forall a. IO (Either Void a) -> IO a
completed (Socket -> SockAddr -> STM Void -> IO (Either Void ())
forall a. Socket -> SockAddr -> STM a -> IO (Either a ())
Socket.connectWith Socket
socket (AddrInfo -> SockAddr
Socket.addrAddress AddrInfo
info) STM Void
forall a. STM a
retry)
Socket -> IO Socket
forall a. a -> IO a
forall (f :: * -> *) a. Applicative f => a -> f a
pure Socket
socket
resolve :: String -> Int -> IO [Socket.AddrInfo]
resolve :: String -> Int -> IO [AddrInfo]
resolve String
host Int
port = do
MVar (Either SomeException [AddrInfo])
result <- IO (MVar (Either SomeException [AddrInfo]))
forall a. IO (MVar a)
newEmptyMVar
ThreadId
_ <- IO [AddrInfo]
-> (Either SomeException [AddrInfo] -> IO ()) -> IO ThreadId
forall a. IO a -> (Either SomeException a -> IO ()) -> IO ThreadId
forkFinally (Maybe AddrInfo -> Maybe String -> Maybe String -> IO [AddrInfo]
forall (t :: * -> *).
GetAddrInfo t =>
Maybe AddrInfo -> Maybe String -> Maybe String -> IO (t AddrInfo)
Socket.getAddrInfo (AddrInfo -> Maybe AddrInfo
forall a. a -> Maybe a
Just AddrInfo
Socket.defaultHints {Socket.addrSocketType = Socket.Stream}) (String -> Maybe String
forall a. a -> Maybe a
Just (String -> String
Http.strippedHostName String
host)) (String -> Maybe String
forall a. a -> Maybe a
Just (Int -> String
forall a. Show a => a -> String
show Int
port))) (MVar (Either SomeException [AddrInfo])
-> Either SomeException [AddrInfo] -> IO ()
forall a. MVar a -> a -> IO ()
putMVar MVar (Either SomeException [AddrInfo])
result)
[AddrInfo]
addresses <- MVar (Either SomeException [AddrInfo])
-> IO (Either SomeException [AddrInfo])
forall a. MVar a -> IO a
takeMVar MVar (Either SomeException [AddrInfo])
result IO (Either SomeException [AddrInfo])
-> (Either SomeException [AddrInfo] -> IO [AddrInfo])
-> IO [AddrInfo]
forall a b. IO a -> (a -> IO b) -> IO b
forall (m :: * -> *) a b. Monad m => m a -> (a -> m b) -> m b
>>= (SomeException -> IO [AddrInfo])
-> ([AddrInfo] -> IO [AddrInfo])
-> Either SomeException [AddrInfo]
-> IO [AddrInfo]
forall a c b. (a -> c) -> (b -> c) -> Either a b -> c
either SomeException -> IO [AddrInfo]
forall e a. Exception e => e -> IO a
throwIO [AddrInfo] -> IO [AddrInfo]
forall a. a -> IO a
forall (f :: * -> *) a. Applicative f => a -> f a
pure
if [AddrInfo] -> Bool
forall a. [a] -> Bool
forall (t :: * -> *) a. Foldable t => t a -> Bool
null [AddrInfo]
addresses then IOException -> IO [AddrInfo]
forall a. IOException -> IO a
ioError (String -> IOException
userError String
"HTTP destination has no addresses") else [AddrInfo] -> IO [AddrInfo]
forall a. a -> IO a
forall (f :: * -> *) a. Applicative f => a -> f a
pure [AddrInfo]
addresses
proxyTargetPort :: ByteString -> IO Int
proxyTargetPort :: ByteString -> IO Int
proxyTargetPort ByteString
request = case ByteString -> [ByteString]
C.words ((Char -> Bool) -> ByteString -> ByteString
C.takeWhile (Char -> Char -> Bool
forall a. Eq a => a -> a -> Bool
/= Char
'\r') ByteString
request) of
[ByteString
"CONNECT", ByteString
authority, ByteString
"HTTP/1.1"] -> case ByteString -> Maybe (Int, ByteString)
C.readInt ((ByteString, ByteString) -> ByteString
forall a b. (a, b) -> b
snd ((Char -> Bool) -> ByteString -> (ByteString, ByteString)
C.breakEnd (Char -> Char -> Bool
forall a. Eq a => a -> a -> Bool
== Char
':') ByteString
authority)) of
Just (Int
port, ByteString
rest) | ByteString -> Bool
B.null ByteString
rest Bool -> Bool -> Bool
&& Int
port Int -> Int -> Bool
forall a. Ord a => a -> a -> Bool
> Int
0 Bool -> Bool -> Bool
&& Int
port Int -> Int -> Bool
forall a. Ord a => a -> a -> Bool
<= Int
65535 -> Int -> IO Int
forall a. a -> IO a
forall (f :: * -> *) a. Applicative f => a -> f a
pure Int
port
Maybe (Int, ByteString)
_ -> IO Int
forall {a}. IO a
invalid
[ByteString]
_ -> IO Int
forall {a}. IO a
invalid
where
invalid :: IO a
invalid = IOException -> IO a
forall a. IOException -> IO a
ioError (String -> IOException
userError String
"Invalid HTTP proxy CONNECT authority")
completed :: IO (Either Void a) -> IO a
completed :: forall a. IO (Either Void a) -> IO a
completed IO (Either Void a)
operation = do
Either Void a
result <- IO (Either Void a)
operation
case Either Void a
result of
Left Void
impossible -> Void -> IO a
forall a. Void -> a
absurd Void
impossible
Right a
value -> a -> IO a
forall a. a -> IO a
forall (f :: * -> *) a. Applicative f => a -> f a
pure a
value
secureConnection :: Tls.ClientParams -> HttpConnection.Connection -> IO HttpConnection.Connection
secureConnection :: ClientParams -> Connection -> IO Connection
secureConnection ClientParams
parameters Connection
connection =
IO Context
-> (Context -> IO ())
-> (Context -> IO Connection)
-> IO Connection
forall a b c. IO a -> (a -> IO b) -> (a -> IO c) -> IO c
bracketOnError (Backend -> ClientParams -> IO Context
forall (m :: * -> *) backend params.
(MonadIO m, HasBackend backend, TLSParams params) =>
backend -> params -> m Context
Tls.contextNew Backend
backend ClientParams
parameters) Context -> IO ()
Tls.contextClose ((Context -> IO Connection) -> IO Connection)
-> (Context -> IO Connection) -> IO Connection
forall a b. (a -> b) -> a -> b
$ \Context
context -> do
Context -> IO ()
forall (m :: * -> *). MonadIO m => Context -> m ()
Tls.handshake Context
context
IO ByteString -> (ByteString -> IO ()) -> IO () -> IO Connection
Http.makeConnection
(Context -> IO ByteString
forall (m :: * -> *). MonadIO m => Context -> m ByteString
Tls.recvData Context
context)
(Context -> ByteString -> IO ()
forall (m :: * -> *). MonadIO m => Context -> ByteString -> m ()
Tls.sendData Context
context (ByteString -> IO ())
-> (ByteString -> ByteString) -> ByteString -> IO ()
forall b c a. (b -> c) -> (a -> b) -> a -> c
. ByteString -> ByteString
Lazy.fromStrict)
(Context -> IO ()
Tls.contextClose Context
context)
where
backend :: Backend
backend = Connection -> Backend
connectionBackend Connection
connection
socketBackend :: Socket.Socket -> IO Tls.Backend
socketBackend :: Socket -> IO Backend
socketBackend Socket
socket = Connection -> Backend
connectionBackend (Connection -> Backend) -> IO Connection -> IO Backend
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> Socket -> IO Connection
socketConnection Socket
socket
connectionBackend :: HttpConnection.Connection -> Tls.Backend
connectionBackend :: Connection -> Backend
connectionBackend Connection
connection =
Tls.Backend
{ backendFlush :: IO ()
Tls.backendFlush = () -> IO ()
forall a. a -> IO a
forall (f :: * -> *) a. Applicative f => a -> f a
pure (),
backendClose :: IO ()
Tls.backendClose = Connection -> IO ()
HttpConnection.connectionClose Connection
connection,
backendSend :: ByteString -> IO ()
Tls.backendSend = Connection -> ByteString -> IO ()
HttpConnection.connectionWrite Connection
connection,
backendRecv :: Int -> IO ByteString
Tls.backendRecv = Connection -> Int -> IO ByteString
receiveExactly Connection
connection
}
receiveExactly :: HttpConnection.Connection -> Int -> IO ByteString
receiveExactly :: Connection -> Int -> IO ByteString
receiveExactly Connection
connection Int
count = Int -> [ByteString] -> IO ByteString
go Int
count []
where
go :: Int -> [ByteString] -> IO ByteString
go Int
0 [ByteString]
chunks = ByteString -> IO ByteString
forall a. a -> IO a
forall (f :: * -> *) a. Applicative f => a -> f a
pure ([ByteString] -> ByteString
B.concat ([ByteString] -> [ByteString]
forall a. [a] -> [a]
reverse [ByteString]
chunks))
go Int
remaining [ByteString]
chunks = do
ByteString
bytes <- Connection -> IO ByteString
HttpConnection.connectionRead Connection
connection
if ByteString -> Bool
B.null ByteString
bytes
then ByteString -> IO ByteString
forall a. a -> IO a
forall (f :: * -> *) a. Applicative f => a -> f a
pure ([ByteString] -> ByteString
B.concat ([ByteString] -> [ByteString]
forall a. [a] -> [a]
reverse [ByteString]
chunks))
else do
let (ByteString
wanted, ByteString
rest) = Int -> ByteString -> (ByteString, ByteString)
B.splitAt Int
remaining ByteString
bytes
Bool -> IO () -> IO ()
forall (f :: * -> *). Applicative f => Bool -> f () -> f ()
unless (ByteString -> Bool
B.null ByteString
rest) (Connection -> ByteString -> IO ()
HttpConnection.connectionUnread Connection
connection ByteString
rest)
Int -> [ByteString] -> IO ByteString
go (Int
remaining Int -> Int -> Int
forall a. Num a => a -> a -> a
- ByteString -> Int
B.length ByteString
wanted) (ByteString
wanted ByteString -> [ByteString] -> [ByteString]
forall a. a -> [a] -> [a]
: [ByteString]
chunks)