-- | Minimal DNS wire-format codec for mDNS (RFC 1035 §4, RFC 6762).
--
-- Only what mDNS discovery needs:
--
--   * a 12-byte header with the byte counts of the four sections;
--   * question entries (domain name, type, class);
--   * resource records with @PTR@, @TXT@ and @SRV@ rdata decoded
--     (unknown types are passed through as raw bytes);
--   * name compression (RFC 1035 §4.1.4 pointers) on /read/: peers
--     using other implementations compress names, so we must follow
--     pointers. On write we emit plain, uncompressed names — valid
--     for every reader.
--
-- mDNS-specific notes (RFC 6762): the header ID is 0 on genuine
-- multicast traffic; legacy unicast queries keep their ID and are
-- answered unicast. Class values carry the cache-flush /
-- unicast-response bits in their high bits; we keep the raw 16-bit
-- class and never interpret those bits.
module LibP2P.Discovery.MDNS.Message
  ( -- * Packet types
    DnsPacket (..)
  , DnsQuestion (..)
  , DnsRecord (..)
  , DnsRData (..)
    -- * Record types (RFC 1035)
  , typePTR
  , typeTXT
  , typeSRV
  , classIN
    -- * Codec
  , encodeDnsPacket
  , decodeDnsPacket
  ) where

import Data.ByteString (ByteString)
import qualified Data.ByteString as BS
import qualified Data.ByteString.Builder as B
import qualified Data.ByteString.Lazy as BL
import Data.Bits ((.&.))
import Data.Maybe (fromMaybe)
import Data.Text (Text)
import qualified Data.Text as T
import Data.Text.Encoding (decodeUtf8With, encodeUtf8)
import Data.Text.Encoding.Error (lenientDecode)
import Data.Word (Word16, Word32)

-- | An mDNS packet: header plus the four sections (the name-server
-- section is ignored; mDNS never uses it).
data DnsPacket = DnsPacket
  { DnsPacket -> Word16
pkID :: !Word16
  -- ^ Transaction id; 0 on genuine mDNS traffic
  , DnsPacket -> Word16
pkFlags :: !Word16
  -- ^ Raw 16-bit flags (QR, opcode, AA, TC, RD, RA, rcode)
  , DnsPacket -> [DnsQuestion]
pkQuestion :: ![DnsQuestion]
  , DnsPacket -> [DnsRecord]
pkAnswer :: ![DnsRecord]
  , DnsPacket -> [DnsRecord]
pkAdditional :: ![DnsRecord]
  } deriving (Int -> DnsPacket -> ShowS
[DnsPacket] -> ShowS
DnsPacket -> String
(Int -> DnsPacket -> ShowS)
-> (DnsPacket -> String)
-> ([DnsPacket] -> ShowS)
-> Show DnsPacket
forall a.
(Int -> a -> ShowS) -> (a -> String) -> ([a] -> ShowS) -> Show a
$cshowsPrec :: Int -> DnsPacket -> ShowS
showsPrec :: Int -> DnsPacket -> ShowS
$cshow :: DnsPacket -> String
show :: DnsPacket -> String
$cshowList :: [DnsPacket] -> ShowS
showList :: [DnsPacket] -> ShowS
Show, DnsPacket -> DnsPacket -> Bool
(DnsPacket -> DnsPacket -> Bool)
-> (DnsPacket -> DnsPacket -> Bool) -> Eq DnsPacket
forall a. (a -> a -> Bool) -> (a -> a -> Bool) -> Eq a
$c== :: DnsPacket -> DnsPacket -> Bool
== :: DnsPacket -> DnsPacket -> Bool
$c/= :: DnsPacket -> DnsPacket -> Bool
/= :: DnsPacket -> DnsPacket -> Bool
Eq)

-- | A question section entry.
data DnsQuestion = DnsQuestion
  { DnsQuestion -> Text
qName :: !Text
  -- ^ Domain name, dot-separated, lower case (mDNS names are
  -- case-insensitive, RFC 6762 §10)
  , DnsQuestion -> Word16
qType :: !Word16
  , DnsQuestion -> Word16
qClass :: !Word16
  -- ^ Class with the cache-flush / unicast-response bits as received
  } deriving (Int -> DnsQuestion -> ShowS
[DnsQuestion] -> ShowS
DnsQuestion -> String
(Int -> DnsQuestion -> ShowS)
-> (DnsQuestion -> String)
-> ([DnsQuestion] -> ShowS)
-> Show DnsQuestion
forall a.
(Int -> a -> ShowS) -> (a -> String) -> ([a] -> ShowS) -> Show a
$cshowsPrec :: Int -> DnsQuestion -> ShowS
showsPrec :: Int -> DnsQuestion -> ShowS
$cshow :: DnsQuestion -> String
show :: DnsQuestion -> String
$cshowList :: [DnsQuestion] -> ShowS
showList :: [DnsQuestion] -> ShowS
Show, DnsQuestion -> DnsQuestion -> Bool
(DnsQuestion -> DnsQuestion -> Bool)
-> (DnsQuestion -> DnsQuestion -> Bool) -> Eq DnsQuestion
forall a. (a -> a -> Bool) -> (a -> a -> Bool) -> Eq a
$c== :: DnsQuestion -> DnsQuestion -> Bool
== :: DnsQuestion -> DnsQuestion -> Bool
$c/= :: DnsQuestion -> DnsQuestion -> Bool
/= :: DnsQuestion -> DnsQuestion -> Bool
Eq)

-- | A resource record from answer / additional sections.
data DnsRecord = DnsRecord
  { DnsRecord -> Text
rName :: !Text
  -- ^ Domain name, dot-separated, lower case (compression resolved)
  , DnsRecord -> Word16
rType :: !Word16
  , DnsRecord -> Word16
rClass :: !Word16
  , DnsRecord -> Word32
rTTL :: !Word32
  , DnsRecord -> DnsRData
rData :: !DnsRData
  } deriving (Int -> DnsRecord -> ShowS
[DnsRecord] -> ShowS
DnsRecord -> String
(Int -> DnsRecord -> ShowS)
-> (DnsRecord -> String)
-> ([DnsRecord] -> ShowS)
-> Show DnsRecord
forall a.
(Int -> a -> ShowS) -> (a -> String) -> ([a] -> ShowS) -> Show a
$cshowsPrec :: Int -> DnsRecord -> ShowS
showsPrec :: Int -> DnsRecord -> ShowS
$cshow :: DnsRecord -> String
show :: DnsRecord -> String
$cshowList :: [DnsRecord] -> ShowS
showList :: [DnsRecord] -> ShowS
Show, DnsRecord -> DnsRecord -> Bool
(DnsRecord -> DnsRecord -> Bool)
-> (DnsRecord -> DnsRecord -> Bool) -> Eq DnsRecord
forall a. (a -> a -> Bool) -> (a -> a -> Bool) -> Eq a
$c== :: DnsRecord -> DnsRecord -> Bool
== :: DnsRecord -> DnsRecord -> Bool
$c/= :: DnsRecord -> DnsRecord -> Bool
/= :: DnsRecord -> DnsRecord -> Bool
Eq)

-- | Decoded rdata for the record types mDNS discovery uses; anything
-- else travels as raw bytes, so a forward-compatible peer's extra
-- records never break parsing of the records we do care about.
data DnsRData
  = RdPtr !Text -- ^ @PTR@: the pointed-to name
  | RdTxt ![ByteString] -- ^ @TXT@: character-strings (len-prefixed on the wire)
  | RdSrv !Word16 !Word16 !Word16 !Text -- ^ @SRV@: priority weight port target
  | RdOther !ByteString
  deriving (Int -> DnsRData -> ShowS
[DnsRData] -> ShowS
DnsRData -> String
(Int -> DnsRData -> ShowS)
-> (DnsRData -> String) -> ([DnsRData] -> ShowS) -> Show DnsRData
forall a.
(Int -> a -> ShowS) -> (a -> String) -> ([a] -> ShowS) -> Show a
$cshowsPrec :: Int -> DnsRData -> ShowS
showsPrec :: Int -> DnsRData -> ShowS
$cshow :: DnsRData -> String
show :: DnsRData -> String
$cshowList :: [DnsRData] -> ShowS
showList :: [DnsRData] -> ShowS
Show, DnsRData -> DnsRData -> Bool
(DnsRData -> DnsRData -> Bool)
-> (DnsRData -> DnsRData -> Bool) -> Eq DnsRData
forall a. (a -> a -> Bool) -> (a -> a -> Bool) -> Eq a
$c== :: DnsRData -> DnsRData -> Bool
== :: DnsRData -> DnsRData -> Bool
$c/= :: DnsRData -> DnsRData -> Bool
/= :: DnsRData -> DnsRData -> Bool
Eq)

-- | @PTR@ record type (RFC 1035).
typePTR :: Word16
typePTR :: Word16
typePTR = Word16
12

-- | @TXT@ record type (RFC 1035).
typeTXT :: Word16
typeTXT :: Word16
typeTXT = Word16
16

-- | @SRV@ record type (RFC 2782).
typeSRV :: Word16
typeSRV :: Word16
typeSRV = Word16
33

-- | @IN@ class (RFC 1035) without any cache-flush bit.
classIN :: Word16
classIN :: Word16
classIN = Word16
1

--------------------------------------------------------------------------------
-- Encode
--------------------------------------------------------------------------------

-- | Encode a packet. Names are written uncompressed (valid for every
-- reader); 'RdPtr' / 'RdTxt' / 'RdSrv' rdata is re-encoded and
-- 'RdOther' passes through verbatim.
--
-- Section counts are derived from the lists, so a caller can never
-- set inconsistent counts.
encodeDnsPacket :: DnsPacket -> ByteString
encodeDnsPacket :: DnsPacket -> ByteString
encodeDnsPacket DnsPacket
pk = LazyByteString -> ByteString
BL.toStrict (LazyByteString -> ByteString) -> LazyByteString -> ByteString
forall a b. (a -> b) -> a -> b
$ Builder -> LazyByteString
B.toLazyByteString (Builder -> LazyByteString) -> Builder -> LazyByteString
forall a b. (a -> b) -> a -> b
$
     Word16 -> Builder
B.word16BE (DnsPacket -> Word16
pkID DnsPacket
pk)
  Builder -> Builder -> Builder
forall a. Semigroup a => a -> a -> a
<> Word16 -> Builder
B.word16BE (DnsPacket -> Word16
pkFlags DnsPacket
pk)
  Builder -> Builder -> Builder
forall a. Semigroup a => a -> a -> a
<> Word16 -> Builder
B.word16BE (Int -> Word16
forall a b. (Integral a, Num b) => a -> b
fromIntegral ([DnsQuestion] -> Int
forall a. [a] -> Int
forall (t :: * -> *) a. Foldable t => t a -> Int
length (DnsPacket -> [DnsQuestion]
pkQuestion DnsPacket
pk)))
  Builder -> Builder -> Builder
forall a. Semigroup a => a -> a -> a
<> Word16 -> Builder
B.word16BE (Int -> Word16
forall a b. (Integral a, Num b) => a -> b
fromIntegral ([DnsRecord] -> Int
forall a. [a] -> Int
forall (t :: * -> *) a. Foldable t => t a -> Int
length (DnsPacket -> [DnsRecord]
pkAnswer DnsPacket
pk)))
  Builder -> Builder -> Builder
forall a. Semigroup a => a -> a -> a
<> Word16 -> Builder
B.word16BE Word16
0
  Builder -> Builder -> Builder
forall a. Semigroup a => a -> a -> a
<> Word16 -> Builder
B.word16BE (Int -> Word16
forall a b. (Integral a, Num b) => a -> b
fromIntegral ([DnsRecord] -> Int
forall a. [a] -> Int
forall (t :: * -> *) a. Foldable t => t a -> Int
length (DnsPacket -> [DnsRecord]
pkAdditional DnsPacket
pk)))
  Builder -> Builder -> Builder
forall a. Semigroup a => a -> a -> a
<> (DnsQuestion -> Builder) -> [DnsQuestion] -> Builder
forall m a. Monoid m => (a -> m) -> [a] -> m
forall (t :: * -> *) m a.
(Foldable t, Monoid m) =>
(a -> m) -> t a -> m
foldMap DnsQuestion -> Builder
encodeQuestion (DnsPacket -> [DnsQuestion]
pkQuestion DnsPacket
pk)
  Builder -> Builder -> Builder
forall a. Semigroup a => a -> a -> a
<> (DnsRecord -> Builder) -> [DnsRecord] -> Builder
forall m a. Monoid m => (a -> m) -> [a] -> m
forall (t :: * -> *) m a.
(Foldable t, Monoid m) =>
(a -> m) -> t a -> m
foldMap DnsRecord -> Builder
encodeRecord (DnsPacket -> [DnsRecord]
pkAnswer DnsPacket
pk)
  Builder -> Builder -> Builder
forall a. Semigroup a => a -> a -> a
<> (DnsRecord -> Builder) -> [DnsRecord] -> Builder
forall m a. Monoid m => (a -> m) -> [a] -> m
forall (t :: * -> *) m a.
(Foldable t, Monoid m) =>
(a -> m) -> t a -> m
foldMap DnsRecord -> Builder
encodeRecord (DnsPacket -> [DnsRecord]
pkAdditional DnsPacket
pk)

encodeQuestion :: DnsQuestion -> B.Builder
encodeQuestion :: DnsQuestion -> Builder
encodeQuestion DnsQuestion {qName :: DnsQuestion -> Text
qName = Text
name, qType :: DnsQuestion -> Word16
qType = Word16
qtype, qClass :: DnsQuestion -> Word16
qClass = Word16
qclass} =
  Text -> Builder
encodeName Text
name Builder -> Builder -> Builder
forall a. Semigroup a => a -> a -> a
<> Word16 -> Builder
B.word16BE Word16
qtype Builder -> Builder -> Builder
forall a. Semigroup a => a -> a -> a
<> Word16 -> Builder
B.word16BE Word16
qclass

encodeRecord :: DnsRecord -> B.Builder
encodeRecord :: DnsRecord -> Builder
encodeRecord DnsRecord {rName :: DnsRecord -> Text
rName = Text
name, rType :: DnsRecord -> Word16
rType = Word16
rtype, rClass :: DnsRecord -> Word16
rClass = Word16
rclass, rTTL :: DnsRecord -> Word32
rTTL = Word32
rttl, rData :: DnsRecord -> DnsRData
rData = DnsRData
rdata} =
  Text -> Builder
encodeName Text
name
    Builder -> Builder -> Builder
forall a. Semigroup a => a -> a -> a
<> Word16 -> Builder
B.word16BE Word16
rtype
    Builder -> Builder -> Builder
forall a. Semigroup a => a -> a -> a
<> Word16 -> Builder
B.word16BE Word16
rclass
    Builder -> Builder -> Builder
forall a. Semigroup a => a -> a -> a
<> Word32 -> Builder
B.word32BE Word32
rttl
    Builder -> Builder -> Builder
forall a. Semigroup a => a -> a -> a
<> Word16 -> Builder
B.word16BE (Int -> Word16
forall a b. (Integral a, Num b) => a -> b
fromIntegral (ByteString -> Int
BS.length ByteString
rdataBytes)) Builder -> Builder -> Builder
forall a. Semigroup a => a -> a -> a
<> ByteString -> Builder
B.byteString ByteString
rdataBytes
  where
    rdataBytes :: ByteString
rdataBytes = DnsRData -> ByteString
encodeRData DnsRData
rdata

-- | Encode a dot-separated name as wire labels, terminated by the
-- zero label.
encodeName :: Text -> B.Builder
encodeName :: Text -> Builder
encodeName Text
name
  | Text -> Bool
T.null Text
name = Word8 -> Builder
B.word8 Word8
0
  | Bool
otherwise =
      (Text -> Builder) -> [Text] -> Builder
forall m a. Monoid m => (a -> m) -> [a] -> m
forall (t :: * -> *) m a.
(Foldable t, Monoid m) =>
(a -> m) -> t a -> m
foldMap
        ( \Text
label ->
            Word8 -> Builder
B.word8 (Int -> Word8
forall a b. (Integral a, Num b) => a -> b
fromIntegral (Text -> Int
T.length Text
label)) Builder -> Builder -> Builder
forall a. Semigroup a => a -> a -> a
<> ByteString -> Builder
B.byteString (Text -> ByteString
encodeUtf8 Text
label)
        )
        (HasCallStack => Text -> Text -> [Text]
Text -> Text -> [Text]
T.splitOn Text
"." Text
name)
        Builder -> Builder -> Builder
forall a. Semigroup a => a -> a -> a
<> Word8 -> Builder
B.word8 Word8
0

encodeRData :: DnsRData -> ByteString
encodeRData :: DnsRData -> ByteString
encodeRData DnsRData
rdata = LazyByteString -> ByteString
BL.toStrict (LazyByteString -> ByteString) -> LazyByteString -> ByteString
forall a b. (a -> b) -> a -> b
$ Builder -> LazyByteString
B.toLazyByteString (Builder -> LazyByteString) -> Builder -> LazyByteString
forall a b. (a -> b) -> a -> b
$ case DnsRData
rdata of
  RdPtr Text
name -> Text -> Builder
encodeName Text
name
  RdTxt [ByteString]
strings ->
    (ByteString -> Builder) -> [ByteString] -> Builder
forall m a. Monoid m => (a -> m) -> [a] -> m
forall (t :: * -> *) m a.
(Foldable t, Monoid m) =>
(a -> m) -> t a -> m
foldMap (\ByteString
s -> Word8 -> Builder
B.word8 (Int -> Word8
forall a b. (Integral a, Num b) => a -> b
fromIntegral (ByteString -> Int
BS.length ByteString
s)) Builder -> Builder -> Builder
forall a. Semigroup a => a -> a -> a
<> ByteString -> Builder
B.byteString ByteString
s) [ByteString]
strings
  RdSrv Word16
priority Word16
weight Word16
port Text
target ->
    Word16 -> Builder
B.word16BE Word16
priority Builder -> Builder -> Builder
forall a. Semigroup a => a -> a -> a
<> Word16 -> Builder
B.word16BE Word16
weight Builder -> Builder -> Builder
forall a. Semigroup a => a -> a -> a
<> Word16 -> Builder
B.word16BE Word16
port Builder -> Builder -> Builder
forall a. Semigroup a => a -> a -> a
<> Text -> Builder
encodeName Text
target
  RdOther ByteString
bs -> ByteString -> Builder
B.byteString ByteString
bs

--------------------------------------------------------------------------------
-- Decode
--------------------------------------------------------------------------------

-- headerSize is 12 bytes: ID, flags, and the four section counts.
headerSize :: Int
headerSize :: Int
headerSize = Int
12

-- | Decode a packet, resolving name compression. A structurally
-- invalid packet is a 'Left'; the mDNS service ignores malformed
-- packets — multicast input is unauthenticated.
decodeDnsPacket :: ByteString -> Either String DnsPacket
decodeDnsPacket :: ByteString -> Either String DnsPacket
decodeDnsPacket ByteString
raw = do
  Bool -> String -> Either String ()
unlessLen (ByteString -> Int
BS.length ByteString
raw Int -> Int -> Bool
forall a. Ord a => a -> a -> Bool
>= Int
headerSize) String
"packet shorter than DNS header"
  let id' :: Word16
id' = ByteString -> Int -> Word16
be16 ByteString
raw Int
0
      flags :: Word16
flags = ByteString -> Int -> Word16
be16 ByteString
raw Int
2
      nQuestion :: Word16
nQuestion = ByteString -> Int -> Word16
be16 ByteString
raw Int
4
      nAnswer :: Word16
nAnswer = ByteString -> Int -> Word16
be16 ByteString
raw Int
6
      nNS :: Word16
nNS = ByteString -> Int -> Word16
be16 ByteString
raw Int
8
      nAdditional :: Word16
nAdditional = ByteString -> Int -> Word16
be16 ByteString
raw Int
10
  Bool -> String -> Either String ()
unlessLen (Word16
nNS Word16 -> Word16 -> Bool
forall a. Eq a => a -> a -> Bool
== Word16
0) String
"name-server section must be empty (mDNS)"
  (questions, off1) <- ByteString -> Int -> Word16 -> Either String ([DnsQuestion], Int)
parseQuestions ByteString
raw Int
headerSize Word16
nQuestion
  (answers, off2) <- parseRecords raw off1 nAnswer
  (additional, _) <- parseRecords raw off2 nAdditional
  pure
    DnsPacket
      { pkID = id'
      , pkFlags = flags
      , pkQuestion = questions
      , pkAnswer = answers
      , pkAdditional = additional
      }

be16 :: ByteString -> Int -> Word16
be16 :: ByteString -> Int -> Word16
be16 ByteString
bs Int
i = Word8 -> Word16
forall a b. (Integral a, Num b) => a -> b
fromIntegral (HasCallStack => ByteString -> Int -> Word8
ByteString -> Int -> Word8
BS.index ByteString
bs Int
i) Word16 -> Word16 -> Word16
forall a. Num a => a -> a -> a
* Word16
256 Word16 -> Word16 -> Word16
forall a. Num a => a -> a -> a
+ Word8 -> Word16
forall a b. (Integral a, Num b) => a -> b
fromIntegral (HasCallStack => ByteString -> Int -> Word8
ByteString -> Int -> Word8
BS.index ByteString
bs (Int
i Int -> Int -> Int
forall a. Num a => a -> a -> a
+ Int
1))

be32 :: ByteString -> Int -> Word32
be32 :: ByteString -> Int -> Word32
be32 ByteString
bs Int
i =
  Word8 -> Word32
forall a b. (Integral a, Num b) => a -> b
fromIntegral (HasCallStack => ByteString -> Int -> Word8
ByteString -> Int -> Word8
BS.index ByteString
bs Int
i) Word32 -> Word32 -> Word32
forall a. Num a => a -> a -> a
* Word32
0x1000000
    Word32 -> Word32 -> Word32
forall a. Num a => a -> a -> a
+ Word8 -> Word32
forall a b. (Integral a, Num b) => a -> b
fromIntegral (HasCallStack => ByteString -> Int -> Word8
ByteString -> Int -> Word8
BS.index ByteString
bs (Int
i Int -> Int -> Int
forall a. Num a => a -> a -> a
+ Int
1)) Word32 -> Word32 -> Word32
forall a. Num a => a -> a -> a
* Word32
0x10000
    Word32 -> Word32 -> Word32
forall a. Num a => a -> a -> a
+ Word8 -> Word32
forall a b. (Integral a, Num b) => a -> b
fromIntegral (HasCallStack => ByteString -> Int -> Word8
ByteString -> Int -> Word8
BS.index ByteString
bs (Int
i Int -> Int -> Int
forall a. Num a => a -> a -> a
+ Int
2)) Word32 -> Word32 -> Word32
forall a. Num a => a -> a -> a
* Word32
0x100
    Word32 -> Word32 -> Word32
forall a. Num a => a -> a -> a
+ Word8 -> Word32
forall a b. (Integral a, Num b) => a -> b
fromIntegral (HasCallStack => ByteString -> Int -> Word8
ByteString -> Int -> Word8
BS.index ByteString
bs (Int
i Int -> Int -> Int
forall a. Num a => a -> a -> a
+ Int
3))

unlessLen :: Bool -> String -> Either String ()
unlessLen :: Bool -> String -> Either String ()
unlessLen Bool
True String
_ = () -> Either String ()
forall a b. b -> Either a b
Right ()
unlessLen Bool
False String
err = String -> Either String ()
forall a b. a -> Either a b
Left String
err

parseQuestions :: ByteString -> Int -> Word16 -> Either String ([DnsQuestion], Int)
parseQuestions :: ByteString -> Int -> Word16 -> Either String ([DnsQuestion], Int)
parseQuestions ByteString
raw Int
off Word16
n = Int
-> Integer -> [DnsQuestion] -> Either String ([DnsQuestion], Int)
forall {t}.
(Eq t, Num t) =>
Int -> t -> [DnsQuestion] -> Either String ([DnsQuestion], Int)
parseQ Int
off (Word16 -> Integer
forall a b. (Integral a, Num b) => a -> b
fromIntegral Word16
n) []
  where
    parseQ :: Int -> t -> [DnsQuestion] -> Either String ([DnsQuestion], Int)
parseQ Int
o t
0 [DnsQuestion]
acc = ([DnsQuestion], Int) -> Either String ([DnsQuestion], Int)
forall a. a -> Either String a
forall (f :: * -> *) a. Applicative f => a -> f a
pure ([DnsQuestion] -> [DnsQuestion]
forall a. [a] -> [a]
reverse [DnsQuestion]
acc, Int
o)
    parseQ Int
o t
k [DnsQuestion]
acc = do
      (name, o1) <- ByteString -> Int -> Either String (Text, Int)
decodeName ByteString
raw Int
o
      unlessLen (o1 + 4 <= BS.length raw) "truncated question (name/type/class)"
      parseQ (o1 + 4) (k - 1)
        (DnsQuestion name (be16 raw o1) (be16 raw (o1 + 2)) : acc)

parseRecords :: ByteString -> Int -> Word16 -> Either String ([DnsRecord], Int)
parseRecords :: ByteString -> Int -> Word16 -> Either String ([DnsRecord], Int)
parseRecords ByteString
raw Int
off Word16
n = Int -> Integer -> [DnsRecord] -> Either String ([DnsRecord], Int)
forall {t}.
(Eq t, Num t) =>
Int -> t -> [DnsRecord] -> Either String ([DnsRecord], Int)
parseR Int
off (Word16 -> Integer
forall a b. (Integral a, Num b) => a -> b
fromIntegral Word16
n) []
  where
    parseR :: Int -> t -> [DnsRecord] -> Either String ([DnsRecord], Int)
parseR Int
o t
0 [DnsRecord]
acc = ([DnsRecord], Int) -> Either String ([DnsRecord], Int)
forall a. a -> Either String a
forall (f :: * -> *) a. Applicative f => a -> f a
pure ([DnsRecord] -> [DnsRecord]
forall a. [a] -> [a]
reverse [DnsRecord]
acc, Int
o)
    parseR Int
o t
k [DnsRecord]
acc = do
      (name, o1) <- ByteString -> Int -> Either String (Text, Int)
decodeName ByteString
raw Int
o
      unlessLen (o1 + 10 <= BS.length raw) "truncated record header"
      let rtype = ByteString -> Int -> Word16
be16 ByteString
raw Int
o1
          rclass = ByteString -> Int -> Word16
be16 ByteString
raw (Int
o1 Int -> Int -> Int
forall a. Num a => a -> a -> a
+ Int
2)
          rttl = ByteString -> Int -> Word32
be32 ByteString
raw (Int
o1 Int -> Int -> Int
forall a. Num a => a -> a -> a
+ Int
4)
          rdataLen = Word16 -> Int
forall a b. (Integral a, Num b) => a -> b
fromIntegral (ByteString -> Int -> Word16
be16 ByteString
raw (Int
o1 Int -> Int -> Int
forall a. Num a => a -> a -> a
+ Int
8))
          bodyOff = Int
o1 Int -> Int -> Int
forall a. Num a => a -> a -> a
+ Int
10
      unlessLen (bodyOff + rdataLen <= BS.length raw) "rdata runs past the packet"
      rdata <- parseRData raw bodyOff rdataLen rtype
      parseR (bodyOff + rdataLen) (k - 1)
        (DnsRecord name rtype rclass rttl rdata : acc)

parseRData :: ByteString -> Int -> Int -> Word16 -> Either String DnsRData
parseRData :: ByteString -> Int -> Int -> Word16 -> Either String DnsRData
parseRData ByteString
raw Int
off Int
len Word16
rtype = case Word16
rtype of
  Word16
t
    | Word16
t Word16 -> Word16 -> Bool
forall a. Eq a => a -> a -> Bool
== Word16
typePTR -> do
        (name, _) <- ByteString -> Int -> Either String (Text, Int)
decodeName ByteString
raw Int
off
        pure (RdPtr name)
    | Word16
t Word16 -> Word16 -> Bool
forall a. Eq a => a -> a -> Bool
== Word16
typeTXT -> do
        strings <- ByteString -> Int -> Int -> Either String [ByteString]
parseTxt ByteString
raw Int
off Int
len
        pure (RdTxt strings)
    | Word16
t Word16 -> Word16 -> Bool
forall a. Eq a => a -> a -> Bool
== Word16
typeSRV -> ByteString -> Int -> Int -> Either String DnsRData
parseSrv ByteString
raw Int
off Int
len
    | Bool
otherwise -> DnsRData -> Either String DnsRData
forall a. a -> Either String a
forall (f :: * -> *) a. Applicative f => a -> f a
pure (ByteString -> DnsRData
RdOther (Int -> ByteString -> ByteString
BS.take Int
len (Int -> ByteString -> ByteString
BS.drop Int
off ByteString
raw)))

-- | TXT rdata (RFC 1035 §3.3.14): a sequence of character-strings,
-- each length-prefixed (1-255 bytes).
parseTxt :: ByteString -> Int -> Int -> Either String [ByteString]
parseTxt :: ByteString -> Int -> Int -> Either String [ByteString]
parseTxt ByteString
raw Int
off Int
len = Int -> [ByteString] -> Either String [ByteString]
go Int
off []
  where
    end :: Int
end = Int
off Int -> Int -> Int
forall a. Num a => a -> a -> a
+ Int
len
    go :: Int -> [ByteString] -> Either String [ByteString]
go Int
o [ByteString]
acc
      | Int
o Int -> Int -> Bool
forall a. Ord a => a -> a -> Bool
>= Int
end = [ByteString] -> Either String [ByteString]
forall a. a -> Either String a
forall (f :: * -> *) a. Applicative f => a -> f a
pure ([ByteString] -> [ByteString]
forall a. [a] -> [a]
reverse [ByteString]
acc)
      | Int
o Int -> Int -> Int
forall a. Num a => a -> a -> a
+ Int
1 Int -> Int -> Bool
forall a. Ord a => a -> a -> Bool
> Int
end = String -> Either String [ByteString]
forall a b. a -> Either a b
Left String
"truncated TXT string length"
      | Bool
otherwise = do
          let slen :: Int
slen = Word8 -> Int
forall a b. (Integral a, Num b) => a -> b
fromIntegral (HasCallStack => ByteString -> Int -> Word8
ByteString -> Int -> Word8
BS.index ByteString
raw Int
o)
          Bool -> String -> Either String ()
unlessLen (Int
o Int -> Int -> Int
forall a. Num a => a -> a -> a
+ Int
1 Int -> Int -> Int
forall a. Num a => a -> a -> a
+ Int
slen Int -> Int -> Bool
forall a. Ord a => a -> a -> Bool
<= Int
end) String
"TXT string runs past rdata"
          Int -> [ByteString] -> Either String [ByteString]
go (Int
o Int -> Int -> Int
forall a. Num a => a -> a -> a
+ Int
1 Int -> Int -> Int
forall a. Num a => a -> a -> a
+ Int
slen) (Int -> ByteString -> ByteString
BS.take Int
slen (Int -> ByteString -> ByteString
BS.drop (Int
o Int -> Int -> Int
forall a. Num a => a -> a -> a
+ Int
1) ByteString
raw) ByteString -> [ByteString] -> [ByteString]
forall a. a -> [a] -> [a]
: [ByteString]
acc)

parseSrv :: ByteString -> Int -> Int -> Either String DnsRData
parseSrv :: ByteString -> Int -> Int -> Either String DnsRData
parseSrv ByteString
raw Int
off Int
len = do
  Bool -> String -> Either String ()
unlessLen (Int
len Int -> Int -> Bool
forall a. Ord a => a -> a -> Bool
>= Int
6) String
"SRV rdata too short"
  let priority :: Word16
priority = ByteString -> Int -> Word16
be16 ByteString
raw Int
off
      weight :: Word16
weight = ByteString -> Int -> Word16
be16 ByteString
raw (Int
off Int -> Int -> Int
forall a. Num a => a -> a -> a
+ Int
2)
      port :: Word16
port = ByteString -> Int -> Word16
be16 ByteString
raw (Int
off Int -> Int -> Int
forall a. Num a => a -> a -> a
+ Int
4)
  (target, _) <- ByteString -> Int -> Either String (Text, Int)
decodeName ByteString
raw (Int
off Int -> Int -> Int
forall a. Num a => a -> a -> a
+ Int
6)
  pure (RdSrv priority weight port target)

-- | Decode a (possibly compressed) domain name (RFC 1035 §4.1.4).
--
-- Returns the lower-cased name and the offset just past it: a
-- compression pointer does not advance the cursor, so the first byte
-- after the pointer belongs to the enclosing record.
--
-- Guards against malformed compression: a pointer must jump
-- /backwards/ (RFC 1035: "an offset ... prior ... occurrence") and
-- pointer chains are capped at 127 jumps, so a crafted loop cannot
-- hang the reader.
decodeName :: ByteString -> Int -> Either String (Text, Int)
decodeName :: ByteString -> Int -> Either String (Text, Int)
decodeName ByteString
raw Int
start = Int
-> Maybe Int
-> Integer
-> [ByteString]
-> Either String (Text, Int)
forall {t}.
(Ord t, Num t) =>
Int -> Maybe Int -> t -> [ByteString] -> Either String (Text, Int)
go Int
start Maybe Int
forall a. Maybe a
Nothing Integer
0 []
  where
    total :: Int
total = ByteString -> Int
BS.length ByteString
raw
    decodeLabel :: ByteString -> Text
decodeLabel = Text -> Text
T.toLower (Text -> Text) -> (ByteString -> Text) -> ByteString -> Text
forall b c a. (b -> c) -> (a -> b) -> a -> c
. OnDecodeError -> ByteString -> Text
decodeUtf8With OnDecodeError
lenientDecode

    -- o: current offset; Just res: cursor past the /outermost/ name
    -- (fixed at the first pointer); d: pointer jumps so far; acc:
    -- labels collected so far (reverse order).
    go :: Int -> Maybe Int -> t -> [ByteString] -> Either String (Text, Int)
go Int
o Maybe Int
mCursor t
d [ByteString]
acc
      | t
d t -> t -> Bool
forall a. Ord a => a -> a -> Bool
> t
127 = String -> Either String (Text, Int)
forall a b. a -> Either a b
Left String
"name compression chain too deep"
      | Int
o Int -> Int -> Bool
forall a. Ord a => a -> a -> Bool
>= Int
total = String -> Either String (Text, Int)
forall a b. a -> Either a b
Left String
"name runs past the packet"
      | Word8
lenByte Word8 -> Word8 -> Bool
forall a. Eq a => a -> a -> Bool
== Word8
0 =
          (Text, Int) -> Either String (Text, Int)
forall a. a -> Either String a
forall (f :: * -> *) a. Applicative f => a -> f a
pure (Text -> [Text] -> Text
T.intercalate Text
"." ((ByteString -> Text) -> [ByteString] -> [Text]
forall a b. (a -> b) -> [a] -> [b]
map ByteString -> Text
decodeLabel ([ByteString] -> [ByteString]
forall a. [a] -> [a]
reverse [ByteString]
acc)), Int -> Maybe Int -> Int
forall a. a -> Maybe a -> a
fromMaybe (Int
o Int -> Int -> Int
forall a. Num a => a -> a -> a
+ Int
1) Maybe Int
mCursor)
      | Word8
lenByte Word8 -> Word8 -> Bool
forall a. Ord a => a -> a -> Bool
>= Word8
0xC0 = do
          Bool -> String -> Either String ()
unlessLen (Int
o Int -> Int -> Int
forall a. Num a => a -> a -> a
+ Int
1 Int -> Int -> Bool
forall a. Ord a => a -> a -> Bool
< Int
total) String
"truncated compression pointer"
          Bool -> String -> Either String ()
unlessLen (Word8
lenByte Word8 -> Word8 -> Bool
forall a. Ord a => a -> a -> Bool
< Word8
0xC4) String
"compression pointer sets reserved bits"
          let target :: Int
target =
                Word8 -> Int
forall a b. (Integral a, Num b) => a -> b
fromIntegral (Word8
lenByte Word8 -> Word8 -> Word8
forall a. Bits a => a -> a -> a
.&. Word8
0x3F) Int -> Int -> Int
forall a. Num a => a -> a -> a
* Int
256
                  Int -> Int -> Int
forall a. Num a => a -> a -> a
+ Word8 -> Int
forall a b. (Integral a, Num b) => a -> b
fromIntegral (HasCallStack => ByteString -> Int -> Word8
ByteString -> Int -> Word8
BS.index ByteString
raw (Int
o Int -> Int -> Int
forall a. Num a => a -> a -> a
+ Int
1))
          Bool -> String -> Either String ()
unlessLen (Int
target Int -> Int -> Bool
forall a. Ord a => a -> a -> Bool
< Int
o) String
"compression pointer must point backwards"
          Int -> Maybe Int -> t -> [ByteString] -> Either String (Text, Int)
go Int
target (Int -> Maybe Int
forall a. a -> Maybe a
Just (Int -> Maybe Int -> Int
forall a. a -> Maybe a -> a
fromMaybe (Int
o Int -> Int -> Int
forall a. Num a => a -> a -> a
+ Int
2) Maybe Int
mCursor)) (t
d t -> t -> t
forall a. Num a => a -> a -> a
+ t
1) [ByteString]
acc
      | Bool
otherwise = do
          Bool -> String -> Either String ()
unlessLen (Int
o Int -> Int -> Int
forall a. Num a => a -> a -> a
+ Int
1 Int -> Int -> Int
forall a. Num a => a -> a -> a
+ Word8 -> Int
forall a b. (Integral a, Num b) => a -> b
fromIntegral Word8
lenByte Int -> Int -> Bool
forall a. Ord a => a -> a -> Bool
<= Int
total) String
"label runs past the packet"
          let label :: ByteString
label = Int -> ByteString -> ByteString
BS.take (Word8 -> Int
forall a b. (Integral a, Num b) => a -> b
fromIntegral Word8
lenByte) (Int -> ByteString -> ByteString
BS.drop (Int
o Int -> Int -> Int
forall a. Num a => a -> a -> a
+ Int
1) ByteString
raw)
          Int -> Maybe Int -> t -> [ByteString] -> Either String (Text, Int)
go (Int
o Int -> Int -> Int
forall a. Num a => a -> a -> a
+ Int
1 Int -> Int -> Int
forall a. Num a => a -> a -> a
+ Word8 -> Int
forall a b. (Integral a, Num b) => a -> b
fromIntegral Word8
lenByte) Maybe Int
mCursor t
d (ByteString
label ByteString -> [ByteString] -> [ByteString]
forall a. a -> [a] -> [a]
: [ByteString]
acc)
      where
        lenByte :: Word8
lenByte = HasCallStack => ByteString -> Int -> Word8
ByteString -> Int -> Word8
BS.index ByteString
raw Int
o