git-annex/Utility/SRV.hs

60 lines
1.3 KiB
Haskell
Raw Normal View History

2012-10-25 21:56:03 +00:00
{- SRV record lookup
-
- Copyright 2012 Joey Hess <id@joeyh.name>
2012-10-25 21:56:03 +00:00
-
- License: BSD-2-clause
2012-10-25 21:56:03 +00:00
-}
{-# LANGUAGE CPP #-}
module Utility.SRV (
2012-10-26 17:03:08 +00:00
mkSRVTcp,
mkSRV,
2012-10-25 21:56:03 +00:00
lookupSRV,
HostPort,
2012-10-25 21:56:03 +00:00
) where
import Data.Function
import Data.List
import Network
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
deriving (Show, Eq)
2012-10-26 17:03:08 +00:00
2012-10-25 21:56:03 +00:00
type HostPort = (HostName, PortID)
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
["_", 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]
lookupSRV (SRV srv) = do
seed <- makeResolvSeed defaultResolvConf
r <- withResolver seed $ flip DNS.lookupSRV $ B8.fromString srv
2013-09-17 15:54:09 +00:00
return $
#if MIN_VERSION_dns(1,0,0)
either (const []) use r
#else
maybe [] use r
#endif
2012-12-13 04:24:19 +00:00
where
use = orderHosts . map tohosts
2012-12-13 04:24:19 +00:00
tohosts (priority, weight, port, hostname) =
( (priority, weight)
, (B8.toString hostname, PortNumber $ fromIntegral port)
)
2012-10-25 21:56:03 +00:00
orderHosts :: [(PriorityWeight, HostPort)] -> [HostPort]
orderHosts = map snd . sortBy (compare `on` fst)