-
Notifications
You must be signed in to change notification settings - Fork 2
/
ZhinaDNS.hs
75 lines (63 loc) · 2.48 KB
/
ZhinaDNS.hs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
module ZhinaDNS where
import qualified Resolve.Types as R
import Resolve.DNS.Types hiding (Query, Response)
import Resolve.DNS.Lookup hiding (Config)
import qualified IPSet
import qualified NameSet
import Control.Monad
import Control.Monad.Trans.Except
import Control.Concurrent
import Control.Exception
import Control.Monad.Trans.Class
import System.Log.Logger
nameM = "ZhinaDNS"
data Config = Config { china :: R.Resolve Query Response
, world :: R.Resolve Query Response
, chinaIP :: IPSet.IPSet IPv4
, worldName :: NameSet.NameSet
}
resolve :: Config -> R.Resolve Query Response
resolve c a = do
let nameF = nameM ++ ".resolve"
m_china <- newEmptyMVar
m_world <- newEmptyMVar
let isForeignName = NameSet.test (worldName c) (qname $ qquestion a)
bracket
(do
t_china <- forkIO $ when (not isForeignName) $ putMVar m_china =<< try (china c a)
t_world <- forkIO $ putMVar m_world =<< try (world c a)
return (t_china, t_world)
)
(\(t_china, t_world) -> do
killThread t_china
killThread t_world
)
(\_ -> either id id <$> (runExceptT $
do
b_china' <- if isForeignName then do
lift $ debugM nameF "foreign name detected, using only foreign DNS"
return Nothing
else do
b_china' <- lift $ takeMVar m_china
b_china <- case b_china' of
Left e -> do
lift $ debugM nameF $ "zhina: " ++ show (e :: SomeException)
lift $ throwIO e
Right b' -> return b'
let isForeignIP rdata' = case rdata' of
RR_A ip -> not $ IPSet.test (chinaIP c) ip
_ -> False
if any (\rr -> isForeignIP (rdata rr)) (ranswer b_china) then do
lift $ debugM nameF "foreign results detected, waiting for foreign DNS"
return Nothing
else return $ Just b_china
case b_china' of
Nothing -> do
b_world' <- lift $ takeMVar m_world
case b_world' of
Left e -> do
lift $ debugM nameF $ "world: " ++ show (e :: SomeException)
lift $ throwIO e
Right b' -> return b'
Just b_china -> return b_china
))