{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE StrictData #-}

-- | Simple tools for establishing and using Secure WebSockets connections on
-- top of TLS (i.e, @wss:\/\/@).
--
-- See the
-- [network-simple-ws](https://hackage.haskell.org/package/network-simple-ws)
-- package for insecure WebSockets (i.e, @ws:\/\/@) support.
--
-- Notice that, currently, this is package offers tools that are mostly
-- intreresting from a client's point of view. Server side support will come
-- later.
module Network.Simple.WSS
 ( -- * Sending and receiving
   WS.Connection
 , WS.recv
 , WS.send
 , WS.close
   -- * Client side
 , connect
 , connectOverSOCKS5
   -- * Low level
 , WS.clientConnectionFromStream
 , streamFromContext
 ) where


import qualified Control.Concurrent.Async as Async
import Control.Monad.IO.Class (MonadIO, liftIO)
import qualified Control.Exception.Safe as Ex
import qualified Data.ByteString as B
import Data.Foldable (traverse_)

import qualified Network.Simple.TCP.TLS as T
import qualified Network.Simple.WS as WS
import qualified Network.WebSockets as W
import qualified Network.WebSockets.Connection as W (pingThread)
import qualified Network.WebSockets.Stream as W (Stream, makeStream, close)

--------------------------------------------------------------------------------

-- | Connect to the specified Secure WebSockets server.
connect
  :: (MonadIO m, Ex.MonadMask m)
  => T.ClientParams  -- ^ TLS settings.
  -> T.HostName
  -- ^ Secure WebSockets server host name (e.g., @\"www.example.com\"@ or IP
  -- address).
  -> T.ServiceName
  -- ^ Secure WebSockets server port (e.g., @\"443\"@ or @\"www\"@).
  -> B.ByteString
  -- ^ Secure WebSockets resource (e.g., @\"/foo\/qux?bar=wat&baz\"@).
  --
  -- Leading @\'\/\'@ is optional.
  -> [(B.ByteString, B.ByteString)]
  -- ^ Extra HTTP Headers
  -- (e.g., @[(\"Authorization\", \"Basic dXNlcjpwYXNzd29yZA==\")]@).
  -> ((W.Connection, T.SockAddr) -> m r)
  -- ^ Computation to run after establishing a Secure WebSockets to the remote
  -- server. Takes the WebSockets connection and remote end address.
  -> m r
connect :: forall (m :: * -> *) r.
(MonadIO m, MonadMask m) =>
ClientParams
-> HostName
-> HostName
-> ByteString
-> [(ByteString, ByteString)]
-> ((Connection, SockAddr) -> m r)
-> m r
connect ClientParams
cs HostName
hn HostName
sn ByteString
res [(ByteString, ByteString)]
hds (Connection, SockAddr) -> m r
act = do
  forall (m :: * -> *) r.
(MonadIO m, MonadMask m) =>
ClientParams
-> HostName -> HostName -> ((Context, SockAddr) -> m r) -> m r
T.connect ClientParams
cs HostName
hn HostName
sn forall a b. (a -> b) -> a -> b
$ \(Context
ctx, SockAddr
saddr) -> do
     forall (m :: * -> *) a b c.
MonadMask m =>
m a -> (a -> m b) -> (a -> m c) -> m c
Ex.bracket (forall (m :: * -> *). MonadIO m => Context -> m Stream
streamFromContext Context
ctx) (forall (m :: * -> *) a. MonadIO m => IO a -> m a
liftIO forall b c a. (b -> c) -> (a -> b) -> a -> c
. Stream -> IO ()
W.close) forall a b. (a -> b) -> a -> b
$ \Stream
stream -> do
        Connection
conn <- forall (m :: * -> *).
MonadIO m =>
Stream
-> HostName
-> HostName
-> ByteString
-> [(ByteString, ByteString)]
-> m Connection
WS.clientConnectionFromStream Stream
stream HostName
hn HostName
sn ByteString
res [(ByteString, ByteString)]
hds
        forall (m :: * -> *) a b.
(MonadMask m, MonadIO m) =>
IO a -> (Async a -> m b) -> m b
withAsync (Connection -> Int -> IO () -> IO ()
W.pingThread Connection
conn Int
30 (forall (f :: * -> *) a. Applicative f => a -> f a
pure ())) forall a b. (a -> b) -> a -> b
$ \Async ()
_ -> 
          (Connection, SockAddr) -> m r
act (Connection
conn, SockAddr
saddr)

-- | Like 'connect', but connects to the destination server through a SOCKS5
-- proxy.
connectOverSOCKS5
  :: (MonadIO m, Ex.MonadMask m)
  => T.HostName -- ^ SOCKS5 proxy server hostname or IP address.
  -> T.ServiceName -- ^ SOCKS5 proxy server service port name or number.
  -> T.ClientParams -- ^ TLS settings.
  -> T.HostName
  -- ^ Destination Secure WebSockets server hostname or IP address. We connect
  -- to this host /through/ the SOCKS5 proxy specified in the previous
  -- arguments.
  --
  -- Note that if hostname resolution on this 'T.HostName' is necessary, it
  -- will happen on the proxy side for security reasons, not locally.
  -> T.ServiceName
  -- ^ Destination Secure WebSockets server port (e.g., @\"443\"@ or @\"www\"@).
  -> B.ByteString
  -- ^ WebSockets resource (e.g., @\"/foo\/qux?bar=wat&baz\"@).
  --
  -- Leading @\'\/\'@ is optional.
  -> [(B.ByteString, B.ByteString)]
  -- ^ Extra HTTP Headers
  -- (e.g., @[(\"Authorization\", \"Basic dXNlcjpwYXNzd29yZA==\")]@).
  -> ((W.Connection, T.SockAddr, T.SockAddr) -> m r)
  -- ^ Computation taking a 'W.Connection' for communicating with the
  -- destination Secure WebSockets server through the SOCKS5 server, the address
  -- of that SOCKS5 server, and the address of the destination WebSockets
  -- server, in that order.
 -> m r
connectOverSOCKS5 :: forall (m :: * -> *) r.
(MonadIO m, MonadMask m) =>
HostName
-> HostName
-> ClientParams
-> HostName
-> HostName
-> ByteString
-> [(ByteString, ByteString)]
-> ((Connection, SockAddr, SockAddr) -> m r)
-> m r
connectOverSOCKS5 HostName
phn HostName
psn ClientParams
tcs HostName
dhn HostName
dsn ByteString
res [(ByteString, ByteString)]
hds (Connection, SockAddr, SockAddr) -> m r
act = do
  forall (m :: * -> *) r.
(MonadIO m, MonadMask m) =>
HostName
-> HostName
-> ClientParams
-> HostName
-> HostName
-> ((Context, SockAddr, SockAddr) -> m r)
-> m r
T.connectOverSOCKS5 HostName
phn HostName
psn ClientParams
tcs HostName
dhn HostName
dsn forall a b. (a -> b) -> a -> b
$ \(Context
ctx, SockAddr
pa, SockAddr
da) -> do
    forall (m :: * -> *) a b c.
MonadMask m =>
m a -> (a -> m b) -> (a -> m c) -> m c
Ex.bracket (forall (m :: * -> *). MonadIO m => Context -> m Stream
streamFromContext Context
ctx) (forall (m :: * -> *) a. MonadIO m => IO a -> m a
liftIO forall b c a. (b -> c) -> (a -> b) -> a -> c
. Stream -> IO ()
W.close) forall a b. (a -> b) -> a -> b
$ \Stream
stream -> do
      Connection
conn <- forall (m :: * -> *).
MonadIO m =>
Stream
-> HostName
-> HostName
-> ByteString
-> [(ByteString, ByteString)]
-> m Connection
WS.clientConnectionFromStream Stream
stream HostName
dhn HostName
dsn ByteString
res [(ByteString, ByteString)]
hds
      forall (m :: * -> *) a b.
(MonadMask m, MonadIO m) =>
IO a -> (Async a -> m b) -> m b
withAsync (Connection -> Int -> IO () -> IO ()
W.pingThread Connection
conn Int
30 (forall (f :: * -> *) a. Applicative f => a -> f a
pure ())) forall a b. (a -> b) -> a -> b
$ \Async ()
_ -> 
        (Connection, SockAddr, SockAddr) -> m r
act (Connection
conn, SockAddr
pa, SockAddr
da)

-- | Obtain a 'W.Stream' implemented using the given TLS 'T.Context'. You can
-- use the
-- [network-simple-tls](https://hackage.haskell.org/package/network-simple-tls)
-- library to get one of those.
streamFromContext :: MonadIO m => T.Context -> m W.Stream
streamFromContext :: forall (m :: * -> *). MonadIO m => Context -> m Stream
streamFromContext Context
ctx = forall (m :: * -> *) a. MonadIO m => IO a -> m a
liftIO forall a b. (a -> b) -> a -> b
$ do
  IO (Maybe ByteString) -> (Maybe ByteString -> IO ()) -> IO Stream
W.makeStream (forall (m :: * -> *). MonadIO m => Context -> m (Maybe ByteString)
T.recv Context
ctx) (forall (t :: * -> *) (f :: * -> *) a b.
(Foldable t, Applicative f) =>
(a -> f b) -> t a -> f ()
traverse_ (forall (m :: * -> *). MonadIO m => Context -> ByteString -> m ()
T.sendLazy Context
ctx))

-- | Like 'Async.async', but generalized to 'Ex.MonadMask' and 'MonadIO'.
withAsync
  :: (Ex.MonadMask m, MonadIO m) 
  => IO a 
  -> (Async.Async a -> m b) 
  -> m b
withAsync :: forall (m :: * -> *) a b.
(MonadMask m, MonadIO m) =>
IO a -> (Async a -> m b) -> m b
withAsync IO a
io = forall (m :: * -> *) a b c.
MonadMask m =>
m a -> (a -> m b) -> (a -> m c) -> m c
Ex.bracket
  (forall (m :: * -> *) a. MonadIO m => IO a -> m a
liftIO forall a b. (a -> b) -> a -> b
$ forall a. ((forall b. IO b -> IO b) -> IO a) -> IO (Async a)
Async.asyncWithUnmask (\forall b. IO b -> IO b
u -> forall b. IO b -> IO b
u IO a
io))
  (forall (m :: * -> *) a. MonadIO m => IO a -> m a
liftIO forall b c a. (b -> c) -> (a -> b) -> a -> c
. forall a. Async a -> IO ()
Async.uninterruptibleCancel)