summaryrefslogtreecommitdiff
path: root/ToxToXMPP.hs
blob: 367e5bf7c9aae2fdc8d8d44a6b641d26f2c21c78 (plain)
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
{-# LANGUAGE CPP            #-}
{-# LANGUAGE LambdaCase     #-}
{-# LANGUAGE NamedFieldPuns #-}
module ToxToXMPP where

import Data.Conduit                 as C
import qualified Data.Conduit.List  as CL
import Data.XML.Types               as XML
import Network.Tox.Crypto.Transport as Tox
import XMPPServer                   as XMPP
import EventUtil

import Announcer
import Announcer.Tox
import Connection
import Network.QueryResponse
-- import Control.Concurrent
import Control.Concurrent.STM
import Control.Monad
import Crypto.Tox
import qualified Data.HashMap.Strict         as HashMap
import Data.Maybe
import qualified Data.Set                    as Set
import qualified Data.Text                   as T
import Data.Time.Clock.POSIX
import Network.Address
import Network.Kademlia.Search
import qualified Network.Tox                 as Tox
import Network.Tox.ContactInfo               as Tox
import qualified Network.Tox.Crypto.Handlers as Tox
-- import qualified Network.Tox.DHT.Handlers    as Tox
import Announcer
import ClientState
import Control.Concurrent.STM
import Control.Monad
import Crypto.Tox
import Data.Bits
import Data.Function
import qualified Data.Map                    as Map
import qualified Data.Set                    as Set
import qualified Data.Text                   as T
         ;import Data.Text                   (Text)
import Data.Word
import qualified Network.Kademlia.Routing    as R
import Network.Tox
import Network.Tox.ContactInfo
import Network.Tox.DHT.Handlers
import qualified Network.Tox.DHT.Transport   as Tox
         ;import Network.Tox.DHT.Transport   (FriendRequest (..))
import Network.Tox.NodeId
import qualified Network.Tox.Onion.Handlers  as Tox
import qualified Network.Tox.Onion.Transport as Tox
         ;import Network.Tox.Onion.Transport (OnionData (..))
import Presence
import Presence
import System.IO
import Text.Read
import XMPPServer                            (ConnectionKey)
#ifdef THREAD_DEBUG
import Control.Concurrent.Lifted.Instrument
#else
import Control.Concurrent.Lifted
import GHC.Conc                  (labelThread)
#endif

xmppToTox :: Conduit XML.Event IO Tox.CryptoMessage
xmppToTox = do
    awaitForever (\_ -> return ())

toxToXmpp :: Monad m => Text -> Conduit Tox.CryptoMessage m XML.Event
toxToXmpp toxhost = do
    CL.sourceList $ XMPP.greet' "jabber:server" toxhost
    awaitForever $ \toxmsg -> do
        xmppInstantMessage "jabber:server" (Just toxhost) (T.pack $ show $ msgID toxmsg)

xmppInstantMessage :: Monad m => Text -> Maybe Text -> Text -> ConduitM i Event m ()
xmppInstantMessage namespace mfrom text = do
    let ns n = n { nameNamespace = Just namespace }
    C.yield $ EventBeginElement (ns "message")
               ((maybe id (\t->(attr "from" t:)) mfrom)
                 [attr "type" "normal" ])
    C.yield $   EventBeginElement (ns "body") []
    C.yield $     EventContent $ ContentText text
    C.yield $   EventEndElement (ns "body")
    C.yield $   EventBeginElement "{http://jabber.org/protocol/xhtml-im}html" []
    C.yield $     EventBeginElement "{http://www.w3.org/1999/xhtml}body" []
    C.yield $        EventBeginElement "{http://www.w3.org/1999/xhtml}p"
                       [ attr "style" "font-weight:bold; color:red" ]
    C.yield $          EventContent $ ContentText text
    C.yield $        EventEndElement "{http://www.w3.org/1999/xhtml}p"
    C.yield $     EventEndElement "{http://www.w3.org/1999/xhtml}body"
    C.yield $   EventEndElement "{http://jabber.org/protocol/xhtml-im}html"
    C.yield $ EventEndElement (ns "message")

key2jid :: Word32 -> PublicKey -> Text
key2jid nospam key = T.pack $ show $ NoSpamId nsp key
 where
    nsp = NoSpam nospam (Just sum)
    sum = nlo `xor` nhi `xor` xorsum key
    nlo = fromIntegral (0x0FFFF .&. nospam) :: Word16
    nhi = fromIntegral (0x0FFFF .&. (nospam `shiftR` 16)) :: Word16

type JabberClients = Map.Map ConnectionKey PerClient

data PerClient = PerClient
    { pcDeliveredFRs :: TVar (Set.Set Tox.FriendRequest)
    }

initPerClient :: STM PerClient
initPerClient = do
    frs <- newTVar Set.empty
    return PerClient
        { pcDeliveredFRs = frs
        }

data ToxToXMPP = ToxToXMPP
    { txAnnouncer :: Announcer
    , txAccount   :: Account JabberClients
    , txPresence  :: PresenceState
    , txTox       :: Tox JabberClients
    }

dispatch :: ToxToXMPP -> ContactEvent -> IO ()
dispatch tx (SessionEstablished theirKey) = stopConnecting tx theirKey
dispatch tx (SessionTerminated theirKey)  = startConnecting tx theirKey
dispatch tx (AddrChange   theirkey saddr)                    = return () -- todo
dispatch tx (PolicyChange theirkey TryingToConnect         ) = startConnecting tx theirkey
dispatch tx (PolicyChange theirkey policy                  ) = stopConnecting tx theirkey
dispatch tx (OnionRouted  theirkey (OnionDHTPublicKey pkey)) = return () -- todo
dispatch tx (OnionRouted  theirkey (OnionFriendRequest fr) ) = do
    let ToxToXMPP { txAnnouncer = acr
                  , txAccount   = acnt
                  , txPresence  = st } = tx
    k2c <- atomically $ do
        refs <- readTVar (accountExtra acnt)
        k2c <- Map.intersectionWith (,) refs <$> readTVar (keyToChan st)
        clients <- readTVar (clients st)
        return $ Map.intersectionWith (,) k2c clients
    -- TODO: Below we're using a hard coded default as their jabber user id.
    -- This isn't the right thing, but we don't know their user-id.  Perhaps
    -- there should be a way to parse it out of the friend request text.  Maybe
    -- after a zero-termination, or as visible text (nospam:...).
    let default_nospam = 0x6a7a27fc -- big-endian base64: anon/A==
        theirjid = key2jid default_nospam theirkey
    forM_ k2c $ \((PerClient{pcDeliveredFRs},conn),client) -> do
        alreadyDelivered <- atomically $ do
            frs <- readTVar pcDeliveredFRs
            writeTVar pcDeliveredFRs $ Set.insert fr frs
            return $ Set.member fr frs
        when (not alreadyDelivered) $ do
        self <- localJID (clientUser client) (clientProfile client) (clientResource client)
        ask <- presenceSolicitation theirjid self
        -- TODO Send friend-request text as an instant message or at least
        -- embed it in the stanza as a <status> element.
        sendModifiedStanzaToClient ask (connChan conn)

interweave :: [a] -> [a] -> [a]
interweave []     ys = ys
interweave (x:xs) ys = x : interweave ys xs

akeyDHTKeyShare announcer me them = atomically $ do
    packAnnounceKey announcer $ "dhtkey:" ++ (take 8 $ show me) ++ ":" ++ show (key2id them)
akeyConnect announcer me them = atomically $ do
    packAnnounceKey announcer $ "connect:" ++ (take 8 $ show me) ++ ":" ++ show (key2id them)

startConnecting0 :: ToxToXMPP -> PublicKey -> Contact -> IO ()
startConnecting0 tx them contact = do
        let ToxToXMPP { txTox       = tox
                      , txAnnouncer = announcer
                      , txAccount   = acnt     } = tx
        let nearNodes nid = do
                bkts4 <- readTVar $ routing4 $ toxRouting tox
                bkts6 <- readTVar $ routing6 $ toxRouting tox
                let nss = map (R.kclosest (searchSpace (toxQSearch tox)) searchK nid)
                              [bkts4,bkts6]
                return $ foldr interweave [] nss
        wanted <- atomically $ (==Just TryingToConnect) <$> readTVar (contactPolicy contact)
        when wanted $ do
            let pub = toPublic $ userSecret acnt
                me  = key2id pub
            akey <- akeyDHTKeyShare announcer me them
                    -- We send this packet every 30 seconds if there is more
                    -- than one peer (in the 8) that says they our friend is
                    -- announced on them. This packet can also be sent through
                    -- the DHT module as a DHT request packet (see DHT) if we
                    -- know the DHT public key of the friend and are looking
                    -- for them in the DHT but have not connected to them yet.
                    -- 30 second is a reasonable timeout to not flood the
                    -- network with too many packets while making sure the
                    -- other will eventually receive the packet. Since packets
                    -- are sent through every peer that knows the friend,
                    -- resending it right away without waiting has a high
                    -- likelihood of failure as the chances of packet loss
                    -- happening to all (up to to 8) packets sent is low.
                    --
            scheduleSearch announcer
                     akey
                     (SearchMethod   (toxQSearch tox)
                                     (\theirkey rendezvous -> do
                                        dkey <- Tox.getContactInfo tox
                                        sendMessage
                                            (Tox.toxToRoute tox)
                                            (Tox.AnnouncedRendezvous theirkey rendezvous)
                                            (pub,Tox.OnionDHTPublicKey dkey))
                                     nearNodes
                                     (key2id them)
                                     30) -- every 30 seconds
                     pub

startConnecting :: ToxToXMPP -> PublicKey -> IO ()
startConnecting tx them = do
    mc <- atomically $ HashMap.lookup (key2id them)
                        <$> readTVar (contacts $ txAccount tx)
    forM_ mc $ startConnecting0 tx them


stopConnecting :: ToxToXMPP -> PublicKey -> IO ()
stopConnecting ToxToXMPP{txAnnouncer=announcer,txAccount=acnt} them = do
    hPutStrLn stderr $ "STOP CONNECTING " ++ show (key2id them)
    let pub = toPublic $ userSecret acnt
        me  = key2id pub
    akey <- akeyDHTKeyShare announcer me them
    cancel announcer akey

forkAccountWatcher :: Account JabberClients -> Tox JabberClients -> PresenceState -> Announcer -> IO ThreadId
forkAccountWatcher acc tox st announcer = forkIO $ do
    myThreadId >>= flip labelThread ("tox-xmpp:"
                                      ++ show (key2id $ toPublic $ userSecret acc))
    (chan,cs) <- atomically $ do
                chan <- dupTChan $ eventChan acc -- duplicate broadcast channel for reading.
                contacts <- readTVar (contacts acc)
                return (chan,contacts)
    let tx = ToxToXMPP { txAnnouncer = announcer
                       , txAccount   = acc
                       , txPresence  = st
                       , txTox       = tox
                       }
    forM_ (HashMap.toList cs) $ \(them,c) -> do
        startConnecting0 tx (id2key them) c

    -- Loop endlessly until accountExtra is null.
    fix $ \loop -> do
    mev <- atomically $
            (Just <$> readTChan chan)
            `orElse` do
                refs <- readTVar $ accountExtra acc
                check $ Map.null refs
                return Nothing

    forM_ mev $ \ev -> dispatch tx ev >> loop

    cs <- atomically $ readTVar (contacts acc)
    forM_ (HashMap.toList cs) $ \(them,c) -> do
        stopConnecting tx (id2key them)


toxQSearch :: Tox extra -> Search Tox.NodeId (IP, PortNumber) Nonce32 Tox.NodeInfo Tox.Rendezvous
toxQSearch tox = Tox.toxidSearch (Tox.onionTimeout tox) (Tox.toxCryptoKeys tox) (Tox.toxOnion tox)

toxAnnounceInterval :: POSIXTime
toxAnnounceInterval = 15