| 1 |
{-# LANGUAGE CPP #-} |
| 2 |
|
| 3 |
module Lambdabot.Util.Network ( |
| 4 |
connectTo', |
| 5 |
) where |
| 6 |
|
| 7 |
import Network.Socket |
| 8 |
import Network.BSD |
| 9 |
import System.IO |
| 10 |
import Control.Exception |
| 11 |
|
| 12 |
-- |This is essentially a reimplementation of the former Network.connectTo |
| 13 |
-- function, except that we don't do the service name lookup. |
| 14 |
|
| 15 |
-- Code originally from the network package. |
| 16 |
connectTo' :: HostName -> PortNumber -> IO Handle |
| 17 |
connectTo' host port = do |
| 18 |
proto <- getProtocolNumber "tcp" |
| 19 |
let hints = defaultHints { addrFlags = [AI_ADDRCONFIG] |
| 20 |
, addrProtocol = proto |
| 21 |
, addrSocketType = Stream } |
| 22 |
addrs <- getAddrInfo (Just hints) (Just host) (Just (show port)) |
| 23 |
firstSuccessful $ map tryToConnect addrs |
| 24 |
where |
| 25 |
tryToConnect addr = |
| 26 |
bracketOnError |
| 27 |
(socket (addrFamily addr) (addrSocketType addr) (addrProtocol addr)) |
| 28 |
(close) -- only done if there's an error |
| 29 |
(\sock -> do |
| 30 |
connect sock (addrAddress addr) |
| 31 |
socketToHandle sock ReadWriteMode |
| 32 |
) |
| 33 |
firstSuccessful = go [] |
| 34 |
where |
| 35 |
go :: [IOException] -> [IO a] -> IO a |
| 36 |
go [] [] = ioError . userError $ "host name `" ++ show host ++ |
| 37 |
"` could not be resolved" |
| 38 |
go l@(_:_) [] = ioError . userError $ "could not connect to host `" ++ |
| 39 |
show host |
| 40 |
go acc (act:followingActs) = do |
| 41 |
er <- try act |
| 42 |
case er of |
| 43 |
Left err -> go (err:acc) followingActs |
| 44 |
Right r -> return r |