2012-10-25 21:56:03 +00:00
|
|
|
{- SRV record lookup
|
|
|
|
-
|
2015-01-21 16:50:09 +00:00
|
|
|
- Copyright 2012 Joey Hess <id@joeyh.name>
|
2012-10-25 21:56:03 +00:00
|
|
|
-
|
2014-05-10 14:01:27 +00:00
|
|
|
- License: BSD-2-clause
|
2012-10-25 21:56:03 +00:00
|
|
|
-}
|
|
|
|
|
|
|
|
module Utility.SRV (
|
2012-10-26 17:03:08 +00:00
|
|
|
mkSRVTcp,
|
|
|
|
mkSRV,
|
2012-10-25 21:56:03 +00:00
|
|
|
lookupSRV,
|
2013-05-27 18:36:20 +00:00
|
|
|
HostPort,
|
2012-10-25 21:56:03 +00:00
|
|
|
) where
|
|
|
|
|
|
|
|
import Data.Function
|
|
|
|
import Data.List
|
2016-01-26 12:48:14 +00:00
|
|
|
import Network
|
2012-10-28 23:14:30 +00:00
|
|
|
import qualified Network.DNS.Lookup as DNS
|
|
|
|
import Network.DNS.Resolver
|
|
|
|
import qualified Data.ByteString.UTF8 as B8
|
2012-10-25 21:56:03 +00:00
|
|
|
|
2012-10-26 17:03:08 +00:00
|
|
|
newtype SRV = SRV String
|
2012-10-26 18:17:09 +00:00
|
|
|
deriving (Show, Eq)
|
2012-10-26 17:03:08 +00:00
|
|
|
|
2012-10-25 21:56:03 +00:00
|
|
|
type HostPort = (HostName, PortID)
|
|
|
|
|
2012-10-28 23:14:30 +00:00
|
|
|
type PriorityWeight = (Int, Int) -- sort by priority first, then weight
|
|
|
|
|
2012-10-26 17:03:08 +00:00
|
|
|
mkSRV :: String -> String -> HostName -> SRV
|
|
|
|
mkSRV transport protocol host = SRV $ concat
|
2012-10-26 18:17:09 +00:00
|
|
|
["_", protocol, "._", transport, ".", host]
|
2012-10-26 17:03:08 +00:00
|
|
|
|
|
|
|
mkSRVTcp :: String -> HostName -> SRV
|
|
|
|
mkSRVTcp = mkSRV "tcp"
|
|
|
|
|
2012-10-25 21:56:03 +00:00
|
|
|
{- Returns an ordered list, with highest priority hosts first.
|
|
|
|
-
|
|
|
|
- On error, returns an empty list. -}
|
2012-10-26 17:03:08 +00:00
|
|
|
lookupSRV :: SRV -> IO [HostPort]
|
2012-10-28 23:14:30 +00:00
|
|
|
lookupSRV (SRV srv) = do
|
|
|
|
seed <- makeResolvSeed defaultResolvConf
|
|
|
|
r <- withResolver seed $ flip DNS.lookupSRV $ B8.fromString srv
|
2017-03-10 19:49:14 +00:00
|
|
|
return $ either (const []) use r
|
2012-12-13 04:24:19 +00:00
|
|
|
where
|
2014-10-09 18:53:13 +00:00
|
|
|
use = orderHosts . map tohosts
|
2012-12-13 04:24:19 +00:00
|
|
|
tohosts (priority, weight, port, hostname) =
|
2017-11-24 14:49:31 +00:00
|
|
|
( (fromIntegral priority, fromIntegral weight)
|
2012-12-13 04:24:19 +00:00
|
|
|
, (B8.toString hostname, PortNumber $ fromIntegral port)
|
|
|
|
)
|
2012-10-25 21:56:03 +00:00
|
|
|
|
2012-10-28 23:14:30 +00:00
|
|
|
orderHosts :: [(PriorityWeight, HostPort)] -> [HostPort]
|
|
|
|
orderHosts = map snd . sortBy (compare `on` fst)
|