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
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
|
{-# LANGUAGE CPP #-}
{-# LANGUAGE ExistentialQuantification #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE LambdaCase #-}
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE NamedFieldPuns #-}
{-# LANGUAGE NondecreasingIndentation #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE PartialTypeSignatures #-}
{-# LANGUAGE RankNTypes #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE TupleSections #-}
{-# LANGUAGE TypeFamilies #-}
import Control.Arrow
import Control.Concurrent.STM
import Control.DeepSeq
import Control.Exception
import Control.Monad
import Data.Char
import Data.List
import qualified Data.Map as Map
import Data.Time.Clock
import GHC.Stats
import Network.Socket
import System.Environment
import System.IO
import System.Mem
import System.Posix.Process
import Text.Printf
import Text.Read
#ifdef THREAD_DEBUG
import Control.Concurrent.Lifted.Instrument
#else
import Control.Concurrent.Lifted
import GHC.Conc (labelThread)
#endif
import Network.Address hiding (NodeId, NodeInfo(..))
import Network.BitTorrent.DHT.Search
import Network.QueryResponse
import Network.StreamServer
import Kademlia
import qualified Mainline
import Network.DHT.Routing as R
import Data.Aeson as J (ToJSON, FromJSON)
import qualified Data.Aeson as J
import qualified Data.ByteString.Lazy as L
import Control.Concurrent.Async.Pool
import System.IO.Error
showReport :: [(String,String)] -> String
showReport kvs = do
let colwidth = maximum $ map (length . fst) kvs
(k,v) <- kvs
concat [ printf " %-*s" (colwidth+1) k, v, "\n" ]
marshalForClient :: String -> String
marshalForClient s = show (length s) ++ ":" ++ s
-- | Writes a message and signals ready for next command.
hPutClient :: Handle -> String -> IO ()
hPutClient h s = hPutStr h ('.' : marshalForClient s)
-- | Writes message, but signals there is more to come.
hPutClientChunk :: Handle -> String -> IO ()
hPutClientChunk h s = hPutStr h (' ' : marshalForClient s)
data DHTQuery nid ni = forall addr r tok. DHTQuery
{ qsearch :: Search nid addr tok ni r
, qhandler :: ni -> nid -> IO ([ni], [r], tok)
, qshowR :: r -> String
, qshowTok :: tok -> Maybe String
}
data DHT = forall nid ni. ( Show ni
, Read ni
, ToJSON ni
, FromJSON ni
) =>
DHT
{ dhtBuckets :: TVar (BucketList ni)
, dhtPing :: ni -> IO Bool
, dhtQuery :: Map.Map String (DHTQuery nid ni)
, dhtParseId :: String -> Either String nid
}
nodesFileName :: String -> String
nodesFileName netname = netname ++ "-nodes.json"
saveNodes :: String -> DHT -> IO ()
saveNodes netname DHT{dhtBuckets} = do
bkts <- atomically $ readTVar dhtBuckets
let ns = map fst $ concat $ R.toList bkts
bs = J.encode ns
fname = nodesFileName netname
L.writeFile fname bs
loadNodes :: FromJSON ni => String -> IO [ni]
loadNodes netname = do
let fname = nodesFileName netname
attempt <- tryIOError $ do
J.decode <$> L.readFile fname
>>= maybe (ioError $ userError "Nothing") return
either (const $ return []) return attempt
pingNodes :: String -> DHT -> IO Bool
pingNodes netname DHT{dhtPing} = do
let fname = nodesFileName netname
attempt <- tryIOError $ do
J.decode <$> L.readFile fname
>>= maybe (ioError $ userError "Nothing") return
case attempt of
Left _ -> return False
Right ns -> do fork $ do
myThreadId >>= flip labelThread ("pinging."++fname)
putStrLn $ "Forked "++show fname
withTaskGroup 10 $ \g -> do
mapTasks_ g (map dhtPing ns)
putStrLn $ "Load finished "++show fname
return True
reportTable :: Show ni => BucketList ni -> [(String,String)]
reportTable bkts = map (show *** show . fst)
$ concat
$ zipWith map (map (,) [0::Int ..])
$ R.toList
$ bkts
reportResult :: Show ni =>
String
-> (r -> String)
-> (tok -> Maybe String)
-> Handle
-> Either String ([ni],[r],tok)
-> IO ()
reportResult meth showR showTok h (Left e) = hPutClient h e
reportResult meth showR showTok h (Right (ns,rs,tok)) = do
hPutClient h $ showReport report
where
report = intercalate [("","")] [ tok_r , node_r , result_r ]
tok_r = maybe [] (pure . ("token:",)) $ showTok tok
node_r = map ( ("n",) . show ) ns
result_r | (meth=="node") = []
| otherwise = map ( (take 1 meth,) . showR ) rs
data Session = Session
{ netname :: String
, dhts :: Map.Map String DHT
, externalAddresses :: IO [SockAddr]
, signalQuit :: MVar ()
}
clientSession s@Session{..} sock cnum h = do
line <- map toLower . dropWhile isSpace <$> hGetLine h
let (c,args) = second (dropWhile isSpace) $ break isSpace line
cmd0 :: IO () -> IO ()
cmd0 action = action >> clientSession s sock cnum h
switchNetwork dest = do hPutClient h ("Network: "++dest)
clientSession s{netname=dest} sock cnum h
case (c,args) of
("stop", _) -> do hPutClient h "Terminating DHT Daemon."
hClose h
putMVar signalQuit ()
("quit", _) -> hPutClient h "" >> hClose h
("pid", _) -> cmd0 $ do
pid <- getProcessID
hPutClient h (show pid)
("external-ip", _) -> cmd0 $ do
unlines . map show <$> externalAddresses
>>= hPutClient h
#ifdef THREAD_DEBUG
("threads", _) -> cmd0 $ do
ts <- threadsInformation
tm <- getCurrentTime
let r = map (\PerThread{..} -> (show lbl,show (diffUTCTime tm startTime))) ts
hPutClient h $ showReport r
("mem", s) -> cmd0 $ do
case s of
"gc" -> do hPutClient h "Performing garbage collection..."
performMajorGC
"" -> do
is_enabled <- getGCStatsEnabled
if is_enabled
then do
GCStats{..} <- getGCStats
let r = [ ("bytesAllocated", show bytesAllocated)
, ("numGcs", show numGcs)
, ("maxBytesUsed", show maxBytesUsed)
, ("numByteUsageSamples", show numByteUsageSamples)
, ("cumulativeBytesUsed", show cumulativeBytesUsed)
, ("bytesCopied", show bytesCopied)
, ("currentBytesUsed", show currentBytesUsed)
, ("currentBytesSlop", show currentBytesSlop)
, ("maxBytesSlop", show maxBytesSlop)
, ("peakMegabytesAllocated", show peakMegabytesAllocated)
, ("mutatorCpuSeconds", show mutatorCpuSeconds)
, ("mutatorWallSeconds", show mutatorWallSeconds)
, ("gcCpuSeconds", show gcCpuSeconds)
, ("gcWallSeconds", show gcWallSeconds)
, ("cpuSeconds", show cpuSeconds)
, ("wallSeconds", show wallSeconds)
, ("parTotBytesCopied", show parTotBytesCopied)
, ("parMaxBytesCopied", show parMaxBytesCopied)
]
hPutClient h $ showReport r
else hPutClient h "Run with +RTS -T to obtain live memory-usage information."
_ -> hPutClient h "error."
#endif
("ls", _) | Just DHT{dhtBuckets} <- Map.lookup netname dhts
-> cmd0 $ do
bkts <- atomically $ readTVar dhtBuckets
let r = reportTable bkts
hPutClient h $
showReport $
r ++ [ ("buckets", show $ R.shape bkts)
, ("node-id", show $ thisNode bkts)
, ("network", netname) ]
("ping", s) | Just DHT{dhtPing} <- Map.lookup netname dhts
-> cmd0 $ do
case readEither s of
Right addr -> do result <- dhtPing addr
let rs = [" ", show result]
hPutClient h $ unlines rs
Left er -> hPutClient h er
("g", s) | Just DHT{..} <- Map.lookup netname dhts
-> cmd0 $ do
-- arguments: method
-- nid
-- (optional dest-ni)
self <- atomically $ thisNode <$> readTVar dhtBuckets
let (method,xs) = break isSpace $ dropWhile isSpace s
(nidstr,ys) = break isSpace $ dropWhile isSpace xs
destination = dropWhile isSpace ys
goQuery qry = either (hPutClient h . ("Bad search target: "++))
(goTarget qry)
$ dhtParseId nidstr
goTarget DHTQuery{..} nid =
go nid >>= reportResult method qshowR qshowTok h
where
go | null destination = fmap Right . qhandler self
| otherwise = case readEither destination of
Right ni -> fmap (maybe (Left "Timeout.") Right)
. flip (searchQuery qsearch) ni
Left e -> const $ return $ Left ("Bad destination: "++e)
maybe (hPutClient h ("Unsupported method: "++method))
goQuery
$ Map.lookup method dhtQuery
("save", _) | Just dht <- Map.lookup netname dhts
-> cmd0 $ do
saveNodes netname dht
hPutClient h $ "Saved " ++ nodesFileName netname ++ "."
("load", _) | Just dht <- Map.lookup netname dhts
-> cmd0 $ do
b <- pingNodes netname dht
if b then hPutClient h $ "Pinging " ++ nodesFileName netname ++ "."
else hPutClient h $ "Failed: " ++ nodesFileName netname ++ "."
(n, _) | n `elem` Map.keys dhts -> switchNetwork n
_ -> cmd0 $ hPutClient h "error."
readExternals :: [TVar (BucketList Mainline.NodeInfo)] -> IO [SockAddr]
readExternals vars = do
as <- atomically $ mapM (fmap (Mainline.nodeAddr . selfNode) . readTVar) vars
-- TODO: Filter to only global addresses?
return as
defaultPort = "6881"
main = do
args <- getArgs
p <- case take 2 (dropWhile (/="-p") args) of
["-p",port] | not ("-" `isPrefixOf` port) -> return port
("-p":_) -> error "Port not specified! (-p PORT)"
_ -> return defaultPort
addr <- getBindAddress p True{- ipv6 -}
(bt,btR,swarms) <- Mainline.newClient addr
quitBt <- forkListener bt
tox <- return $ error "TODO: Tox.newClient"
quitTox <- return $ return () -- TODO: forkListener tox
let mainlineDHT bkts = DHT
{ dhtBuckets = bkts btR
, dhtPing = Mainline.ping bt
, dhtQuery = Map.fromList
[ ("node", DHTQuery (Mainline.nodeSearch bt)
(\ni -> fmap Mainline.unwrapNodes
. Mainline.findNodeH btR ni
. flip Mainline.FindNode (Just Mainline.Want_Both))
show
(const Nothing))
, ("peer", DHTQuery (Mainline.peerSearch bt)
(\ni -> fmap Mainline.unwrapPeers
. Mainline.getPeersH btR swarms ni
. flip Mainline.GetPeers (Just Mainline.Want_Both)
. (read . show)) -- TODO: InfoHash -> NodeId
show
(Just . show))
]
, dhtParseId = readEither :: String -> Either String Mainline.NodeId
}
dhts = Map.fromList
[ ("bt4", mainlineDHT Mainline.routing4)
, ("bt6", mainlineDHT Mainline.routing6)
]
waitForSignal <- do
signalQuit <- newEmptyMVar
let session = clientSession $ Session
{ netname = "bt4" -- initial default DHT
, dhts = dhts -- all DHTs
, signalQuit = signalQuit
, externalAddresses = readExternals
[ Mainline.routing4 btR
, Mainline.routing6 btR
]
}
srv <- streamServer (withSession session) (SockAddrUnix "dht.sock")
return $ do
() <- takeMVar signalQuit
quitListening srv
let bkts4 = Mainline.routing4 btR
btSaved4 <- loadNodes "bt4" :: IO [Mainline.NodeInfo]
putStrLn $ "Loaded "++show (length btSaved4)++" nodes for bt4."
fallbackNodes4 <- Mainline.bootstrapNodes Mainline.Want_IP4
fork $ do
myThreadId >>= flip labelThread "bootstrap.Mainline4"
bootstrap (Mainline.nodeSearch bt) bkts4 (Mainline.ping bt) btSaved4 fallbackNodes4
saveNodes "bt4" (dhts Map.! "bt4")
btSaved6 <- loadNodes "bt6"
putStrLn $ "Loaded "++show (length btSaved6)++" nodes for bt6."
let bkts6 = Mainline.routing6 btR
fallbackNodes6 <- Mainline.bootstrapNodes Mainline.Want_IP6
fork $ do
myThreadId >>= flip labelThread "bootstrap.Mainline6"
bootstrap (Mainline.nodeSearch bt) bkts6 (Mainline.ping bt) btSaved6 fallbackNodes6
saveNodes "bt6" (dhts Map.! "bt6")
hPutStr stderr $ showReport $ map (("bootstrap (IPv4)",) . show) fallbackNodes4
++ map (("bootstrap (IPv6)",) . show) fallbackNodes6
waitForSignal
quitBt
quitTox
|