@@ -4,57 +4,71 @@
4{-# LANGUAGE RecordWildCards #-}
4{-# LANGUAGE RecordWildCards #-}
5{-# LANGUAGE DeriveDataTypeable #-}
5{-# LANGUAGE DeriveDataTypeable #-}
6{-# LANGUAGE PatternGuards #-}
6{-# LANGUAGE PatternGuards #-}
9−-- | HTTP over SSL/TLS support for Warp via the TLS package.
8+-- | HTTP over TLS support for Warp via the TLS package.
10+-- If HTTP\/2 is negotiated by ALPN, HTTP\/2 over TLS is used.
11+-- Otherwise HTTP\/1.1 over TLS is used.
13+-- Support for SSL is now obsoleted.
11module Network.Wai.Handler.WarpTLS (
15module Network.Wai.Handler.WarpTLS (
12 -- * Settings
16 -- * Settings
13 TLSSettings
17 TLSSettings
19+ -- * Smart constructors
23+ , tlsSettingsChainMemory
14 , certFile
25 , certFile
17 , tlsLogging
27 , tlsLogging
18 , tlsAllowedVersions
28 , tlsAllowedVersions
19 , tlsCiphers
29 , tlsCiphers
20 , tlsWantClientCert
30 , tlsWantClientCert
21 , tlsServerHooks
31 , tlsServerHooks
22− , defaultTlsSettings
32+ , tlsServerDHEParams
23− , tlsSettings
33+ , tlsSessionManagerConfig
24− , tlsSettingsMemory
34+ , onInsecure
26− , tlsSettingsChainMemory
27 , OnInsecure (..)
35 , OnInsecure (..)
28 -- * Runner
36 -- * Runner
30 , runTLSSocket
38 , runTLSSocket
31 -- * Exception
39 -- * Exception
32 , WarpTLSException (..)
40 , WarpTLSException (..)
35−#if __GLASGOW_HASKELL__ < 709
36−import Control.Applicative ((<$>))
45+import Control.Applicative ((<|>))
38−import Control.Exception (Exception, throwIO, bracket, finally, handle, fromException, try, IOException, onException)
46+import Control.Exception (Exception, throwIO, bracket, finally, handle, fromException, try, IOException, onException, SomeException(..), handleJust)
47+import qualified Control.Exception as E
39−import Control.Monad (void)
48+import Control.Monad (void, guard)
40−import qualified Crypto.Random.AESCtr
41−import qualified Data.ByteString as B
42import qualified Data.ByteString as S
49import qualified Data.ByteString as S
43import qualified Data.ByteString.Lazy as L
50import qualified Data.ByteString.Lazy as L
44import Data.Default.Class (def)
51import Data.Default.Class (def)
45import qualified Data.IORef as I
52import qualified Data.IORef as I
46import Data.Streaming.Network (bindPortTCP, safeRecv)
53import Data.Streaming.Network (bindPortTCP, safeRecv)
47import Data.Typeable (Typeable)
54import Data.Typeable (Typeable)
48−import Network.Socket (Socket, sClose, withSocketsDo, SockAddr, accept)
55+import Network.Socket (Socket, close, withSocketsDo, SockAddr, accept)
56+#if MIN_VERSION_network(3,1,1)
57+import Network.Socket (gracefulClose)
49import Network.Socket.ByteString (sendAll)
59import Network.Socket.ByteString (sendAll)
50import qualified Network.TLS as TLS
60import qualified Network.TLS as TLS
61+import qualified Crypto.PubKey.DH as DH
51import qualified Network.TLS.Extra as TLSExtra
62import qualified Network.TLS.Extra as TLSExtra
63+import qualified Network.TLS.SessionManager as SM
52import Network.Wai (Application)
64import Network.Wai (Application)
53import Network.Wai.Handler.Warp
65import Network.Wai.Handler.Warp
66+import Network.Wai.Handler.Warp.Internal
54import System.IO.Error (isEOFError)
67import System.IO.Error (isEOFError)
56----------------------------------------------------------------
69----------------------------------------------------------------
71+-- | Settings for WarpTLS.
58data TLSSettings = TLSSettings {
72data TLSSettings = TLSSettings {
59 certFile :: FilePath
73 certFile :: FilePath
60 -- ^ File containing the certificate.
74 -- ^ File containing the certificate.
@@ -66,8 +80,10 @@ data TLSSettings = TLSSettings {
66 , chainCertsMemory :: [S.ByteString]
80 , chainCertsMemory :: [S.ByteString]
67 , keyMemory :: Maybe S.ByteString
81 , keyMemory :: Maybe S.ByteString
68 , onInsecure :: OnInsecure
82 , onInsecure :: OnInsecure
69− -- ^ Do we allow insecure connections with this server as well? Default
83+ -- ^ Do we allow insecure connections with this server as well?
70− -- is a simple text response stating that a secure connection is required.
84+ --
85+ -- >>> onInsecure defaultTlsSettings
86+ -- DenyInsecure "This server only accepts secure HTTPS connections."
72 -- Since 1.4.0
88 -- Since 1.4.0
73 , tlsLogging :: TLS.Logging
89 , tlsLogging :: TLS.Logging
@@ -77,23 +93,44 @@ data TLSSettings = TLSSettings {
78 -- Since 1.4.0
94 -- Since 1.4.0
79 , tlsAllowedVersions :: [TLS.Version]
95 , tlsAllowedVersions :: [TLS.Version]
96+#if MIN_VERSION_tls(1,5,0)
97+ -- ^ The TLS versions this server accepts.
99+ -- >>> tlsAllowedVersions defaultTlsSettings
100+ -- [TLS13,TLS12,TLS11,TLS10]
80 -- ^ The TLS versions this server accepts.
104 -- ^ The TLS versions this server accepts.
82− -- Default: '[TLS.TLS10,TLS.TLS11,TLS.TLS12]'.
106+ -- >>> tlsAllowedVersions defaultTlsSettings
107+ -- [TLS12,TLS11,TLS10]
84 -- Since 1.4.2
109 -- Since 1.4.2
85 , tlsCiphers :: [TLS.Cipher]
111 , tlsCiphers :: [TLS.Cipher]
112+#if MIN_VERSION_tls(1,5,0)
86 -- ^ The TLS ciphers this server accepts.
113 -- ^ The TLS ciphers this server accepts.
88− -- Default: '[TLSExtra.cipher_AES128_SHA1, TLSExtra.cipher_AES256_SHA1, TLSEtra.cipher_RC4_128_MD5, TLSExtra.cipher_RC4_128_SHA1]'
115+ -- >>> tlsCiphers defaultTlsSettings
116+ -- [ECDHE-ECDSA-AES256GCM-SHA384,ECDHE-ECDSA-AES128GCM-SHA256,ECDHE-RSA-AES256GCM-SHA384,ECDHE-RSA-AES128GCM-SHA256,DHE-RSA-AES256GCM-SHA384,DHE-RSA-AES128GCM-SHA256,ECDHE-ECDSA-AES256CBC-SHA384,ECDHE-RSA-AES256CBC-SHA384,DHE-RSA-AES256-SHA256,ECDHE-ECDSA-AES256CBC-SHA,ECDHE-RSA-AES256CBC-SHA,DHE-RSA-AES256-SHA1,RSA-AES256GCM-SHA384,RSA-AES256-SHA256,RSA-AES256-SHA1,AES128GCM-SHA256,AES256GCM-SHA384]
90 -- Since 1.4.2
118 -- Since 1.4.2
120+ -- ^ The TLS ciphers this server accepts.
122+ -- >>> tlsCiphers defaultTlsSettings
123+ -- [ECDHE-ECDSA-AES256GCM-SHA384,ECDHE-ECDSA-AES128GCM-SHA256,ECDHE-RSA-AES256GCM-SHA384,ECDHE-RSA-AES128GCM-SHA256,DHE-RSA-AES256GCM-SHA384,DHE-RSA-AES128GCM-SHA256,ECDHE-ECDSA-AES256CBC-SHA384,ECDHE-RSA-AES256CBC-SHA384,DHE-RSA-AES256-SHA256,ECDHE-ECDSA-AES256CBC-SHA,ECDHE-RSA-AES256CBC-SHA,DHE-RSA-AES256-SHA1,RSA-AES256GCM-SHA384,RSA-AES256-SHA256,RSA-AES256-SHA1]
91 , tlsWantClientCert :: Bool
127 , tlsWantClientCert :: Bool
92 -- ^ Whether or not to demand a certificate from the client. If this
128 -- ^ Whether or not to demand a certificate from the client. If this
93 -- is set to True, you must handle received certificates in a server hook
129 -- is set to True, you must handle received certificates in a server hook
94 -- or all connections will fail.
130 -- or all connections will fail.
132+ -- >>> tlsWantClientCert defaultTlsSettings
96− -- Default: False
133+ -- False
98 -- Since 3.0.2
135 -- Since 3.0.2
99 , tlsServerHooks :: TLS.ServerHooks
136 , tlsServerHooks :: TLS.ServerHooks
@@ -104,9 +141,25 @@ data TLSSettings = TLSSettings {
104 -- Default: def
141 -- Default: def
106 -- Since 3.0.2
143 -- Since 3.0.2
144+ , tlsServerDHEParams :: Maybe DH.Params
145+ -- ^ Configuration for ServerDHEParams
146+ -- more function lives in `cryptonite` package
151+ , tlsSessionManagerConfig :: Maybe SM.Config
152+ -- ^ Configuration for in-memory TLS session manager.
153+ -- If Nothing, 'TLS.noSessionManager' is used.
154+ -- Otherwise, an in-memory TLS session manager is created
155+ -- according to 'Config'.
109−-- | Default 'TLSSettings'. Use this to create 'TLSSettings' with the field record name.
162+-- | Default 'TLSSettings'. Use this to create 'TLSSettings' with the field record name (aka accessors).
110defaultTlsSettings :: TLSSettings
163defaultTlsSettings :: TLSSettings
111defaultTlsSettings = TLSSettings {
164defaultTlsSettings = TLSSettings {
112 certFile = "certificate.pem"
165 certFile = "certificate.pem"
@@ -117,39 +170,32 @@ defaultTlsSettings = TLSSettings {
117 , keyMemory = Nothing
170 , keyMemory = Nothing
118 , onInsecure = DenyInsecure "This server only accepts secure HTTPS connections."
171 , onInsecure = DenyInsecure "This server only accepts secure HTTPS connections."
119 , tlsLogging = def
172 , tlsLogging = def
173+#if MIN_VERSION_tls(1,5,0)
120− , tlsAllowedVersions = [TLS.TLS10,TLS.TLS11,TLS.TLS12]
174+ , tlsAllowedVersions = [TLS.TLS13,TLS.TLS12,TLS.TLS11,TLS.TLS10]
176+ , tlsAllowedVersions = [TLS.TLS12,TLS.TLS11,TLS.TLS10]
121 , tlsCiphers = ciphers
178 , tlsCiphers = ciphers
122 , tlsWantClientCert = False
179 , tlsWantClientCert = False
123 , tlsServerHooks = def
180 , tlsServerHooks = def
181+ , tlsServerDHEParams = Nothing
182+ , tlsSessionManagerConfig = Nothing
126-- taken from stunnel example in tls-extra
185-- taken from stunnel example in tls-extra
127ciphers :: [TLS.Cipher]
186ciphers :: [TLS.Cipher]
128−ciphers =
187+ciphers = TLSExtra.ciphersuite_strong
129− [ TLSExtra.cipher_ECDHE_RSA_AES128GCM_SHA256
130− , TLSExtra.cipher_DHE_RSA_AES128GCM_SHA256
131− , TLSExtra.cipher_DHE_RSA_AES256_SHA256
132− , TLSExtra.cipher_DHE_RSA_AES128_SHA256
133− , TLSExtra.cipher_DHE_RSA_AES256_SHA1
134− , TLSExtra.cipher_DHE_RSA_AES128_SHA1
135− , TLSExtra.cipher_DHE_DSS_AES128_SHA1
136− , TLSExtra.cipher_DHE_DSS_AES256_SHA1
137− , TLSExtra.cipher_DHE_DSS_RC4_SHA1
138− , TLSExtra.cipher_AES128_SHA1
139− , TLSExtra.cipher_AES256_SHA1
140− , TLSExtra.cipher_RC4_128_MD5
141− , TLSExtra.cipher_RC4_128_SHA1
144----------------------------------------------------------------
189----------------------------------------------------------------
146-- | An action when a plain HTTP comes to HTTP over TLS/SSL port.
191-- | An action when a plain HTTP comes to HTTP over TLS/SSL port.
147data OnInsecure = DenyInsecure L.ByteString
192data OnInsecure = DenyInsecure L.ByteString
148 | AllowInsecure
193 | AllowInsecure
150----------------------------------------------------------------
196----------------------------------------------------------------
152−-- | A smart constructor for 'TLSSettings'.
198+-- | A smart constructor for 'TLSSettings' based on 'defaultTlsSettings'.
153tlsSettings :: FilePath -- ^ Certificate file
199tlsSettings :: FilePath -- ^ Certificate file
154 -> FilePath -- ^ Key file
200 -> FilePath -- ^ Key file
155 -> TLSSettings
201 -> TLSSettings
@@ -159,7 +205,7 @@ tlsSettings cert key = defaultTlsSettings {
161-- | A smart constructor for 'TLSSettings' that allows specifying
207-- | A smart constructor for 'TLSSettings' that allows specifying
162−-- chain certificates.
208+-- chain certificates based on 'defaultTlsSettings'.
164-- Since 3.0.3
210-- Since 3.0.3
165tlsSettingsChain
211tlsSettingsChain
@@ -174,7 +220,7 @@ tlsSettingsChain cert chainCerts key = defaultTlsSettings {
176-- | A smart constructor for 'TLSSettings', but uses in-memory representations
222-- | A smart constructor for 'TLSSettings', but uses in-memory representations
177−-- of the certificate and key
223+-- of the certificate and key based on 'defaultTlsSettings'.
179-- Since 3.0.1
225-- Since 3.0.1
180tlsSettingsMemory
226tlsSettingsMemory
@@ -187,7 +233,7 @@ tlsSettingsMemory cert key = defaultTlsSettings
189-- | A smart constructor for 'TLSSettings', but uses in-memory representations
235-- | A smart constructor for 'TLSSettings', but uses in-memory representations
190−-- of the certificate and key
236+-- of the certificate and key based on 'defaultTlsSettings'.
192-- Since 3.0.3
238-- Since 3.0.3
193tlsSettingsChainMemory
239tlsSettingsChainMemory
@@ -203,13 +249,12 @@ tlsSettingsChainMemory cert chainCerts key = defaultTlsSettings
204----------------------------------------------------------------
250----------------------------------------------------------------
207-- | Running 'Application' with 'TLSSettings' and 'Settings'.
252-- | Running 'Application' with 'TLSSettings' and 'Settings'.
208runTLS :: TLSSettings -> Settings -> Application -> IO ()
253runTLS :: TLSSettings -> Settings -> Application -> IO ()
209runTLS tset set app = withSocketsDo $
254runTLS tset set app = withSocketsDo $
211 (bindPortTCP (getPort set) (getHost set))
256 (bindPortTCP (getPort set) (getHost set))
213 (\sock -> runTLSSocket tset set sock app)
258 (\sock -> runTLSSocket tset set sock app)
215----------------------------------------------------------------
260----------------------------------------------------------------
@@ -227,93 +272,186 @@ runTLSSocket tlsset@TLSSettings{..} set sock app = do
227 key <- maybe (S.readFile keyFile) return mkey
272 key <- maybe (S.readFile keyFile) return mkey
228 either error return $
273 either error return $
229 TLS.credentialLoadX509ChainFromMemory cert chainCertsMemory key
274 TLS.credentialLoadX509ChainFromMemory cert chainCertsMemory key
275+ mgr <- case tlsSessionManagerConfig of
276+ Nothing -> return TLS.noSessionManager
277+ Just config -> SM.newSessionManager config
230− runTLSSocket' tlsset set credential sock app
278+ runTLSSocket' tlsset set credential mgr sock app
232−runTLSSocket' :: TLSSettings -> Settings -> TLS.Credential -> Socket -> Application -> IO ()
280+runTLSSocket' :: TLSSettings -> Settings -> TLS.Credential -> TLS.SessionManager -> Socket -> Application -> IO ()
233−runTLSSocket' tlsset@TLSSettings{..} set credential sock app =
281+runTLSSocket' tlsset@TLSSettings{..} set credential mgr sock app =
234 runSettingsConnectionMakerSecure set get app
282 runSettingsConnectionMakerSecure set get app
236− get = getter tlsset sock params
284+ get = getter tlsset set sock params
237− params = def {
285+ params = def { -- TLS.ServerParams
238 TLS.serverWantClientCert = tlsWantClientCert
286 TLS.serverWantClientCert = tlsWantClientCert
239− , TLS.serverSupported = def {
287+ , TLS.serverCACertificates = []
240− TLS.supportedVersions = tlsAllowedVersions
288+ , TLS.serverDHEParams = tlsServerDHEParams
241− , TLS.supportedCiphers = tlsCiphers
243− , TLS.serverShared = def {
244− TLS.sharedCredentials = TLS.Credentials [credential]
246− , TLS.serverHooks = tlsServerHooks
289+ , TLS.serverHooks = hooks
290+ , TLS.serverShared = shared
291+ , TLS.serverSupported = supported
292+#if MIN_VERSION_tls(1,5,0)
293+ , TLS.serverEarlyDataSize = 2018
296+ -- Adding alpn to user's tlsServerHooks.
297+ hooks = tlsServerHooks {
298+ TLS.onALPNClientSuggest = TLS.onALPNClientSuggest tlsServerHooks <|>
299+ (if settingsHTTP2Enabled set then Just alpn else Nothing)
302+ TLS.sharedCredentials = TLS.Credentials [credential]
303+ , TLS.sharedSessionManager = mgr
305+ supported = def { -- TLS.Supported
306+ TLS.supportedVersions = tlsAllowedVersions
307+ , TLS.supportedCiphers = tlsCiphers
308+ , TLS.supportedCompressions = [TLS.nullCompression]
309+ , TLS.supportedSecureRenegotiation = True
310+ , TLS.supportedClientInitiatedRenegotiation = False
311+ , TLS.supportedSession = True
312+ , TLS.supportedFallbackScsv = True
313+#if MIN_VERSION_tls(1,5,0)
314+ , TLS.supportedGroups = [TLS.X25519,TLS.P256,TLS.P384]
318+alpn :: [S.ByteString] -> IO S.ByteString
320+ | "h2" `elem` xs = return "h2"
321+ | otherwise = return "http/1.1"
249----------------------------------------------------------------
323----------------------------------------------------------------
251−getter :: TLS.TLSParams params => TLSSettings -> Socket -> params -> IO (IO (Connection, Transport), SockAddr)
325+getter :: TLS.TLSParams params => TLSSettings -> Settings -> Socket -> params -> IO (IO (Connection, Transport), SockAddr)
252−getter tlsset@TLSSettings{..} sock params = do
326+getter tlsset@TLSSettings{..} set sock params = do
328+ (s, sa) <- windowsThreadBlockHack $ accept sock
253 (s, sa) <- accept sock
330 (s, sa) <- accept sock
332+ setSocketCloseOnExec s
254− return (mkConn tlsset s params, sa)
333+ return (mkConn tlsset set s params, sa)
256−mkConn :: TLS.TLSParams params => TLSSettings -> Socket -> params -> IO (Connection, Transport)
335+mkConn :: TLS.TLSParams params => TLSSettings -> Settings -> Socket -> params -> IO (Connection, Transport)
257−mkConn tlsset s params = do
336+mkConn tlsset set s params = switch `onException` close s
258− firstBS <- safeRecv s 4096
339+ firstBS <- safeRecv s 4096
259− cachedRef <- I.newIORef firstBS
260− (if not (B.null firstBS) && B.head firstBS == 0x16 then
340+ if not (S.null firstBS) && S.head firstBS == 0x16 then
261− httpOverTls tlsset s cachedRef params
341+ httpOverTls tlsset set s firstBS params
263− plainHTTP tlsset s cachedRef) `onException` sClose s
343+ plainHTTP tlsset set s firstBS
265----------------------------------------------------------------
345----------------------------------------------------------------
267−httpOverTls :: TLS.TLSParams params => TLSSettings -> Socket -> I.IORef B.ByteString -> params -> IO (Connection, Transport)
347+httpOverTls :: TLS.TLSParams params => TLSSettings -> Settings -> Socket -> S.ByteString -> params -> IO (Connection, Transport)
268−httpOverTls TLSSettings{..} s cachedRef params = do
348+httpOverTls TLSSettings{..} _set s bs0 params = do
269−#if MIN_VERSION_tls(1,3,0)
349+ recvN <- makePlainReceiveN s bs0
270− ctx <- TLS.contextNew backend params
272− gen <- Crypto.Random.AESCtr.makeSystem
273− ctx <- TLS.contextNew backend params gen
350+ ctx <- TLS.contextNew (backend recvN) params
275 TLS.contextHookSetLogging ctx tlsLogging
351 TLS.contextHookSetLogging ctx tlsLogging
276 TLS.handshake ctx
352 TLS.handshake ctx
353+ h2 <- (== Just "h2") <$> TLS.getNegotiatedProtocol ctx
354+ isH2 <- I.newIORef h2
277 writeBuf <- allocateBuffer bufferSize
355 writeBuf <- allocateBuffer bufferSize
356+ -- Creating a cache for leftover input data.
357+ ref <- I.newIORef ""
278 tls <- getTLSinfo ctx
358 tls <- getTLSinfo ctx
279− return (conn ctx writeBuf, tls)
359+ return (conn ctx writeBuf ref isH2, tls)
281− backend = TLS.Backend {
361+ backend recvN = TLS.Backend {
282 TLS.backendFlush = return ()
362 TLS.backendFlush = return ()
283− , TLS.backendClose = sClose s
363+#if MIN_VERSION_network(3,1,1)
364+ , TLS.backendClose = gracefulClose s 5000 `E.catch` \(SomeException _) -> return ()
366+ , TLS.backendClose = close s
284− , TLS.backendSend = sendAll s
368+ , TLS.backendSend = sendAll' s
285− , TLS.backendRecv = recvTLS cachedRef s
369+ , TLS.backendRecv = recvN
371+ sendAll' sock bs = sendAll sock bs `E.catch` \(SomeException _) ->
372+ throwIO ConnectionClosedByPeer
287− conn ctx writeBuf = Connection {
373+ conn ctx writeBuf ref isH2 = Connection {
288 connSendMany = TLS.sendData ctx . L.fromChunks
374 connSendMany = TLS.sendData ctx . L.fromChunks
289 , connSendAll = sendall
375 , connSendAll = sendall
290 , connSendFile = sendfile
376 , connSendFile = sendfile
291− , connClose = close
377+ , connClose = close'
378+ , connFree = freeBuffer writeBuf
292− , connRecv = recv
379+ , connRecv = recv ref
380+ , connRecvBuf = recvBuf ref
293 , connWriteBuffer = writeBuf
381 , connWriteBuffer = writeBuf
294 , connBufferSize = bufferSize
382 , connBufferSize = bufferSize
297 sendall = TLS.sendData ctx . L.fromChunks . return
386 sendall = TLS.sendData ctx . L.fromChunks . return
298 sendfile fid offset len hook headers =
387 sendfile fid offset len hook headers =
299 readSendFile writeBuf bufferSize sendall fid offset len hook headers
388 readSendFile writeBuf bufferSize sendall fid offset len hook headers
301− close = freeBuffer writeBuf `finally`
302− void (tryIO $ TLS.bye ctx) `finally`
390+ close' = void (tryIO sendBye) `finally`
303− TLS.contextClose ctx
391+ TLS.contextClose ctx
394+ -- It's fine if the connection was closed by the other side before
395+ -- receiving close_notify, see RFC 5246 section 7.2.1.
397+ (\e -> guard (e == ConnectionClosedByPeer) >> return e)
401+ -- TLS version of recv with a cache for leftover input data.
402+ -- The cache is shared with recvBuf.
404+ cached <- I.readIORef cref
405+ if cached /= "" then do
406+ I.writeIORef cref ""
411+ -- TLS version of recv (decrypting) without a cache.
305− recv = handle onEOF go
412+ recv' = handle onEOF go
308− | Just TLS.Error_EOF <- fromException e = return B.empty
415+ | Just TLS.Error_EOF <- fromException e = return S.empty
309− | Just ioe <- fromException e, isEOFError ioe = return B.empty | otherwise = throwIO e
416+ | Just ioe <- fromException e, isEOFError ioe = return S.empty | otherwise = throwIO e
311 x <- TLS.recvData ctx
418 x <- TLS.recvData ctx
312− if B.null x then
419+ if S.null x then
424+ -- TLS version of recvBuf with a cache for leftover input data.
425+ recvBuf cref buf siz = do
426+ cached <- I.readIORef cref
427+ (ret, leftover) <- fill cached buf siz recv'
428+ I.writeIORef cref leftover
431+fill :: S.ByteString -> Buffer -> BufSize -> Recv -> IO (Bool,S.ByteString)
432+fill bs0 buf0 siz0 recv
434+ let (bs, leftover) = S.splitAt siz0 bs0
436+ return (True, leftover)
438+ buf <- copy buf0 bs0
439+ loop buf (siz0 - len0)
442+ loop _ 0 = return (True, "")
445+ let len = S.length bs
446+ if len == 0 then return (False, "")
447+ else if (len <= siz) then do
449+ loop buf' (siz - len)
451+ let (bs1,bs2) = S.splitAt siz bs
317getTLSinfo :: TLS.Context -> IO Transport
455getTLSinfo :: TLS.Context -> IO Transport
318getTLSinfo ctx = do
456getTLSinfo ctx = do
319 proto <- TLS.getNegotiatedProtocol ctx
457 proto <- TLS.getNegotiatedProtocol ctx
@@ -327,11 +465,16 @@ getTLSinfo ctx = do
327 TLS.TLS10 -> (3,1)
465 TLS.TLS10 -> (3,1)
328 TLS.TLS11 -> (3,2)
466 TLS.TLS11 -> (3,2)
329 TLS.TLS12 -> (3,3)
467 TLS.TLS12 -> (3,3)
468+#if MIN_VERSION_tls(1,5,0)
471+ clientCert <- TLS.getClientCertificateChain ctx
330 return TLS {
472 return TLS {
331 tlsMajorVersion = major
473 tlsMajorVersion = major
332 , tlsMinorVersion = minor
474 , tlsMinorVersion = minor
333 , tlsNegotiatedProtocol = proto
475 , tlsNegotiatedProtocol = proto
334 , tlsChiperID = TLS.cipherID infoCipher
476 , tlsChiperID = TLS.cipherID infoCipher
477+ , tlsClientCertificate = clientCert
337tryIO :: IO a -> IO (Either IOException a)
480tryIO :: IO a -> IO (Either IOException a)
@@ -339,52 +482,46 @@ tryIO = try
340----------------------------------------------------------------
483----------------------------------------------------------------
342−plainHTTP :: TLSSettings -> Socket -> I.IORef B.ByteString -> IO (Connection, Transport)
485+plainHTTP :: TLSSettings -> Settings -> Socket -> S.ByteString -> IO (Connection, Transport)
343−plainHTTP TLSSettings{..} s cachedRef = case onInsecure of
486+plainHTTP TLSSettings{..} set s bs0 = case onInsecure of
344 AllowInsecure -> do
487 AllowInsecure -> do
345− conn' <- socketConnection s
488+ conn' <- socketConnection set s
489+ cachedRef <- I.newIORef bs0
346 let conn'' = conn'
490 let conn'' = conn'
347 { connRecv = recvPlain cachedRef (connRecv conn')
491 { connRecv = recvPlain cachedRef (connRecv conn')
349 return (conn'', TCP)
493 return (conn'', TCP)
350 DenyInsecure lbs -> do
494 DenyInsecure lbs -> do
495+ -- Listening port 443 but TLS records do not arrive.
496+ -- We want to let the browser know that TLS is required.
498+ -- http://tools.ietf.org/html/rfc2817#section-4.2
499+ -- https://tools.ietf.org/html/rfc7231#section-6.5.15
500+ -- FIXME: should we distinguish HTTP/1.1 and HTTP/2?
501+ -- In the case of HTTP/2, should we send
502+ -- GOAWAY + INADEQUATE_SECURITY?
503+ -- FIXME: Content-Length:
504+ -- FIXME: TLS/<version>
505+ sendAll s "HTTP/1.1 426 Upgrade Required\
506+ \r\nUpgrade: TLS/1.0, HTTP/1.1\
507+ \r\nConnection: Upgrade\
351− sendAll s "HTTP/1.1 200 OK\r\nContent-Type: text/plain\r\n\r\n"
508+ \r\nContent-Type: text/plain\r\n\r\n"
352 mapM_ (sendAll s) $ L.toChunks lbs
509 mapM_ (sendAll s) $ L.toChunks lbs
353− sClose s
510+ close s
354 throwIO InsecureConnectionDenied
511 throwIO InsecureConnectionDenied
356----------------------------------------------------------------
513----------------------------------------------------------------
358−recvTLS :: I.IORef B.ByteString -> Socket -> Int -> IO B.ByteString
359−recvTLS cachedRef s size = do
360− cached <- I.readIORef cachedRef
363− loop bs | B.length bs >= size = do
364− let (x, y) = B.splitAt size bs
365− I.writeIORef cachedRef y
368− bs2 <- safeRecv s 4096
369− if B.null bs2 then do
370− -- FIXME does this deserve an exception being thrown?
371− I.writeIORef cachedRef B.empty
374− loop $ B.append bs1 bs2
376−----------------------------------------------------------------
378-- | Modify the given receive function to first check the given @IORef@ for a
515-- | Modify the given receive function to first check the given @IORef@ for a
379-- chunk of data. If present, takes the chunk of data from the @IORef@ and
516-- chunk of data. If present, takes the chunk of data from the @IORef@ and
380-- empties out the @IORef@. Otherwise, calls the supplied receive function.
517-- empties out the @IORef@. Otherwise, calls the supplied receive function.
381−recvPlain :: I.IORef B.ByteString -> IO B.ByteString -> IO B.ByteString
518+recvPlain :: I.IORef S.ByteString -> IO S.ByteString -> IO S.ByteString
382recvPlain ref fallback = do
519recvPlain ref fallback = do
383 bs <- I.readIORef ref
520 bs <- I.readIORef ref
384− if B.null bs
521+ if S.null bs
385 then fallback
522 then fallback
387− I.writeIORef ref B.empty
524+ I.writeIORef ref S.empty
388 return bs
525 return bs
390----------------------------------------------------------------
527----------------------------------------------------------------