summaryrefslogtreecommitdiff
path: root/xmppServer.hs
blob: 4270f89c0a05a2404283f643e911bcd3d9773b39 (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
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
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE TupleSections #-}
import System.Posix.Signals
import Control.Concurrent.STM
import Control.Concurrent.STM.TMVar
import Control.Monad.Trans.Resource (runResourceT)
import Control.Monad.Trans
import Control.Monad.IO.Class (MonadIO, liftIO)
import Network.Socket
    ( addrAddress
    , getAddrInfo
    , defaultHints
    , addrFlags
    , AddrInfoFlag(AI_CANONNAME,AI_V4MAPPED,AI_NUMERICHOST)
    , SockAddr(..)
    )
import System.Endian (fromBE32)
import Data.List (nub, (\\) )
import Data.Monoid ( (<>) )
import qualified Data.Text as Text
import qualified Data.Text.IO as Text
import qualified Data.Text.Encoding as Text
import Control.Monad
import qualified Network.BSD as BSD
import qualified Data.Text as Text
import Data.Text (Text)
import qualified Data.Map as Map
import Data.Map (Map)
import Control.Exception ({-evaluate,-}handle,SomeException(..),bracketOnError,ErrorCall(..))
import System.IO.Error (isDoesNotExistError)
import System.Posix.User (getUserEntryForID,userName)
import qualified Data.ByteString.Lazy.Char8 as L
import qualified ConfigFiles
import Data.Maybe (maybeToList,listToMaybe,mapMaybe)
import Data.Bits
import Data.Int (Int8)

import TraversableT
import UTmp (ProcessID,users)
import LocalPeerCred
import XMPPServer

type UserName = Text
type ResourceName = Text

unsplitJID :: (Maybe UserName,Text,Maybe ResourceName) -> Text
unsplitJID (n,h,r) = username <> h <> resource
 where
    username = maybe "" (<>"@") n
    resource = maybe "" ("/"<>) r

splitJID :: Text -> (Maybe UserName,Text,Maybe ResourceName)
splitJID bjid = 
    let xs = splitAll '@' bjid
        ys = splitAll '/' (last xs)
        splitAll c bjid = take 1 xs0 ++ map (Text.drop 1) (drop 1 xs0)
            where xs0 = Text.groupBy (\x y-> y/=c) bjid
        server = head ys
        name = case xs of
                (n:s:_) -> Just n
                (s:_)   -> Nothing
        rsrc = case ys of
                (s:_:_) -> Just $ last ys
                _       -> Nothing
    in (name,server,rsrc)

isPeerKey :: ConnectionKey -> Bool
isPeerKey k = case k of { PeerKey {} -> True ; _ -> False }

isClientKey :: ConnectionKey -> Bool
isClientKey k = case k of { ClientKey {} -> True ; _ -> False }

textHostName = fmap Text.pack BSD.getHostName

localJID user resource = do
    hostname <- textHostName
    return $ user <> "@" <> hostname <> "/" <> resource

cf_available :: Int8
cf_available = 0x1
cf_interested :: Int8
cf_interested = 0x2

data ClientState = ClientState
    { clientResource :: Text
    , clientUser :: Text
    , clientPid :: Maybe ProcessID
    , clientStatus :: TVar (Maybe Stanza)
    , clientFlags :: Int8
    }

-- | True if the client has sent an initial presence
clientIsAvailable c  = clientFlags c .&. cf_available /= 0

-- | True if the client has requested a roster
clientIsInterested c = clientFlags c .&. cf_interested /= 0

data LocalPresence = LocalPresence
    { networkClients :: Map ConnectionKey ClientState
    -- TODO: loginClients
    }

data RemotePresence = RemotePresence
    { resources :: Map Text Stanza
    -- , localSubscribers :: Map Text ()
    -- ^ subset of clientsByUser who should be
    -- notified about this presence.
    }



pcSingletonNetworkClient key client =
    LocalPresence
    { networkClients = Map.singleton key client
    } 

pcInsertNetworkClient key client pc =
    pc { networkClients = Map.insert key client (networkClients pc) }

pcRemoveNewtworkClient key pc = if pcIsEmpty pc' then Nothing
                                                 else Just pc'
 where
    pc' = pc { networkClients = Map.delete key (networkClients pc) }

pcIsEmpty pc = Map.null (networkClients pc)


data PresenceState = PresenceState
    { clients :: TVar (Map ConnectionKey ClientState)
    , clientsByUser :: TVar (Map Text LocalPresence)
    , remotesByPeer :: TVar (Map ConnectionKey
                                 (Map UserName
                                      RemotePresence))
    , associatedPeers :: TVar (Map SockAddr ())
    , server :: TMVar XMPPServer
    , keyToChan :: TVar (Map ConnectionKey Conn)
    }


make6mapped4 addr@(SockAddrInet6 {}) = addr
make6mapped4 addr@(SockAddrInet port a) = SockAddrInet6 port 0 (0,0,0xFFFF,fromBE32 a) 0

resolvePeer :: Text -> IO [SockAddr]
resolvePeer addrtext = do
        fmap (map $ make6mapped4 . addrAddress) $ 
            getAddrInfo (Just $ defaultHints { addrFlags = [ AI_CANONNAME, AI_V4MAPPED ]})
                    (Just $ Text.unpack $ strip_brackets addrtext)
                    (Just "5269")

strip_brackets s = 
    case Text.uncons s of
      Just ('[',t) -> Text.takeWhile (/=']') t
      _            -> s


getConsolePids :: PresenceState -> IO [(Text,ProcessID)]
getConsolePids state = do
    us <- UTmp.users
    return $ map (\(_,tty,pid)->(lazyByteStringToText tty,pid)) us

lazyByteStringToText = (foldr1 (<>) . map Text.decodeUtf8 . L.toChunks)
textToLazyByteString s = L.fromChunks [Text.encodeUtf8 s]

identifyTTY' ttypids uid inode = ttypid
 where ttypids' = map (\(tty,pid)->(L.fromChunks [Text.encodeUtf8 tty], pid)) ttypids
       ttypid = fmap textify $ identifyTTY ttypids' uid inode
       textify (tty,pid) = (fmap lazyByteStringToText tty, pid)

chooseResourceName state k addr desired = do
    muid <- getLocalPeerCred' addr
    (mtty,pid) <- getTTYandPID muid
    user <- getJabberUserForId muid
    status <- atomically $ newTVar Nothing
    let client = ClientState { clientResource = maybe "fallback" id mtty
                             , clientUser = user
                             , clientPid = pid
                             , clientStatus = status
                             , clientFlags = 0 }

    atomically $ do
        modifyTVar' (clients state) $ Map.insert k client
        modifyTVar' (clientsByUser state) $ flip Map.alter (clientUser client)
            $ \mb -> Just $ maybe (pcSingletonNetworkClient k client)
                                  (pcInsertNetworkClient k client)
                                  mb

    localJID (clientUser client) (clientResource client)
    
  where
    getTTYandPID muid = do
        -- us <- fmap (map (second fst) . Map.toList) . readTVarIO $ activeUsers state
        ttypids <- getConsolePids state
        -- let tailOf3 ((_,a),b) = (a,b)
        (t,pid) <- case muid of
                      Just (uid,inode) -> identifyTTY' ttypids uid inode
                      Nothing          -> return (Nothing,Nothing)
        let rsc = t `mplus` fmap ( ("pid."<>) . Text.pack . show ) pid
        return (rsc,pid)

    getJabberUserForId muid =
             maybe (return "nobody") 
                   (\(uid,_) -> 
                        handle (\(SomeException _) -> 
                                return . (<> "uid.") . Text.pack . show $ uid)
                          $ do
                             user <- fmap userName $ getUserEntryForID uid
                             return (Text.pack user)
                        )
                   muid

forClient state k fallback f = do
    mclient <- atomically $ do
        cs <- readTVar (clients state)
        return $ Map.lookup k cs
    maybe fallback f mclient

tellClientHisName state k = forClient state k fallback go
 where
    fallback  = localJID "nobody" "fallback"
    go client = localJID (clientUser client) (clientResource client)

toMapUnit xs = Map.fromList $ map (,()) xs

resolveAllPeers :: [Text] -> IO (Map SockAddr ())
resolveAllPeers hosts = fmap (toMapUnit . concat) $ Prelude.mapM (fmap (take 1) . resolvePeer) hosts


rosterGetStuff
  :: (L.ByteString -> IO [L.ByteString])
     -> PresenceState -> ConnectionKey -> IO [Text]
rosterGetStuff what state k = forClient state k (return [])
    $ \client -> do
    jids <- configText what (clientUser client)
    let hosts = map ((\(_,h,_)->h) . splitJID) jids
    addrs <- resolveAllPeers hosts 
    peers <- atomically $ readTVar (associatedPeers state)
    addrs <- return $ addrs `Map.difference` peers
    sv <- atomically $ takeTMVar $ server state
    -- Grok peers to associate with from the roster:
    forM_ (Map.keys addrs) $ \addr -> do
        putStrLn $ "new addr: "++show addr
        addPeer sv addr
    -- Update local set of associated peers
    atomically $ do
        writeTVar (associatedPeers state) (addrs `Map.union` peers)
        putTMVar (server state) sv
    return jids

rosterGetBuddies :: PresenceState -> ConnectionKey -> IO [Text]
rosterGetBuddies state k = rosterGetStuff ConfigFiles.getBuddies state k

rosterGetSolicited :: PresenceState -> ConnectionKey -> IO [Text]
rosterGetSolicited = rosterGetStuff ConfigFiles.getSolicited

rosterGetOthers :: PresenceState -> ConnectionKey -> IO [Text]
rosterGetOthers = rosterGetStuff ConfigFiles.getOthers

rosterGetSubscribers :: PresenceState -> ConnectionKey -> IO [Text]
rosterGetSubscribers = rosterGetStuff ConfigFiles.getSubscribers

data Conn = Conn { connChan :: TChan Stanza
                 , auxAddr :: SockAddr }

configText what u = fmap (map lazyByteStringToText)
                        $ what (textToLazyByteString u)

getBuddies' :: Text -> IO [Text]
getBuddies' = configText ConfigFiles.getBuddies
getSolicited' :: Text -> IO [Text]
getSolicited' = configText ConfigFiles.getSolicited

sendProbesAndSolicitations state k laddr chan = do
    -- get all buddies & solicited matching k for all users
    xs <- runTraversableT $ do
        cbu <- lift $ atomically $ readTVar $ clientsByUser state
        user <- liftT $ Map.keys cbu
        (isbud,getter) <- liftT [(True ,getBuddies'  )
                                ,(False,getSolicited')]
        bud  <- liftMT $ getter user
        let (u,h,r) = splitJID bud
        addr <- liftMT $ nub `fmap` resolvePeer h
        liftT $ guard (PeerKey addr == k)
        -- Note: Earlier I was tempted to do all the IO
        -- within the TraversableT monad.  That apparently
        -- is a bad idea.  Perhaps due to laziness and an
        -- unforced list?  Instead, we will return a list
        -- of (Bool,Text) for processing outside.
        return (isbud,u)
    -- XXX: The following O(n²) nub may be a little
    --      too onerous.
    forM_ (nub xs) $ \(isbud,u) -> do
        let make = if isbud then presenceProbe 
                            else presenceSolicitation
            toh = peerKeyToText k
            jid = unsplitJID (u,toh,Nothing)
            me = addrToText laddr
        stanza <- make me jid
        -- send probes for buddies, solicitations for solicited.
        putStrLn $ "probing "++show k++" for: " ++ show (isbud,jid)
        atomically $ writeTChan chan stanza
    -- reverse xs `seq` return ()

newConn state k addr outchan = do
    atomically $ modifyTVar' (keyToChan state)
        $ Map.insert k Conn { connChan = outchan
                            , auxAddr  = addr }
    when (isPeerKey k)
        $ sendProbesAndSolicitations state k addr outchan

eofConn state k = do
    atomically $ modifyTVar' (keyToChan state) $ Map.delete k
    case k of
        ClientKey {} -> do
            stanza <- makePresenceStanza "jabber:server" Nothing Offline
            informClientPresence state k stanza
        PeerKey {} -> do
            let h = peerKeyToText k
            jids <- atomically $ do
                rbp <- readTVar (remotesByPeer state)
                return $ do
                    umap <- maybeToList $ Map.lookup k rbp
                    (u,rp) <- Map.toList umap
                    r <- Map.keys (resources rp)
                    return $ unsplitJID (Just u, h, Just r)
            forM_ jids $ \jid -> do
            stanza <- makePresenceStanza "jabber:client" (Just jid) Offline
            informPeerPresence state k stanza

{-
rewriteJIDForClient1:: Text -> IO (Maybe ((Maybe Text,Text,Maybe Text),SockAddr))
rewriteJIDForClient1 jid = do
    let (n,h,r) = splitJID jid
    maddr <- fmap listToMaybe $ resolvePeer h
    flip (maybe $ return Nothing) maddr $ \addr -> do
        h' <- peerKeyToResolvedName (PeerKey addr)
        return $ Just ((n,h',r), addr)
-}

parseAddress :: Text -> IO (Maybe SockAddr)
parseAddress addr_str = do
    info <- getAddrInfo (Just $ defaultHints { addrFlags = [ AI_NUMERICHOST ] }) 
                        (Just . Text.unpack $ addr_str) 
                        (Just "0")
    return . listToMaybe $ map addrAddress info

todo = error "Unimplemented"


-- | for example:  2001-db8-85a3-8d3-1319-8a2e-370-7348.ipv6-literal.net
ip6literal :: Text -> Text
ip6literal addr = Text.map dash addr <> ".ipv6-literal.net"
 where
    dash ':' = '-'
    dash x   = x

withPort (SockAddrInet _ a)      port = SockAddrInet (toEnum port) a
withPort (SockAddrInet6 _ a b c) port = SockAddrInet6 (toEnum port) a b c

-- | The given address is taken to be the local address for the socket this JID
-- came in on.  The returned JID parts are suitable for unsplitJID to create a
-- valid JID for communicating to a client.  The returned Bool is True when the
-- host part refers to this local host (i.e. it equals the given SockAddr).
rewriteJIDForClient :: SockAddr -> Text -> IO (Bool,(Maybe Text,Text,Maybe Text))
rewriteJIDForClient laddr jid = do
    let (n,h,r) = splitJID jid
    maddr <- parseAddress (strip_brackets h)
    flip (maybe $ return (False,(n,ip6literal h,r))) maddr $ \addr -> do
    let mine =  laddr `withPort` 0  == addr `withPort` 0
    h' <- if mine then textHostName
                  else peerKeyToResolvedName (PeerKey addr)
    return (mine,(n,h',r))

multiplyJIDForClient :: SockAddr -> Text -> IO (Bool,[(Maybe Text,Text,Maybe Text)])
multiplyJIDForClient laddr jid = do
    let (n,h,r) = splitJID jid
    maddr <- parseAddress (strip_brackets h)
    flip (maybe $ return (False,[(n,ip6literal h,r)])) maddr $ \addr -> do
    let mine =  laddr `withPort` 0  == addr `withPort` 0
    names <- if mine then fmap (:[]) textHostName
                     else peerKeyToResolvedNames (PeerKey addr)
    return (mine,map (\h' -> (n,h',r)) names)


addrTextToKey h = do
    maddr <- parseAddress (strip_brackets h)
    return (fmap PeerKey maddr)

guardPortStrippedAddress h laddr = do
    maddr <- fmap (fmap (`withPort` 0)) $ parseAddress (strip_brackets h)
    let laddr' = laddr `withPort` 0
    return $ maddr >>= guard . (==laddr')


-- | Accepts a textual representation of a domainname
-- JID suitable for client connections, and returns the
-- coresponding ipv6 address JID suitable for peers paired
-- with a SockAddr with the address part of that JID in
-- binary form.  If no suitable address could be resolved
-- for the given name, Nothing is returned.
rewriteJIDForPeer :: Text -> IO (Maybe (Text,SockAddr))
rewriteJIDForPeer jid = do
    let (n,h,r) = splitJID jid
    maddr <- fmap listToMaybe $ resolvePeer h
    return $ flip fmap maddr $ \addr ->
        let h' = addrToText addr
            to' = unsplitJID (n,h',r)
        in (to',addr)

-- | deliver <message/> or error stanza
deliverMessage state fail msg = 
    case stanzaOrigin msg of
      NetworkOrigin senderk@(ClientKey {}) _ -> do
        -- Case 1.  Client -> Peer
        mto <- do
            flip (maybe $ return Nothing) (stanzaTo msg) $ \to -> do
            rewriteJIDForPeer to
        flip (maybe fail {- reverse lookup failure -})
             mto
            $ \(to',addr) -> do
        let k = PeerKey addr
        chans <- atomically $ readTVar (keyToChan state)
        flip (maybe fail) (Map.lookup k chans) $ \(Conn { connChan=chan
                                                        , auxAddr=laddr }) -> do
        (n,r) <- forClient state senderk (return (Nothing,Nothing))
                        $ \c -> return (Just (clientUser c), Just (clientResource c))
        -- original 'from' address is discarded.
        let from' = unsplitJID (n,addrToText laddr,r)
        -- dup <- atomically $ cloneStanza (msg { stanzaTo=Just to', stanzaFrom=Just from' })
        let dup = (msg { stanzaTo=Just to', stanzaFrom=Just from' })
        sendModifiedStanzaToPeer dup chan
      NetworkOrigin senderk@(PeerKey {}) _ -> do
        key_to_chan <- atomically $ readTVar (keyToChan state)
        flip (maybe fail) (Map.lookup senderk key_to_chan)
            $ \(Conn { connChan=sender_chan
                     , auxAddr=laddr }) -> do
        flip (maybe fail) (stanzaTo msg) $ \to -> do
        (mine,(n,h,r)) <- rewriteJIDForClient laddr to
        if not mine then fail else do
        let to' = unsplitJID (n,h,r)
        from' <- do
            flip (maybe $ return Nothing) (stanzaFrom msg) $ \from -> do
            (_,trip) <- rewriteJIDForClient laddr from
            return . Just $ unsplitJID trip
        cmap <- atomically . readTVar $ clientsByUser state
        flip (maybe fail) n $ \n -> do
        flip (maybe fail) (Map.lookup n cmap) $ \presence_container -> do
        let ks = Map.keys (networkClients presence_container)
            chans = mapMaybe (flip Map.lookup key_to_chan) ks
        if null chans then fail else do
        forM_ chans $ \Conn { connChan=chan} -> do
        putStrLn $ "sending "++show (stanzaId msg)++" to clients "++show ks
        -- TODO: Cloning isn't really neccessary unless there are multiple
        -- destinations and we should probably transition to minimal cloning,
        -- or else we should distinguish between announcable stanzas and
        -- consumable stanzas and announcables use write-only broadcast
        -- channels that must be cloned in order to be consumed.
        -- For now, we are doing redundant cloning.
        dup <- cloneStanza (msg { stanzaTo=Just to'
                                , stanzaFrom=from' })
        sendModifiedStanzaToClient dup
                                  chan


setClientFlag state k flag = 
        atomically $ modifyTVar' (clients state)
            $ Map.adjust  
                (\c -> c { clientFlags = clientFlags c .|. flag })
                k

informSentRoster state k = setClientFlag state k cf_interested


subscribedPeers user = do
    jids <- configText ConfigFiles.getSubscribers user
    let hosts = map ((\(_,h,_)->h) . splitJID) jids
    fmap Map.keys $ resolveAllPeers hosts 

clientJID con client = unsplitJID ( Just $ clientUser client
                                  , addrToText $ auxAddr con
                                  , Just $ clientResource client)

-- | Send presence notification to subscribed peers.
-- Note that a full JID from address will be added to the
-- stanza if it is not present.
informClientPresence state k stanza = do
    dup <- cloneStanza stanza
    atomically $ do
        mb <- fmap (Map.lookup k) $ readTVar (clients state)
        flip (maybe $ return ()) mb $ \cstate -> do
        writeTVar (clientStatus cstate) $ Just dup
    forClient state k (return ()) $ \client -> do
    when (not $ clientIsAvailable client) $ do
        setClientFlag state k cf_available
        sendCachedPresence state k
    addrs <- subscribedPeers (clientUser client)
    ktc <- atomically $ readTVar (keyToChan state)
    let connected = mapMaybe (flip Map.lookup ktc . PeerKey) addrs
    forM_ connected $ \con -> do
    let from' = clientJID con client
    mto <- runTraversableT $ do
            to <- liftT $ stanzaTo stanza
            (to',_) <- liftMT $ rewriteJIDForPeer to
            return to'
    dup <- cloneStanza stanza
    sendModifiedStanzaToPeer dup { stanzaFrom = Just from'
                                 , stanzaTo = mto }
                             (connChan con)

informPeerPresence state k stanza = do
    -- Presence must indicate full JID with resource...
    putStrLn $ "xmppInformPeerPresence checking from address..."
    flip (maybe $ return ()) (stanzaFrom stanza) $ \from -> do
    let (muser,h,mresource) = splitJID from
    flip (maybe $ return ()) mresource       $ \resource -> do
    flip (maybe $ return ()) muser           $ \user -> do
    
    clients <- atomically $ do

        -- Update remotesByPeer...
        rbp <- readTVar (remotesByPeer state)
        let umap = maybe Map.empty id $ Map.lookup k rbp
            rp = case (presenceShow $ stanzaType stanza) of
                    Offline ->
                         maybe (Map.empty)
                               (Map.delete resource . resources)
                             $ Map.lookup user umap
                    _ -> maybe (Map.singleton resource stanza) 
                               (Map.insert resource stanza . resources )
                             $ Map.lookup user umap
            umap' = Map.insert user (RemotePresence rp) umap
        writeTVar (remotesByPeer state) $ Map.insert k umap' rbp
        -- TODO: Store or delete the stanza (remotesByPeer)
        
        -- all clients, we'll filter available/authorized later

        ktc <- readTVar (keyToChan state)
        runTraversableT $ do
        (ck,client) <- liftMT $ fmap Map.toList $ readTVar (clients state)
        con <- liftMaybe $ Map.lookup ck ktc 
        return (ck,con,client)
    putStrLn $ "xmppInformPeerPresence (length clients="++show (length clients)++")"
    forM_ clients $ \(ck,con,client) -> do
        -- (TODO: appropriately authorized clients only.)
        -- For now, all "available" clients (available = sent initial presence)
        when (clientIsAvailable client) $ do
        froms <- do
            let ClientKey laddr = ck
            (_,trip) <- multiplyJIDForClient laddr from
            return (map unsplitJID trip)
        putStrLn $ "sending to client: " ++ show (stanzaType stanza)
        forM_ froms $ \from' -> do
        dup <- cloneStanza stanza
        sendModifiedStanzaToClient (dup { stanzaFrom=Just from' })
                                   (connChan con)

answerProbe state k stanza chan = do
    -- putStrLn $ "answerProbe! " ++ show (stanzaType stanza)
    ktc <- atomically $ readTVar (keyToChan state)
    muser <- runTraversableT $ do
        to <- liftT $ stanzaTo stanza
        conn <- liftT $ Map.lookup k ktc
        let (mu,h,_) = splitJID to -- TODO: currently resource-id is ignored on presence
                                   --  probes.  Is this correct? Check the spec.
        liftMT $ guardPortStrippedAddress h (auxAddr conn)
        u <- liftT mu
        let ch = addrToText (auxAddr conn)
        return (u,conn,ch)

    flip (maybe $ return ()) muser $ \(u,conn,ch) -> do

    -- only subscribed peers should get probe replies
    addrs <- subscribedPeers u
    when (k `elem` map PeerKey addrs) $ do

    replies <- runTraversableT $ do
        cbu <- lift . atomically $ readTVar (clientsByUser state)
        lpres <- liftMaybe $ Map.lookup u cbu
        clientState <- liftT $ Map.elems (networkClients lpres)
        stanza <- liftIOMaybe $ atomically (readTVar (clientStatus clientState))
        stanza <- lift $ cloneStanza stanza
        let jid = unsplitJID (Just $ clientUser clientState
                             , ch
                             ,Just $ clientResource clientState)
        return stanza { stanzaFrom = Just jid }

    forM_ replies $ \reply -> do
        sendModifiedStanzaToPeer reply chan

    -- if no presence, send offline message
    when (null replies) $ do
        let jid = unsplitJID (Just u,ch,Nothing)
        pstanza <- makePresenceStanza "jabber:server" (Just jid) Offline
        atomically $ writeTChan (connChan conn) pstanza

sendCachedPresence state k = do
    forClient state k (return ()) $ \client -> do
    rbp <- atomically $ readTVar (remotesByPeer state)
    jids <- configText ConfigFiles.getBuddies (clientUser client)
    let hosts = map ((\(_,h,_)->h) . splitJID) jids
    addrs <- resolveAllPeers hosts 
    let onlines = rbp `Map.intersection` Map.mapKeys PeerKey addrs
        ClientKey laddr = k
    forM_ (Map.toList onlines) $ \(pk, umap) -> do
        forM_ (Map.toList umap) $ \(user,rp) -> do
        let h = peerKeyToText pk
        forM_ (Map.toList $ resources rp) $ \(resource,stanza) -> do
        let jid = unsplitJID (Just user,h,Just resource)
        (mine,js) <- multiplyJIDForClient laddr jid
        forM_ js $ \jid -> do
        let from' = unsplitJID jid
        dup <- cloneStanza stanza
        mcon <- atomically $ do ktc <- readTVar (keyToChan state)
                                return $ Map.lookup k ktc
        flip (maybe $ return ()) mcon $ \con -> do
        sendModifiedStanzaToClient (dup { stanzaFrom=Just from' })
                                   (connChan con)

    -- Note: relying on self peer connection to send
    -- send local buddies.
    return ()

addToRosterFile doit whose to addrs =
    modifyRosterFile doit whose to addrs True

removeFromRosterFile doit whose to addrs =
    modifyRosterFile doit whose to addrs False

modifyRosterFile doit whose to addrs bAdd = do
    let (mu,_,_) = splitJID to
        cmp jid = runTraversableT $ do
            let (mu,stored_h,mr) = splitJID (lazyByteStringToText jid)
            flip (maybe mzero) mr . const $ do
            flip (maybe mzero) mu $ \stored_u -> do
            flip (maybe $ return jid) mu $ \u -> do
            if stored_u /= u then return jid else do
            stored_addrs <- lift $ nub `fmap` resolvePeer stored_h
            if null (stored_addrs \\ addrs) then return jid else do
            mzero
    doit (textToLazyByteString whose)
         cmp
         (guard bAdd >> Just (textToLazyByteString to))

clientSubscriptionRequest :: PresenceState -> IO () -> ConnectionKey -> Stanza -> TChan Stanza -> IO ()
clientSubscriptionRequest state fail k stanza chan = do
    forClient state k fail $ \client -> do
    flip (maybe fail) (stanzaTo stanza) $ \to -> do
    putStrLn $ "Forwarding solictation to peer"
    let (mu,h,_) = splitJID to
    to <- return $ unsplitJID (mu,h,Nothing) -- delete resource
    flip (maybe fail) mu $ \u -> do
    addrs <- nub `fmap` resolvePeer h
    if null addrs then fail else do
    -- add to-address to from's solicited
    addToRosterFile ConfigFiles.modifySolicited (clientUser client) to addrs
    (ktc,ap) <- atomically $ 
        liftM2 (,) (readTVar $ keyToChan state)
                   (readTVar $ associatedPeers state)
    let dsts = Map.fromList $ map ((,()) . PeerKey) addrs
        cdsts = ktc Map.\\ dsts
    forM_ (Map.toList cdsts) $ \(pk,con) -> do
        -- if already connected, send solicitation ...
        let from = clientJID con client
        sendModifiedStanzaToPeer (stanza { stanzaTo = Just to
                                         , stanzaFrom = Just from })
                                 (connChan con)
    let addrm = Map.fromList (map (,()) addrs)
    when (not . Map.null $ addrm Map.\\ ap) $ do
        -- Add peer if we are not already associated ...
        sv <- atomically $ takeTMVar $ server state
        addPeer sv (head addrs)


resolvedFromRoster
  :: (L.ByteString -> IO [L.ByteString])
     -> UserName -> IO [(Maybe UserName, ConnectionKey)]
resolvedFromRoster doit u = do
    subs <- configText doit u
    runTraversableT $ do
            (mu,h,_) <- liftT $ splitJID `fmap` subs
            addr <- liftMT $ resolvePeer h
            return (mu,PeerKey addr)

peerSubscriptionRequest :: PresenceState -> IO () -> ConnectionKey -> Stanza -> TChan Stanza -> IO ()
peerSubscriptionRequest state fail k stanza chan = do
    putStrLn $ "Handling pending subscription from remote"
    flip (maybe fail) (stanzaFrom stanza) $ \from -> do
    flip (maybe fail) (stanzaTo stanza) $ \to -> do
    let (mto_u,h,_) = splitJID to
        (mfrom_u,from_h,_) = splitJID from
    to <- return $ unsplitJID (mto_u,h,Nothing) -- delete resource
    from <- return $ unsplitJID (mfrom_u,from_h,Nothing) -- delete resource
    ktc <- atomically . readTVar $ keyToChan state
    flip (maybe fail) (Map.lookup k ktc)
         $ \Conn { auxAddr=laddr } -> do
    (mine,totup) <- rewriteJIDForClient laddr to
    if not mine then fail else do
    (_,fromtup) <- rewriteJIDForClient laddr from
    flip (maybe fail) mto_u $ \u -> do
    flip (maybe fail) mfrom_u $ \from_u -> do
    resolved_subs <- resolvedFromRoster ConfigFiles.getSubscribers u
    let already_subscribed = elem (mfrom_u,k) resolved_subs
    --    Section 8 says (for presence of type "subscribe", the server MUST
    --    adhere to the rules defined under Section 3 and summarized under
    --    see Appendix A. (pariticularly Appendex A.3.1)
    if already_subscribed
     then do
        -- contact ∈ subscribers --> SHOULD NOT, already handled
        -- already subscribed, reply and quit
        -- (note: swapping to and from for reply)
        reply <- makeInformSubscription "jabber:server" to from True
        sendModifiedStanzaToPeer reply chan
     else do

    -- TODO: if peer-connection is to self, then auto-approve local user.
    
    -- Catch exception in case the user does not exist
    handle (\e -> let _ = isDoesNotExistError e in fail) $ do
    -- add from-address to to's pending
    addrs <- resolvePeer from_h
    already_pending <- addToRosterFile ConfigFiles.modifyPending u from addrs

    -- contact ∉ subscribers & contact ∈ pending --> SHOULD NOT
    when (not already_pending) $ do
    -- contact ∉ subscribers & contact ∉ pending --> MUST
    mlp <- atomically $ do
            cmap <- readTVar $ clientsByUser state
            return $ Map.lookup u cmap
    let ks = do lp <- maybeToList mlp
                Map.keys (networkClients lp)
        chans = mapMaybe (flip Map.lookup ktc) ks
    forM_ chans $ \Conn { connChan=chan } -> do
    -- send to clients
    -- TODO: interested/available clients only?
    dup <- cloneStanza stanza
    sendModifiedStanzaToClient dup { stanzaFrom = Just $ unsplitJID fromtup
                                   , stanzaTo = Just $ unsplitJID totup }
                               chan


clientInformSubscription state fail k stanza = do
    forClient state k fail $ \client -> do
    flip (maybe fail) (stanzaTo stanza) $ \to -> do
    putStrLn $ "clientInformSubscription"
    let (mu,h,mr) = splitJID to
    addrs <- resolvePeer h
    -- remove from pending
    buds <- resolvedFromRoster ConfigFiles.getBuddies (clientUser client)
    let is_buddy = not . null $ map ((mu,) . PeerKey) addrs \\ buds
    removeFromRosterFile ConfigFiles.modifyPending (clientUser client) to addrs
    let (relationship,addf,remf) =
         case stanzaType stanza of
           PresenceInformSubscription True ->
                ( if is_buddy then "both"
                              else "from"
                , ConfigFiles.modifySubscribers
                , ConfigFiles.modifyOthers )
           _ -> ( if is_buddy then "to"
                              else "none"
                , ConfigFiles.modifyOthers
                , ConfigFiles.modifySubscribers )
    addToRosterFile      addf (clientUser client) to addrs
    removeFromRosterFile remf (clientUser client) to addrs

    -- send roster update to clients
    (clients,ktc) <- atomically $ do
        cbu <- readTVar (clientsByUser state)
        let mlp = mu >>= flip Map.lookup cbu
        let cs = maybe [] (Map.toList . networkClients) mlp
        ktc <- readTVar (keyToChan state)
        return (cs,ktc)
    forM_ clients $ \(ck, client) -> do
        when (clientIsInterested client) $ do
        flip (maybe $ return ()) (Map.lookup ck ktc) $ \con -> do
        hostname <- textHostName
        -- TODO: Should cjid include the resource?
        let cjid = unsplitJID (mu, hostname, Nothing)
        update <- makeRosterUpdate cjid to relationship
        sendModifiedStanzaToClient update (connChan con)

    -- notify peer
    let dsts = Map.fromList $ map ((,()) . PeerKey) addrs
        cdsts = ktc Map.\\ dsts
    forM_ (Map.toList cdsts) $ \(pk,con) -> do
        let from = clientJID con client
            to' = unsplitJID (mu, peerKeyToText pk, Nothing)
        dup <- cloneStanza stanza
        sendModifiedStanzaToPeer (dup { stanzaTo = Just $ to'
                                      , stanzaFrom = Just from })
                                 (connChan con)
    
peerInformSubscription state fail k stanza = do
    putStrLn $ "TODO: peerInformSubscription"
    -- remove from solicited
    -- if it was in solicited:
    --   approval:
    --     add to buddies
    --     remove from others
    --   rejection:
    --     remove from buddies
    --     add to others
    --   send update to clients
    return ()

main = runResourceT $ do
    state <- liftIO . atomically $ do
        clients <- newTVar Map.empty
        clientsByUser <- newTVar Map.empty
        remotesByPeer <- newTVar Map.empty
        associatedPeers <- newTVar Map.empty
        xmpp <- newEmptyTMVar
        keyToChan <- newTVar Map.empty
        return PresenceState
            { clients = clients
            , clientsByUser = clientsByUser
            , remotesByPeer = remotesByPeer
            , associatedPeers = associatedPeers
            , keyToChan = keyToChan
            , server = xmpp
            }
    sv <- xmppServer
        XMPPServerParameters
        { xmppChooseResourceName = chooseResourceName state
        , xmppTellClientHisName = tellClientHisName state
        , xmppTellMyNameToClient = textHostName
        , xmppTellMyNameToPeer = \addr -> return $ addrToText addr
        , xmppTellPeerHisName = return . peerKeyToText
        , xmppTellClientNameOfPeer = peerKeyToResolvedName
        , xmppNewConnection = newConn state
        , xmppEOF = eofConn state
        , xmppRosterBuddies = rosterGetBuddies state
        , xmppRosterSubscribers = rosterGetSubscribers state
        , xmppRosterSolicited = rosterGetSolicited state
        , xmppRosterOthers = rosterGetOthers state
        , xmppSubscribeToRoster = informSentRoster state
        , xmppDeliverMessage = deliverMessage state
        , xmppInformClientPresence = informClientPresence state
        , xmppInformPeerPresence = informPeerPresence state
        , xmppAnswerProbe = answerProbe state
        , xmppClientSubscriptionRequest = clientSubscriptionRequest state
        , xmppPeerSubscriptionRequest = peerSubscriptionRequest state
        , xmppClientInformSubscription = clientInformSubscription state
        , xmppPeerInformSubscription = peerInformSubscription state
        }
    liftIO $ do
    atomically $ putTMVar (server state) sv

    quitVar <- newEmptyTMVarIO
    installHandler sigTERM (CatchOnce (atomically $ putTMVar quitVar True)) Nothing
    installHandler sigINT (CatchOnce (atomically $ putTMVar quitVar True)) Nothing
    quitMessage <- atomically $ takeTMVar quitVar

    putStrLn "goodbye."
    return ()