|
1 | 1 | {-# LANGUAGE OverloadedStrings #-}
|
2 | 2 |
|
3 |
| -import Network.HTTP.Proxy (ProxySettings (..), Request (..)) |
| 3 | +import qualified Data.ByteString.Char8 as BS |
| 4 | + |
| 5 | +import Network.HTTP.Proxy (Settings (..), Request (..)) |
4 | 6 | import qualified Network.HTTP.Proxy as Proxy
|
| 7 | +import Network.URI (URI (..), URIAuth (..), parseURI) |
| 8 | +import Network.Wai.Internal (Response) |
5 | 9 |
|
6 | 10 | main :: IO ()
|
7 | 11 | main =
|
8 | 12 | Proxy.runProxySettings $
|
9 | 13 | Proxy.defaultProxySettings
|
10 | 14 | { proxyPort = 31081
|
11 |
| - , proxyHttpRequestModifier = Just secureGoogle |
| 15 | + , proxyHttpRequestModifier = secureGoogle |
12 | 16 | }
|
13 | 17 |
|
14 | 18 | -- Modifying the request like this is only possible for unencrypted HTTP connections
|
15 | 19 | -- by my be useful for eg redirecting HTTP to HTTPS.
|
16 | 20 | -- HTTPS cnnections cannot be modified like this because the for HTTPS connections
|
17 | 21 | -- even the request itself is encrypted.
|
18 | 22 |
|
19 |
| -secureGoogle :: Request -> IO Request |
20 |
| -secureGoogle req |
21 |
| - | "www.google.com" `BS.isInfixOf` requestPath req |
22 |
| - && not ("https" `BS.isprefixOf` requestPath req = |
23 |
| - pure $ req |
24 |
| - { requestPath = "encrypted.google.com" |
25 |
| - } |
| 23 | +secureGoogle :: Request -> IO (Either Response Request) |
| 24 | +secureGoogle req = do |
| 25 | + case parseURI $ BS.unpack (requestPath req) of |
| 26 | + Nothing -> do |
| 27 | + putStrLn $ "Not able to parse: " ++ show (requestPath req) |
| 28 | + -- Not much to be done other than just return the Request unmodified. |
| 29 | + pure $ Right req |
| 30 | + Just uri -> |
| 31 | + pure . Right $ req { requestPath = BS.pack $ show (modifyURI uri) } |
| 32 | + |
| 33 | +modifyURI :: URI -> URI |
| 34 | +modifyURI uri = |
| 35 | + uri |
| 36 | + { uriAuthority = modifyUriAthority <$> uriAuthority uri |
| 37 | + , uriScheme = modifyUriScheme (uriScheme uri) |
| 38 | + } |
| 39 | + where |
| 40 | + modifyUriAthority :: URIAuth -> URIAuth |
| 41 | + modifyUriAthority auth = |
| 42 | + if uriRegName auth == "www.google.com" |
| 43 | + then auth { uriRegName = "encrypted.google.com", uriPort = "" } |
| 44 | + else auth |
26 | 45 |
|
27 |
| - | otherwise = pure req |
| 46 | + modifyUriScheme :: String -> String |
| 47 | + modifyUriScheme scheme = |
| 48 | + if scheme =="http:" then "https:" else scheme |
0 commit comments