{-# LANGUAGE CPP #-}

module Distribution.Client.Security.DNS
  ( queryBootstrapMirrors
  ) where

import Control.Exception (try)
import Distribution.Client.Compat.Prelude
import Distribution.Simple.Utils
import Network.URI (URI (..), URIAuth (..), parseURI)
import Prelude ()

#if defined(MIN_VERSION_resolv) || defined(MIN_VERSION_windns)
import Network.DNS (queryTXT, Name(..), CharStr(..))
import qualified Data.ByteString.Char8 as BS.Char8
#else
import Distribution.Simple.Program.Db
         ( emptyProgramDb, addKnownProgram
         , configureAllKnownPrograms, lookupProgram )
import Distribution.Simple.Program
         ( simpleProgram
         , programInvocation
         , getProgramInvocationOutput )
#endif

-- | Try to lookup RFC1464-encoded mirror urls for a Hackage
-- repository url by performing a DNS TXT lookup on the
-- @_mirrors.@-prefixed URL hostname.
--
-- Example: for @http://hackage.haskell.org/@
-- perform a DNS TXT query for the hostname
-- @_mirrors.hackage.haskell.org@ which may look like e.g.
--
-- > _mirrors.hackage.haskell.org. 300 IN TXT
-- >    "0.urlbase=http://hackage.fpcomplete.com/"
-- >    "1.urlbase=http://objects-us-west-1.dream.io/hackage-mirror/"
--
-- NB: hackage-security doesn't require DNS lookups being trustworthy,
-- as the trust is established via the cryptographically signed TUF
-- meta-data that is retrieved from the resolved Hackage repository.
-- Moreover, we already have to protect against a compromised
-- @hackage.haskell.org@ DNS entry, so an the additional
-- @_mirrors.hackage.haskell.org@ DNS entry in the same SOA doesn't
-- constitute a significant new attack vector anyway.
queryBootstrapMirrors :: Verbosity -> URI -> IO [URI]

#if defined(MIN_VERSION_resolv) || defined(MIN_VERSION_windns)
-- use @resolv@ package for performing DNS queries
queryBootstrapMirrors :: Verbosity -> URI -> IO [URI]
queryBootstrapMirrors Verbosity
verbosity URI
repoUri
  | Just URIAuth
auth <- URI -> Maybe URIAuth
uriAuthority URI
repoUri = do
         let mirrorsDnsName :: Name
mirrorsDnsName = ByteString -> Name
Name ([Char] -> ByteString
BS.Char8.pack ([Char]
"_mirrors." [Char] -> [Char] -> [Char]
forall a. [a] -> [a] -> [a]
++ URIAuth -> [Char]
uriRegName URIAuth
auth))

         mirrors' <- IO [URI] -> IO (Either SomeException [URI])
forall e a. Exception e => IO a -> IO (Either e a)
try (IO [URI] -> IO (Either SomeException [URI]))
-> IO [URI] -> IO (Either SomeException [URI])
forall a b. (a -> b) -> a -> b
$ do
                  txts <- Name -> IO [(TTL, [CharStr])]
queryTXT Name
mirrorsDnsName
                  evaluate (force $ extractMirrors (map snd txts))

         mirrors <- case mirrors' of
             Left SomeException
e -> do
                 Verbosity -> [Char] -> IO ()
warn Verbosity
verbosity ([Char]
"Caught exception during _mirrors lookup:"[Char] -> [Char] -> [Char]
forall a. [a] -> [a] -> [a]
++
                                 SomeException -> [Char]
forall e. Exception e => e -> [Char]
displayException (SomeException
e :: SomeException))
                 [URI] -> IO [URI]
forall a. a -> IO a
forall (m :: * -> *) a. Monad m => a -> m a
return []
             Right [URI]
v -> [URI] -> IO [URI]
forall a. a -> IO a
forall (m :: * -> *) a. Monad m => a -> m a
return [URI]
v

         if null mirrors
         then warn verbosity ("No mirrors found for " ++ show repoUri)
         else do info verbosity ("located " ++ show (length mirrors) ++
                                 " mirrors for " ++ show repoUri ++ " :")
                 for_ mirrors $ \URI
url -> Verbosity -> [Char] -> IO ()
info Verbosity
verbosity ([Char]
"- " [Char] -> [Char] -> [Char]
forall a. [a] -> [a] -> [a]
++ URI -> [Char]
forall a. Show a => a -> [Char]
show URI
url)

         return mirrors

  | Bool
otherwise = [URI] -> IO [URI]
forall a. a -> IO a
forall (m :: * -> *) a. Monad m => a -> m a
return []

-- | Extract list of mirrors from 'queryTXT' result
extractMirrors :: [[CharStr]] -> [URI]
extractMirrors :: [[CharStr]] -> [URI]
extractMirrors [[CharStr]]
txtChunks = ((Int, [Char]) -> Maybe URI) -> [(Int, [Char])] -> [URI]
forall a b. (a -> Maybe b) -> [a] -> [b]
mapMaybe ([Char] -> Maybe URI
parseURI ([Char] -> Maybe URI)
-> ((Int, [Char]) -> [Char]) -> (Int, [Char]) -> Maybe URI
forall b c a. (b -> c) -> (a -> b) -> a -> c
. (Int, [Char]) -> [Char]
forall a b. (a, b) -> b
snd) ([(Int, [Char])] -> [URI])
-> ([(Int, [Char])] -> [(Int, [Char])]) -> [(Int, [Char])] -> [URI]
forall b c a. (b -> c) -> (a -> b) -> a -> c
. [(Int, [Char])] -> [(Int, [Char])]
forall a. Ord a => [a] -> [a]
sort ([(Int, [Char])] -> [URI]) -> [(Int, [Char])] -> [URI]
forall a b. (a -> b) -> a -> b
$ [(Int, [Char])]
vals
  where
    vals :: [(Int, [Char])]
vals = [ (Int
kn,[Char]
v) | CharStr ByteString
e <- [[CharStr]] -> [CharStr]
forall (t :: * -> *) a. Foldable t => t [a] -> [a]
concat [[CharStr]]
txtChunks
                    , Just ([Char]
k,[Char]
v) <- [[Char] -> Maybe ([Char], [Char])
splitRfc1464 (ByteString -> [Char]
BS.Char8.unpack ByteString
e)]
                    , Just Int
kn <- [[Char] -> Maybe Int
isUrlBase [Char]
k]
                    ]

----------------------------------------------------------------------------
#else /* !defined(MIN_VERSION_resolv) */
-- use external method via @nslookup@
queryBootstrapMirrors verbosity repoUri
  | Just auth <- uriAuthority repoUri = do
        progdb <- configureAllKnownPrograms verbosity $
                  addKnownProgram nslookupProg emptyProgramDb

        case lookupProgram nslookupProg progdb of
          Nothing -> do
              warn verbosity "'nslookup' tool missing - can't locate mirrors"
              return []

          Just nslookup -> do
              let mirrorsDnsName = "_mirrors." ++ uriRegName auth

              mirrors' <- try $ do
                  out <- getProgramInvocationOutput verbosity $
                         programInvocation nslookup ["-query=TXT", mirrorsDnsName]
                  evaluate (force $ extractMirrors mirrorsDnsName out)

              mirrors <- case mirrors' of
                Left e -> do
                    warn verbosity ("Caught exception during _mirrors lookup:"++
                                    displayException (e :: SomeException))
                    return []
                Right v -> return v

              if null mirrors
              then warn verbosity ("No mirrors found for " ++ show repoUri)
              else do info verbosity ("located " ++ show (length mirrors) ++
                                      " mirrors for " ++ show repoUri ++ " :")
                      for_ mirrors $ \url -> info verbosity ("- " ++ show url)

              return mirrors

  | otherwise = return []
  where
    nslookupProg = simpleProgram "nslookup"

-- | Extract list of mirrors from @nslookup -query=TXT@ output.
extractMirrors :: String -> String -> [URI]
extractMirrors hostname s0 = mapMaybe (parseURI . snd) . sort $ vals
  where
    vals = [ (kn,v) | (h,ents) <- fromMaybe [] $ parseNsLookupTxt s0
                    , h == hostname
                    , e <- ents
                    , Just (k,v) <- [splitRfc1464 e]
                    , Just kn <- [isUrlBase k]
                    ]

-- | Parse output of @nslookup -query=TXT $HOSTNAME@ tolerantly
parseNsLookupTxt :: String -> Maybe [(String,[String])]
parseNsLookupTxt = go0 [] []
  where
    -- approximate grammar:
    -- <entries> := { <entry> }
    -- (<entry> starts at begin of line, but may span multiple lines)
    -- <entry> := ^ <hostname> TAB "text =" { <qstring> }
    -- <qstring> := string enclosed by '"'s ('\' and '"' are \-escaped)

    -- scan for ^ <word> <TAB> "text ="
    go0 []  _  []                                = Nothing
    go0 res _  []                                = Just (reverse res)
    go0 res _  ('\n':xs)                         = go0 res [] xs
    go0 res lw ('\t':'t':'e':'x':'t':' ':'=':xs) = go1 res (reverse lw) [] (dropWhile isSpace xs)
    go0 res lw (x:xs)                            = go0 res (x:lw) xs

    -- collect at least one <qstring>
    go1 res lw qs ('"':xs) = case qstr "" xs of
      Just (s, xs') -> go1 res lw (s:qs) (dropWhile isSpace xs')
      Nothing       -> Nothing -- bad quoting
    go1 _   _  [] _  = Nothing -- missing qstring
    go1 res lw qs xs = go0 ((lw,reverse qs):res) [] xs

    qstr _   ('\n':_) = Nothing -- We don't support unquoted LFs
    qstr acc ('\\':'\\':cs) = qstr ('\\':acc) cs
    qstr acc ('\\':'"':cs)  = qstr ('"':acc) cs
    qstr acc ('"':cs) = Just (reverse acc, cs)
    qstr acc (c:cs)   = qstr (c:acc) cs
    qstr _   []       = Nothing

#endif
----------------------------------------------------------------------------

-- | Helper used by 'extractMirrors' for extracting @urlbase@ keys from Rfc1464-encoded data
isUrlBase :: String -> Maybe Int
isUrlBase :: [Char] -> Maybe Int
isUrlBase [Char]
s
  | [Char]
".urlbase" [Char] -> [Char] -> Bool
forall a. Eq a => [a] -> [a] -> Bool
`isSuffixOf` [Char]
s, Bool -> Bool
not ([Char] -> Bool
forall a. [a] -> Bool
forall (t :: * -> *) a. Foldable t => t a -> Bool
null [Char]
ns), (Char -> Bool) -> [Char] -> Bool
forall (t :: * -> *) a. Foldable t => (a -> Bool) -> t a -> Bool
all Char -> Bool
isDigit [Char]
ns = [Char] -> Maybe Int
forall a. Read a => [Char] -> Maybe a
readMaybe [Char]
ns
  | Bool
otherwise = Maybe Int
forall a. Maybe a
Nothing
  where
    ns :: [Char]
ns = Int -> [Char] -> [Char]
forall a. Int -> [a] -> [a]
take ([Char] -> Int
forall a. [a] -> Int
forall (t :: * -> *) a. Foldable t => t a -> Int
length [Char]
s Int -> Int -> Int
forall a. Num a => a -> a -> a
- Int
8) [Char]
s

-- | Split a TXT string into key and value according to RFC1464.
-- Returns 'Nothing' if parsing fails.
splitRfc1464 :: String -> Maybe (String, String)
splitRfc1464 :: [Char] -> Maybe ([Char], [Char])
splitRfc1464 = [Char] -> [Char] -> Maybe ([Char], [Char])
go [Char]
""
  where
    go :: [Char] -> [Char] -> Maybe ([Char], [Char])
go [Char]
_ [] = Maybe ([Char], [Char])
forall a. Maybe a
Nothing
    go [Char]
acc (Char
'`' : Char
c : [Char]
cs) = [Char] -> [Char] -> Maybe ([Char], [Char])
go (Char
c Char -> [Char] -> [Char]
forall a. a -> [a] -> [a]
: [Char]
acc) [Char]
cs
    go [Char]
acc (Char
'=' : [Char]
cs) = [Char] -> [Char] -> [Char] -> Maybe ([Char], [Char])
forall {t}. t -> [Char] -> [Char] -> Maybe (t, [Char])
go2 ([Char] -> [Char]
forall a. [a] -> [a]
reverse [Char]
acc) [Char]
"" [Char]
cs
    go [Char]
acc (Char
c : [Char]
cs)
      | Char -> Bool
isSpace Char
c = [Char] -> [Char] -> Maybe ([Char], [Char])
go [Char]
acc [Char]
cs
      | Bool
otherwise = [Char] -> [Char] -> Maybe ([Char], [Char])
go (Char
c Char -> [Char] -> [Char]
forall a. a -> [a] -> [a]
: [Char]
acc) [Char]
cs

    go2 :: t -> [Char] -> [Char] -> Maybe (t, [Char])
go2 t
k [Char]
acc [] = (t, [Char]) -> Maybe (t, [Char])
forall a. a -> Maybe a
Just (t
k, [Char] -> [Char]
forall a. [a] -> [a]
reverse [Char]
acc)
    go2 t
_ [Char]
_ [Char
'`'] = Maybe (t, [Char])
forall a. Maybe a
Nothing
    go2 t
k [Char]
acc (Char
'`' : Char
c : [Char]
cs) = t -> [Char] -> [Char] -> Maybe (t, [Char])
go2 t
k (Char
c Char -> [Char] -> [Char]
forall a. a -> [a] -> [a]
: [Char]
acc) [Char]
cs
    go2 t
k [Char]
acc (Char
c : [Char]
cs) = t -> [Char] -> [Char] -> Maybe (t, [Char])
go2 t
k (Char
c Char -> [Char] -> [Char]
forall a. a -> [a] -> [a]
: [Char]
acc) [Char]
cs