summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
-rw-r--r--.gitignore1
-rw-r--r--ConduitServer.hs48
-rw-r--r--Connection.hs58
-rw-r--r--Control/Concurrent/STM/StatusCache.hs160
-rw-r--r--Control/Concurrent/STM/UpdateStream.hs169
-rw-r--r--Data/BitSyntax.hs429
-rw-r--r--PingMachine.hs113
-rw-r--r--Presence/ByteStringOperators.hs50
-rw-r--r--Presence/ClientState.hs34
-rw-r--r--Presence/ConfigFiles.hs130
-rw-r--r--Presence/ConnectionKey.hs10
-rw-r--r--Presence/ConsoleWriter.hs411
-rw-r--r--Presence/ControlMaybe.hs29
-rw-r--r--Presence/DNSCache.hs270
-rw-r--r--Presence/EventUtil.hs83
-rw-r--r--Presence/FGConsole.hs67
-rw-r--r--Presence/GetHostByAddr.hs77
-rw-r--r--Presence/IDMangler.hs68
-rw-r--r--Presence/LocalPeerCred.hs234
-rw-r--r--Presence/LockedChan.hs78
-rw-r--r--Presence/Logging.hs25
-rw-r--r--Presence/Nesting.hs88
-rw-r--r--Presence/Paths.hs62
-rw-r--r--Presence/PeerResolve.hs39
-rw-r--r--Presence/Presence.hs1041
-rw-r--r--Presence/Server.hs826
-rw-r--r--Presence/SockAddr.hs13
-rw-r--r--Presence/UTmp.hs249
-rw-r--r--Presence/Util.hs59
-rw-r--r--Presence/XMPP.hs1461
-rw-r--r--Presence/XMPPServer.hs1856
-rw-r--r--Presence/monitortty.c182
-rw-r--r--Setup.hs96
-rw-r--r--TraversableT.hs94
-rwxr-xr-xb16
-rwxr-xr-xbp20
-rw-r--r--consolation.hs186
-rw-r--r--dht-client.cabal50
-rw-r--r--doc/rfc6120.html9372
-rw-r--r--doc/rfc6121.html4738
-rw-r--r--examples/dhtd.hs165
-rwxr-xr-xg25
-rwxr-xr-xgi14
-rwxr-xr-xgraphdeps19
-rw-r--r--modules.svg337
-rw-r--r--nalias.hs70
-rw-r--r--nalias2.hs18
-rwxr-xr-xp28
-rw-r--r--presence.cabal.bak156
-rw-r--r--presence.service11
-rw-r--r--pwrite.hs105
-rw-r--r--simplechat.hs66
-rw-r--r--stack.yaml35
-rwxr-xr-xt14
-rw-r--r--test-server.hs541
-rw-r--r--whosocket.hs60
-rw-r--r--xmppServer.hs47
57 files changed, 24623 insertions, 80 deletions
diff --git a/.gitignore b/.gitignore
index 7a23ede7..2c40503c 100644
--- a/.gitignore
+++ b/.gitignore
@@ -15,3 +15,4 @@ upload-docs
15*.ps 15*.ps
16*.prof 16*.prof
17res/rtorrent-sessiondir 17res/rtorrent-sessiondir
18/.stack-work/
diff --git a/ConduitServer.hs b/ConduitServer.hs
new file mode 100644
index 00000000..0838ce26
--- /dev/null
+++ b/ConduitServer.hs
@@ -0,0 +1,48 @@
1{-# LANGUAGE OverloadedStrings #-}
2module Main where
3
4import Data.Conduit.Binary
5import Data.Conduit.Network
6import Data.Conduit
7import qualified Data.Conduit.List as CL
8import qualified Data.ByteString.Char8 as S
9
10import Network.Socket (Family(..))
11import Data.HList
12import ServerC
13
14{-
15data AppData m = AppData
16 { appSource :: Source m ByteString
17 , appSink :: Sink ByteString m ()
18 , appSockAddr :: SockAddr
19 , appLocalAddr :: Maybe SockAddr
20 }
21-}
22
23-- handleConnection will simply output everything
24-- it sees from the connection to the terminal
25handleConnection :: AppData IO -> IO ()
26handleConnection appdata = do
27 sourceLbs "<stream>\n" $$ appSink appdata -- send bytestring
28 appSource appdata $$ CL.mapM_ S.putStrLn -- display inbound bytestring
29
30mainOld = do
31 -- Listen to port 5222 and invoke handleConnection on every
32 -- inbound connection.
33 runTCPServer (serverSettings 5222 HostAny) handleConnection
34 return ()
35
36
37
38
39handleC st src snk = do
40 sourceLbs "<stream>\n" $$ snk
41 src $$ CL.mapM_ S.putStrLn
42
43mainC = do
44 doServer (AF_INET .*. 5222 .*. HNil) handleC
45 _ <- getLine
46 return ()
47
48main = mainC
diff --git a/Connection.hs b/Connection.hs
new file mode 100644
index 00000000..3287bc1b
--- /dev/null
+++ b/Connection.hs
@@ -0,0 +1,58 @@
1{-# LANGUAGE DeriveFunctor #-}
2module Connection where
3
4import Control.Applicative
5import Control.Arrow
6import Control.Concurrent.STM
7import qualified Data.Map as Map
8 ;import Data.Map (Map)
9
10import PingMachine
11
12data Status status
13 = Dormant
14 | InProgress status
15 | Established
16 deriving Functor
17
18data Policy
19 = RefusingToConnect
20 | OpenToConnect
21 | TryingToConnect
22
23data Connection status = Connection
24 { connStatus :: STM (Status status)
25 , connPolicy :: STM Policy
26 , connPingLogic :: PingMachine
27 }
28 deriving Functor
29
30data Manager status k = Manager
31 { setPolicy :: k -> Policy -> IO ()
32 , connections :: STM (Map k (Connection status))
33 , stringToKey :: String -> Maybe k
34 , showProgress :: status -> String
35 , showKey :: k -> String
36 }
37
38showStatus :: Manager status k -> Status status -> String
39showStatus mgr Dormant = "dormant"
40showStatus mgr Established = "established"
41showStatus mgr (InProgress s) = "in progress ("++showProgress mgr s++")"
42
43
44addManagers :: (Ord kA, Ord kB) =>
45 Manager statusA kA
46 -> Manager statusB kB
47 -> Manager (Either statusA statusB) (Either kA kB)
48addManagers mgrA mgrB = Manager
49 { setPolicy = either (setPolicy mgrA) (setPolicy mgrB)
50 , connections = do
51 as <- Map.toList <$> connections mgrA
52 bs <- Map.toList <$> connections mgrB
53 return $ Map.fromList $ map (Left *** fmap Left) as ++ map (Right *** fmap Right) bs
54 , stringToKey = \str -> Left <$> stringToKey mgrA str
55 <|> Right <$> stringToKey mgrB str
56 , showProgress = either (showProgress mgrA) (showProgress mgrB)
57 , showKey = either (showKey mgrA) (showKey mgrB)
58 }
diff --git a/Control/Concurrent/STM/StatusCache.hs b/Control/Concurrent/STM/StatusCache.hs
new file mode 100644
index 00000000..d1c977ae
--- /dev/null
+++ b/Control/Concurrent/STM/StatusCache.hs
@@ -0,0 +1,160 @@
1---------------------------------------------------------------------------
2-- |
3-- Module : Control.Concurrent.STM.StatusCache
4--
5--
6-- Maintainer : joe@jerkface.net
7-- Stability : experimental
8--
9-- Motivation: Suppose you must communicate state changes over a stream. If
10-- the stream is consumed slowly, then it may occur that backlogged state
11-- changes are obsoleted by newer changes in state. In this case, it is
12-- desirable to discard the obsolete messages from the stream.
13--
14-- A streamed status message might be very large, and it would be wasteful in
15-- both time and space, to treat it as a monolithic blob that must be built
16-- completely before it can be sent. Therefore, we require that each message
17-- consist of a stream of smaller chunks of type @x@ and we require predicates
18-- that indicate when a chunk starts a new message and when it ends a message.
19--
20-- In the folowing example, our chunk type is Char and complete messages are
21-- delimited by the characters '(' and ')'. We process the input stream
22-- \"(aaa(a))(bb)(cc(c)cc)\" first with a delayed processor and then again with
23-- an efficient dedicated thread. The result follows:
24--
25-- > Backlogged consumer: (cc(c)cc)
26-- > Fast consumer: (aaa(a))(bb)(cc(c)cc)
27--
28-- The complete source code:
29--
30-- > import Control.Monad (when, forever, (>=>))
31-- > import Control.Monad.STM (atomically)
32-- > import Control.Concurrent (forkIO, threadDelay)
33-- > import System.IO (hFlush, stdout)
34-- > import qualified Control.Concurrent.STM.StatusCache as Cache
35-- >
36-- > main = do q <- atomically $ Cache.new (== '(') (==')')
37-- > backlog q "(aaa(a))(bb)(cc(c)cc)"
38-- > fast q "(aaa(a))(bb)(cc(c)cc)"
39-- >
40-- > while pred body = pred >>= flip when (body >> while pred body)
41-- >
42-- > backlog q xs = do putStr $ "Backlogged consumer: "
43-- > mapM_ (atomically . Cache.push q) xs
44-- > while (atomically $ fmap not $ Cache.isEmpty q) $ do
45-- > c <- atomically $ Cache.pull q
46-- > putChar c
47-- > putStrLn ""
48-- > hFlush stdout
49-- >
50-- > fast q xs = do putStr "Fast consumer: "
51-- > forkIO $ forever $ do
52-- > c <- atomically $ Cache.pull q
53-- > putChar c
54-- > hFlush stdout
55-- > mapM_ (atomically . Cache.push q >=> const (threadDelay 10000))
56-- > xs
57-- > putStrLn ""
58--
59-- As shown above, it is intended that this module be imported qualified.
60--
61{-# LANGUAGE DoAndIfThenElse #-}
62module Control.Concurrent.STM.StatusCache
63 ( StatusCache
64 , new
65 , push
66 , pull
67 , pullDepth
68 , isStopper
69 , isStarter
70 , isEmpty
71 ) where
72import Control.Monad
73import Control.Monad.STM
74import Control.Concurrent.STM.TVar
75import Control.Concurrent.STM.TChan
76
77data StatusCache x =
78 StatusCache { feed :: TVar (TChan x)
79 , cache :: TVar (TChan x)
80 , feedFlag :: TVar Bool
81 , pushDepth :: TVar Int
82 , pullDepth :: TVar Int -- ^ current nesting depth of next-to-pull data
83 , isStarter :: x -> Bool -- ^ True if the given chunk begins a message.
84 , isStopper :: x -> Bool -- ^ True if the given chunk ends a message.
85 }
86
87-- | @new isStart isStop@
88--
89-- The @isStart@ and @isStop@ predicates indicate when an element
90-- begins or ends a message.
91new :: (x -> Bool) -> (x -> Bool) -> STM (StatusCache x)
92new isStart isStop = do
93 feed <- newTChan >>= newTVar
94 cache <- newTChan >>= newTVar
95 flag <- newTVar True
96 pushd <- newTVar 0
97 pulld <- newTVar 0
98 return StatusCache { feed = feed
99 , cache = cache
100 , feedFlag = flag
101 , pushDepth = pushd
102 , pullDepth = pulld
103 , isStarter = isStart
104 , isStopper = isStop
105 }
106
107
108-- | Pull off a chunk from the 'StatusCache' for processing.
109--
110-- If chunks are not pulled off quickly, they may be obsoleted
111-- and discarded when new messages are 'push'ed.
112pull :: StatusCache x -> STM x
113pull q = do
114 hasCache <- readTVar (feedFlag q)
115 exhausted <- readTVar (feed q) >>= isEmptyTChan
116 when (hasCache && exhausted) $ do
117 next <- newTChan >>= swapTVar (cache q)
118 writeTVar (feedFlag q) False
119 writeTVar (feed q) next
120 chan <- readTVar $ feed q
121 exhausted <- isEmptyTChan chan
122 if exhausted then retry
123 else do
124 v <- readTChan chan
125 when (isStarter q v) $ do
126 depth <- readTVar (pullDepth q)
127 modifyTVar' (pullDepth q) (+1)
128 when (depth==0)
129 $ writeTVar (feedFlag q) False
130 when (isStopper q v)
131 $ modifyTVar' (pullDepth q) (subtract 1)
132 return v
133
134-- | Enqueue a chunk into the 'StatusCache'.
135push :: StatusCache a -> a -> STM ()
136push q v = do
137 shouldCache <- readTVar (feedFlag q)
138 depth <- readTVar (pushDepth q)
139 when (isStopper q v) $ do
140 modifyTVar' (pushDepth q) (subtract 1)
141 when (depth==0)
142 $ writeTVar (feedFlag q) True
143 when (isStarter q v)
144 $ modifyTVar' (pushDepth q) (+1)
145 chan <-
146 if shouldCache then do
147 when (depth==0 && isStarter q v)
148 $ newTChan
149 >>= writeTVar (cache q)
150 readTVar $ cache q
151 else do
152 readTVar $ feed q
153 writeTChan chan v
154
155-- | True when the 'StatusCache' is completely exhuasted.
156isEmpty :: StatusCache x -> STM Bool
157isEmpty q = do
158 empty_feed <- readTVar (feed q) >>= isEmptyTChan
159 empty_cache <- readTVar (cache q) >>= isEmptyTChan
160 return $ empty_feed && empty_cache
diff --git a/Control/Concurrent/STM/UpdateStream.hs b/Control/Concurrent/STM/UpdateStream.hs
new file mode 100644
index 00000000..b01fc0bc
--- /dev/null
+++ b/Control/Concurrent/STM/UpdateStream.hs
@@ -0,0 +1,169 @@
1---------------------------------------------------------------------------
2-- |
3-- Module : Control.Concurrent.STM.UpdateStream
4--
5--
6-- Maintainer : joe@jerkface.net
7-- Stability : experimental
8--
9-- An UpdateSream consists of pass-through messages that are queued up and
10-- slotted messages which might be obsoleted and discarded if they are not
11-- consumed before newer slotted messages with the same slot value occur.
12--
13-- Slots are implemented with "Control.Concurrent.STM.StatusCache" and it is
14-- recommended that you read that documentation first.
15--
16-- For example, the output
17--
18-- > Backlogged consumer: (set x = 5)(set y = 100)(Hello)(Joe)(was)(here)
19-- > Fast consumer: (set x = 2)(Hello)(set y = 23)(Joe)(set y = 100)(was)(set x = 5)(here)
20--
21-- is produced by the following code:
22--
23-- > import Control.Monad (when, forever, (>=>))
24-- > import Control.Monad.STM (atomically)
25-- > import Control.Concurrent (forkIO, threadDelay)
26-- > import System.IO (hFlush, stdout)
27-- > import qualified Control.Concurrent.STM.UpdateStream as Cache
28-- >
29-- > messages :: [(Maybe String, Char)]
30-- > messages = concat
31-- > [ slot "x" "(set x = 2)"
32-- > , message "(Hello)"
33-- > , slot "y" "(set y = 23)"
34-- > , message "(Joe)"
35-- > , slot "y" "(set y = 100)"
36-- > , message "(was)"
37-- > , slot "x" "(set x = 5)"
38-- > , message "(here)"
39-- > ]
40-- > where
41-- > slot v cs = map ((,) (Just v)) cs
42-- > message cs = map ((,) Nothing) cs
43-- >
44-- > main = do
45-- > q <- atomically $ Cache.new (== '(') (==')')
46-- > let go = mapM_ (atomically . (uncurry $ Cache.push q)
47-- > >=> const (threadDelay 10000))
48-- > messages
49-- > slowly = do
50-- > while (atomically $ fmap not $ Cache.isEmpty q) $ do
51-- > c <- atomically $ Cache.pull q
52-- > putChar c
53-- > putStrLn ""
54-- > hFlush stdout
55-- > where while pred body =
56-- > pred >>= flip when (body >> while pred body)
57-- > quickly = forkIO . forever $ do
58-- > c <- atomically $ Cache.pull q
59-- > putChar c
60-- > hFlush stdout
61-- > putStr $ "Backlogged consumer: "
62-- > go >> slowly
63-- > putStr "Fast consumer: "
64-- > quickly >> go
65-- > putStrLn ""
66--
67module Control.Concurrent.STM.UpdateStream
68 ( UpdateStream
69 , new
70 , push
71 , pull
72 , isStopper
73 , isStarter
74 , isEmpty
75 ) where
76
77import Control.Monad
78import Control.Monad.STM
79import Control.Concurrent.STM.TVar
80import Control.Concurrent.STM.TChan
81import Control.Concurrent.STM.StatusCache (StatusCache)
82import qualified Control.Concurrent.STM.StatusCache as Status
83import Data.Map (Map)
84import qualified Data.Map as Map
85import Data.Maybe
86import Data.Foldable (foldlM)
87
88data UpdateStream slot x =
89 UpdateStream { cache :: TVar (Map slot (StatusCache x))
90 , events :: TChan x
91 , inMessage :: TVar (Maybe (StatusCache x))
92 , isStarter :: x -> Bool -- ^ True if the given chunk begins a message.
93 , isStopper :: x -> Bool -- ^ True if the given chunk ends a message.
94 }
95
96-- | @new isStart isStop@
97--
98-- The @isStart@ and @isStop@ predicates indicate when an element
99-- begins or ends a message.
100new :: Ord slot => (x->Bool) -> (x->Bool) -> STM (UpdateStream slot x)
101new isStart isStop = do
102 cache <- newTVar Map.empty
103 events <- newTChan
104 inMessage <- newTVar Nothing
105 return UpdateStream { cache = cache
106 , events = events
107 , inMessage = inMessage
108 , isStarter = isStart
109 , isStopper = isStop
110 }
111
112-- | Enqueue a chunk into the 'UpdateStream'
113--
114-- If a slot is provided, then the message may be obsoleted when a new message
115-- starts with the same slot value. Otherwise, the chunk is preserved. Note
116-- that the same slot value must be passed again for every chunk of the message
117-- as it is not remembered.
118--
119-- Note that although a slot value is provided on each push, it is assumed that
120-- messages will be pushed in contiguous streams. To change this, we would
121-- need to add a mutable integer to track the nesting level of the primary
122-- (non-slotted) stream.
123push :: Ord slot => UpdateStream slot x -> Maybe slot -> x -> STM ()
124push u Nothing x = writeTChan (events u) x
125push u (Just n) x = do
126 smap <- readTVar (cache u)
127 scache <-
128 case Map.lookup n smap of
129 Just scache -> return scache
130 Nothing -> do
131 scache <- Status.new (isStarter u) (isStopper u)
132 modifyTVar (cache u) (Map.insert n scache)
133 return scache
134
135 Status.push scache x
136
137-- | Pull off a chunk from the 'UpdateStream' for processing.
138--
139-- If chunks are not pulled off quickly, they may be obsoleted
140-- and discarded when new messages are 'push'ed.
141pull :: Ord slot => UpdateStream slot x -> STM x
142pull u = do
143 mbscache <- readTVar $ inMessage u
144 let action =
145 case mbscache of
146 Just scache -> do
147 x <- Status.pull scache
148 nesting <- readTVar (Status.pullDepth scache)
149 when (nesting==0) $ writeTVar (inMessage u) Nothing
150 return x
151 Nothing -> do
152 cs <- fmap (Map.toList) $ readTVar (cache u)
153 cs <- filterM (return . not <=< Status.isEmpty . snd)
154 cs
155 maybe (readTChan $ events u)
156 (\(n,scache) -> do
157 writeTVar (inMessage u) (Just scache) -- (Just n)
158 Status.pull scache)
159 (listToMaybe cs)
160 x <- action
161 return x
162
163-- | True when the 'UpdateStream' is completely exhuasted.
164isEmpty :: UpdateStream slot x -> STM Bool
165isEmpty q = do
166 e <- isEmptyTChan (events q)
167 qs <- readTVar (cache q)
168 d <- foldlM (\b s -> fmap (b &&) $ Status.isEmpty s) True qs
169 return $ e && d
diff --git a/Data/BitSyntax.hs b/Data/BitSyntax.hs
new file mode 100644
index 00000000..dbb43f45
--- /dev/null
+++ b/Data/BitSyntax.hs
@@ -0,0 +1,429 @@
1{-# LANGUAGE TemplateHaskell #-}
2{-# LANGUAGE ForeignFunctionInterface #-}
3-- | This module contains fuctions and templates for building up and breaking
4-- down packed bit structures. It's something like Erlang's bit-syntax (or,
5-- actually, more like Python's struct module).
6--
7-- This code uses Data.ByteString which is included in GHC 6.5 and you can
8-- get it for 6.4 at <http://www.cse.unsw.edu.au/~dons/fps.html>
9module Data.BitSyntax (
10 -- * Building bit structures
11 -- | The core function here is makeBits, which is a perfectly normal function.
12 -- Here's an example which makes a SOCKS4a request header:
13 -- @
14 -- makeBits [U8 4, U8 1, U16 80, U32 10, NullTerminated \"username\",
15 -- NullTerminated \"www.haskell.org\"]
16 -- @
17 BitBlock(..),
18 makeBits,
19 -- * Breaking up bit structures
20 -- | The main function for this is bitSyn, which is a template function and
21 -- so you'll need to run with @-fth@ to enable template haskell
22 -- <http://www.haskell.org/th/>.
23 --
24 -- To expand the function you use the splice command:
25 -- @
26 -- $(bitSyn [...])
27 -- @
28 --
29 -- The expanded function has type @ByteString -> (...)@ where the elements of
30 -- the tuple depend of the argument to bitSyn (that's why it has to be a template
31 -- function).
32 --
33 -- Heres an example, translated from the Erlang manual, which parses an IP header:
34 --
35 -- @
36 -- decodeOptions bs ([_, hlen], _, _, _, _, _, _, _, _, _)
37 -- | hlen > 5 = return $ BS.splitAt (fromIntegral ((hlen - 5) * 4)) bs
38 -- | otherwise = return (BS.empty, bs)
39 -- @
40 --
41 -- @
42 -- ipDecode = $(bitSyn [PackedBits [4, 4], Unsigned 1, Unsigned 2, Unsigned 2,
43 -- PackedBits [3, 13], Unsigned 1, Unsigned 1, Unsigned 2,
44 -- Fixed 4, Fixed 4, Context \'decodeOptions, Rest])
45 -- @
46 --
47 -- @
48 -- ipPacket = BS.pack [0x45, 0, 0, 0x34, 0xd8, 0xd2, 0x40, 0, 0x40, 0x06,
49 -- 0xa0, 0xca, 0xac, 0x12, 0x68, 0x4d, 0xac, 0x18,
50 -- 0x00, 0xaf]
51 -- @
52 --
53 -- This function has several weaknesses compared to the Erlang version: The
54 -- elements of the bit structure are not named in place, instead you have to
55 -- do a pattern match on the resulting tuple and match up the indexes. The
56 -- type system helps in this, but it's still not quite as nice.
57
58 ReadType(..), bitSyn,
59
60 -- I get errors if these aren't exported (Can't find interface-file
61 -- declaration for Data.BitSyntax.decodeU16)
62 decodeU8, decodeU16, decodeU32, decodeU16LE, decodeU32LE) where
63
64import Language.Haskell.TH.Lib
65import Language.Haskell.TH.Syntax
66
67import qualified Data.ByteString as BS
68import Data.Char (ord)
69import Control.Monad
70-- import Test.QuickCheck (Arbitrary(), arbitrary, Gen())
71
72import Foreign
73
74foreign import ccall unsafe "htonl" htonl :: Word32 -> Word32
75foreign import ccall unsafe "htons" htons :: Word16 -> Word16
76
77-- There's no good way to convert to little-endian. The htons functions only
78-- convert to big endian and they don't have any little endian friends. So we
79-- need to detect which kind of system we are on and act accordingly. We can
80-- detect the type of system by seeing if htonl actaully doesn't anything (it's
81-- the identity function on big-endian systems, of course). If it doesn't we're
82-- on a big-endian system and so need to do the byte-swapping in Haskell because
83-- the C functions are no-ops
84
85-- | A native Haskell version of htonl for the case where we need to convert
86-- to little-endian on a big-endian system
87endianSwitch32 :: Word32 -> Word32
88endianSwitch32 a = ((a .&. 0xff) `shiftL` 24) .|.
89 ((a .&. 0xff00) `shiftL` 8) .|.
90 ((a .&. 0xff0000) `shiftR` 8) .|.
91 (a `shiftR` 24)
92
93-- | A native Haskell version of htons for the case where we need to convert
94-- to little-endian on a big-endian system
95endianSwitch16 :: Word16 -> Word16
96endianSwitch16 a = ((a .&. 0xff) `shiftL` 8) .|.
97 (a `shiftR` 8)
98
99littleEndian32 :: Word32 -> Word32
100littleEndian32 a = if htonl 1 == 1
101 then endianSwitch32 a
102 else a
103
104littleEndian16 :: Word16 -> Word16
105littleEndian16 a = if htonl 1 == 1
106 then endianSwitch16 a
107 else a
108
109data BitBlock = -- | Unsigned 8-bit int
110 U8 Int |
111 -- | Unsigned 16-bit int
112 U16 Int |
113 -- | Unsigned 32-bit int
114 U32 Int |
115 -- | Little-endian, unsigned 16-bit int
116 U16LE Int |
117 -- | Little-endian, unsigned 32-bit int
118 U32LE Int |
119 -- | Appends the string with a trailing NUL byte
120 NullTerminated String |
121 -- | Appends the string without any terminator
122 RawString String |
123 -- | Appends a ByteString
124 RawByteString BS.ByteString |
125 -- | Packs a series of bit fields together. The argument is
126 -- a list of pairs where the first element is the size
127 -- (in bits) and the second is the value. The sum of the
128 -- sizes for a given PackBits must be a multiple of 8
129 PackBits [(Int, Int)]
130 deriving (Show)
131
132-- Encodes a member of the Bits class as a series of bytes and returns the
133-- ByteString of those bytes.
134getBytes :: (Integral a, Bounded a, Bits a) => a -> BS.ByteString
135getBytes input =
136 let getByte _ 0 = []
137 getByte x remaining = (fromIntegral $ (x .&. 0xff)) :
138 getByte (shiftR x 8) (remaining - 1)
139 in
140 if (bitSize input `mod` 8) /= 0
141 then error "Input data bit size must be a multiple of 8"
142 else BS.pack $ getByte input (bitSize input `div` 8)
143
144-- Performs the work behind PackBits
145packBits :: (Word8, Int, [Word8]) -- ^ The current byte, the number of bits
146 -- used in that byte and the (reverse)
147 -- list of produced bytes
148 -> (Int, Int) -- ^ The size (in bits) of the value, and the value
149 -> (Word8, Int, [Word8]) -- See first argument
150packBits (current, used, bytes) (size, value) =
151 if bitsWritten < size
152 then packBits (0, 0, current' : bytes) (size - bitsWritten, value)
153 else if used' == 8
154 then (0, 0, current' : bytes)
155 else (current', used', bytes)
156 where
157 top = size - 1
158 topOfByte = 7 - used
159 aligned = value `shift` (topOfByte - top)
160 newBits = (fromIntegral aligned) :: Word8
161 current' = current .|. newBits
162 bitsWritten = min (8 - used) size
163 used' = used + bitsWritten
164
165bits :: BitBlock -> BS.ByteString
166bits (U8 v) = BS.pack [((fromIntegral v) :: Word8)]
167bits (U16 v) = getBytes ((htons $ fromIntegral v) :: Word16)
168bits (U32 v) = getBytes ((htonl $ fromIntegral v) :: Word32)
169bits (U16LE v) = getBytes (littleEndian16 $ fromIntegral v)
170bits (U32LE v) = getBytes (littleEndian32 $ fromIntegral v)
171bits (NullTerminated str) = BS.pack $ (map (fromIntegral . ord) str) ++ [0]
172bits (RawString str) = BS.pack $ map (fromIntegral . ord) str
173bits (RawByteString bs) = bs
174bits (PackBits bitspec) =
175 if (sum $ map fst bitspec) `mod` 8 /= 0
176 then error "Sum of sizes of a bit spec must == 0 mod 8"
177 else (\(_, _, a) -> BS.pack $ reverse a) $ foldl packBits (0, 0, []) bitspec
178
179-- | Make a binary string from the list of elements given
180makeBits :: [BitBlock] -> BS.ByteString
181makeBits = BS.concat . (map bits)
182
183data ReadType = -- | An unsigned number of some number of bytes. Valid
184 -- arguments are 1, 2 and 4
185 Unsigned Integer |
186 -- | An unsigned, little-endian integer of some number of
187 -- bytes. Valid arguments are 2 and 4
188 UnsignedLE Integer |
189 -- | A variable length element to be decoded by a custom
190 -- function. The function's name is given as the single
191 -- argument and should have type
192 -- @Monad m => ByteString -> m (v, ByteString)@
193 Variable Name |
194 -- | Skip some number of bytes
195 Skip Integer |
196 -- | A fixed size field, the result of which is a ByteString
197 -- of that length.
198 Fixed Integer |
199 -- | Decode a value and ignore it (the result will not be part
200 -- of the returned tuple)
201 Ignore ReadType |
202 -- | Like variable, but the decoding function is passed the
203 -- entire result tuple so far. Thus the function whose name
204 -- passed has type
205 -- @Monad m => ByteString -> (...) -> m (v, ByteString)@
206 Context Name |
207 -- | Takes the most recent element of the result tuple and
208 -- interprets it as the length of this field. Results in
209 -- a ByteString
210 LengthPrefixed |
211 -- | Decode a series of bit fields, results in a list of
212 -- Integers. Each element of the argument is the length of
213 -- the bit field. The sums of the lengths must be a multiple
214 -- of 8
215 PackedBits [Integer] |
216 -- | Results in a ByteString containing the undecoded bytes so
217 -- far. Generally used at the end to return the trailing body
218 -- of a structure, it can actually be used at any point in the
219 -- decoding to return the trailing part at that point.
220 Rest
221
222fromBytes :: (Num a, Bits a) => [a] -> a
223fromBytes input =
224 let dofb accum [] = accum
225 dofb accum (x:xs) = dofb ((shiftL accum 8) .|. x) xs
226 in
227 dofb 0 $ reverse input
228
229decodeU8 :: BS.ByteString -> Word8
230decodeU8 = fromIntegral . head . BS.unpack
231decodeU16 :: BS.ByteString -> Word16
232decodeU16 = htons . fromBytes . map fromIntegral . BS.unpack
233decodeU32 :: BS.ByteString -> Word32
234decodeU32 = htonl . fromBytes . map fromIntegral . BS.unpack
235decodeU16LE :: BS.ByteString -> Word16
236decodeU16LE = littleEndian16 . fromBytes . map fromIntegral . BS.unpack
237decodeU32LE :: BS.ByteString -> Word32
238decodeU32LE = littleEndian32 . fromBytes . map fromIntegral . BS.unpack
239
240decodeBits :: [Integer] -> BS.ByteString -> [Integer]
241decodeBits sizes bs =
242 reverse values
243 where
244 (values, _, _) = foldl unpackBits ([], 0, BS.unpack bitdata) sizes
245 bytesize = (sum sizes) `shiftR` 3
246 (bitdata, _) = BS.splitAt (fromIntegral bytesize) bs
247
248unpackBits :: ([Integer], Integer, [Word8]) -> Integer -> ([Integer], Integer, [Word8])
249unpackBits state size = unpackBitsInner 0 state size
250
251unpackBitsInner :: Integer ->
252 ([Integer], Integer, [Word8]) ->
253 Integer ->
254 ([Integer], Integer, [Word8])
255unpackBitsInner _ (output, used, []) _ = (output, used, [])
256unpackBitsInner val (output, used, current : input) bitsToGet =
257 if bitsToGet' > 0
258 then unpackBitsInner val'' (output, 0, input) bitsToGet'
259 else if used' < 8
260 then (val'' : output, used', current'' : input)
261 else (val'' : output, 0, input)
262 where
263 bitsAv = 8 - used
264 bitsTaken = min bitsAv bitsToGet
265 val' = val `shift` (fromIntegral bitsTaken)
266 current' = current `shiftR` (fromIntegral (8 - bitsTaken))
267 current'' = current `shiftL` (fromIntegral bitsTaken)
268 val'' = val' .|. (fromIntegral current')
269 bitsToGet' = bitsToGet - bitsTaken
270 used' = used + bitsTaken
271
272readElement :: ([Stmt], Name, [Name]) -> ReadType -> Q ([Stmt], Name, [Name])
273
274readElement (stmts, inputname, tuplenames) (Context funcname) = do
275 valname <- newName "val"
276 restname <- newName "rest"
277
278 let stmt = BindS (TupP [VarP valname, VarP restname])
279 (AppE (AppE (VarE funcname)
280 (VarE inputname))
281 (TupE $ map VarE $ reverse tuplenames))
282
283 return (stmt : stmts, restname, valname : tuplenames)
284
285readElement (stmts, inputname, tuplenames) (Fixed n) = do
286 valname <- newName "val"
287 restname <- newName "rest"
288 let dec1 = ValD (TupP [VarP valname, VarP restname])
289 (NormalB $ AppE (AppE (VarE 'BS.splitAt)
290 (LitE (IntegerL n)))
291 (VarE inputname))
292 []
293
294 return (LetS [dec1] : stmts, restname, valname : tuplenames)
295
296readElement state@(_, _, tuplenames) (Ignore n) = do
297 (a, b, _) <- readElement state n
298 return (a, b, tuplenames)
299
300readElement (stmts, inputname, tuplenames) LengthPrefixed = do
301 valname <- newName "val"
302 restname <- newName "rest"
303
304 let sourcename = head tuplenames
305 dec = ValD (TupP [VarP valname, VarP restname])
306 (NormalB $ AppE (AppE (VarE 'BS.splitAt)
307 (AppE (VarE 'fromIntegral)
308 (VarE sourcename)))
309 (VarE inputname))
310 []
311
312 return (LetS [dec] : stmts, restname, valname : tuplenames)
313
314readElement (stmts, inputname, tuplenames) (Variable funcname) = do
315 valname <- newName "val"
316 restname <- newName "rest"
317
318 let stmt = BindS (TupP [VarP valname, VarP restname])
319 (AppE (VarE funcname) (VarE inputname))
320
321 return (stmt : stmts, restname, valname : tuplenames)
322
323readElement (stmts, inputname, tuplenames) Rest = do
324 restname <- newName "rest"
325 let dec = ValD (VarP restname)
326 (NormalB $ VarE inputname)
327 []
328 return (LetS [dec] : stmts, inputname, restname : tuplenames)
329
330readElement (stmts, inputname, tuplenames) (Skip n) = do
331 -- Expands to something like:
332 -- rest = Data.ByteString.drop n input
333 restname <- newName "rest"
334 let dec = ValD (VarP restname)
335 (NormalB $ AppE (AppE (VarE 'BS.drop)
336 (LitE (IntegerL n)))
337 (VarE inputname))
338 []
339 return (LetS [dec] : stmts, restname, tuplenames)
340
341readElement state (Unsigned size) = do
342 -- Expands to something like:
343 -- (aval, arest) = Data.ByteString.splitAt 1 input
344 -- a = BitSyntax.decodeU8 aval
345 let decodefunc = case size of
346 1 -> 'decodeU8
347 2 -> 'decodeU16
348 _ -> 'decodeU32 -- Default to 32
349 decodeHelper state (VarE decodefunc) size
350
351readElement state (UnsignedLE size) = do
352 -- Expands to something like:
353 -- (aval, arest) = Data.ByteString.splitAt 1 input
354 -- a = BitSyntax.decodeU8LE aval
355 let decodefunc = case size of
356 2 -> 'decodeU16LE
357 _ -> 'decodeU32LE -- Default to 4
358 decodeHelper state (VarE decodefunc) size
359
360readElement state (PackedBits sizes) =
361 if sum sizes `mod` 8 /= 0
362 then error "Sizes of packed bits must == 0 mod 8"
363 else decodeHelper state
364 (AppE (VarE 'decodeBits)
365 (ListE $ map (LitE . IntegerL) sizes))
366 ((sum sizes) `shiftR` 3)
367
368decodeHelper :: ([Stmt], Name, [Name]) -> Exp
369 -> Integer
370 -> Q ([Stmt], Name, [Name])
371decodeHelper (stmts, inputname, tuplenames) decodefunc size = do
372 valname <- newName "val"
373 restname <- newName "rest"
374 tuplename <- newName "tup"
375 let dec1 = ValD (TupP [VarP valname, VarP restname])
376 (NormalB $ AppE (AppE (VarE 'BS.splitAt)
377 (LitE (IntegerL size)))
378 (VarE inputname))
379 []
380 let dec2 = ValD (VarP tuplename)
381 (NormalB $ AppE decodefunc (VarE valname))
382 []
383
384 return (LetS [dec1, dec2] : stmts, restname, tuplename : tuplenames)
385
386decGetName :: Dec -> Name
387decGetName (ValD (VarP name) _ _) = name
388decGetName _ = undefined -- Error!
389
390bitSyn :: [ReadType] -> Q Exp
391bitSyn elements = do
392 inputname <- newName "input"
393 (stmts, restname, tuplenames) <- foldM readElement ([], inputname, []) elements
394 returnS <- NoBindS `liftM` [| return $(tupE . map varE $ reverse tuplenames) |]
395 return $ LamE [VarP inputname] (DoE . reverse $ returnS : stmts)
396
397
398-- Tests
399prop_bitPacking :: [(Int, Int)] -> Bool
400prop_bitPacking fields =
401 prevalues == (map fromIntegral postvalues) ||
402 any (< 1) (map fst fields) ||
403 any (< 0) (map snd fields)
404 where
405 undershoot = sum (map fst fields) `mod` 8
406 fields' = if undershoot > 0
407 then (8 - undershoot, 1) : fields
408 else fields
409 prevalues = map snd fields'
410 packed = bits $ PackBits fields'
411 postvalues = decodeBits (map (fromIntegral . fst) fields') packed
412
413{-
414instance Arbitrary Word16 where
415 arbitrary = (arbitrary :: Gen Int) >>= return . fromIntegral
416instance Arbitrary Word32 where
417 arbitrary = (arbitrary :: Gen Int) >>= return . fromIntegral
418-}
419
420-- | This only works on little-endian machines as it checks that the foreign
421-- functions (htonl and htons) match the native ones
422prop_nativeByteShuffle32 :: Word32 -> Bool
423prop_nativeByteShuffle32 x = endianSwitch32 x == htonl x
424prop_nativeByteShuffle16 :: Word16 -> Bool
425prop_nativeByteShuffle16 x = endianSwitch16 x == htons x
426prop_littleEndian16 :: Word16 -> Bool
427prop_littleEndian16 x = littleEndian16 x == x
428prop_littleEndian32 :: Word32 -> Bool
429prop_littleEndian32 x = littleEndian32 x == x
diff --git a/PingMachine.hs b/PingMachine.hs
new file mode 100644
index 00000000..b714d71e
--- /dev/null
+++ b/PingMachine.hs
@@ -0,0 +1,113 @@
1{-# LANGUAGE CPP #-}
2module PingMachine where
3
4import Control.Monad
5import Data.Function
6#ifdef THREAD_DEBUG
7import Control.Concurrent.Lifted.Instrument
8#else
9import Control.Concurrent.Lifted
10import GHC.Conc (labelThread)
11#endif
12import Control.Concurrent.STM
13
14import InterruptibleDelay
15
16type Miliseconds = Int
17type TimeOut = Miliseconds
18type PingInterval = Miliseconds
19
20-- | Events that occur as a result of the 'PingMachine' watchdog.
21--
22-- Use 'pingWait' to wait for one of these to occur.
23data PingEvent
24 = PingIdle -- ^ You should send a ping if you observe this event.
25 | PingTimeOut -- ^ You should give up on the connection in case of this event.
26
27data PingMachine = PingMachine
28 { pingFlag :: TVar Bool
29 , pingInterruptible :: InterruptibleDelay
30 , pingEvent :: TMVar PingEvent
31 , pingStarted :: TMVar Bool
32 }
33
34-- | Fork a thread to monitor a connection for a ping timeout.
35--
36-- If 'pingBump' is not invoked after a idle is signaled, a timeout event will
37-- occur. When that happens, even if the caller chooses to ignore this event,
38-- the watchdog thread will be terminated and no more ping events will be
39-- signaled.
40--
41-- An idle connection will be signaled by:
42--
43-- (1) 'pingFlag' is set 'True'
44--
45-- (2) 'pingWait' returns 'PingIdle'
46--
47-- Either may be tested to determine whether a ping should be sent but
48-- 'pingFlag' is difficult to use properly because it is up to the caller to
49-- remember that the ping is already in progress.
50forkPingMachine
51 :: PingInterval -- ^ Milliseconds of idle before a ping is considered necessary.
52 -> TimeOut -- ^ Milliseconds after 'PingIdle' before we signal 'PingTimeOut'.
53 -> IO PingMachine
54forkPingMachine idle timeout = do
55 d <- interruptibleDelay
56 flag <- atomically $ newTVar False
57 canceled <- atomically $ newTVar False
58 event <- atomically newEmptyTMVar
59 started <- atomically $ newEmptyTMVar
60 when (idle/=0) $ void . forkIO $ do
61 myThreadId >>= flip labelThread ("ping.watchdog")
62 (>>=) (atomically (readTMVar started)) $ flip when $ do
63 fix $ \loop -> do
64 atomically $ writeTVar flag False
65 fin <- startDelay d (1000*idle)
66 (>>=) (atomically (readTMVar started)) $ flip when $ do
67 if (not fin) then loop
68 else do
69 -- Idle event
70 atomically $ do
71 tryTakeTMVar event
72 putTMVar event PingIdle
73 writeTVar flag True
74 fin <- startDelay d (1000*timeout)
75 (>>=) (atomically (readTMVar started)) $ flip when $ do
76 me <- myThreadId
77 if (not fin) then loop
78 else do
79 -- Timeout event
80 atomically $ do
81 tryTakeTMVar event
82 writeTVar flag False
83 putTMVar event PingTimeOut
84 return PingMachine
85 { pingFlag = flag
86 , pingInterruptible = d
87 , pingEvent = event
88 , pingStarted = started
89 }
90
91-- | Terminate the watchdog thread. Call this upon connection close.
92--
93-- You should ensure no threads are waiting on 'pingWait' because there is no
94-- 'PingEvent' signaling termination.
95pingCancel :: PingMachine -> IO ()
96pingCancel me = do
97 atomically $ do tryTakeTMVar (pingStarted me)
98 putTMVar (pingStarted me) False
99 interruptDelay (pingInterruptible me)
100
101-- | Reset the ping timer. Call this regularly to prevent 'PingTimeOut'.
102pingBump :: PingMachine -> IO ()
103pingBump me = do
104 atomically $ do
105 b <- tryReadTMVar (pingStarted me)
106 when (b/=Just False) $ do
107 tryTakeTMVar (pingStarted me)
108 putTMVar (pingStarted me) True
109 interruptDelay (pingInterruptible me)
110
111-- | Retries until a 'PingEvent' occurs.
112pingWait :: PingMachine -> STM PingEvent
113pingWait me = takeTMVar (pingEvent me)
diff --git a/Presence/ByteStringOperators.hs b/Presence/ByteStringOperators.hs
new file mode 100644
index 00000000..4453aca0
--- /dev/null
+++ b/Presence/ByteStringOperators.hs
@@ -0,0 +1,50 @@
1{-# LANGUAGE CPP #-}
2module ByteStringOperators where
3
4import qualified Data.ByteString as S (ByteString)
5import Data.ByteString.Lazy.Char8 as L
6import Control.Applicative
7
8-- These two were imported to provide an NFData instance.
9import qualified Data.ByteString.Lazy.Internal as L (ByteString(..))
10import Control.DeepSeq
11
12
13(<++>) :: ByteString -> ByteString -> ByteString
14(<++.>) :: ByteString -> S.ByteString -> ByteString
15(<.++>) :: S.ByteString -> ByteString -> ByteString
16(<.++.>) :: S.ByteString -> S.ByteString -> ByteString
17a <++> b = L.append a b
18a <++.> b = L.append a (fromChunks [b])
19a <.++> b = L.append (fromChunks [a]) b
20a <.++.> b = fromChunks [a,b]
21infixr 5 <.++.>
22infixr 5 <.++>
23infixr 5 <++>
24infixr 5 <++.>
25
26a <++$> b = fmap (a<++>) b
27a <$++> b = fmap (<++>b) a
28a <$++$> b = liftA2 (<++>) a b
29infixr 6 <++$>
30infixr 6 <$++>
31infixr 6 <$++$>
32
33Nothing <?++> b = b
34Just a <?++> b = a <++> b
35infixr 5 <?++>
36
37a <++?> Nothing = a
38a <++?> Just b = a <++> b
39infixr 5 <++?>
40
41bshow :: Show a => a -> ByteString
42bshow = L.pack . show
43
44
45#if MIN_VERSION_bytestring(0,10,0)
46#else
47instance NFData L.ByteString where
48 rnf L.Empty = ()
49 rnf (L.Chunk _ b) = rnf b
50#endif
diff --git a/Presence/ClientState.hs b/Presence/ClientState.hs
new file mode 100644
index 00000000..30a53131
--- /dev/null
+++ b/Presence/ClientState.hs
@@ -0,0 +1,34 @@
1module ClientState where
2
3import Control.Concurrent.STM
4import Data.Text ( Text )
5import Data.Int ( Int8 )
6import Data.Bits ( (.&.) )
7
8import UTmp ( ProcessID )
9import XMPPServer ( Stanza )
10
11data ClientState = ClientState
12 { clientResource :: Text
13 , clientUser :: Text
14 , clientPid :: Maybe ProcessID
15 , clientStatus :: TVar (Maybe Stanza)
16 , clientFlags :: TVar Int8
17 }
18
19cf_available :: Int8
20cf_available = 0x1
21cf_interested :: Int8
22cf_interested = 0x2
23
24-- | True if the client has sent an initial presence
25clientIsAvailable :: ClientState -> STM Bool
26clientIsAvailable c = do
27 flgs <- readTVar (clientFlags c)
28 return $ flgs .&. cf_available /= 0
29
30-- | True if the client has requested a roster
31clientIsInterested :: ClientState -> STM Bool
32clientIsInterested c = do
33 flgs <- readTVar (clientFlags c)
34 return $ flgs .&. cf_interested /= 0
diff --git a/Presence/ConfigFiles.hs b/Presence/ConfigFiles.hs
new file mode 100644
index 00000000..808e6dd8
--- /dev/null
+++ b/Presence/ConfigFiles.hs
@@ -0,0 +1,130 @@
1{-# LANGUAGE OverloadedStrings #-}
2module ConfigFiles where
3
4import Data.ByteString.Lazy.Char8 as L
5import System.Posix.User
6import System.Posix.Files (fileExist)
7import System.FilePath
8import System.Directory
9import System.IO
10-- import System.IO.Strict
11import System.IO.Error
12import Control.Exception
13import Control.Monad
14import Control.DeepSeq
15import ByteStringOperators () -- For NFData instance
16import ControlMaybe
17import Data.List (partition)
18import Data.Maybe (catMaybes,isJust)
19
20type User = ByteString
21
22configDir = ".presence"
23buddyFile = "buddies"
24subscriberFile = "subscribers"
25otherFile = "others"
26pendingFile = "pending"
27solicitedFile = "solicited"
28
29
30configPath :: User -> String -> IO String
31configPath user filename = do
32 ue <- getUserEntryForName (unpack user)
33 return $ (++("/"++configDir++"/"++filename)) $ homeDirectory ue
34
35
36createConfigFile tag path = do
37 let dir = dropFileName path
38 doesDirectoryExist dir >>= flip unless (do
39 createDirectory dir
40 )
41 withFile path WriteMode $ \h -> do
42 L.hPutStrLn h tag
43
44addItem item tag path =
45 let doit = do
46 handle (\e -> when (isDoesNotExistError e)
47 (createConfigFile tag path >> doit))
48 $ do exists <- fileExist path
49 if exists
50 then withFile path AppendMode $ \h ->
51 L.hPutStrLn h item
52 else withFile path WriteMode $ \h -> do
53 L.hPutStrLn h tag
54 L.hPutStrLn h item
55 in doit
56
57
58modifyFile ::
59 (ByteString,FilePath)
60 -> ByteString
61 -> (ByteString -> IO (Maybe ByteString))
62 -> Maybe ByteString
63 -> IO Bool -- Returns True if test function ever returned Nothing
64modifyFile (tag,file) user test appending = configPath user file >>= doit
65 where
66 doit path = do
67 handle (\e -> if (isDoesNotExistError e)
68 then (createConfigFile tag path >> doit path)
69 else return False)
70 $ do exists <- fileExist path
71 if exists
72 then do
73 xs <- withFile path ReadMode $ \h -> do
74 contents <- L.hGetContents h
75 case L.lines contents of
76 x:xs -> mapM test xs
77 _ -> return []
78 let (keepers,deleted) = partition isJust xs
79 withFile path WriteMode $ \h -> do
80 L.hPutStrLn h tag
81 forM_ (catMaybes keepers) (L.hPutStrLn h)
82 withJust appending (L.hPutStrLn h)
83 return . not . Prelude.null $ deleted
84 else do
85 withFile path WriteMode $ \h -> do
86 L.hPutStrLn h tag
87 withJust appending (L.hPutStrLn h)
88 return False
89
90
91modifySolicited = modifyFile ("<? solicited ?>" , solicitedFile)
92modifyBuddies = modifyFile ("<? buddies ?>" , buddyFile)
93modifyOthers = modifyFile ("<? others ?>" , otherFile)
94modifyPending = modifyFile ("<? pending ?>" , pendingFile)
95modifySubscribers = modifyFile ("<? subscribers ?>", subscriberFile)
96
97addBuddy :: User -> ByteString -> IO ()
98addBuddy user buddy =
99 configPath user buddyFile >>= addItem buddy "<? buddies ?>"
100
101addSubscriber :: User -> ByteString -> IO ()
102addSubscriber user subscriber =
103 configPath user subscriberFile >>= addItem subscriber "<? subscribers ?>"
104
105addSolicited :: User -> ByteString -> IO ()
106addSolicited user solicited =
107 configPath user solicitedFile >>= addItem solicited "<? solicited ?>"
108
109
110getConfigList path =
111 handle (\e -> if isDoesNotExistError e then (return []) else throw e)
112 $ withFile path ReadMode $
113 L.hGetContents
114 >=> return . Prelude.tail . L.lines
115 >=> (\a -> seq (rnf a) (return a))
116
117getBuddies :: User -> IO [ByteString]
118getBuddies user = configPath user buddyFile >>= getConfigList
119
120getSubscribers :: User -> IO [ByteString]
121getSubscribers user = configPath user subscriberFile >>= getConfigList
122
123getOthers :: User -> IO [ByteString]
124getOthers user = configPath user otherFile >>= getConfigList
125
126getPending :: User -> IO [ByteString]
127getPending user = configPath user pendingFile >>= getConfigList
128
129getSolicited :: User -> IO [ByteString]
130getSolicited user = configPath user solicitedFile >>= getConfigList
diff --git a/Presence/ConnectionKey.hs b/Presence/ConnectionKey.hs
new file mode 100644
index 00000000..944f4f6f
--- /dev/null
+++ b/Presence/ConnectionKey.hs
@@ -0,0 +1,10 @@
1module ConnectionKey where
2
3import Network.Socket ( SockAddr(..) )
4import SockAddr ()
5
6data ConnectionKey
7 = PeerKey { callBackAddress :: SockAddr }
8 | ClientKey { localAddress :: SockAddr }
9 deriving (Show, Ord, Eq)
10
diff --git a/Presence/ConsoleWriter.hs b/Presence/ConsoleWriter.hs
new file mode 100644
index 00000000..986294f4
--- /dev/null
+++ b/Presence/ConsoleWriter.hs
@@ -0,0 +1,411 @@
1{-# LANGUAGE CPP #-}
2{-# LANGUAGE OverloadedStrings #-}
3{-# LANGUAGE RankNTypes #-}
4module ConsoleWriter
5 ( ConsoleWriter(cwPresenceChan)
6 , newConsoleWriter
7 , writeActiveTTY
8 , writeAllPty
9 , cwClients
10 ) where
11
12import Control.Monad
13-- import Control.Applicative
14import Control.Concurrent
15import Control.Concurrent.STM
16import Data.Monoid
17import Data.Char
18import Data.Maybe
19import System.Environment hiding (setEnv)
20import System.Exit ( ExitCode(ExitSuccess) )
21import System.Posix.Env ( setEnv )
22import System.Posix.Process ( forkProcess, exitImmediately, executeFile )
23import System.Posix.User ( setUserID, getUserEntryForName, userID )
24import System.Posix.Files ( getFileStatus, fileMode )
25import System.INotify ( initINotify, EventVariety(Modify), addWatch )
26import Data.Word ( Word8 )
27import Data.Text ( Text )
28import Data.Map ( Map )
29import Data.List ( foldl', groupBy )
30import Data.Bits ( (.&.) )
31import qualified Data.Map as Map
32import qualified Data.Traversable as Traversable
33import qualified Data.Text as Text
34-- import qualified Data.Text.IO as Text
35import qualified Network.BSD as BSD
36
37import UTmp ( users2, utmp_file, UtmpRecord(..), UT_Type(..) )
38import FGConsole ( forkTTYMonitor )
39import XMPPServer ( Stanza, makePresenceStanza, JabberShow(..), stanzaType
40 , LangSpecificMessage(..), msgLangMap, cloneStanza, stanzaFrom )
41import ControlMaybe ( handleIO_ )
42import ClientState
43
44data ConsoleWriter = ConsoleWriter
45 { cwPresenceChan :: TMVar (ClientState,Stanza)
46 -- ^ tty switches and logins are announced on this mvar
47 , csActiveTTY :: TVar Word8
48 , csUtmp :: TVar (Map Text (TVar (Maybe UtmpRecord)))
49 , cwClients :: TVar (Map Text ClientState)
50 -- ^ This 'TVar' holds a map from resource id (tty name)
51 -- to ClientState for all active TTYs and PTYs.
52 }
53
54tshow :: forall a. Show a => a -> Text
55tshow x = Text.pack . show $ x
56
57retryWhen :: forall b. STM b -> (b -> Bool) -> STM b
58retryWhen var pred = do
59 value <- var
60 if pred value then retry
61 else return value
62
63
64onLogin ::
65 forall t.
66 ConsoleWriter
67 -> (STM (Word8, Maybe UtmpRecord)
68 -> TVar (Maybe UtmpRecord) -> IO ())
69 -> t
70 -> IO ()
71onLogin cs start = \e -> do
72 us <- UTmp.users2
73 let (m,cruft) =
74 foldl' (\(m,cruft) x ->
75 case utmpType x of
76 USER_PROCESS
77 -> (Map.insert (utmpTty x) x m,cruft)
78 DEAD_PROCESS | utmpPid x /= 0
79 -> (m,Map.insert (utmpTty x) x cruft)
80 _ -> (m,cruft))
81 (Map.empty,Map.empty)
82 us
83 forM_ (Map.elems cruft) $ \c -> do
84 putStrLn $ "cruft " ++ show (utmpTty c, utmpPid c,utmpHost c, utmpRemoteAddr c)
85 newborn <- atomically $ do
86 old <- readTVar (csUtmp cs) -- swapTVar (csUtmp cs) m
87 newborn <- flip Traversable.mapM (m Map.\\ old)
88 $ newTVar . Just
89 updated <- let upd v u = writeTVar v $ Just u
90 in Traversable.sequence $ Map.intersectionWith upd old m
91 let dead = old Map.\\ m
92 Traversable.mapM (flip writeTVar Nothing) dead
93 writeTVar (csUtmp cs) $ (old `Map.union` newborn) Map.\\ dead
94 return newborn
95 let getActive = do
96 tty <- readTVar $ csActiveTTY cs
97 utmp <- readTVar $ csUtmp cs
98 flip (maybe $ return (tty,Nothing))
99 (Map.lookup ("tty"<>tshow tty) utmp)
100 $ \tuvar -> do
101 tu <- readTVar tuvar
102 return (tty,tu)
103
104 forM_ (Map.elems newborn) $
105 forkIO . start getActive
106 -- forM_ (Map.elems dead ) $ putStrLn . ("gone: "++) . show
107
108-- | Sets up threads to monitor tty switches and logins that are
109-- written to the system utmp file and returns a 'ConsoleWriter'
110-- object for interacting with that information.
111newConsoleWriter :: IO (Maybe ConsoleWriter)
112newConsoleWriter = do
113 chan <- atomically $ newEmptyTMVar
114 cs <- atomically $ do
115 ttyvar <- newTVar 0
116 utmpvar <- newTVar Map.empty
117 clients <- newTVar Map.empty
118 return $ ConsoleWriter { cwPresenceChan = chan
119 , csActiveTTY = ttyvar
120 , csUtmp = utmpvar
121 , cwClients = clients
122 }
123 outvar <- atomically $ newTMVar ()
124 let logit outvar s = do
125 {-
126 atomically $ takeTMVar outvar
127 Text.putStrLn s
128 atomically $ putTMVar outvar ()
129 -}
130 return ()
131 onTTY outvar cs vtnum = do
132 logit outvar $ "switch: " <> tshow vtnum
133 atomically $ writeTVar (csActiveTTY cs) vtnum
134
135 inotify <- initINotify
136
137 -- get active tty
138 mtty <- forkTTYMonitor (onTTY outvar cs)
139 forM mtty $ \_ -> do
140 atomically $ retryWhen (readTVar $ csActiveTTY cs) (==0)
141
142 -- read utmp
143 onLogin cs (newCon (logit outvar) cs) Modify
144
145 -- monitor utmp
146 wd <- addWatch
147 inotify
148 [Modify] -- [CloseWrite,Open,Close,Access,Modify,Move]
149 utmp_file
150 (onLogin cs (newCon (logit outvar) cs))
151 return cs
152
153-- Transforms a string of form language[_territory][.codeset][@modifier]
154-- typically used in LC_ locale variables into the BCP 47
155-- language codes used in xml:lang attributes.
156toBCP47 :: [Char] -> [Char]
157toBCP47 lang = map hyphen $ takeWhile (/='.') lang
158 where hyphen '_' = '-'
159 hyphen c = c
160
161#if MIN_VERSION_base(4,6,0)
162#else
163lookupEnv k = fmap (lookup k) getEnvironment
164#endif
165
166getPreferedLang :: IO Text
167getPreferedLang = do
168 lang <- do
169 lc_all <- lookupEnv "LC_ALL"
170 lc_messages <- lookupEnv "LC_MESSAGES"
171 lang <- lookupEnv "LANG"
172 return $ lc_all `mplus` lc_messages `mplus` lang
173 return $ maybe "en" (Text.pack . toBCP47) lang
174
175cimatch :: Text -> Text -> Bool
176cimatch w t = Text.toLower w == Text.toLower t
177
178cimatches :: Text -> [Text] -> [Text]
179cimatches w ts = dropWhile (not . cimatch w) ts
180
181-- rfc4647 lookup of best match language tag
182lookupLang :: [Text] -> [Text] -> Maybe Text
183lookupLang (w:ws) tags
184 | Text.null w = lookupLang ws tags
185 | otherwise = case cimatches w tags of
186 (t:_) -> Just t
187 [] -> lookupLang (reduce w:ws) tags
188 where
189 reduce w = Text.concat $ reverse nopriv
190 where
191 rparts = reverse . init $ Text.groupBy (\_ c -> c/='-') w
192 nopriv = dropWhile ispriv rparts
193 ispriv t = Text.length t == 2 && Text.head t == '-'
194
195lookupLang [] tags | "" `elem` tags = Just ""
196 | otherwise = listToMaybe $ tags
197
198
199messageText :: Stanza -> IO Text
200messageText msg = do
201 pref <- getPreferedLang
202 let m = msgLangMap (stanzaType msg)
203 key = lookupLang [pref] (map fst m)
204 choice = do
205 k <- key
206 lookup k m
207 flip (maybe $ return "") choice $ \choice -> do
208 let subj = fmap ("Subject: " <>) $ msgSubject choice
209 ts = catMaybes [subj, msgBody choice]
210 return $ Text.intercalate "\n\n" ts
211
212readEnvFile :: String -> FilePath -> IO (Maybe String)
213readEnvFile var file = fmap parse $ readFile file
214 where
215 parse xs = listToMaybe $ map (drop 1 . concat . drop 1) $ filter ofinterest bs
216 where
217 bs = map (groupBy (\_ x -> x/='=')) $ split (/='\0') xs
218 ofinterest (k:vs) | k==var = True
219 ofinterest _ = False
220
221 split pred xs = take 1 gs ++ map (drop 1) (drop 1 gs)
222 where
223 gs = groupBy (\_ x -> pred x) xs
224
225-- | Delivers an XMPP message stanza to the currently active
226-- tty. If that is a linux console, it will write to it similar
227-- to the manner of the BSD write command. If that is an X11
228-- display, it will attempt to notify the user via a libnotify
229-- interface.
230writeActiveTTY :: ConsoleWriter -> Stanza -> IO Bool
231writeActiveTTY cw msg = do
232 putStrLn $ "writeActiveTTY"
233 -- TODO: Do not deliver if the detination user does not own the active tty!
234 (tty, mbu) <- atomically $ do
235 num <- readTVar $ csActiveTTY cw
236 utmp <- readTVar $ csUtmp cw
237 mbu <- maybe (return Nothing) readTVar
238 $ Map.lookup ("tty"<>tshow num) utmp
239 return ( "/dev/tty" <> tshow num
240 , mbu )
241 flip (maybe $ return False) mbu $ \utmp -> do
242 display <- fmap (fmap Text.pack)
243 $ readEnvFile "DISPLAY" ("/proc/" ++ show (utmpPid utmp) ++ "/environ")
244 case fmap (==utmpHost utmp) display of
245 Just True -> deliverGUIMessage cw tty utmp msg
246 _ -> deliverTerminalMessage cw tty utmp msg
247
248deliverGUIMessage ::
249 forall t t1. t -> t1 -> UtmpRecord -> Stanza -> IO Bool
250deliverGUIMessage cw tty utmp msg = do
251 text <- do
252 t <- messageText msg
253 return $ Text.unpack
254 $ case stanzaFrom msg of
255 Just from -> from <> ": " <> t
256 Nothing -> t
257 putStrLn $ "deliverGUI: " ++ text
258 handleIO_ (return False) $ do
259 uentry <- getUserEntryForName (Text.unpack $ utmpUser utmp)
260 let display = Text.unpack $ utmpHost utmp
261 pid <- forkProcess $ do
262 setUserID (userID uentry)
263 setEnv "DISPLAY" display True
264 -- rawSystem "/usr/bin/notify-send" [text]
265 executeFile "/usr/bin/notify-send" False [text] (Just [("DISPLAY",display)])
266 exitImmediately ExitSuccess
267 return True
268
269crlf :: Text -> Text
270crlf t = Text.unlines $ map cr (Text.lines t)
271 where
272 cr t | Text.last t == '\r' = t
273 | otherwise = t <> "\r"
274
275deliverTerminalMessage ::
276 forall t t1. t -> Text -> t1 -> Stanza -> IO Bool
277deliverTerminalMessage cw tty utmp msg = do
278 mode <- fmap fileMode (getFileStatus $ Text.unpack tty)
279 let mesgy = mode .&. 0o020 /= 0 -- verify mode g+w
280 if not mesgy then return False else do
281 text <- do
282 t <- messageText msg
283 return $ Text.unpack
284 $ case stanzaFrom msg of
285 Just from -> "\r\n" <> from <> " says...\r\n" <> crlf t <> "\r\n"
286 Nothing -> crlf t <> "\r\n"
287 writeFile (Text.unpack tty) text
288 return True -- return True if a message was delivered
289
290-- | Deliver the given message to all a user's PTYs.
291writeAllPty :: ConsoleWriter -> Stanza -> IO Bool
292writeAllPty cw msg = do
293 -- TODO: filter only ptys owned by the destination user.
294 us <- atomically $ readTVar (csUtmp cw)
295 let ptys = Map.filterWithKey ispty us
296 ispty k _ = "pts/" `Text.isPrefixOf` k
297 && Text.all isDigit (Text.drop 4 k)
298 bs <- forM (Map.toList ptys) $ \(tty,utmp) -> do
299 deliverTerminalMessage cw ("/dev/" <> tty) utmp msg
300 return $ or bs
301
302resource :: UtmpRecord -> Text
303resource u =
304 case utmpTty u of
305 s | Text.take 3 s == "tty" -> s
306 s | Text.take 4 s == "pts/" -> "pty" <> Text.drop 4 s <> ":" <> utmpHost u
307 s -> escapeR s <> ":" <> utmpHost u
308 where
309 escapeR s = s
310
311textHostName :: IO Text
312textHostName = fmap Text.pack BSD.getHostName
313
314ujid :: UtmpRecord -> IO Text
315ujid u = do
316 h <- textHostName
317 return $ utmpUser u <> "@" <> h <> "/" <> resource u
318
319newCon :: (Text -> IO ())
320 -> ConsoleWriter
321 -> STM (Word8,Maybe UtmpRecord)
322 -> TVar (Maybe UtmpRecord)
323 -> IO ()
324newCon log cw activeTTY utmp = do
325 ((tty,tu),u) <- atomically $
326 liftM2 (,) activeTTY
327 (readTVar utmp)
328 flip (maybe $ return ()) u $ \u -> do
329 jid <- ujid u
330 log $ status (resource u) tty tu <> " " <> jid <> " pid=" <> tshow (utmpPid u)
331 <> (if istty (resource u)
332 then " host=" <> tshow (utmpHost u)
333 else "")
334 <> " session=" <> tshow (utmpSession u)
335 <> " addr=" <> tshow (utmpRemoteAddr u)
336 let r = resource u
337 stanza <- makePresenceStanza
338 "jabber:client"
339 (Just jid)
340 (jstatus r tty tu)
341 statusv <- atomically $ newTVar (Just stanza)
342 flgs <- atomically $ newTVar 0
343 let client = ClientState { clientResource = r
344 , clientUser = utmpUser u
345 , clientPid = Nothing
346 , clientStatus = statusv
347 , clientFlags = flgs }
348 atomically $ do
349 modifyTVar (cwClients cw) $ Map.insert r client
350 putTMVar (cwPresenceChan cw) (client,stanza)
351 loop client tty tu (Just u)
352 where
353 bstatus r ttynum mtu
354 = r == ttystr
355 || match mtu
356 where ttystr = "tty" <> tshow ttynum
357 searchstr mtu = maybe ttystr utmpHost $ do
358 tu <- mtu
359 guard (not $ Text.null $ utmpHost tu)
360 return tu
361 match mtu = searchstr mtu `Text.isInfixOf` Text.dropWhile (/=':') r
362 jstatus r ttynum tu =
363 if bstatus r ttynum tu
364 then Available
365 else Away
366 status r ttynum tu = tshow $ jstatus r ttynum tu
367
368 istty r = fst3 == "tty" && Text.all isDigit rst
369 where
370 (fst3,rst) = Text.splitAt 3 r
371
372 loop client tty tu u = do
373 what <- atomically $ foldr1 orElse
374 [ do (tty',tu') <- retryWhen activeTTY
375 (\ttyu -> bstatus r tty tu == uncurry (bstatus r) ttyu)
376 return $ ttyChanged tty' tu'
377 , do u' <- retryWhen (readTVar utmp) (==u)
378 return $ utmpChanged u'
379 ]
380 what
381 where
382 r = maybe "" resource u
383
384 ttyChanged tty' tu' = do
385 jid <- maybe (return "") ujid u
386 stanza <- makePresenceStanza
387 "jabber:client"
388 (Just jid)
389 (jstatus r tty' tu')
390 dup <- cloneStanza stanza
391 atomically $ do
392 writeTVar (clientStatus client) $ Just dup
393 putTMVar (cwPresenceChan cw) (client,stanza)
394 log $ status r tty' tu' <> " " <> jid
395 loop client tty' tu' u
396
397 utmpChanged u' = maybe dead changed u'
398 where
399 changed u' = do
400 jid0 <- maybe (return "") ujid u
401 jid <- ujid u'
402 log $ "changed: " <> jid0 <> " --> " <> jid
403 loop client tty tu (Just u')
404 dead = do
405 jid <- maybe (return "") ujid u
406 stanza <- makePresenceStanza "jabber:client" (Just jid) Offline
407 atomically $ do
408 modifyTVar (cwClients cw) $ Map.delete (clientResource client)
409 putTMVar (cwPresenceChan cw) (client,stanza)
410 log $ "Offline " <> jid
411
diff --git a/Presence/ControlMaybe.hs b/Presence/ControlMaybe.hs
new file mode 100644
index 00000000..659dab74
--- /dev/null
+++ b/Presence/ControlMaybe.hs
@@ -0,0 +1,29 @@
1{-# LANGUAGE ScopedTypeVariables #-}
2module ControlMaybe where
3
4-- import GHC.IO.Exception (IOException(..))
5import Control.Exception as Exception (IOException(..),catch)
6
7
8withJust :: Monad m => Maybe x -> (x -> m ()) -> m ()
9withJust (Just x) f = f x
10withJust Nothing f = return ()
11
12whenJust :: Monad m => m (Maybe x) -> (x -> m ()) -> m ()
13whenJust acn f = do
14 x <- acn
15 withJust x f
16
17
18catchIO_ :: IO a -> IO a -> IO a
19catchIO_ a h = Exception.catch a (\(_ :: IOException) -> h)
20
21catchIO :: IO a -> (IOException -> IO a) -> IO a
22catchIO body handler = Exception.catch body handler
23
24handleIO_ :: IO a -> IO a -> IO a
25handleIO_ = flip catchIO_
26
27
28handleIO :: (IOException -> IO a) -> IO a -> IO a
29handleIO = flip catchIO
diff --git a/Presence/DNSCache.hs b/Presence/DNSCache.hs
new file mode 100644
index 00000000..aaf1a7be
--- /dev/null
+++ b/Presence/DNSCache.hs
@@ -0,0 +1,270 @@
1-- | Both 'getAddrInfo' and 'getHostByAddr' have hard-coded timeouts for
2-- waiting upon network queries that can be a little too long for some use
3-- cases. This module wraps both of them so that they block for at most one
4-- second. It caches late-arriving results so that they can be returned by
5-- repeated timed-out queries.
6--
7-- In order to achieve the shorter timeout, it is likely that the you will need
8-- to build with GHC's -threaded option. Otherwise, if the wrapped FFI calls
9-- to resolve the address will block Haskell threads. Note: I didn't verify
10-- this.
11{-# LANGUAGE TupleSections #-}
12{-# LANGUAGE RankNTypes #-}
13{-# LANGUAGE CPP #-}
14module DNSCache
15 ( DNSCache
16 , reverseResolve
17 , forwardResolve
18 , newDNSCache
19 , parseAddress
20 , strip_brackets
21 , withPort
22 ) where
23
24#ifdef THREAD_DEBUG
25import Control.Concurrent.Lifted.Instrument
26#else
27import Control.Concurrent.Lifted
28import GHC.Conc (labelThread)
29#endif
30import Control.Concurrent.STM
31import Data.Text ( Text )
32import Network.Socket ( SockAddr(..), AddrInfoFlag(..), defaultHints, getAddrInfo, AddrInfo(..) )
33import Data.Time.Clock ( UTCTime, getCurrentTime, diffUTCTime )
34import System.IO.Error ( isDoesNotExistError )
35import System.Endian ( fromBE32, toBE32 )
36import Control.Exception ( handle )
37import Data.Map ( Map )
38import qualified Data.Map as Map
39import qualified Network.BSD as BSD
40import qualified Data.Text as Text
41import Control.Monad
42import Data.Function
43import Data.List
44import Data.Ord
45import Data.Maybe
46import System.IO
47import System.IO.Error
48
49import SockAddr ()
50import ControlMaybe ( handleIO_ )
51import GetHostByAddr ( getHostByAddr )
52import InterruptibleDelay
53
54type TimeStamp = UTCTime
55
56data DNSCache =
57 DNSCache
58 { fcache :: TVar (Map Text [(TimeStamp, SockAddr)])
59 , rcache :: TVar (Map SockAddr [(TimeStamp, Text)])
60 }
61
62
63newDNSCache :: IO DNSCache
64newDNSCache = do
65 fcache <- newTVarIO Map.empty
66 rcache <- newTVarIO Map.empty
67 return DNSCache { fcache=fcache, rcache=rcache }
68
69updateCache :: Eq x =>
70 Bool -> TimeStamp -> [x] -> Maybe [(TimeStamp,x)] -> Maybe [(TimeStamp,x)]
71updateCache withScrub utc xs mys = do
72 let ys = maybe [] id mys
73 ys' = filter scrub ys
74 ys'' = map (utc,) xs ++ ys'
75 minute = 60
76 scrub (t,x) | withScrub && diffUTCTime utc t < minute = False
77 scrub (t,x) | x `elem` xs = False
78 scrub _ = True
79 guard $ not (null ys'')
80 return ys''
81
82dnsObserve :: DNSCache -> Bool -> TimeStamp -> [(Text,SockAddr)] -> STM ()
83dnsObserve dns withScrub utc obs = do
84 f <- readTVar $ fcache dns
85 r <- readTVar $ rcache dns
86 let obs' = map (\(n,a)->(n,a `withPort` 0)) obs
87 gs = do
88 g <- groupBy ((==) `on` fst) $ sortBy (comparing fst) obs'
89 (n,_) <- take 1 g
90 return (n,map snd g)
91 f' = foldl' updatef f gs
92 hs = do
93 h <- groupBy ((==) `on` snd) $ sortBy (comparing snd) obs'
94 (_,a) <- take 1 h
95 return (a,map fst h)
96 r' = foldl' updater r hs
97 writeTVar (fcache dns) f'
98 writeTVar (rcache dns) r'
99 where
100 updatef f (n,addrs) = Map.alter (updateCache withScrub utc addrs) n f
101 updater r (a,ns) = Map.alter (updateCache withScrub utc ns) a r
102
103make6mapped4 :: SockAddr -> SockAddr
104make6mapped4 addr@(SockAddrInet6 {}) = addr
105make6mapped4 addr@(SockAddrInet port a) = SockAddrInet6 port 0 (0,0,0xFFFF,fromBE32 a) 0
106
107tryForkOS :: IO () -> IO ThreadId
108tryForkOS action = catchIOError (forkOS action) $ \e -> do
109 hPutStrLn stderr $ "DNSCache: Link with -threaded to avoid excessively long time-out."
110 forkIO action
111
112
113-- Attempt to resolve the given domain name. Returns an empty list if the
114-- resolve operation takes longer than the timeout, but the 'DNSCache' will be
115-- updated when the resolve completes.
116--
117-- When the resolve operation does complete, any entries less than a minute old
118-- will be overwritten with the new results. Older entries are allowed to
119-- persist for reasons I don't understand as of this writing. (See 'updateCache')
120rawForwardResolve ::
121 DNSCache -> (Text -> IO ()) -> Int -> Text -> IO [SockAddr]
122rawForwardResolve dns onFail timeout addrtext = do
123 r <- atomically newEmptyTMVar
124 mvar <- interruptibleDelay
125 rt <- tryForkOS $ do
126 myThreadId >>= flip labelThread ("resolve."++show addrtext)
127 resolver r mvar
128 startDelay mvar timeout
129 did <- atomically $ tryPutTMVar r []
130 when did (onFail addrtext)
131 atomically $ readTMVar r
132 where
133 resolver r mvar = do
134 xs <- handle (\e -> let _ = isDoesNotExistError e in return [])
135 $ do fmap (nub . map (make6mapped4 . addrAddress)) $
136 getAddrInfo (Just $ defaultHints { addrFlags = [ AI_CANONNAME, AI_V4MAPPED ]})
137 (Just $ Text.unpack $ strip_brackets addrtext)
138 (Just "5269")
139 did <- atomically $ tryPutTMVar r xs
140 when did $ do
141 interruptDelay mvar
142 utc <- getCurrentTime
143 atomically $ dnsObserve dns True utc $ map (addrtext,) xs
144 return ()
145
146strip_brackets :: Text -> Text
147strip_brackets s =
148 case Text.uncons s of
149 Just ('[',t) -> Text.takeWhile (/=']') t
150 _ -> s
151
152
153reportTimeout :: forall a. Show a => a -> IO ()
154reportTimeout addrtext = do
155 hPutStrLn stderr $ "timeout resolving: "++show addrtext
156 -- killThread rt
157
158unmap6mapped4 :: SockAddr -> SockAddr
159unmap6mapped4 addr@(SockAddrInet6 port _ (0,0,0xFFFF,a) _) =
160 SockAddrInet port (toBE32 a)
161unmap6mapped4 addr = addr
162
163rawReverseResolve ::
164 DNSCache -> (SockAddr -> IO ()) -> Int -> SockAddr -> IO [Text]
165rawReverseResolve dns onFail timeout addr = do
166 r <- atomically newEmptyTMVar
167 mvar <- interruptibleDelay
168 rt <- forkOS $ resolver r mvar
169 startDelay mvar timeout
170 did <- atomically $ tryPutTMVar r []
171 when did (onFail addr)
172 atomically $ readTMVar r
173 where
174 resolver r mvar =
175 handleIO_ (return ()) $ do
176 ent <- getHostByAddr (unmap6mapped4 addr) -- AF_UNSPEC addr
177 let names = BSD.hostName ent : BSD.hostAliases ent
178 xs = map Text.pack $ nub names
179 forkIO $ do
180 utc <- getCurrentTime
181 atomically $ dnsObserve dns False utc $ map (,addr) xs
182 atomically $ putTMVar r xs
183
184-- Returns expired (older than a minute) cached reverse-dns results
185-- and removes them from the cache.
186expiredReverse :: DNSCache -> SockAddr -> IO [Text]
187expiredReverse dns addr = do
188 utc <- getCurrentTime
189 addr <- return $ addr `withPort` 0
190 es <- atomically $ do
191 r <- readTVar $ rcache dns
192 let ns = maybe [] id $ Map.lookup addr r
193 minute = 60 -- seconds
194 -- XXX: Is this right? flip diffUTCTime utc returns the age of the
195 -- cache entry?
196 (es0,ns') = partition ( (>=minute) . flip diffUTCTime utc . fst ) ns
197 es = map snd es0
198 modifyTVar' (rcache dns) $ Map.insert addr ns'
199 f <- readTVar $ fcache dns
200 let f' = foldl' (flip $ Map.alter (expire utc)) f es
201 expire utc Nothing = Nothing
202 expire utc (Just as) = if null as' then Nothing else Just as'
203 where as' = filter ( (<minute) . flip diffUTCTime utc . fst) as
204 writeTVar (fcache dns) f'
205 return es
206 return es
207
208cachedReverse :: DNSCache -> SockAddr -> IO [Text]
209cachedReverse dns addr = do
210 utc <- getCurrentTime
211 addr <- return $ addr `withPort` 0
212 atomically $ do
213 r <- readTVar (rcache dns)
214 let ns = maybe [] id $ Map.lookup addr r
215 {-
216 ns' = filter ( (<minute) . flip diffUTCTime utc . fst) ns
217 minute = 60 -- seconds
218 modifyTVar' (rcache dns) $ Map.insert addr ns'
219 return $ map snd ns'
220 -}
221 return $ map snd ns
222
223-- Returns any dns query results for the given name that were observed less
224-- than a minute ago and updates the forward-cache to remove any results older
225-- than that.
226cachedForward :: DNSCache -> Text -> IO [SockAddr]
227cachedForward dns n = do
228 utc <- getCurrentTime
229 atomically $ do
230 f <- readTVar (fcache dns)
231 let as = maybe [] id $ Map.lookup n f
232 as' = filter ( (<minute) . flip diffUTCTime utc . fst) as
233 minute = 60 -- seconds
234 modifyTVar' (fcache dns) $ Map.insert n as'
235 return $ map snd as'
236
237-- Reverse-resolves an address to a domain name. Returns both the result of a
238-- new query and any freshly cached results. Cache entries older than a minute
239-- will not be returned, but will be refreshed in spawned threads so that they
240-- may be available for the next call.
241reverseResolve :: DNSCache -> SockAddr -> IO [Text]
242reverseResolve dns addr = do
243 expired <- expiredReverse dns addr
244 forM_ expired $ \n -> forkIO $ do
245 rawForwardResolve dns (const $ return ()) 1000000 n
246 return ()
247 xs <- rawReverseResolve dns (const $ return ()) 1000000 addr
248 cs <- cachedReverse dns addr
249 return $ xs ++ filter (not . flip elem xs) cs
250
251-- Resolves a name, if there's no result within one second, then any cached
252-- results that are less than a minute old are returned.
253forwardResolve :: DNSCache -> Text -> IO [SockAddr]
254forwardResolve dns n = do
255 as <- rawForwardResolve dns (const $ return ()) 1000000 n
256 if null as
257 then cachedForward dns n
258 else return as
259
260parseAddress :: Text -> IO (Maybe SockAddr)
261parseAddress addr_str = do
262 info <- getAddrInfo (Just $ defaultHints { addrFlags = [ AI_NUMERICHOST ] })
263 (Just . Text.unpack $ addr_str)
264 (Just "0")
265 return . listToMaybe $ map addrAddress info
266
267
268withPort :: SockAddr -> Int -> SockAddr
269withPort (SockAddrInet _ a) port = SockAddrInet (toEnum port) a
270withPort (SockAddrInet6 _ a b c) port = SockAddrInet6 (toEnum port) a b c
diff --git a/Presence/EventUtil.hs b/Presence/EventUtil.hs
new file mode 100644
index 00000000..908e09e0
--- /dev/null
+++ b/Presence/EventUtil.hs
@@ -0,0 +1,83 @@
1{-# LANGUAGE OverloadedStrings #-}
2module EventUtil where
3
4import Control.Monad
5import Data.XML.Types as XML
6import qualified Data.List as List
7import Data.Text (Text)
8
9-- getStreamName (EventBeginElement name _) = name
10
11isEventBeginElement :: Event -> Bool
12isEventBeginElement (EventBeginElement {}) = True
13isEventBeginElement _ = False
14
15isEventEndElement :: Event -> Bool
16isEventEndElement (EventEndElement {}) = True
17isEventEndElement _ = False
18
19-- Note: This function ignores name space qualification
20elementAttrs ::
21 MonadPlus m =>
22 Text -> Event -> m [(Name, [Content])]
23elementAttrs expected (EventBeginElement name attrs)
24 | nameLocalName name==expected
25 = return attrs
26elementAttrs _ _ = mzero
27
28streamP :: Text -> Name
29streamP name = Name name (Just "http://etherx.jabber.org/streams") (Just "stream")
30
31attr :: Name -> Text -> (Name,[Content])
32attr name value = (name,[ContentText value])
33
34isServerIQOf :: Event -> Text -> Bool
35isServerIQOf (EventBeginElement name attrs) testType
36 | name=="{jabber:server}iq"
37 && matchAttrib "type" testType attrs
38 = True
39isServerIQOf _ _ = False
40
41isClientIQOf :: Event -> Text -> Bool
42isClientIQOf (EventBeginElement name attrs) testType
43 | name=="{jabber:client}iq"
44 && matchAttrib "type" testType attrs
45 = True
46isClientIQOf _ _ = False
47
48matchAttrib :: Name -> Text -> [(Name, [Content])] -> Bool
49matchAttrib name value attrs =
50 case List.find ( (==name) . fst) attrs of
51 Just (_,[ContentText x]) | x==value -> True
52 Just (_,[ContentEntity x]) | x==value -> True
53 _ -> False
54
55lookupAttrib :: Name -> [(Name, [Content])] -> Maybe Text
56lookupAttrib name attrs =
57 case List.find ( (==name) . fst) attrs of
58 Just (_,[ContentText x]) -> Just x
59 Just (_,[ContentEntity x]) -> Just x
60 _ -> Nothing
61
62tagAttrs :: Event -> [(Name, [Content])]
63tagAttrs (EventBeginElement _ xs) = xs
64tagAttrs _ = []
65
66
67{-
68iqTypeSet = "set"
69iqTypeGet = "get"
70iqTypeResult = "result"
71iqTypeError = "error"
72-}
73
74
75tagName :: Event -> Name
76tagName (EventBeginElement n _) = n
77tagName _ = ""
78
79closerFor :: Event -> Event
80closerFor (EventBeginElement n _) = EventEndElement n
81closerFor _ = error "closerFor: unsupported event"
82
83
diff --git a/Presence/FGConsole.hs b/Presence/FGConsole.hs
new file mode 100644
index 00000000..03aaebf2
--- /dev/null
+++ b/Presence/FGConsole.hs
@@ -0,0 +1,67 @@
1{-# LANGUAGE ForeignFunctionInterface #-}
2{-# LANGUAGE ScopedTypeVariables #-}
3module FGConsole where
4
5import Data.Word
6import System.Posix.IO
7import System.Posix.Types
8import Control.Concurrent
9-- import GHC.IO.Handle
10import Unsafe.Coerce
11import Control.Exception as E
12-- import Prelude as E
13import Control.Monad
14import Foreign.C
15
16import Logging
17import System.Posix.Signals
18
19-- c_monitorTTY fd = trace "c_monitorTTY" (return ()) -- (trace "WTF" todo)
20
21foreign import ccall "monitorTTY" c_monitorTTY :: Fd -> IO CInt
22foreign import ccall "closeTTY" c_closeTTY :: IO ()
23
24forkTTYMonitor :: (Word8 -> IO ()) -> IO (Maybe (Fd,ThreadId))
25forkTTYMonitor handler = do
26 (rfd,wfd) <- createPipe
27 retvar <- newEmptyMVar
28 thread <- forkIO $ do
29 let cleanup = do
30 trace "quitting monitorTTY thread." (return ())
31 closeFd wfd `E.catch` \(e::IOException) -> return ()
32 closeFd rfd `E.catch` \(e::IOException) -> return ()
33 c_closeTTY
34 -- rh <- fdToHandle rfd
35 didfork <- c_monitorTTY wfd
36 putMVar retvar didfork
37 when (didfork == 0) $ do
38 let monitor =
39 (do
40 threadWaitRead rfd
41 (cs,cnt) <- fdRead rfd 1
42 forM_ cs (handler . unsafeCoerce {- . trace "read byte" -})
43 monitor)
44 `E.catch`
45 \(e :: IOException) -> do
46 err <- getErrno
47 case () of
48 _ | err==eAGAIN -> monitor
49 _ | otherwise -> cleanup
50 `E.catch`
51 \(e :: AsyncException) -> cleanup
52 monitor
53 didfork <- takeMVar retvar
54 if didfork == 0
55 then return $! Just (rfd,thread)
56 else return $! Nothing
57
58killTTYMonitor :: (Fd, ThreadId) -> IO ()
59killTTYMonitor (rfd,thread) = do
60 closeFd rfd
61 yield
62 killThread thread
63 raiseSignal sigUSR1
64 -- threadDelay 1000000
65
66
67-- vim:ft=haskell:
diff --git a/Presence/GetHostByAddr.hs b/Presence/GetHostByAddr.hs
new file mode 100644
index 00000000..45bca5e9
--- /dev/null
+++ b/Presence/GetHostByAddr.hs
@@ -0,0 +1,77 @@
1{-# LANGUAGE ForeignFunctionInterface #-}
2module GetHostByAddr where
3
4import Network.BSD
5import Foreign.Ptr
6import Foreign.C.Types
7import Foreign.Storable (Storable(..))
8import Foreign.Marshal.Utils (with)
9import Foreign.Marshal.Alloc
10import Control.Concurrent
11import System.IO.Unsafe
12import System.IO.Error (ioeSetErrorString, mkIOError)
13import Network.Socket
14import GHC.IO.Exception
15
16
17throwNoSuchThingIfNull :: String -> String -> IO (Ptr a) -> IO (Ptr a)
18throwNoSuchThingIfNull loc desc act = do
19 ptr <- act
20 if (ptr == nullPtr)
21 then ioError (ioeSetErrorString (mkIOError NoSuchThing loc Nothing Nothing) desc)
22 else return ptr
23
24{-# NOINLINE lock #-}
25lock :: MVar ()
26lock = unsafePerformIO $ newMVar ()
27
28withLock :: IO a -> IO a
29withLock act = withMVar lock (\_ -> act)
30
31trySysCall :: IO a -> IO a
32trySysCall act = act
33
34{-
35-- The locking of gethostbyaddr is similar to gethostbyname.
36-- | Get a 'HostEntry' corresponding to the given address and family.
37-- Note that only IPv4 is currently supported.
38getHostByAddr :: Family -> SockAddr -> IO HostEntry
39getHostByAddr family addr = do
40 withSockAddr addr $ \ ptr_addr len -> withLock $ do
41 throwNoSuchThingIfNull "getHostByAddr" "no such host entry"
42 $ trySysCall $ c_gethostbyaddr ptr_addr (fromIntegral len) (packFamily family)
43 >>= peek
44-}
45
46
47-- The locking of gethostbyaddr is similar to gethostbyname.
48-- | Get a 'HostEntry' corresponding to the given address and family.
49-- Note that only IPv4 is currently supported.
50-- getHostByAddr :: Family -> HostAddress -> IO HostEntry
51-- getHostByAddr family addr = do
52getHostByAddr :: SockAddr -> IO HostEntry
53getHostByAddr (SockAddrInet port addr ) = do
54 let family = AF_INET
55 with addr $ \ ptr_addr -> withLock $ do
56 throwNoSuchThingIfNull "getHostByAddr" "no such host entry"
57 $ trySysCall $ c_gethostbyaddr ptr_addr (fromIntegral (sizeOf addr)) (packFamily family)
58 >>= peek
59getHostByAddr (SockAddrInet6 port flow (a,b,c,d) scope) = do
60 let family = AF_INET6
61 allocaBytes 16 $ \ ptr_addr -> do
62 pokeElemOff ptr_addr 0 a
63 pokeElemOff ptr_addr 1 b
64 pokeElemOff ptr_addr 2 c
65 pokeElemOff ptr_addr 3 d
66 withLock $ do
67 throwNoSuchThingIfNull "getHostByAddr" "no such host entry"
68 $ trySysCall $ c_gethostbyaddr ptr_addr 16 (packFamily family)
69 >>= peek
70
71
72foreign import ccall safe "gethostbyaddr"
73 c_gethostbyaddr :: Ptr a -> CInt -> CInt -> IO (Ptr HostEntry)
74
75
76
77-- vim:ft=haskell:
diff --git a/Presence/IDMangler.hs b/Presence/IDMangler.hs
new file mode 100644
index 00000000..664d4f54
--- /dev/null
+++ b/Presence/IDMangler.hs
@@ -0,0 +1,68 @@
1---------------------------------------------------------------------------
2-- |
3-- Module : IDMangler
4--
5-- This library is useful for generating id attributes for use in an XMPP
6-- application. It conveniently encodes a key value for looking up context and
7-- an original id attribute in case of forwarded messages.
8--
9-- For example, an id attribute with an embedded 'XMPPServer.ConnectionKey'
10-- for a forwarded message with an original id attribute of \"purplecfa6168a\"
11-- might look something like this:
12--
13-- > AAAAAAAAAAIBksnqOQiYmtmupcLxbXakI9zcmUl4:purplecfa6168a
14--
15{-# LANGUAGE OverloadedStrings #-}
16module IDMangler
17 ( IDMangler
18 , newIDMangler
19 , generateUniqueID
20 , unmangleId
21 ) where
22
23import Control.Monad.STM
24import Control.Concurrent.STM
25import Data.Text (Text)
26import qualified Data.Text as Text
27import qualified Data.ByteString.Lazy as LazyByteString
28import Data.Binary
29import qualified Codec.Binary.Base64 as Base64
30import Control.Monad
31import Data.Monoid ( (<>) )
32
33
34data IDMangler k
35 = IDMangler { idmCounter :: TVar Int }
36
37newIDMangler :: IO (IDMangler k)
38newIDMangler = do
39 nv <- atomically $ newTVar 0
40 return $ IDMangler nv
41
42-- | Use the given state and optional data to generate a unique id attribute
43-- suitable for xml. To recover the optional encoded data, see 'unmangleId'.
44generateUniqueID :: Binary k =>
45 IDMangler k -- ^ the state (a counter) for ensuring uniqueness
46 -> Maybe k -- ^ optional recoverable key for context
47 -> Maybe Text -- ^ optional recoverable auxilary id attribute
48 -> IO Text -- ^ unique id attribute with encoded data
49generateUniqueID mangler mkey mid = do
50 n <- atomically $ do
51 modifyTVar' (idmCounter mangler) (+1)
52 readTVar (idmCounter mangler)
53 let bs = encode (n,mkey)
54 base64 = Base64.encode (LazyByteString.unpack bs)
55 suf = maybe "" (":" <>) mid
56 return $ Text.pack base64 <> suf
57
58-- | Recover data from an encoded id attribute.
59unmangleId :: Binary k => Text -> (Maybe k, Maybe Text)
60unmangleId encoded = (k,mid)
61 where
62 (e,postcolon) = Text.span (/=':') encoded
63 bytes = Base64.decode (Text.unpack e)
64 decoded = fmap (decode . LazyByteString.pack) bytes
65 k = decoded >>= (\(n,k) -> let _ = n :: Int in k)
66 mid = do guard (not . Text.null $ postcolon)
67 return $ Text.drop 1 postcolon
68
diff --git a/Presence/LocalPeerCred.hs b/Presence/LocalPeerCred.hs
new file mode 100644
index 00000000..9054f180
--- /dev/null
+++ b/Presence/LocalPeerCred.hs
@@ -0,0 +1,234 @@
1{-# LANGUAGE ViewPatterns #-}
2{-# LANGUAGE TupleSections #-}
3module LocalPeerCred where
4
5import System.Endian
6import qualified Data.ByteString.Lazy.Char8 as L
7 -- hiding (map,putStrLn,tail,splitAt,tails,filter)
8 -- import qualified Data.ByteString.Lazy.Char8 as L (splitAt)
9import qualified Data.ByteString.Lazy as W8
10import Data.List as List (tails,groupBy)
11import System.IO ( withFile, IOMode(..))
12import System.Directory
13import Control.Arrow (first)
14import Data.Char
15import Data.Maybe
16import Data.Bits
17import Data.Serialize
18import Data.Word
19import System.Posix.Types
20import System.Posix.Files
21import Logging
22import Network.SocketLike
23import ControlMaybe
24import Data.String
25import System.IO
26
27(??) :: (Num t, Ord t) => [a] -> t -> Maybe a
28xs ?? n | n < 0 = Nothing
29[] ?? _ = Nothing
30(x:_) ?? 0 = Just x
31(_:xs) ?? n = xs ?? (n-1)
32
33parseHex :: W8.ByteString -> W8.ByteString
34parseHex bs = L.concat . parseHex' $ bs
35 where
36 parseHex' bs =
37 let (dnib,ts) = L.splitAt 2 bs
38 parseNibble x = W8.pack $ group2 toW8 (W8.unpack $ W8.map hexDigit x)
39 hexDigit d = d - (if d>0x39 then 0x37 else 0x30)
40 group2 f (x:y:ys) = f x y : group2 f ys
41 group2 _ _ = []
42 toW8 a b = shift a 4 .|. b
43 in parseNibble dnib :
44 if L.null ts
45 then []
46 else parseHex' ts
47
48getLocalPeerCred' :: SockAddr -> IO (Maybe (UserID, W8.ByteString))
49getLocalPeerCred' (unmap6mapped4 -> SockAddrInet portn host) = do
50 let port = fromEnum portn
51 {- trace ("tcp4 "++show(port,host)) $ -}
52 withFile "/proc/net/tcp" ReadMode (parseProcNet port host)
53
54getLocalPeerCred' (unmap6mapped4 -> SockAddrInet6 portn flow host scope) = do
55 let port = fromEnum portn
56 (a,b,c,d) = host
57 host' = (toBE32 a, toBE32 b, toBE32 c, toBE32 d)
58 withFile "/proc/net/tcp6" ReadMode (parseProcNet port host')
59
60getLocalPeerCred' (unmap6mapped4 -> addr@(SockAddrUnix _)) =
61 -- TODO: parse /proc/net/unix
62 -- see also: Network.Socket.getPeerCred
63 return Nothing
64
65getLocalPeerCred :: SocketLike sock => sock -> IO (Maybe UserID)
66getLocalPeerCred sock = do
67 addr <- getPeerName sock
68 muid <- getLocalPeerCred' addr
69 case muid of
70 Just (uid,inode) -> return (Just uid)
71 Nothing -> trace "proc failed." $ fmap (validate . CUid . fromIntegral . sndOf3) (getPeerCred sock)
72 where sndOf3 (pid,uid,gid) = uid
73 where
74 validate uid = Just uid -- TODO
75
76from16 :: Word16 -> Int
77from16 = fromEnum
78
79as16 :: Word16 -> Word16
80as16 = id
81
82parseProcNet :: (Serialize t, Num t1, Eq t, Eq t1) =>
83 t1
84 -> t
85 -> Handle
86 -> IO (Maybe (UserID, W8.ByteString))
87parseProcNet port host h = do
88 tcp <- L.hGetContents h -- Failed: tcp <- hFileSize h >>= hGet h . fromIntegral
89 let u = do
90 ls <- listToMaybe . tail . tails . L.lines $ tcp
91 let ws = map L.words ls
92 let rs = ( catMaybes . flip map ws $ \xs -> do
93 let ys = snd (Prelude.splitAt 1 xs)
94 localaddr <- listToMaybe ys
95 let zs = L.splitWith (==':') localaddr
96 addr <- fmap parseHex $ listToMaybe zs
97 port <- either (const Nothing) (Just . fromIntegral . as16) . decode . L.toStrict . parseHex
98 =<< listToMaybe (snd (Prelude.splitAt 1 zs))
99 let ys' = snd (Prelude.splitAt 5 (tail ys))
100 ys'' = snd (Prelude.splitAt 2 ys')
101 uid <- listToMaybe ys'
102 inode <- listToMaybe ys''
103 peer <- either (const Nothing) Just $ do
104 a <- decode $ L.toStrict addr
105 return (port,a)
106 let user = toEnum (read (L.unpack uid) ::Int) ::UserID -- CUid . fromIntegral $ (read (unpack uid)::Int)
107 return $ {-trace ("peer:"++show(peer,user,inode))-} (peer,(user,inode))
108 )
109 fmap snd . listToMaybe $ filter ((==(port,host)).fst) rs
110 {- trace ("found: "++show u) -}
111 u `seq` return u
112 {-
113 where
114 a === b = let r= a==b in trace ("Comparing "++show (a,b)++"-->"++show r) r
115 -}
116
117
118-- PEER NAME: [::ffff:127.0.0.1]:34307
119unmap6mapped4 :: SockAddr -> SockAddr
120unmap6mapped4 addr@(SockAddrInet6 port _ (0,0,0xFFFF,a) _) = SockAddrInet port (toBE32 a)
121unmap6mapped4 addr = addr
122
123identifyTTY ::
124 [(W8.ByteString, ProcessID)]
125 -> UserID -> W8.ByteString -> IO (Maybe W8.ByteString, Maybe CPid)
126identifyTTY tty_pids uid inode = do
127 pid <- scanProc (show uid) (L.unpack inode)
128 -- putStrLn $ "scanProc --> "++show pid
129 flip (maybe (return (Nothing,Nothing))) pid $ \(pid,ttydev) -> do
130 tty <- ttyOrDisplay pid ttydev
131 -- putStrLn $ "users = " ++ show tty_pids
132 dts <- ttyToXorgs tty_pids
133 -- putStrLn $ "displays = " ++ show dts
134 -- putStrLn $ "tty = " ++ show tty
135 -- -- displays = [(":5",Chunk "tty7" Empty)]
136 let tty' = if take 3 tty=="tty"
137 then Just (L.pack tty)
138 else lookup (parseTty tty) (map (first parseTty) dts)
139 return (tty',Just pid)
140 where
141 parseTty :: String -> Float
142 parseTty = read . tail . dropWhile (/=':')
143
144ttyToXorgs :: Show a => [(t, a)] -> IO [([Char], t)]
145ttyToXorgs tty_pids = do
146 dts' <- flip mapM tty_pids $ \(tty,pid) -> do
147 cmd' <- readFile $ "/proc/"++show pid++"/cmdline"
148 case listToMaybe . words . takeWhile (/='\0') $ cmd' of
149 Nothing -> return Nothing
150 Just cmd -> do
151 if notElem cmd ["gdm-session-worker"]
152 then return Nothing
153 else do
154 display <- readDisplayVariable pid
155 return (fmap ( (,tty) . snd ) display)
156 let dts = catMaybes dts'
157 return dts
158
159
160scanProc :: t -> [Char] -> IO (Maybe (CPid, FilePath))
161scanProc uid inode = do
162 contents <- getDirectoryContents "/proc" `catchIO_` return []
163 let pids = reverse $ filter (\n -> not (null n) && isDigit (head n)) contents
164 let searchPids [] = return Nothing
165 searchPids (pid:pids) = do
166 loginuid <- fmap makeUidStr $ readFile $ "/proc/"++pid++"/loginuid"
167 if False -- (uid/=loginuid) -- this check proved bad when mcabber ran on tty3
168 then searchPids pids
169 else do
170 -- putStrLn $ "pid "++show pid ++ " --> uid "++show loginuid
171 let loop [] = return Nothing
172 loop ("0":fds) = loop fds
173 loop (fd:fds) = do
174 handleIO_ (loop fds) $ do
175 what <- readSymbolicLink $ "/proc/"++pid++"/fd/"++fd
176 -- putStrLn $ " what= "++show what
177 if (what=="socket:["++inode++"]")
178 then do
179 tty <- readSymbolicLink $ "/proc/"++pid++"/fd/0"
180 return (Just (pid,tty))
181 else loop fds
182 -- requires root (or same user as for pid)...
183 fds <- getDirectoryContents ("/proc/"++pid++"/fd") `catchIO_` return []
184 mb <- loop fds
185 maybe (searchPids pids) (return . Just) mb
186
187 fmap (fmap (first (read :: String -> CPid))) $ searchPids pids
188
189ttyOrDisplay :: Show a => a -> FilePath -> IO [Char]
190ttyOrDisplay pid ttydev = do
191 ptty <- searchParentsForTTY (show pid) ttydev
192 case ptty of
193 Just tty -> return tty
194 Nothing -> do
195 display <- readDisplayVariable pid
196 -- putStrLn $ "display = " ++ show display
197 case display of
198 Just (_,disp) -> return disp
199 _ -> return ttydev
200
201
202readDisplayVariable :: Show a => a -> IO (Maybe ([Char], [Char]))
203readDisplayVariable pid = do
204 env <- handleIO_ (return "")
205 . readFile $ "/proc/"++show pid++"/environ"
206 let vs = unzero $ List.groupBy (\_ c->c/='\0') env
207 unzero [] = []
208 unzero (v:vs) = v:map tail vs
209 keyvalue xs = (key,value)
210 where
211 (key,ys) = break (=='=') xs
212 value = case ys of { [] -> []; (_:ys') -> ys' }
213 display = listToMaybe
214 . filter ((=="DISPLAY").fst)
215 . map keyvalue
216 $ vs
217 return display
218
219
220makeUidStr :: (Data.String.IsString t, Eq t) => t -> t
221makeUidStr "4294967295" = "invalid"
222makeUidStr uid = uid
223
224
225searchParentsForTTY :: String -> FilePath -> IO (Maybe [Char])
226searchParentsForTTY pid ttydev | take 8 ttydev == "/dev/tty" = return . Just $ drop 5 ttydev
227searchParentsForTTY "1" ttydev | otherwise = return Nothing
228searchParentsForTTY pid ttydev = do
229 stat <- handleIO_ (return "") . readFile $ "/proc/"++pid++"/stat"
230 case words stat ?? 3 of
231 Nothing -> return Nothing
232 Just ppid -> do
233 tty <- handleIO_ (return "") $ readSymbolicLink $ "/proc/"++ppid++"/fd/0"
234 searchParentsForTTY ppid tty
diff --git a/Presence/LockedChan.hs b/Presence/LockedChan.hs
new file mode 100644
index 00000000..eac2b5ad
--- /dev/null
+++ b/Presence/LockedChan.hs
@@ -0,0 +1,78 @@
1{-# LANGUAGE CPP #-}
2module LockedChan
3 ( LockedChan
4 , cloneLChan
5 , newLockedChan
6 , peekLChan
7 , unlockChan
8 , writeLChan )
9 where
10
11
12import Control.Monad.STM
13import Control.Concurrent.STM
14
15data LockedChan a = LockedChan
16 { lock :: TVar Bool
17 , chan :: TChan a
18 }
19
20unlockChan :: LockedChan a -> IO (TChan a)
21unlockChan c = do
22 waslocked <- atomically $ swapTVar (lock c) False
23 if waslocked
24 then return (chan c)
25 else error "Attempt to read unlocked channel"
26
27writeLChan :: LockedChan a -> a -> STM ()
28writeLChan c a = writeTChan (chan c) a
29
30-- This one blocks rather than throwing an exception...
31-- todo: probably this should be changed to conform to the rest
32-- of the api.
33peekLChan :: LockedChan a -> STM a
34peekLChan c = do
35 readTVar (lock c) >>= check
36 peekTChan (chan c)
37
38newLockedChan :: STM (LockedChan a)
39newLockedChan = do
40 lock <- newTVar True
41 chan <- newTChan
42 return $ LockedChan lock chan
43
44cloneLChan :: LockedChan a -> IO (LockedChan a)
45cloneLChan c = do
46 mchan <- atomically $ do
47 locked <- readTVar (lock c)
48 if locked
49 then fmap Just $ do
50 c2 <- cloneTChan (chan c)
51 l2 <- newTVar True
52 return $ LockedChan l2 c2
53 else return Nothing
54 maybe (do putStrLn "LockedChan: Attempt to clone unlocked channel"
55 error "Attempt to clone unlocked channel")
56 return
57 mchan
58
59#if MIN_VERSION_stm(2,4,0)
60#else
61-- |Clone a 'TChan': similar to dupTChan, but the cloned channel starts with the
62-- same content available as the original channel.
63--
64-- Terrible inefficient implementation provided to build against older libraries.
65cloneTChan :: TChan a -> STM (TChan a)
66cloneTChan chan = do
67 contents <- chanContents' chan
68 chan2 <- dupTChan chan
69 mapM_ (writeTChan chan) contents
70 return chan2
71 where
72 chanContents' chan = do
73 b <- isEmptyTChan chan
74 if b then return [] else do
75 x <- readTChan chan
76 xs <- chanContents' chan
77 return (x:xs)
78#endif
diff --git a/Presence/Logging.hs b/Presence/Logging.hs
new file mode 100644
index 00000000..b997d341
--- /dev/null
+++ b/Presence/Logging.hs
@@ -0,0 +1,25 @@
1{-# LANGUAGE RankNTypes #-}
2module Logging where
3
4import qualified Data.ByteString.Lazy.Char8 as L
5import qualified Data.ByteString.Char8 as S
6import qualified Data.Text.IO as Text
7import qualified Data.Text as Text
8import qualified Debug.Trace as Debug
9
10debugL :: L.ByteString -> IO ()
11debugS :: S.ByteString -> IO ()
12debugStr :: String -> IO ()
13debugText :: Text.Text -> IO ()
14trace :: forall a. String -> a -> a
15
16
17debugStr str = putStrLn str
18
19debugL bs = L.putStrLn bs
20
21debugS bs = S.putStrLn bs
22
23debugText text = Text.putStrLn text
24
25trace str a = Debug.trace str a
diff --git a/Presence/Nesting.hs b/Presence/Nesting.hs
new file mode 100644
index 00000000..720237fd
--- /dev/null
+++ b/Presence/Nesting.hs
@@ -0,0 +1,88 @@
1{-# LANGUAGE OverloadedStrings #-}
2{-# LANGUAGE FlexibleContexts #-}
3module Nesting where
4
5import Data.Conduit
6import Data.Conduit.Lift
7import Data.XML.Types
8import qualified Data.Text as S
9import Control.Monad.State.Strict
10import qualified Data.List as List
11
12type Lang = S.Text
13
14data StrictList a = a :! !(StrictList a) | StrictNil
15
16data XMLState = XMLState {
17 nestingLevel :: Int,
18 langStack :: StrictList (Int,Lang)
19}
20
21type NestingXML o m a = ConduitM Event o (StateT XMLState m) a
22
23doNestingXML :: Monad m => NestingXML o m r -> ConduitM Event o m r
24doNestingXML m =
25 evalStateC (XMLState 0 StrictNil) (trackNesting =$= m)
26
27nesting :: Monad m => NestingXML o m Int
28nesting = lift $ (return . nestingLevel) =<< get
29
30xmlLang :: Monad m => NestingXML o m (Maybe Lang)
31xmlLang = fmap (fmap snd . top . langStack) (lift get)
32 where
33 top ( a :! _as ) = Just a
34 top _ = Nothing
35
36trackNesting :: Monad m => Conduit Event (StateT XMLState m) Event
37trackNesting = awaitForever doit
38 where
39 doit xml = do
40 XMLState lvl langs <- lift get
41 lift . put $ case xml of
42 EventBeginElement _ attrs ->
43 case lookupLang attrs of
44 Nothing -> XMLState (lvl+1) langs
45 Just lang -> XMLState (lvl+1) ( (lvl+1,lang) :! langs)
46 EventEndElement _ ->
47 case langs of
48 (llvl,_) :! ls | llvl==lvl -> XMLState (lvl-1) ls
49 _ | otherwise -> XMLState (lvl-1) langs
50 _ -> XMLState lvl langs
51 yield xml
52
53
54lookupLang :: [(Name, [Content])] -> Maybe S.Text
55lookupLang attrs =
56 case List.find ( (=="xml:lang") . fst) attrs of
57 Just (_,[ContentText x]) -> Just x
58 Just (_,[ContentEntity x]) -> Just x
59 _ -> Nothing
60
61
62awaitCloser :: Monad m => Int -> NestingXML o m ()
63awaitCloser lvl =
64 fix $ \loop -> do
65 lvl' <- nesting
66 when (lvl' >= lvl) $ do
67 xml <- await
68 maybe (return ()) (const loop) xml
69
70withXML ::
71 Monad m =>
72 (i -> ConduitM i o m ()) -> ConduitM i o m ()
73withXML f = await >>= maybe (return ()) f
74
75nextElement :: Monad m => NestingXML o m (Maybe Event)
76nextElement = do
77 lvl <- nesting
78 fix $ \loop -> do
79 xml <- await
80 case xml of
81 Nothing -> return Nothing
82 Just (EventBeginElement _ _) -> return xml
83 Just _ -> do
84 lvl' <- nesting
85 if (lvl'>=lvl) then loop
86 else return Nothing
87
88
diff --git a/Presence/Paths.hs b/Presence/Paths.hs
new file mode 100644
index 00000000..9d51b66e
--- /dev/null
+++ b/Presence/Paths.hs
@@ -0,0 +1,62 @@
1{-# LANGUAGE CPP #-}
2module Paths where
3
4#include <paths.h>
5
6bshell :: String
7console :: String
8cshell :: String
9devdb :: String
10devnull :: String
11drum :: String
12gshadow :: String
13klog :: String
14kmem :: String
15lastlog :: String
16maildir :: String
17man :: String
18mem :: String
19mnttab :: String
20mounted :: String
21nologin :: String
22preserve :: String
23rwhodir :: String
24sendmail :: String
25shadow :: String
26shells :: String
27tty :: String
28unix :: String
29utmp :: String
30vi :: String
31wtmp :: String
32
33
34
35bshell = _PATH_BSHELL
36console = _PATH_CONSOLE
37cshell = _PATH_CSHELL
38devdb = _PATH_DEVDB
39devnull = _PATH_DEVNULL
40drum = _PATH_DRUM
41gshadow = _PATH_GSHADOW
42klog = _PATH_KLOG
43kmem = _PATH_KMEM
44lastlog = _PATH_LASTLOG
45maildir = _PATH_MAILDIR
46man = _PATH_MAN
47mem = _PATH_MEM
48mnttab = _PATH_MNTTAB
49mounted = _PATH_MOUNTED
50nologin = _PATH_NOLOGIN
51preserve = _PATH_PRESERVE
52rwhodir = _PATH_RWHODIR
53sendmail = _PATH_SENDMAIL
54shadow = _PATH_SHADOW
55shells = _PATH_SHELLS
56tty = _PATH_TTY
57unix = _PATH_UNIX
58utmp = _PATH_UTMP
59vi = _PATH_VI
60wtmp = _PATH_WTMP
61
62
diff --git a/Presence/PeerResolve.hs b/Presence/PeerResolve.hs
new file mode 100644
index 00000000..0854b365
--- /dev/null
+++ b/Presence/PeerResolve.hs
@@ -0,0 +1,39 @@
1module PeerResolve
2 ( peerKeyToResolvedNames
3 , resolvePeer
4 , parseAddress
5 , strip_brackets
6 , withPort
7 ) where
8
9import Data.List ( nub )
10import Data.Text ( Text )
11import Network.Socket ( SockAddr(..) )
12import System.Endian ( fromBE32, toBE32 )
13import System.IO.Error ( isDoesNotExistError )
14import Control.Exception ( handle, ErrorCall(..) )
15import qualified Network.BSD as BSD
16import qualified Data.Text as Text
17import Control.Concurrent
18import Control.Concurrent.STM
19import Control.Monad
20import Data.Maybe
21import System.IO.Unsafe
22
23import GetHostByAddr
24import DNSCache
25import ConnectionKey
26import ControlMaybe
27
28{-# NOINLINE global_dns_cache #-}
29global_dns_cache :: DNSCache
30global_dns_cache = unsafePerformIO $ newDNSCache
31
32resolvePeer :: Text -> IO [SockAddr]
33resolvePeer addrtext = forwardResolve global_dns_cache addrtext
34
35peerKeyToResolvedNames :: ConnectionKey -> IO [Text]
36peerKeyToResolvedNames k@(ClientKey { localAddress=addr }) = return []
37peerKeyToResolvedNames k@(PeerKey { callBackAddress=addr }) = do
38 reverseResolve global_dns_cache addr
39
diff --git a/Presence/Presence.hs b/Presence/Presence.hs
new file mode 100644
index 00000000..15775857
--- /dev/null
+++ b/Presence/Presence.hs
@@ -0,0 +1,1041 @@
1{-# LANGUAGE ExistentialQuantification #-}
2{-# LANGUAGE LambdaCase #-}
3{-# LANGUAGE OverloadedStrings #-}
4{-# LANGUAGE TupleSections #-}
5module Presence where
6
7import System.Environment
8import System.Posix.Signals
9import Control.Concurrent (threadDelay,forkIO,forkOS,killThread,throwTo)
10import Control.Concurrent.STM
11import Control.Concurrent.STM.TMVar
12import Control.Monad.Trans.Resource (runResourceT)
13import Control.Monad.Trans
14import Control.Monad.IO.Class (MonadIO, liftIO)
15import Network.Socket ( SockAddr(..) )
16import System.Endian (fromBE32)
17import Data.List (nub, (\\), intersect, groupBy, sort, sortBy )
18import Data.Ord (comparing )
19import Data.Monoid ( (<>), Sum(..), getSum )
20import qualified Data.Text as Text
21import qualified Data.Text.IO as Text
22import qualified Data.Text.Encoding as Text
23import Control.Monad
24import Control.Monad.Fix
25import qualified Network.BSD as BSD
26import qualified Data.Text as Text
27import Data.Text (Text)
28import qualified Data.Map as Map
29import Data.Map (Map)
30import Control.Exception ({-evaluate,-}handle,SomeException(..),bracketOnError,ErrorCall(..))
31import System.IO.Error (isDoesNotExistError)
32import System.Posix.User (getUserEntryForID,userName)
33import qualified Data.ByteString.Lazy.Char8 as L
34import qualified ConfigFiles
35import Data.Maybe (maybeToList,listToMaybe,mapMaybe)
36import Data.Bits
37import Data.Int (Int8)
38import Data.XML.Types (Event)
39import System.Posix.Types (UserID,CPid)
40import Control.Applicative
41
42import LockedChan (LockedChan)
43import TraversableT
44import UTmp (ProcessID,users)
45import LocalPeerCred
46import XMPPServer
47import PeerResolve
48import ConsoleWriter
49import ClientState
50import Util
51import qualified Connection
52
53isPeerKey :: ConnectionKey -> Bool
54isPeerKey k = case k of { PeerKey {} -> True ; _ -> False }
55
56isClientKey :: ConnectionKey -> Bool
57isClientKey k = case k of { ClientKey {} -> True ; _ -> False }
58
59localJID :: Text -> Text -> IO Text
60localJID user resource = do
61 hostname <- textHostName
62 return $ user <> "@" <> hostname <> "/" <> resource
63
64data PresenceState = forall status. PresenceState
65 { clients :: TVar (Map ConnectionKey ClientState)
66 , clientsByUser :: TVar (Map Text LocalPresence)
67 , remotesByPeer :: TVar (Map ConnectionKey
68 (Map UserName RemotePresence))
69 , server :: TMVar (XMPPServer, Connection.Manager status Text)
70 , keyToChan :: TVar (Map ConnectionKey Conn)
71 , consoleWriter :: Maybe ConsoleWriter
72 }
73
74
75newPresenceState cw xmpp = atomically $ do
76 clients <- newTVar Map.empty
77 clientsByUser <- newTVar Map.empty
78 remotesByPeer <- newTVar Map.empty
79 keyToChan <- newTVar Map.empty
80 return PresenceState
81 { clients = clients
82 , clientsByUser = clientsByUser
83 , remotesByPeer = remotesByPeer
84 , keyToChan = keyToChan
85 , server = xmpp
86 , consoleWriter = cw
87 }
88
89
90presenceHooks state verbosity = XMPPServerParameters
91 { xmppChooseResourceName = chooseResourceName state
92 , xmppTellClientHisName = tellClientHisName state
93 , xmppTellMyNameToClient = textHostName
94 , xmppTellMyNameToPeer = \addr -> return $ addrToText addr
95 , xmppTellPeerHisName = return . peerKeyToText
96 , xmppTellClientNameOfPeer = flip peerKeyToResolvedName
97 , xmppNewConnection = newConn state
98 , xmppEOF = eofConn state
99 , xmppRosterBuddies = rosterGetBuddies state
100 , xmppRosterSubscribers = rosterGetSubscribers state
101 , xmppRosterSolicited = rosterGetSolicited state
102 , xmppRosterOthers = rosterGetOthers state
103 , xmppSubscribeToRoster = informSentRoster state
104 , xmppDeliverMessage = deliverMessage state
105 , xmppInformClientPresence = informClientPresence state
106 , xmppInformPeerPresence = informPeerPresence state
107 , xmppAnswerProbe = \k stanza chan -> answerProbe state (stanzaTo stanza) k chan
108 , xmppClientSubscriptionRequest = clientSubscriptionRequest state
109 , xmppPeerSubscriptionRequest = peerSubscriptionRequest state
110 , xmppClientInformSubscription = clientInformSubscription state
111 , xmppPeerInformSubscription = peerInformSubscription state
112 , xmppVerbosity = return verbosity
113 }
114
115
116data LocalPresence = LocalPresence
117 { networkClients :: Map ConnectionKey ClientState
118 -- TODO: loginClients
119 }
120
121data RemotePresence = RemotePresence
122 { resources :: Map Text Stanza
123 -- , localSubscribers :: Map Text ()
124 -- ^ subset of clientsByUser who should be
125 -- notified about this presence.
126 }
127
128
129
130pcSingletonNetworkClient :: ConnectionKey
131 -> ClientState -> LocalPresence
132pcSingletonNetworkClient key client =
133 LocalPresence
134 { networkClients = Map.singleton key client
135 }
136
137pcInsertNetworkClient :: ConnectionKey -> ClientState -> LocalPresence -> LocalPresence
138pcInsertNetworkClient key client pc =
139 pc { networkClients = Map.insert key client (networkClients pc) }
140
141pcRemoveNewtworkClient :: ConnectionKey
142 -> LocalPresence -> Maybe LocalPresence
143pcRemoveNewtworkClient key pc = if pcIsEmpty pc' then Nothing
144 else Just pc'
145 where
146 pc' = pc { networkClients = Map.delete key (networkClients pc) }
147
148pcIsEmpty :: LocalPresence -> Bool
149pcIsEmpty pc = Map.null (networkClients pc)
150
151
152
153getConsolePids :: PresenceState -> IO [(Text,ProcessID)]
154getConsolePids state = do
155 us <- UTmp.users
156 return $ map (\(_,tty,pid)->(lazyByteStringToText tty,pid)) us
157
158identifyTTY' :: [(Text, ProcessID)]
159 -> System.Posix.Types.UserID
160 -> L.ByteString
161 -> IO (Maybe Text, Maybe System.Posix.Types.CPid)
162identifyTTY' ttypids uid inode = ttypid
163 where ttypids' = map (\(tty,pid)->(L.fromChunks [Text.encodeUtf8 tty], pid)) ttypids
164 ttypid = fmap textify $ identifyTTY ttypids' uid inode
165 textify (tty,pid) = (fmap lazyByteStringToText tty, pid)
166
167chooseResourceName :: PresenceState
168 -> ConnectionKey -> SockAddr -> t -> IO Text
169chooseResourceName state k addr desired = do
170 muid <- getLocalPeerCred' addr
171 (mtty,pid) <- getTTYandPID muid
172 user <- getJabberUserForId muid
173 status <- atomically $ newTVar Nothing
174 flgs <- atomically $ newTVar 0
175 let client = ClientState { clientResource = maybe "fallback" id mtty
176 , clientUser = user
177 , clientPid = pid
178 , clientStatus = status
179 , clientFlags = flgs }
180
181 do -- forward-lookup of the buddies so that it is cached for reversing.
182 buds <- configText ConfigFiles.getBuddies (clientUser client)
183 forM_ buds $ \bud -> do
184 let (_,h,_) = splitJID bud
185 forkIO $ void $ resolvePeer h
186
187 atomically $ do
188 modifyTVar' (clients state) $ Map.insert k client
189 modifyTVar' (clientsByUser state) $ flip Map.alter (clientUser client)
190 $ \mb -> Just $ maybe (pcSingletonNetworkClient k client)
191 (pcInsertNetworkClient k client)
192 mb
193
194 localJID (clientUser client) (clientResource client)
195
196 where
197 getTTYandPID muid = do
198 -- us <- fmap (map (second fst) . Map.toList) . readTVarIO $ activeUsers state
199 ttypids <- getConsolePids state
200 -- let tailOf3 ((_,a),b) = (a,b)
201 (t,pid) <- case muid of
202 Just (uid,inode) -> identifyTTY' ttypids uid inode
203 Nothing -> return (Nothing,Nothing)
204 let rsc = t `mplus` fmap ( ("pid."<>) . Text.pack . show ) pid
205 return (rsc,pid)
206
207 getJabberUserForId muid =
208 maybe (return "nobody")
209 (\(uid,_) ->
210 handle (\(SomeException _) ->
211 return . (<> "uid.") . Text.pack . show $ uid)
212 $ do
213 user <- fmap userName $ getUserEntryForID uid
214 return (Text.pack user)
215 )
216 muid
217
218forClient :: PresenceState
219 -> ConnectionKey -> IO b -> (ClientState -> IO b) -> IO b
220forClient state k fallback f = do
221 mclient <- atomically $ do
222 cs <- readTVar (clients state)
223 return $ Map.lookup k cs
224 maybe fallback f mclient
225
226tellClientHisName :: PresenceState -> ConnectionKey -> IO Text
227tellClientHisName state k = forClient state k fallback go
228 where
229 fallback = localJID "nobody" "fallback"
230 go client = localJID (clientUser client) (clientResource client)
231
232toMapUnit :: Ord k => [k] -> Map k ()
233toMapUnit xs = Map.fromList $ map (,()) xs
234
235resolveAllPeers :: [Text] -> IO (Map SockAddr ())
236resolveAllPeers hosts = fmap (toMapUnit . concat) $ Prelude.mapM (fmap (take 1) . resolvePeer) hosts
237
238
239rosterGetStuff
240 :: (L.ByteString -> IO [L.ByteString])
241 -> PresenceState -> ConnectionKey -> IO [Text]
242rosterGetStuff what state k = forClient state k (return [])
243 $ \client -> do
244 jids <- configText what (clientUser client)
245 let hosts = map ((\(_,h,_)->h) . splitJID) jids
246 case state of
247 PresenceState { server = svVar } -> do
248 (sv,conns) <- atomically $ takeTMVar svVar
249 -- Grok peers to associate with from the roster:
250 forM_ hosts $ \host -> Connection.setPolicy conns host Connection.TryingToConnect
251 atomically $ putTMVar svVar (sv,conns)
252 return jids
253
254rosterGetBuddies :: PresenceState -> ConnectionKey -> IO [Text]
255rosterGetBuddies state k = rosterGetStuff ConfigFiles.getBuddies state k
256
257rosterGetSolicited :: PresenceState -> ConnectionKey -> IO [Text]
258rosterGetSolicited = rosterGetStuff ConfigFiles.getSolicited
259
260rosterGetOthers :: PresenceState -> ConnectionKey -> IO [Text]
261rosterGetOthers = rosterGetStuff ConfigFiles.getOthers
262
263rosterGetSubscribers :: PresenceState -> ConnectionKey -> IO [Text]
264rosterGetSubscribers = rosterGetStuff ConfigFiles.getSubscribers
265
266data Conn = Conn { connChan :: TChan Stanza
267 , auxAddr :: SockAddr }
268
269configText :: Functor f =>
270 (L.ByteString -> f [L.ByteString]) -> Text -> f [Text]
271configText what u = fmap (map lazyByteStringToText)
272 $ what (textToLazyByteString u)
273
274getBuddies' :: Text -> IO [Text]
275getBuddies' = configText ConfigFiles.getBuddies
276getSolicited' :: Text -> IO [Text]
277getSolicited' = configText ConfigFiles.getSolicited
278
279sendProbesAndSolicitations :: PresenceState
280 -> ConnectionKey -> SockAddr -> TChan Stanza -> IO ()
281sendProbesAndSolicitations state k laddr chan = do
282 -- get all buddies & solicited matching k for all users
283 xs <- runTraversableT $ do
284 cbu <- lift $ atomically $ readTVar $ clientsByUser state
285 user <- liftT $ Map.keys cbu
286 (isbud,getter) <- liftT [(True ,getBuddies' )
287 ,(False,getSolicited')]
288 bud <- liftMT $ getter user
289 let (u,h,r) = splitJID bud
290 addr <- liftMT $ nub `fmap` resolvePeer h
291 liftT $ guard (PeerKey addr == k)
292 -- Note: Earlier I was tempted to do all the IO
293 -- within the TraversableT monad. That apparently
294 -- is a bad idea. Perhaps due to laziness and an
295 -- unforced list? Instead, we will return a list
296 -- of (Bool,Text) for processing outside.
297 return (isbud,u,if isbud then "" else user)
298 -- XXX: The following O(n²) nub may be a little
299 -- too onerous.
300 forM_ (nub xs) $ \(isbud,u,user) -> do
301 let make = if isbud then presenceProbe
302 else presenceSolicitation
303 toh = peerKeyToText k
304 jid = unsplitJID (u,toh,Nothing)
305 me = addrToText laddr
306 from = if isbud then me -- probe from server
307 else -- solicitation from particular user
308 unsplitJID (Just user,me,Nothing)
309 stanza <- make from jid
310 -- send probes for buddies, solicitations for solicited.
311 putStrLn $ "probing "++show k++" for: " ++ show (isbud,jid)
312 atomically $ writeTChan chan stanza
313 -- reverse xs `seq` return ()
314
315newConn :: PresenceState -> ConnectionKey -> SockAddr -> TChan Stanza -> IO ()
316newConn state k addr outchan = do
317 atomically $ modifyTVar' (keyToChan state)
318 $ Map.insert k Conn { connChan = outchan
319 , auxAddr = addr }
320 when (isPeerKey k)
321 $ sendProbesAndSolicitations state k addr outchan
322
323delclient :: (Alternative m, Monad m) =>
324 ConnectionKey -> m LocalPresence -> m LocalPresence
325delclient k mlp = do
326 lp <- mlp
327 let nc = Map.delete k $ networkClients lp
328 guard $ not (Map.null nc)
329 return $ lp { networkClients = nc }
330
331eofConn :: PresenceState -> ConnectionKey -> IO ()
332eofConn state k = do
333 atomically $ modifyTVar' (keyToChan state) $ Map.delete k
334 case k of
335 ClientKey {} -> do
336 forClient state k (return ()) $ \client -> do
337 stanza <- makePresenceStanza "jabber:server" Nothing Offline
338 informClientPresence state k stanza
339 atomically $ do
340 modifyTVar' (clientsByUser state)
341 $ Map.alter (delclient k) (clientUser client)
342 PeerKey {} -> do
343 let h = peerKeyToText k
344 jids <- atomically $ do
345 rbp <- readTVar (remotesByPeer state)
346 return $ do
347 umap <- maybeToList $ Map.lookup k rbp
348 (u,rp) <- Map.toList umap
349 r <- Map.keys (resources rp)
350 return $ unsplitJID (Just u, h, Just r)
351 forM_ jids $ \jid -> do
352 stanza <- makePresenceStanza "jabber:client" (Just jid) Offline
353 informPeerPresence state k stanza
354
355{-
356rewriteJIDForClient1:: Text -> IO (Maybe ((Maybe Text,Text,Maybe Text),SockAddr))
357rewriteJIDForClient1 jid = do
358 let (n,h,r) = splitJID jid
359 maddr <- fmap listToMaybe $ resolvePeer h
360 flip (maybe $ return Nothing) maddr $ \addr -> do
361 h' <- peerKeyToResolvedName (PeerKey addr)
362 return $ Just ((n,h',r), addr)
363-}
364
365-- | The given address is taken to be the local address for the socket this JID
366-- came in on. The returned JID parts are suitable for unsplitJID to create a
367-- valid JID for communicating to a client. The returned Bool is True when the
368-- host part refers to this local host (i.e. it equals the given SockAddr).
369-- If there are multiple results, it will prefer one which is a member of the
370-- given list in the last argument.
371rewriteJIDForClient :: SockAddr -> Text -> [Text] -> IO (Bool,(Maybe Text,Text,Maybe Text))
372rewriteJIDForClient laddr jid buds = do
373 let (n,h,r) = splitJID jid
374 maddr <- parseAddress (strip_brackets h)
375 flip (maybe $ return (False,(n,ip6literal h,r))) maddr $ \addr -> do
376 let mine = laddr `withPort` 0 == addr `withPort` 0
377 h' <- if mine then textHostName
378 else peerKeyToResolvedName buds (PeerKey addr)
379 return (mine,(n,h',r))
380
381peerKeyToResolvedName :: [Text] -> ConnectionKey -> IO Text
382peerKeyToResolvedName buds k@(ClientKey { localAddress=addr }) = return "ErrorClIeNt1"
383peerKeyToResolvedName buds pk = do
384 ns <- peerKeyToResolvedNames pk
385 let hs = map (\jid -> let (_,h,_)=splitJID jid in h) buds
386 ns' = sortBy (comparing $ not . flip elem hs) ns
387 return $ maybe (peerKeyToText pk) id (listToMaybe ns')
388
389
390multiplyJIDForClient :: SockAddr -> Text -> IO (Bool,[(Maybe Text,Text,Maybe Text)])
391multiplyJIDForClient laddr jid = do
392 let (n,h,r) = splitJID jid
393 maddr <- parseAddress (strip_brackets h)
394 flip (maybe $ return (False,[(n,ip6literal h,r)])) maddr $ \addr -> do
395 let mine = sameAddress laddr addr
396 names <- if mine then fmap (:[]) textHostName
397 else peerKeyToResolvedNames (PeerKey addr)
398 return (mine,map (\h' -> (n,h',r)) names)
399
400
401addrTextToKey :: Text -> IO (Maybe ConnectionKey)
402addrTextToKey h = do
403 maddr <- parseAddress (strip_brackets h)
404 return (fmap PeerKey maddr)
405
406guardPortStrippedAddress :: Text -> SockAddr -> IO (Maybe ())
407guardPortStrippedAddress h laddr = do
408 maddr <- fmap (fmap (`withPort` 0)) $ parseAddress (strip_brackets h)
409 let laddr' = laddr `withPort` 0
410 return $ maddr >>= guard . (==laddr')
411
412
413-- | Accepts a textual representation of a domainname
414-- JID suitable for client connections, and returns the
415-- coresponding ipv6 address JID suitable for peers paired
416-- with a SockAddr with the address part of that JID in
417-- binary form. If no suitable address could be resolved
418-- for the given name, Nothing is returned.
419rewriteJIDForPeer :: Text -> IO (Maybe (Text,SockAddr))
420rewriteJIDForPeer jid = do
421 let (n,h,r) = splitJID jid
422 maddr <- fmap listToMaybe $ resolvePeer h
423 return $ flip fmap maddr $ \addr ->
424 let h' = addrToText addr
425 to' = unsplitJID (n,h',r)
426 in (to',addr)
427
428deliverToConsole :: PresenceState -> IO () -> Stanza -> IO ()
429deliverToConsole PresenceState{ consoleWriter = Just cw } fail msg = do
430 did1 <- writeActiveTTY cw msg
431 did2 <- writeAllPty cw msg
432 if not (did1 || did2) then fail else return ()
433deliverToConsole _ fail _ = fail
434
435-- | deliver <message/> or error stanza
436deliverMessage :: PresenceState
437 -> IO ()
438 -> StanzaWrap (LockedChan Event)
439 -> IO ()
440deliverMessage state fail msg =
441 case stanzaOrigin msg of
442 NetworkOrigin senderk@(ClientKey {}) _ -> do
443 -- Case 1. Client -> Peer
444 mto <- do
445 flip (maybe $ return Nothing) (stanzaTo msg) $ \to -> do
446 rewriteJIDForPeer to
447 flip (maybe fail {- reverse lookup failure -})
448 mto
449 $ \(to',addr) -> do
450 let k = PeerKey addr
451 chans <- atomically $ readTVar (keyToChan state)
452 flip (maybe fail) (Map.lookup k chans) $ \(Conn { connChan=chan
453 , auxAddr=laddr }) -> do
454 (n,r) <- forClient state senderk (return (Nothing,Nothing))
455 $ \c -> return (Just (clientUser c), Just (clientResource c))
456 -- original 'from' address is discarded.
457 let from' = unsplitJID (n,addrToText laddr,r)
458 -- dup <- atomically $ cloneStanza (msg { stanzaTo=Just to', stanzaFrom=Just from' })
459 let dup = (msg { stanzaTo=Just to', stanzaFrom=Just from' })
460 sendModifiedStanzaToPeer dup chan
461 NetworkOrigin senderk@(PeerKey {}) _ -> do
462 key_to_chan <- atomically $ readTVar (keyToChan state)
463 flip (maybe fail) (Map.lookup senderk key_to_chan)
464 $ \(Conn { connChan=sender_chan
465 , auxAddr=laddr }) -> do
466 flip (maybe fail) (stanzaTo msg) $ \to -> do
467 (mine,(n,h,r)) <- rewriteJIDForClient laddr to []
468 if not mine then fail else do
469 let to' = unsplitJID (n,h,r)
470 cmap <- atomically . readTVar $ clientsByUser state
471 (from',chans,ks) <- do
472 flip (maybe $ return (Nothing,[],[])) n $ \n -> do
473 buds <- configText ConfigFiles.getBuddies n
474 from' <- do
475 flip (maybe $ return Nothing) (stanzaFrom msg) $ \from -> do
476 (_,trip) <- rewriteJIDForClient laddr from buds
477 return . Just $ unsplitJID trip
478 let nope = return (from',[],[])
479 flip (maybe nope) (Map.lookup n cmap) $ \presence_container -> do
480 let ks = Map.keys (networkClients presence_container)
481 chans = mapMaybe (flip Map.lookup key_to_chan) ks
482 return (from',chans,ks)
483 putStrLn $ "chan count: " ++ show (length chans)
484 let msg' = msg { stanzaTo=Just to'
485 , stanzaFrom=from' }
486 if null chans then deliverToConsole state fail msg' else do
487 forM_ chans $ \Conn { connChan=chan} -> do
488 putStrLn $ "sending "++show (stanzaId msg)++" to clients "++show ks
489 -- TODO: Cloning isn't really neccessary unless there are multiple
490 -- destinations and we should probably transition to minimal cloning,
491 -- or else we should distinguish between announcable stanzas and
492 -- consumable stanzas and announcables use write-only broadcast
493 -- channels that must be cloned in order to be consumed.
494 -- For now, we are doing redundant cloning.
495 dup <- cloneStanza msg'
496 sendModifiedStanzaToClient dup
497 chan
498
499
500setClientFlag :: PresenceState -> ConnectionKey -> Int8 -> IO ()
501setClientFlag state k flag =
502 atomically $ do
503 cmap <- readTVar (clients state)
504 flip (maybe $ return ()) (Map.lookup k cmap) $ \client -> do
505 setClientFlag0 client flag
506
507setClientFlag0 :: ClientState -> Int8 -> STM ()
508setClientFlag0 client flag =
509 modifyTVar' (clientFlags client) (\flgs -> flgs .|. flag)
510
511informSentRoster :: PresenceState -> ConnectionKey -> IO ()
512informSentRoster state k = do
513 setClientFlag state k cf_interested
514
515
516subscribedPeers :: Text -> IO [SockAddr]
517subscribedPeers user = do
518 jids <- configText ConfigFiles.getSubscribers user
519 let hosts = map ((\(_,h,_)->h) . splitJID) jids
520 fmap Map.keys $ resolveAllPeers hosts
521
522-- | this JID is suitable for peers, not clients.
523clientJID :: Conn -> ClientState -> Text
524clientJID con client = unsplitJID ( Just $ clientUser client
525 , addrToText $ auxAddr con
526 , Just $ clientResource client)
527
528-- | Send presence notification to subscribed peers.
529-- Note that a full JID from address will be added to the
530-- stanza if it is not present.
531informClientPresence :: PresenceState
532 -> ConnectionKey -> StanzaWrap (LockedChan Event) -> IO ()
533informClientPresence state k stanza = do
534 forClient state k (return ()) $ \client -> do
535 informClientPresence0 state (Just k) client stanza
536
537informClientPresence0 :: PresenceState
538 -> Maybe ConnectionKey
539 -> ClientState
540 -> StanzaWrap (LockedChan Event)
541 -> IO ()
542informClientPresence0 state mbk client stanza = do
543 dup <- cloneStanza stanza
544 atomically $ writeTVar (clientStatus client) $ Just dup
545 is_avail <- atomically $ clientIsAvailable client
546 when (not is_avail) $ do
547 atomically $ setClientFlag0 client cf_available
548 maybe (return ()) (sendCachedPresence state) mbk
549 addrs <- subscribedPeers (clientUser client)
550 ktc <- atomically $ readTVar (keyToChan state)
551 let connected = mapMaybe (flip Map.lookup ktc . PeerKey) addrs
552 forM_ connected $ \con -> do
553 let from' = clientJID con client
554 mto <- runTraversableT $ do
555 to <- liftT $ stanzaTo stanza
556 (to',_) <- liftMT $ rewriteJIDForPeer to
557 return to'
558 dup <- cloneStanza stanza
559 sendModifiedStanzaToPeer dup { stanzaFrom = Just from'
560 , stanzaTo = mto }
561 (connChan con)
562
563informPeerPresence :: PresenceState
564 -> ConnectionKey
565 -> StanzaWrap (LockedChan Event)
566 -> IO ()
567informPeerPresence state k stanza = do
568 -- Presence must indicate full JID with resource...
569 putStrLn $ "xmppInformPeerPresence checking from address..."
570 flip (maybe $ return ()) (stanzaFrom stanza) $ \from -> do
571 let (muser,h,mresource) = splitJID from
572 putStrLn $ "xmppInformPeerPresence from = " ++ show from
573 -- flip (maybe $ return ()) mresource $ \resource -> do
574 flip (maybe $ return ()) muser $ \user -> do
575
576 clients <- atomically $ do
577
578 -- Update remotesByPeer...
579 rbp <- readTVar (remotesByPeer state)
580 let umap = maybe Map.empty id $ Map.lookup k rbp
581 rp = case (presenceShow $ stanzaType stanza) of
582 Offline ->
583 maybe Map.empty
584 (\resource ->
585 maybe (Map.empty)
586 (Map.delete resource . resources)
587 $ Map.lookup user umap)
588 mresource
589
590 _ ->maybe Map.empty
591 (\resource ->
592 maybe (Map.singleton resource stanza)
593 (Map.insert resource stanza . resources )
594 $ Map.lookup user umap)
595 mresource
596 umap' = Map.insert user (RemotePresence rp) umap
597
598 flip (maybe $ return []) (case presenceShow $ stanzaType stanza of
599 Offline -> Just ()
600 _ -> mresource >> Just ())
601 $ \_ -> do
602 writeTVar (remotesByPeer state) $ Map.insert k umap' rbp
603 -- TODO: Store or delete the stanza (remotesByPeer)
604
605 -- all clients, we'll filter available/authorized later
606
607 ktc <- readTVar (keyToChan state)
608 runTraversableT $ do
609 (ck,client) <- liftMT $ fmap Map.toList $ readTVar (clients state)
610 con <- liftMaybe $ Map.lookup ck ktc
611 return (ck,con,client)
612 putStrLn $ "xmppInformPeerPresence (length clients="++show (length clients)++")"
613 forM_ clients $ \(ck,con,client) -> do
614 -- (TODO: appropriately authorized clients only.)
615 -- For now, all "available" clients (available = sent initial presence)
616 is_avail <- atomically $ clientIsAvailable client
617 when is_avail $ do
618 putStrLn $ "reversing for client: " ++ show from
619 froms <- do -- flip (maybe $ return [from]) k . const $ do
620 let ClientKey laddr = ck
621 (_,trip) <- multiplyJIDForClient laddr from
622 return (map unsplitJID trip)
623
624 putStrLn $ "sending to client: " ++ show (stanzaType stanza,froms)
625 forM_ froms $ \from' -> do
626 dup <- cloneStanza stanza
627 sendModifiedStanzaToClient (dup { stanzaFrom=Just from' })
628 (connChan con)
629
630consoleClients :: PresenceState -> STM (Map Text ClientState)
631consoleClients PresenceState{ consoleWriter = Just cw } = readTVar (cwClients cw)
632consoleClients _ = return Map.empty
633
634
635answerProbe :: PresenceState
636 -> Maybe Text -> ConnectionKey -> TChan Stanza -> IO ()
637answerProbe state mto k chan = do
638 -- putStrLn $ "answerProbe! " ++ show (stanzaType stanza)
639 ktc <- atomically $ readTVar (keyToChan state)
640 muser <- runTraversableT $ do
641 to <- liftT $ mto
642 conn <- liftT $ Map.lookup k ktc
643 let (mu,h,_) = splitJID to -- TODO: currently resource-id is ignored on presence
644 -- probes. Is this correct? Check the spec.
645 liftMT $ guardPortStrippedAddress h (auxAddr conn)
646 u <- liftT mu
647 let ch = addrToText (auxAddr conn)
648 return (u,conn,ch)
649
650 flip (maybe $ return ()) muser $ \(u,conn,ch) -> do
651
652 resolved_subs <- resolvedFromRoster ConfigFiles.getSubscribers u
653 let gaddrs = groupBy (\a b -> snd a == snd b) (sort resolved_subs)
654 whitelist = do
655 xs <- gaddrs
656 x <- take 1 xs
657 guard $ snd x==k
658 mapMaybe fst xs
659
660 -- -- only subscribed peers should get probe replies
661 -- addrs <- subscribedPeers u
662
663 -- TODO: notify remote peer that they are unsubscribed?
664 -- reply <- makeInformSubscription "jabber:server" to from False
665 when (not $ null whitelist) $ do
666
667 replies <- runTraversableT $ do
668 cbu <- lift . atomically $ readTVar (clientsByUser state)
669 let lpres = maybeToList $ Map.lookup u cbu
670 cw <- lift . atomically $ consoleClients state
671 clientState <- liftT $ (lpres >>= Map.elems . networkClients)
672 ++ Map.elems cw
673 stanza <- liftIOMaybe $ atomically (readTVar (clientStatus clientState))
674 stanza <- lift $ cloneStanza stanza
675 let jid = unsplitJID (Just $ clientUser clientState
676 , ch
677 ,Just $ clientResource clientState)
678 return stanza { stanzaFrom = Just jid
679 , stanzaType = (stanzaType stanza)
680 { presenceWhiteList = whitelist }
681 }
682
683 forM_ replies $ \reply -> do
684 sendModifiedStanzaToPeer reply chan
685
686 -- if no presence, send offline message
687 when (null replies) $ do
688 let jid = unsplitJID (Just u,ch,Nothing)
689 pstanza <- makePresenceStanza "jabber:server" (Just jid) Offline
690 atomically $ writeTChan (connChan conn) pstanza
691
692sendCachedPresence :: PresenceState -> ConnectionKey -> IO ()
693sendCachedPresence state k = do
694 forClient state k (return ()) $ \client -> do
695 rbp <- atomically $ readTVar (remotesByPeer state)
696 jids <- configText ConfigFiles.getBuddies (clientUser client)
697 let hosts = map ((\(_,h,_)->h) . splitJID) jids
698 addrs <- resolveAllPeers hosts
699 let onlines = rbp `Map.intersection` Map.mapKeys PeerKey addrs
700 ClientKey laddr = k
701 mcon <- atomically $ do ktc <- readTVar (keyToChan state)
702 return $ Map.lookup k ktc
703 flip (maybe $ return ()) mcon $ \con -> do
704 -- me <- textHostName
705 forM_ (Map.toList onlines) $ \(pk, umap) -> do
706 forM_ (Map.toList umap) $ \(user,rp) -> do
707 let h = peerKeyToText pk
708 forM_ (Map.toList $ resources rp) $ \(resource,stanza) -> do
709 let jid = unsplitJID (Just user,h,Just resource)
710 (mine,js) <- multiplyJIDForClient laddr jid
711 forM_ js $ \jid -> do
712 let from' = unsplitJID jid
713 dup <- cloneStanza stanza
714 sendModifiedStanzaToClient (dup { stanzaFrom=Just from' })
715 (connChan con)
716
717 pending <- configText ConfigFiles.getPending (clientUser client)
718 hostname <- textHostName
719 forM_ pending $ \pending_jid -> do
720 let cjid = unsplitJID ( Just $ clientUser client
721 , hostname
722 , Nothing )
723 ask <- presenceSolicitation pending_jid cjid
724 sendModifiedStanzaToClient ask (connChan con)
725
726 -- Note: relying on self peer connection to send
727 -- send local buddies.
728 return ()
729
730addToRosterFile :: (MonadPlus t, Traversable t) =>
731 (L.ByteString -> (L.ByteString -> IO (t L.ByteString))
732 -> Maybe L.ByteString
733 -> t1)
734 -> Text -> Text -> [SockAddr] -> t1
735addToRosterFile doit whose to addrs =
736 modifyRosterFile doit whose to addrs True
737
738removeFromRosterFile :: (MonadPlus t, Traversable t) =>
739 (L.ByteString -> (L.ByteString -> IO (t L.ByteString))
740 -> Maybe L.ByteString
741 -> t1)
742 -> Text -> Text -> [SockAddr] -> t1
743removeFromRosterFile doit whose to addrs =
744 modifyRosterFile doit whose to addrs False
745
746modifyRosterFile :: (Traversable t, MonadPlus t) =>
747 (L.ByteString -> (L.ByteString -> IO (t L.ByteString))
748 -> Maybe L.ByteString
749 -> t1)
750 -> Text -> Text -> [SockAddr] -> Bool -> t1
751modifyRosterFile doit whose to addrs bAdd = do
752 let (mu,_,_) = splitJID to
753 cmp jid = runTraversableT $ do
754 let (msu,stored_h,mr) = splitJID (lazyByteStringToText jid)
755 -- Delete from file if a resource is present in file
756 (\f -> maybe f (const mzero) mr) $ do
757 -- Delete from file if no user is present in file
758 flip (maybe mzero) msu $ \stored_u -> do
759 -- do not delete anything if no user was specified
760 flip (maybe $ return jid) mu $ \u -> do
761 -- do not delete if stored user is same as specified
762 if stored_u /= u then return jid else do
763 stored_addrs <- lift $ resolvePeer stored_h
764 -- do not delete if failed to resolve
765 if null stored_addrs then return jid else do
766 -- delete if specified address matches stored
767 if null (stored_addrs \\ addrs) then mzero else do
768 -- keep
769 return jid
770 doit (textToLazyByteString whose)
771 cmp
772 (guard bAdd >> Just (textToLazyByteString to))
773
774clientSubscriptionRequest :: PresenceState -> IO () -> ConnectionKey -> Stanza -> TChan Stanza -> IO ()
775clientSubscriptionRequest state fail k stanza chan = do
776 forClient state k fail $ \client -> do
777 flip (maybe fail) (stanzaTo stanza) $ \to -> do
778 putStrLn $ "Forwarding solictation to peer"
779 let (mu,h,_) = splitJID to
780 to <- return $ unsplitJID (mu,h,Nothing) -- delete resource
781 flip (maybe fail) mu $ \u -> do
782 -- add to-address to from's solicited
783 addrs <- resolvePeer h
784 addToRosterFile ConfigFiles.modifySolicited (clientUser client) to addrs
785 removeFromRosterFile ConfigFiles.modifyBuddies (clientUser client) to addrs
786 resolved_subs <- resolvedFromRoster ConfigFiles.getSubscribers (clientUser client)
787 let is_subscribed = not . null $ intersect (map ((mu,).PeerKey) addrs) resolved_subs
788 -- subscribers: "from"
789 -- buddies: "to"
790
791 case state of
792 PresenceState { server = svVar } -> do
793
794 (ktc,(sv,conns)) <- atomically $
795 liftM2 (,) (readTVar $ keyToChan state)
796 (takeTMVar svVar)
797
798 case stanzaType stanza of
799 PresenceRequestSubscription True -> do
800 hostname <- textHostName
801 let cjid = unsplitJID (Just $ clientUser client, hostname,Nothing)
802 chans <- clientCons state ktc (clientUser client)
803 forM_ chans $ \( Conn { connChan=chan }, client ) -> do
804 -- roster update ask="subscribe"
805 update <- makeRosterUpdate cjid to
806 [ ("ask","subscribe")
807 , if is_subscribed then ("subscription","from")
808 else ("subscription","none")
809 ]
810 sendModifiedStanzaToClient update chan
811 _ -> return ()
812
813 let dsts = Map.fromList $ map ((,()) . PeerKey) addrs
814 cdsts = ktc `Map.intersection` dsts
815 forM_ (Map.toList cdsts) $ \(pk,con) -> do
816 -- if already connected, send solicitation ...
817 -- let from = clientJID con client
818 let from = unsplitJID ( Just $ clientUser client
819 , addrToText $ auxAddr con
820 , Nothing )
821 mb <- rewriteJIDForPeer to
822 flip (maybe $ return ()) mb $ \(to',addr) -> do
823 dup <- cloneStanza stanza
824 sendModifiedStanzaToPeer (dup { stanzaTo = Just to'
825 , stanzaFrom = Just from })
826 (connChan con)
827 let addrm = Map.fromList (map (,()) addrs)
828 -- Add peer if we are not already associated ...
829 Connection.setPolicy conns h Connection.TryingToConnect
830 atomically $ putTMVar svVar (sv,conns)
831
832
833resolvedFromRoster
834 :: (L.ByteString -> IO [L.ByteString])
835 -> UserName -> IO [(Maybe UserName, ConnectionKey)]
836resolvedFromRoster doit u = do
837 subs <- configText doit u
838 runTraversableT $ do
839 (mu,h,_) <- liftT $ splitJID `fmap` subs
840 addr <- liftMT $ fmap nub $ resolvePeer h
841 return (mu,PeerKey addr)
842
843clientCons :: PresenceState
844 -> Map ConnectionKey t -> Text -> IO [(t, ClientState)]
845clientCons state ktc u = do
846 mlp <- atomically $ do
847 cmap <- readTVar $ clientsByUser state
848 return $ Map.lookup u cmap
849 let ks = do lp <- maybeToList mlp
850 Map.toList (networkClients lp)
851 doit (k,client) = do
852 con <- Map.lookup k ktc
853 return (con,client)
854 return $ mapMaybe doit ks
855
856peerSubscriptionRequest :: PresenceState -> IO () -> ConnectionKey -> Stanza -> TChan Stanza -> IO ()
857peerSubscriptionRequest state fail k stanza chan = do
858 putStrLn $ "Handling pending subscription from remote"
859 flip (maybe fail) (stanzaFrom stanza) $ \from -> do
860 flip (maybe fail) (stanzaTo stanza) $ \to -> do
861 let (mto_u,h,_) = splitJID to
862 (mfrom_u,from_h,_) = splitJID from
863 to <- return $ unsplitJID (mto_u,h,Nothing) -- delete resource
864 from <- return $ unsplitJID (mfrom_u,from_h,Nothing) -- delete resource
865 ktc <- atomically . readTVar $ keyToChan state
866 flip (maybe fail) (Map.lookup k ktc)
867 $ \Conn { auxAddr=laddr } -> do
868 (mine,totup) <- rewriteJIDForClient laddr to []
869 if not mine then fail else do
870 (_,fromtup) <- rewriteJIDForClient laddr from []
871 flip (maybe fail) mto_u $ \u -> do
872 flip (maybe fail) mfrom_u $ \from_u -> do
873 resolved_subs <- resolvedFromRoster ConfigFiles.getSubscribers u
874 let already_subscribed = elem (mfrom_u,k) resolved_subs
875 is_wanted = case stanzaType stanza of
876 PresenceRequestSubscription b -> b
877 _ -> False -- Shouldn't happen.
878 -- Section 8 says (for presence of type "subscribe", the server MUST
879 -- adhere to the rules defined under Section 3 and summarized under
880 -- see Appendix A. (pariticularly Appendex A.3.1)
881 if already_subscribed == is_wanted
882 then do
883 -- contact ∈ subscribers --> SHOULD NOT, already handled
884 -- already subscribed, reply and quit
885 -- (note: swapping to and from for reply)
886 reply <- makeInformSubscription "jabber:server" to from is_wanted
887 sendModifiedStanzaToPeer reply chan
888 answerProbe state (Just to) k chan
889 else do
890
891 -- TODO: if peer-connection is to self, then auto-approve local user.
892
893 -- add from-address to to's pending
894 addrs <- resolvePeer from_h
895
896 -- Catch exception in case the user does not exist
897 if null addrs then fail else do
898
899 let from' = unsplitJID fromtup
900
901 already_pending <-
902 if is_wanted then
903 addToRosterFile ConfigFiles.modifyPending u from' addrs
904 else do
905 removeFromRosterFile ConfigFiles.modifySubscribers u from' addrs
906 reply <- makeInformSubscription "jabber:server" to from is_wanted
907 sendModifiedStanzaToPeer reply chan
908 return False
909
910 -- contact ∉ subscribers & contact ∈ pending --> SHOULD NOT
911 when (not already_pending) $ do
912 -- contact ∉ subscribers & contact ∉ pending --> MUST
913
914 chans <- clientCons state ktc u
915 forM_ chans $ \( Conn { connChan=chan }, client ) -> do
916 -- send to clients
917 -- TODO: interested/available clients only?
918 dup <- cloneStanza stanza
919 sendModifiedStanzaToClient dup { stanzaFrom = Just $ from'
920 , stanzaTo = Just $ unsplitJID totup }
921 chan
922
923
924clientInformSubscription :: PresenceState
925 -> IO ()
926 -> ConnectionKey
927 -> StanzaWrap (LockedChan Event)
928 -> IO ()
929clientInformSubscription state fail k stanza = do
930 forClient state k fail $ \client -> do
931 flip (maybe fail) (stanzaTo stanza) $ \to -> do
932 putStrLn $ "clientInformSubscription"
933 let (mu,h,mr) = splitJID to
934 addrs <- resolvePeer h
935 -- remove from pending
936 buds <- resolvedFromRoster ConfigFiles.getBuddies (clientUser client)
937 let is_buddy = not . null $ map ((mu,) . PeerKey) addrs `intersect` buds
938 removeFromRosterFile ConfigFiles.modifyPending (clientUser client) to addrs
939 let (relationship,addf,remf) =
940 case stanzaType stanza of
941 PresenceInformSubscription True ->
942 ( ("subscription", if is_buddy then "both"
943 else "from" )
944 , ConfigFiles.modifySubscribers
945 , ConfigFiles.modifyOthers )
946 _ -> ( ("subscription", if is_buddy then "to"
947 else "none" )
948 , ConfigFiles.modifyOthers
949 , ConfigFiles.modifySubscribers )
950 addToRosterFile addf (clientUser client) to addrs
951 removeFromRosterFile remf (clientUser client) to addrs
952
953 do
954 cbu <- atomically $ readTVar (clientsByUser state)
955 putStrLn $ "cbu = " ++ show (fmap (fmap clientPid . networkClients) cbu)
956
957 -- send roster update to clients
958 (clients,ktc) <- atomically $ do
959 cbu <- readTVar (clientsByUser state)
960 let mlp = Map.lookup (clientUser client) cbu
961 let cs = maybe [] (Map.toList . networkClients) mlp
962 ktc <- readTVar (keyToChan state)
963 return (cs,ktc)
964 forM_ clients $ \(ck, client) -> do
965 is_intereseted <- atomically $ clientIsInterested client
966 putStrLn $ "clientIsInterested: "++show is_intereseted
967 is_intereseted <- atomically $ clientIsInterested client
968 when is_intereseted $ do
969 flip (maybe $ return ()) (Map.lookup ck ktc) $ \con -> do
970 hostname <- textHostName
971 -- TODO: Should cjid include the resource?
972 let cjid = unsplitJID (mu, hostname, Nothing)
973 update <- makeRosterUpdate cjid to [relationship]
974 sendModifiedStanzaToClient update (connChan con)
975
976 -- notify peer
977 let dsts = Map.fromList $ map ((,()) . PeerKey) addrs
978 cdsts = ktc `Map.intersection` dsts
979 forM_ (Map.toList cdsts) $ \(pk,con) -> do
980 let from = clientJID con client
981 to' = unsplitJID (mu, peerKeyToText pk, Nothing)
982 dup <- cloneStanza stanza
983 sendModifiedStanzaToPeer (dup { stanzaTo = Just $ to'
984 , stanzaFrom = Just from })
985 (connChan con)
986 answerProbe state (Just from) pk (connChan con)
987
988peerInformSubscription :: PresenceState
989 -> IO ()
990 -> ConnectionKey
991 -> StanzaWrap (LockedChan Event)
992 -> IO ()
993peerInformSubscription state fail k stanza = do
994 putStrLn $ "TODO: peerInformSubscription"
995 -- remove from solicited
996 flip (maybe fail) (stanzaFrom stanza) $ \from -> do
997 ktc <- atomically $ readTVar (keyToChan state)
998 flip (maybe fail) (Map.lookup k ktc)
999 $ \(Conn { connChan=sender_chan
1000 , auxAddr=laddr }) -> do
1001 (_,(from_u,from_h,_)) <- rewriteJIDForClient laddr from []
1002 let from'' = unsplitJID (from_u,from_h,Nothing)
1003 muser = do
1004 to <- stanzaTo stanza
1005 let (mu,to_h,to_r) = splitJID to
1006 mu
1007 -- TODO muser = Nothing when wanted=False
1008 -- should probably mean unsubscribed for all users.
1009 -- This would allow us to answer anonymous probes with 'unsubscribed'.
1010 flip (maybe fail) muser $ \user -> do
1011 addrs <- resolvePeer from_h
1012 was_solicited <- removeFromRosterFile ConfigFiles.modifySolicited user from'' addrs
1013 subs <- resolvedFromRoster ConfigFiles.getSubscribers user
1014 let is_sub = not . null $ map ((from_u,) . PeerKey) addrs `intersect` subs
1015 let (relationship,addf,remf) =
1016 case stanzaType stanza of
1017 PresenceInformSubscription True ->
1018 ( ("subscription", if is_sub then "both"
1019 else "to" )
1020 , ConfigFiles.modifyBuddies
1021 , ConfigFiles.modifyOthers )
1022 _ -> ( ("subscription", if is_sub then "from"
1023 else "none")
1024 , ConfigFiles.modifyOthers
1025 , ConfigFiles.modifyBuddies )
1026 addToRosterFile addf user from'' addrs
1027 removeFromRosterFile remf user from'' addrs
1028
1029 hostname <- textHostName
1030 let to' = unsplitJID (Just user, hostname, Nothing)
1031 chans <- clientCons state ktc user
1032 forM_ chans $ \(Conn { connChan=chan }, client) -> do
1033 update <- makeRosterUpdate to' from'' [relationship]
1034 is_intereseted <- atomically $ clientIsInterested client
1035 when is_intereseted $ do
1036 sendModifiedStanzaToClient update chan
1037 -- TODO: interested/availabe clients only?
1038 dup <- cloneStanza stanza
1039 sendModifiedStanzaToClient dup { stanzaFrom = Just $ from''
1040 , stanzaTo = Just to' }
1041 chan
diff --git a/Presence/Server.hs b/Presence/Server.hs
new file mode 100644
index 00000000..c38aec2a
--- /dev/null
+++ b/Presence/Server.hs
@@ -0,0 +1,826 @@
1{-# OPTIONS_HADDOCK prune #-}
2{-# LANGUAGE CPP #-}
3{-# LANGUAGE DoAndIfThenElse #-}
4{-# LANGUAGE FlexibleInstances #-}
5{-# LANGUAGE OverloadedStrings #-}
6{-# LANGUAGE RankNTypes #-}
7{-# LANGUAGE StandaloneDeriving #-}
8{-# LANGUAGE TupleSections #-}
9{-# LANGUAGE LambdaCase #-}
10-----------------------------------------------------------------------------
11-- |
12-- Module : Server
13--
14-- Maintainer : joe@jerkface.net
15-- Stability : experimental
16--
17-- A TCP client/server library.
18--
19-- TODO:
20--
21-- * interface tweaks
22--
23module Server
24 ( module Server
25 , module PingMachine ) where
26
27import Data.ByteString (ByteString,hGetNonBlocking)
28import qualified Data.ByteString.Char8 as S -- ( hPutStrLn, hPutStr, pack)
29import Data.Conduit ( Source, Sink, Flush )
30#if MIN_VERSION_containers(0,5,0)
31import qualified Data.Map.Strict as Map
32import Data.Map.Strict (Map)
33#else
34import qualified Data.Map as Map
35import Data.Map (Map)
36#endif
37import Data.Monoid ( (<>) )
38#ifdef THREAD_DEBUG
39import Control.Concurrent.Lifted.Instrument
40#else
41import Control.Concurrent.Lifted
42import GHC.Conc (labelThread)
43#endif
44
45import Control.Concurrent.STM
46-- import Control.Concurrent.STM.TMVar
47-- import Control.Concurrent.STM.TChan
48-- import Control.Concurrent.STM.Delay
49import Control.Exception ({-evaluate,-}handle,SomeException(..),ErrorCall(..),onException)
50import Control.Monad
51import Control.Monad.Fix
52-- import Control.Monad.STM
53-- import Control.Monad.Trans.Resource
54import Control.Monad.IO.Class (MonadIO (liftIO))
55import System.IO.Error (isDoesNotExistError)
56import System.IO
57 ( IOMode(..)
58 , hSetBuffering
59 , BufferMode(..)
60 , hWaitForInput
61 , hClose
62 , hIsEOF
63 , stderr
64 , Handle
65 , hFlush
66 , hPutStrLn
67 )
68import Network.Socket as Socket
69import Network.BSD
70 ( getProtocolNumber
71 )
72import Debug.Trace
73import Data.Time.Clock (getCurrentTime,diffUTCTime)
74-- import SockAddr ()
75-- import System.Locale (defaultTimeLocale)
76
77import InterruptibleDelay
78import PingMachine
79import Network.StreamServer
80import Network.SocketLike hiding (sClose)
81import qualified Connection as G
82 ;import Connection (Manager (..), Policy(..))
83
84
85type Microseconds = Int
86
87-- | This object is passed with the 'Listen' and 'Connect'
88-- instructions in order to control the behavior of the
89-- connections that are established. It is parameterized
90-- by a user-suplied type @conkey@ that is used as a lookup
91-- key for connections.
92data ConnectionParameters conkey u =
93 ConnectionParameters
94 { pingInterval :: PingInterval
95 -- ^ The miliseconds of idle to allow before a 'RequiresPing'
96 -- event is signaled.
97 , timeout :: TimeOut
98 -- ^ The miliseconds of idle after 'RequiresPing' is signaled
99 -- that are necessary for the connection to be considered
100 -- lost and signalling 'EOF'.
101 , makeConnKey :: RestrictedSocket -> IO (conkey,u)
102 -- ^ This action creates a lookup key for a new connection. If 'duplex'
103 -- is 'True' and the result is already assocatied with an established
104 -- connection, then an 'EOF' will be forced before the the new
105 -- connection becomes active.
106 --
107 , duplex :: Bool
108 -- ^ If True, then the connection will be treated as a normal
109 -- two-way socket. Otherwise, a readable socket is established
110 -- with 'Listen' and a writable socket is established with
111 -- 'Connect' and they are associated when 'makeConnKey' yields
112 -- same value for each.
113 }
114
115-- | Use this function to select appropriate default values for
116-- 'ConnectionParameters' other than 'makeConnKey'.
117--
118-- Current defaults:
119--
120-- * 'pingInterval' = 28000
121--
122-- * 'timeout' = 2000
123--
124-- * 'duplex' = True
125--
126connectionDefaults
127 :: (RestrictedSocket -> IO (conkey,u)) -> ConnectionParameters conkey u
128connectionDefaults f = ConnectionParameters
129 { pingInterval = 28000
130 , timeout = 2000
131 , makeConnKey = f
132 , duplex = True
133 }
134
135-- | Instructions for a 'Server' object
136--
137-- To issue a command, put it into the 'serverCommand' TMVar.
138data ServerInstruction conkey u
139 = Quit
140 -- ^ kill the server. This command is automatically issued when
141 -- the server is released.
142 | Listen PortNumber (ConnectionParameters conkey u)
143 -- ^ listen for incoming connections
144 | Connect SockAddr (ConnectionParameters conkey u)
145 -- ^ connect to addresses
146 | ConnectWithEndlessRetry SockAddr
147 (ConnectionParameters conkey u)
148 Miliseconds
149 -- ^ keep retrying the connection
150 | Ignore PortNumber
151 -- ^ stop listening on specified port
152 | Send conkey ByteString
153 -- ^ send bytes to an established connection
154
155#ifdef TEST
156deriving instance Show conkey => Show (ServerInstruction conkey u)
157instance Show (a -> b) where show _ = "<function>"
158deriving instance Show conkey => Show (ConnectionParameters conkey u)
159#endif
160
161-- | This type specifies which which half of a half-duplex
162-- connection is of interest.
163data InOrOut = In | Out
164 deriving (Enum,Eq,Ord,Show,Read)
165
166-- | These events may be read from 'serverEvent' TChannel.
167--
168data ConnectionEvent b
169 = Connection (STM Bool) (Source IO b) (Sink (Flush b) IO ())
170 -- ^ A new connection was established
171 | ConnectFailure SockAddr
172 -- ^ A 'Connect' command failed.
173 | HalfConnection InOrOut
174 -- ^ Half of a half-duplex connection is avaliable.
175 | EOF
176 -- ^ A connection was terminated
177 | RequiresPing
178 -- ^ 'pingInterval' miliseconds of idle was experienced
179
180#ifdef TEST
181instance Show (IO a) where show _ = "<IO action>"
182instance Show (STM a) where show _ = "<STM action>"
183instance Eq (ByteString -> IO Bool) where (==) _ _ = True
184instance Eq (IO (Maybe ByteString)) where (==) _ _ = True
185instance Eq (STM Bool) where (==) _ _ = True
186deriving instance Show b => Show (ConnectionEvent b)
187deriving instance Eq b => Eq (ConnectionEvent b)
188#endif
189
190-- | This is the per-connection state.
191data ConnectionRecord u
192 = ConnectionRecord { ckont :: TMVar (STM (IO ())) -- ^ used to pass a continuation to update the eof-handler
193 , cstate :: ConnectionState -- ^ used to send/receive data to the connection
194 , cdata :: u -- ^ user data, stored in the connection map for convenience
195 }
196
197-- | This object accepts commands and signals events and maintains
198-- the list of currently listening ports and established connections.
199data Server a u releaseKey b
200 = Server { serverCommand :: TMVar (ServerInstruction a u)
201 , serverEvent :: TChan ((a,u), ConnectionEvent b)
202 , serverReleaseKey :: releaseKey
203 , conmap :: TVar (Map a (ConnectionRecord u))
204 , listenmap :: TVar (Map PortNumber ServerHandle)
205 , retrymap :: TVar (Map SockAddr (TVar Bool,InterruptibleDelay))
206 }
207
208control :: Server a u releaseKey b -> ServerInstruction a u -> IO ()
209control sv = atomically . putTMVar (serverCommand sv)
210
211type Allocate releaseKey m = forall b. IO b -> (b -> IO ()) -> m (releaseKey, b)
212
213noCleanUp :: MonadIO m => Allocate () m
214noCleanUp io _ = ( (,) () ) `liftM` liftIO io
215
216-- | Construct a 'Server' object. Use 'Control.Monad.Trans.Resource.ResourceT'
217-- to ensure proper cleanup. For example,
218--
219-- > import Server
220-- > import Control.Monad.Trans.Resource (runResourceT)
221-- > import Control.Monad.IO.Class (liftIO)
222-- > import Control.Monad.STM (atomically)
223-- > import Control.Concurrent.STM.TMVar (putTMVar)
224-- > import Control.Concurrent.STM.TChan (readTChan)
225-- >
226-- > main = runResourceT $ do
227-- > sv <- server allocate
228-- > let params = connectionDefaults (return . snd)
229-- > liftIO . atomically $ putTMVar (serverCommand sv) (Listen 2942 params)
230-- > let loop = do
231-- > (_,event) <- atomically $ readTChan (serverEvent sv)
232-- > case event of
233-- > Connection getPingFlag readData writeData -> do
234-- > forkIO $ do
235-- > fix $ \readLoop -> do
236-- > readData >>= mapM $ \bytes ->
237-- > putStrLn $ "got: " ++ show bytes
238-- > readLoop
239-- > case event of EOF -> return ()
240-- > _ -> loop
241-- > liftIO loop
242--
243-- Using 'Control.Monad.Trans.Resource.ResourceT' is optional. Pass 'noCleanUp'
244-- to do without automatic cleanup and be sure to remember to write 'Quit' to
245-- the 'serverCommand' variable.
246server ::
247 -- forall (m :: * -> *) a u conkey releaseKey.
248 (Show conkey, MonadIO m, Ord conkey) =>
249 Allocate releaseKey m
250 -> ( IO (Maybe ByteString) -> (ByteString -> IO Bool) -> ( Source IO x, Sink (Flush x) IO () ) )
251 -> m (Server conkey u releaseKey x)
252server allocate sessionConduits = do
253 (key,cmds) <- allocate (atomically newEmptyTMVar)
254 (atomically . flip putTMVar Quit)
255 server <- liftIO . atomically $ do
256 tchan <- newTChan
257 conmap <- newTVar Map.empty
258 listenmap<- newTVar Map.empty
259 retrymap <- newTVar Map.empty
260 return Server { serverCommand = cmds
261 , serverEvent = tchan
262 , serverReleaseKey = key
263 , conmap = conmap
264 , listenmap = listenmap
265 , retrymap = retrymap
266 }
267 liftIO $ do
268 tid <- forkIO $ fix $ \loop -> do
269 instr <- atomically $ takeTMVar cmds
270 -- warn $ "instr = " <> bshow instr
271 let again = do doit server instr
272 -- warn $ "finished " <> bshow instr
273 loop
274 case instr of Quit -> closeAll server
275 _ -> again
276 labelThread tid "server"
277 return server
278 where
279 closeAll server = do
280 listening <- atomically . readTVar $ listenmap server
281 mapM_ quitListening (Map.elems listening)
282 let stopRetry (v,d) = do atomically $ writeTVar v False
283 interruptDelay d
284 retriers <- atomically $ do
285 rmap <- readTVar $ retrymap server
286 writeTVar (retrymap server) Map.empty
287 return rmap
288 mapM_ stopRetry (Map.elems retriers)
289 cons <- atomically . readTVar $ conmap server
290 atomically $ mapM_ (connClose . cstate) (Map.elems cons)
291 atomically $ mapM_ (connWait . cstate) (Map.elems cons)
292 atomically $ writeTVar (conmap server) Map.empty
293
294
295 doit server (Listen port params) = do
296
297 listening <- Map.member port
298 `fmap` atomically (readTVar $ listenmap server)
299 when (not listening) $ do
300
301 hPutStrLn stderr $ "Started listening on "++show port
302
303 let family = AF_INET6
304 address = case family of
305 AF_INET -> SockAddrInet port iNADDR_ANY
306 AF_INET6 -> SockAddrInet6 port 0 iN6ADDR_ANY 0
307
308 sserv <- flip streamServer address ServerConfig
309 { serverWarn = hPutStrLn stderr
310 , serverSession = \sock _ h -> do
311 (conkey,u) <- makeConnKey params sock
312 _ <- newConnection server sessionConduits params conkey u h In
313 return ()
314 }
315
316 atomically $ listenmap server `modifyTVar'` Map.insert port sserv
317
318 doit server (Ignore port) = do
319 hPutStrLn stderr $ "Stopping listen on "++show port
320 mb <- atomically $ do
321 map <- readTVar $ listenmap server
322 modifyTVar' (listenmap server) $ Map.delete port
323 return $ Map.lookup port map
324 maybe (return ()) quitListening $ mb
325
326 doit server (Send con bs) = do -- . void . forkIO $ do
327 map <- atomically $ readTVar (conmap server)
328 let post False = (trace ("cant send: "++show bs) $ return ())
329 post True = return ()
330 maybe (post False)
331 (post <=< flip connWrite bs . cstate)
332 $ Map.lookup con map
333
334 doit server (Connect addr params) = join $ atomically $ do
335 Map.lookup addr <$> readTVar (retrymap server)
336 >>= return . \case
337 Nothing -> forkit
338 Just (v,d) -> do b <- atomically $ readTVar v
339 interruptDelay d
340 when (not b) forkit
341 where
342 forkit = void . forkIO $ do
343 myThreadId >>= flip labelThread ( "Connect." ++ show addr )
344 proto <- getProtocolNumber "tcp"
345 sock <- socket (socketFamily addr) Stream proto
346 handle (\e -> do -- let t = ioeGetErrorType e
347 when (isDoesNotExistError e) $ return () -- warn "GOTCHA"
348 -- warn $ "connect-error: " <> bshow e
349 (conkey,u) <- makeConnKey params (restrictSocket sock) -- XXX: ?
350 Socket.close sock
351 atomically
352 $ writeTChan (serverEvent server)
353 $ ((conkey,u),ConnectFailure addr))
354 $ do
355 connect sock addr
356 (conkey,u) <- makeConnKey params (restrictSocket sock)
357 h <- socketToHandle sock ReadWriteMode
358 newConnection server sessionConduits params conkey u h Out
359 return ()
360
361 doit server (ConnectWithEndlessRetry addr params interval) = do
362 proto <- getProtocolNumber "tcp"
363 void . forkIO $ do
364 myThreadId >>= flip labelThread ("ConnectWithEndlessRetry." ++ show addr)
365 timer <- interruptibleDelay
366 (retryVar,action) <- atomically $ do
367 map <- readTVar (retrymap server)
368 action <- case Map.lookup addr map of
369 Nothing -> return $ return ()
370 Just (v,d) -> do writeTVar v False
371 return $ interruptDelay d
372 v <- newTVar True
373 writeTVar (retrymap server) $! Map.insert addr (v,timer) map
374 return (v,action :: IO ())
375 action
376 fix $ \retryLoop -> do
377 utc <- getCurrentTime
378 shouldRetry <- do
379 handle (\(SomeException e) -> do
380 -- Exceptions thrown by 'socket' need to be handled specially
381 -- since we don't have enough information to broadcast a ConnectFailure
382 -- on serverEvent.
383 warn $ "Failed to create socket: " <> bshow e
384 atomically $ readTVar retryVar) $ do
385 sock <- socket (socketFamily addr) Stream proto
386 handle (\(SomeException e) -> do
387 -- Any thing else goes wrong and we broadcast ConnectFailure.
388 do (conkey,u) <- makeConnKey params (restrictSocket sock)
389 Socket.close sock
390 atomically $ writeTChan (serverEvent server) ((conkey,u),ConnectFailure addr)
391 `onException` return ()
392 atomically $ readTVar retryVar) $ do
393 connect sock addr
394 (conkey,u) <- makeConnKey params (restrictSocket sock)
395 h <- socketToHandle sock ReadWriteMode
396 threads <- newConnection server sessionConduits params conkey u h Out
397 atomically $ do threadsWait threads
398 readTVar retryVar
399 fin_utc <- getCurrentTime
400 when shouldRetry $ do
401 let elapsed = 1000.0 * (fin_utc `diffUTCTime` utc)
402 expected = fromIntegral interval
403 when (shouldRetry && elapsed < expected) $ do
404 debugNoise $ "Waiting to retry " <> bshow addr
405 void $ startDelay timer (round $ 1000 * (expected-elapsed))
406 debugNoise $ "retry " <> bshow (shouldRetry,addr)
407 when shouldRetry $ retryLoop
408
409
410-- INTERNAL ----------------------------------------------------------
411
412{-
413hWriteUntilNothing h outs =
414 fix $ \loop -> do
415 mb <- atomically $ takeTMVar outs
416 case mb of Just bs -> do S.hPutStrLn h bs
417 warn $ "wrote " <> bs
418 loop
419 Nothing -> do warn $ "wrote Nothing"
420 hClose h
421
422-}
423connRead :: ConnectionState -> IO (Maybe ByteString)
424connRead (WriteOnlyConnection w) = do
425 -- atomically $ discardContents (threadsChannel w)
426 return Nothing
427connRead conn = do
428 c <- atomically $ getThreads
429 threadsRead c
430 where
431 getThreads =
432 case conn of SaneConnection c -> return c
433 ReadOnlyConnection c -> return c
434 ConnectionPair c w -> do
435 -- discardContents (threadsChannel w)
436 return c
437
438socketFamily :: SockAddr -> Family
439socketFamily (SockAddrInet _ _) = AF_INET
440socketFamily (SockAddrInet6 _ _ _ _) = AF_INET6
441socketFamily (SockAddrUnix _) = AF_UNIX
442
443
444conevent :: ( IO (Maybe ByteString) -> (ByteString -> IO Bool) -> ( Source IO x, Sink (Flush x) IO () ) )
445 -> ConnectionState
446 -> ConnectionEvent x
447conevent sessionConduits con = Connection pingflag read write
448 where
449 pingflag = swapTVar (pingFlag (connPingTimer con)) False
450 (read,write) = sessionConduits (connRead con) (connWrite con)
451
452newConnection :: Ord a
453 => Server a u1 releaseKey x
454 -> ( IO (Maybe ByteString) -> (ByteString -> IO Bool) -> ( Source IO x, Sink (Flush x) IO () ) )
455 -> ConnectionParameters conkey u
456 -> a
457 -> u1
458 -> Handle
459 -> InOrOut
460 -> IO ConnectionThreads
461newConnection server sessionConduits params conkey u h inout = do
462 hSetBuffering h NoBuffering
463 let (idle_ms,timeout_ms) =
464 case (inout,duplex params) of
465 (Out,False) -> ( 0, 0 )
466 _ -> ( pingInterval params
467 , timeout params )
468
469 new <- do pinglogic <- forkPingMachine idle_ms timeout_ms
470 connectionThreads h pinglogic
471 started <- atomically $ newEmptyTMVar
472 kontvar <- atomically newEmptyTMVar
473 -- XXX: Why does kontvar store STM (IO ()) instead of just IO () ?
474 let _ = kontvar :: TMVar (STM (IO ()))
475 forkIO $ do
476 myThreadId >>= flip labelThread ("connecting...")
477 getkont <- atomically $ takeTMVar kontvar
478 kont <- atomically getkont
479 kont
480
481 atomically $ do
482 current <- fmap (Map.lookup conkey) $ readTVar (conmap server)
483 case current of
484 Nothing -> do
485 (newCon,e) <- return $
486 if duplex params
487 then let newcon = SaneConnection new
488 in ( newcon, ((conkey,u), conevent sessionConduits newcon) )
489 else ( case inout of
490 In -> ReadOnlyConnection new
491 Out -> WriteOnlyConnection new
492 , ((conkey,u), HalfConnection inout) )
493 modifyTVar' (conmap server) $ Map.insert conkey
494 ConnectionRecord { ckont = kontvar
495 , cstate = newCon
496 , cdata = u }
497 announce e
498 putTMVar kontvar $ return $ do
499 myThreadId >>= flip labelThread ("connection."++show inout) -- XXX: more info would be nice.
500 atomically $ putTMVar started ()
501 -- Wait for something interesting.
502 handleEOF conkey u kontvar newCon
503 Just what@ConnectionRecord { ckont =mvar }-> do
504 putTMVar kontvar $ return $ return () -- Kill redundant "connecting..." thread.
505 putTMVar mvar $ do
506 -- The action returned by updateConMap, eventually invokes handleEOF,
507 -- so the sequencer thread will not be terminated.
508 kont <- updateConMap conkey u new what
509 putTMVar started ()
510 return kont
511 return new
512 where
513
514 announce e = writeTChan (serverEvent server) e
515
516 -- This function loops and will not quit unless an action is posted to the
517 -- mvar that does not in turn invoke this function, or if an EOF occurs.
518 handleEOF conkey u mvar newCon = do
519 action <- atomically . foldr1 orElse $
520 [ takeTMVar mvar >>= id -- passed continuation
521 , connWait newCon >> return eof
522 , connWaitPing newCon >>= return . sendPing
523 -- , pingWait pingTimer >>= return . sendPing
524 ]
525 action :: IO ()
526 where
527 eof = do
528 -- warn $ "EOF " <>bshow conkey
529 connCancelPing newCon
530 atomically $ do connFlush newCon
531 announce ((conkey,u),EOF)
532 modifyTVar' (conmap server)
533 $ Map.delete conkey
534 -- warn $ "fin-EOF "<>bshow conkey
535
536 sendPing PingTimeOut = do
537 {-
538 utc <- getCurrentTime
539 let utc' = formatTime defaultTimeLocale "%s" utc
540 warn $ "ping:TIMEOUT " <> bshow utc'
541 -}
542 atomically (connClose newCon)
543 eof
544
545 sendPing PingIdle = do
546 {-
547 utc <- getCurrentTime
548 let utc' = formatTime defaultTimeLocale "%s" utc
549 -- warn $ "ping:IDLE " <> bshow utc'
550 -}
551 atomically $ announce ((conkey,u),RequiresPing)
552 handleEOF conkey u mvar newCon
553
554
555 updateConMap conkey u new (ConnectionRecord { ckont=mvar, cstate=replaced, cdata=u0 }) = do
556 new' <-
557 if duplex params then do
558 announce ((conkey,u),EOF)
559 connClose replaced
560 let newcon = SaneConnection new
561 announce $ ((conkey,u),conevent sessionConduits newcon)
562 return $ newcon
563 else
564 case replaced of
565 WriteOnlyConnection w | inout==In ->
566 do let newcon = ConnectionPair new w
567 announce ((conkey,u),conevent sessionConduits newcon)
568 return newcon
569 ReadOnlyConnection r | inout==Out ->
570 do let newcon = ConnectionPair r new
571 announce ((conkey,u),conevent sessionConduits newcon)
572 return newcon
573 _ -> do -- connFlush todo
574 announce ((conkey,u0), EOF)
575 connClose replaced
576 announce ((conkey,u), HalfConnection inout)
577 return $ case inout of
578 In -> ReadOnlyConnection new
579 Out -> WriteOnlyConnection new
580 modifyTVar' (conmap server) $ Map.insert conkey
581 ConnectionRecord { ckont = mvar
582 , cstate = new'
583 , cdata = u }
584 return $ handleEOF conkey u mvar new'
585
586
587getPacket :: Handle -> IO ByteString
588getPacket h = do hWaitForInput h (-1)
589 hGetNonBlocking h 1024
590
591
592
593-- | 'ConnectionThreads' is an interface to a pair of threads
594-- that are reading and writing a 'Handle'.
595data ConnectionThreads = ConnectionThreads
596 { threadsWriter :: TMVar (Maybe ByteString)
597 , threadsChannel :: TChan ByteString
598 , threadsWait :: STM () -- ^ waits for a 'ConnectionThreads' object to close
599 , threadsPing :: PingMachine
600 }
601
602-- | This spawns the reader and writer threads and returns a newly
603-- constructed 'ConnectionThreads' object.
604connectionThreads :: Handle -> PingMachine -> IO ConnectionThreads
605connectionThreads h pinglogic = do
606
607 (donew,outs) <- atomically $ liftM2 (,) newEmptyTMVar newEmptyTMVar
608
609 (doner,incomming) <- atomically $ liftM2 (,) newEmptyTMVar newTChan
610 readerThread <- forkIO $ do
611 myThreadId >>= flip labelThread ("readerThread")
612 let finished e = do
613 hClose h
614 -- warn $ "finished read: " <> bshow (fmap ioeGetErrorType e)
615 -- let _ = fmap ioeGetErrorType e -- type hint
616 let _ = fmap what e where what (SomeException _) = undefined
617 atomically $ do tryTakeTMVar outs
618 putTMVar outs Nothing -- quit writer
619 putTMVar doner ()
620 handle (finished . Just) $ do
621 pingBump pinglogic -- start the ping timer
622 fix $ \loop -> do
623 packet <- getPacket h
624 -- warn $ "read: " <> S.take 60 packet
625 atomically $ writeTChan incomming packet
626 pingBump pinglogic
627 -- warn $ "bumped: " <> S.take 60 packet
628 isEof <- hIsEOF h
629 if isEof then finished Nothing else loop
630
631 writerThread <- forkIO . fix $ \loop -> do
632 myThreadId >>= flip labelThread ("writerThread")
633 let finished = do -- warn $ "finished write"
634 -- hClose h -- quit reader
635 throwTo readerThread (ErrorCall "EOF")
636 atomically $ putTMVar donew ()
637 mb <- atomically $ readTMVar outs
638 case mb of Just bs -> handle (\(SomeException e)->finished)
639 (do -- warn $ "writing: " <> S.take 60 bs
640 S.hPutStr h bs
641 -- warn $ "wrote: " <> S.take 60 bs
642 atomically $ takeTMVar outs
643 loop)
644 Nothing -> finished
645
646 let wait = do readTMVar donew
647 readTMVar doner
648 return ()
649 return ConnectionThreads { threadsWriter = outs
650 , threadsChannel = incomming
651 , threadsWait = wait
652 , threadsPing = pinglogic }
653
654
655-- | 'threadsWrite' writes the given 'ByteString' to the
656-- 'ConnectionThreads' object. It blocks until the ByteString
657-- is written and 'True' is returned, or the connection is
658-- interrupted and 'False' is returned.
659threadsWrite :: ConnectionThreads -> ByteString -> IO Bool
660threadsWrite c bs = atomically $
661 orElse (const False `fmap` threadsWait c)
662 (const True `fmap` putTMVar (threadsWriter c) (Just bs))
663
664-- | 'threadsClose' signals for the 'ConnectionThreads' object
665-- to quit and close the associated 'Handle'. This operation
666-- is non-blocking, follow it with 'threadsWait' if you want
667-- to wait for the operation to complete.
668threadsClose :: ConnectionThreads -> STM ()
669threadsClose c = do
670 let mvar = threadsWriter c
671 v <- tryReadTMVar mvar
672 case v of
673 Just Nothing -> return () -- already closed
674 _ -> putTMVar mvar Nothing
675
676-- | 'threadsRead' blocks until a 'ByteString' is available which
677-- is returned to the caller, or the connection is interrupted and
678-- 'Nothing' is returned.
679threadsRead :: ConnectionThreads -> IO (Maybe ByteString)
680threadsRead c = atomically $
681 orElse (const Nothing `fmap` threadsWait c)
682 (Just `fmap` readTChan (threadsChannel c))
683
684-- | A 'ConnectionState' is an interface to a single 'ConnectionThreads'
685-- or to a pair of 'ConnectionThreads' objects that are considered as one
686-- connection.
687data ConnectionState =
688 SaneConnection ConnectionThreads
689 -- ^ ordinary read/write connection
690 | WriteOnlyConnection ConnectionThreads
691 | ReadOnlyConnection ConnectionThreads
692 | ConnectionPair ConnectionThreads ConnectionThreads
693 -- ^ Two 'ConnectionThreads' objects, read operations use the
694 -- first, write operations use the second.
695
696
697
698connWrite :: ConnectionState -> ByteString -> IO Bool
699connWrite (ReadOnlyConnection _) bs = return False
700connWrite conn bs = threadsWrite c bs
701 where
702 c = case conn of SaneConnection c -> c
703 WriteOnlyConnection c -> c
704 ConnectionPair _ c -> c
705
706
707mapConn :: Bool ->
708 (ConnectionThreads -> STM ()) -> ConnectionState -> STM ()
709mapConn both action c =
710 case c of
711 SaneConnection rw -> action rw
712 ReadOnlyConnection r -> action r
713 WriteOnlyConnection w -> action w
714 ConnectionPair r w -> do
715 rem <- orElse (const w `fmap` action r)
716 (const r `fmap` action w)
717 when both $ action rem
718
719connClose :: ConnectionState -> STM ()
720connClose c = mapConn True threadsClose c
721
722connWait :: ConnectionState -> STM ()
723connWait c = doit -- mapConn False threadsWait c
724 where
725 action = threadsWait
726 doit =
727 case c of
728 SaneConnection rw -> action rw
729 ReadOnlyConnection r -> action r
730 WriteOnlyConnection w -> action w
731 ConnectionPair r w -> do
732 rem <- orElse (const w `fmap` action r)
733 (const r `fmap` action w)
734 threadsClose rem
735
736connPingTimer :: ConnectionState -> PingMachine
737connPingTimer c =
738 case c of
739 SaneConnection rw -> threadsPing rw
740 ReadOnlyConnection r -> threadsPing r
741 WriteOnlyConnection w -> threadsPing w -- should be disabled.
742 ConnectionPair r w -> threadsPing r
743
744connCancelPing :: ConnectionState -> IO ()
745connCancelPing c = pingCancel (connPingTimer c)
746
747connWaitPing :: ConnectionState -> STM PingEvent
748connWaitPing c = pingWait (connPingTimer c)
749
750connFlush :: ConnectionState -> STM ()
751connFlush c =
752 case c of
753 SaneConnection rw -> waitChan rw
754 ReadOnlyConnection r -> waitChan r
755 WriteOnlyConnection w -> return ()
756 ConnectionPair r w -> waitChan r
757 where
758 waitChan t = do
759 b <- isEmptyTChan (threadsChannel t)
760 when (not b) retry
761
762bshow :: Show a => a -> ByteString
763bshow e = S.pack . show $ e
764
765warn :: ByteString -> IO ()
766warn str = S.hPutStrLn stderr str >> hFlush stderr
767
768debugNoise :: Monad m => t -> m ()
769debugNoise str = return ()
770
771data TCPStatus = Resolving | AwaitingRead | AwaitingWrite
772
773tcpManager :: ( Show k, Ord k, Ord conkey ) =>
774 (conkey -> (SockAddr, ConnectionParameters conkey u, Miliseconds))
775 -> (String -> Maybe k)
776 -> (k -> IO (Maybe conkey))
777 -> Server conkey u releaseKey x
778 -> IO (Manager TCPStatus k)
779tcpManager grokKey s2k resolvKey sv = do
780 rmap <- atomically $ newTVar Map.empty -- Map k (Maybe conkey)
781 nullping <- forkPingMachine 0 0
782 return Manager {
783 setPolicy = \k -> \case
784 TryingToConnect -> join $ atomically $ do
785 r <- readTVar rmap
786 case Map.lookup k r of
787 Just {} -> return $ return () -- Connection already in progress.
788 Nothing -> do
789 modifyTVar' rmap $ Map.insert k Nothing
790 return $ void $ forkIO $ do
791 myThreadId >>= flip labelThread ("resolve."++show k)
792 mconkey <- resolvKey k
793 case mconkey of
794 Nothing -> atomically $ modifyTVar' rmap $ Map.delete k
795 Just conkey -> do
796 control sv $ case grokKey conkey of
797 (saddr,params,ms) -> ConnectWithEndlessRetry saddr params ms
798 OpenToConnect -> hPutStrLn stderr "TODO: TCP OpenToConnect"
799 RefusingToConnect -> hPutStrLn stderr "TODO: TCP RefusingToConnect"
800 , connections = do
801 c <- readTVar $ conmap sv
802 fmap (exportConnection nullping c) <$> readTVar rmap
803 , stringToKey = s2k
804 , showProgress = \case
805 Resolving -> "resolving"
806 AwaitingRead -> "awaiting inbound"
807 AwaitingWrite -> "awaiting outbound"
808 , showKey = show
809 }
810
811exportConnection :: Ord conkey => PingMachine -> Map conkey (ConnectionRecord u) -> Maybe conkey -> G.Connection TCPStatus
812exportConnection nullping conmap mkey = G.Connection
813 { G.connStatus = case mkey of
814 Nothing -> return $ G.Dormant
815 Just conkey -> case Map.lookup conkey conmap of
816 Nothing -> return $ G.InProgress Resolving
817 Just (ConnectionRecord ckont cstate cdata) -> return $ case cstate of
818 SaneConnection {} -> G.Established
819 ConnectionPair {} -> G.Established
820 ReadOnlyConnection {} -> G.InProgress AwaitingWrite
821 WriteOnlyConnection {} -> G.InProgress AwaitingRead
822 , G.connPolicy = return TryingToConnect
823 , G.connPingLogic = case mkey >>= flip Map.lookup conmap of
824 Nothing -> nullping
825 Just (ConnectionRecord _ cstate _) -> connPingTimer cstate
826 }
diff --git a/Presence/SockAddr.hs b/Presence/SockAddr.hs
new file mode 100644
index 00000000..91a03870
--- /dev/null
+++ b/Presence/SockAddr.hs
@@ -0,0 +1,13 @@
1{-# LANGUAGE CPP #-}
2{-# LANGUAGE StandaloneDeriving #-}
3module SockAddr () where
4
5import Network.Socket ( SockAddr(..) )
6
7#if MIN_VERSION_network(2,4,0)
8#else
9deriving instance Ord SockAddr
10#endif
11
12
13
diff --git a/Presence/UTmp.hs b/Presence/UTmp.hs
new file mode 100644
index 00000000..b43278da
--- /dev/null
+++ b/Presence/UTmp.hs
@@ -0,0 +1,249 @@
1{-# LANGUAGE TemplateHaskell #-}
2{-# LANGUAGE RankNTypes #-}
3module UTmp
4 ( users
5 , users2
6 , utmp_file
7 , UserName
8 , Tty
9 , ProcessID
10 , UtmpRecord(..)
11 , UT_Type(..)
12 ) where
13
14import qualified Data.ByteString as S
15import qualified Data.ByteString.Char8 as C
16import qualified Data.ByteString.Lazy.Char8 as L
17import Data.BitSyntax
18import Data.Functor.Identity
19import Data.Maybe
20import System.Posix.Signals
21import System.Posix.Types
22import Control.Monad
23import Data.Word
24import Data.Int
25import Control.Monad.Error.Class
26import System.IO.Error
27import qualified Paths
28import Data.Text ( Text )
29import Unsafe.Coerce ( unsafeCoerce )
30import Network.Socket ( SockAddr(..) )
31import qualified Data.Text.Encoding as Text
32import SockAddr ()
33
34
35utmp_file :: String
36utmp_file = Paths.utmp -- "/var/run/utmp"
37
38utmp_bs :: IO C.ByteString
39utmp_bs = S.readFile utmp_file
40
41decode_utmp_bytestring ::
42 C.ByteString
43 -> (Word32,
44 Word32,
45 C.ByteString,
46 C.ByteString,
47 C.ByteString,
48 C.ByteString,
49 Word16,
50 Word16,
51 Word32,
52 C.ByteString,
53 Word32,
54 Word32,
55 Word32,
56 Word32)
57decode_utmp_bytestring =
58 runIdentity
59 . $(bitSyn [ UnsignedLE 4 -- type
60 , UnsignedLE 4 -- pid
61 , Fixed 32 -- tty
62 , Fixed 4 -- inittab id
63 , Fixed 32 -- username
64 , Fixed 256 -- remote host
65 , UnsignedLE 2 -- termination status
66 , UnsignedLE 2 -- exit status (int)
67 , UnsignedLE 4 -- session id (int)
68 , Fixed 8 -- time entry was made
69 , Unsigned 4 -- remote addr v6 addr[0]
70 , Unsigned 4 -- remote addr v6 addr[1]
71 , Unsigned 4 -- remote addr v6 addr[2]
72 , Unsigned 4 -- remote addr v6 addr[3]
73 , Skip 20 -- reserved
74 ])
75
76utmp_size :: Int
77utmp_size = 384 -- 768
78
79
80utmp_records :: C.ByteString -> [C.ByteString]
81utmp_records bs | S.length bs >= utmp_size
82 = u:utmp_records us
83 where
84 (u,us) = S.splitAt utmp_size bs
85
86utmp_records bs = [bs]
87
88utmp ::
89 IO
90 [(Word32,
91 Word32,
92 C.ByteString,
93 C.ByteString,
94 C.ByteString,
95 C.ByteString,
96 Word16,
97 Word16,
98 Word32,
99 C.ByteString,
100 Word32,
101 Word32,
102 Word32,
103 Word32)]
104utmp = fmap (map decode_utmp_bytestring . utmp_records) utmp_bs
105
106toStr :: C.ByteString -> [Char]
107toStr = takeWhile (/='\0') . C.unpack
108
109interp_utmp_record ::
110 forall t t1 t2 t3 t4 t5 t6 t7 t8 a.
111 Integral a =>
112 (a,
113 Word32,
114 C.ByteString,
115 t,
116 C.ByteString,
117 C.ByteString,
118 t1,
119 t2,
120 t3,
121 t4,
122 t5,
123 t6,
124 t7,
125 t8)
126 -> (UT_Type, [Char], [Char], CPid, [Char])
127interp_utmp_record (typ,pid,tty,inittab,user,hostv4,term,exit,session,time
128 ,addr0,addr1,addr2,addr3) =
129 ( (toEnum . fromIntegral) typ :: UT_Type
130 , toStr user, toStr tty, processId pid, toStr hostv4 )
131 where
132 processId = CPid . coerceToSigned
133
134coerceToSigned :: Word32 -> Int32
135coerceToSigned = unsafeCoerce
136
137
138data UT_Type
139 = EMPTY -- No valid user accounting information. */
140
141 | RUN_LVL -- The system's runlevel. */
142 | BOOT_TIME -- Time of system boot. */
143 | NEW_TIME -- Time after system clock changed. */
144 | OLD_TIME -- Time when system clock changed. */
145
146 | INIT_PROCESS -- Process spawned by the init process. */
147 | LOGIN_PROCESS -- Session leader of a logged in user. */
148 | USER_PROCESS -- Normal process. */
149 | DEAD_PROCESS -- Terminated process. */
150
151 | ACCOUNTING
152
153 deriving (Enum,Show,Eq,Ord,Read)
154
155processAlive :: ProcessID -> IO Bool
156processAlive pid = do
157 catchError (do { signalProcess nullSignal pid ; return True })
158 $ \e -> do { return (not ( isDoesNotExistError e)); }
159
160type UserName = L.ByteString
161type Tty = L.ByteString
162
163users :: IO [(UserName, Tty, ProcessID)]
164users = fmap (map only3) $ do
165 us <- utmp
166 let us' = map interp_utmp_record us
167 us'' = mapMaybe user_proc us'
168 user_proc (USER_PROCESS, u,tty,pid, hostv4)
169 = Just (L.pack u,L.pack tty,pid,hostv4)
170 user_proc _ = Nothing
171 onThrd f (_,_,pid,_) = f pid
172 us3 <- filterM (onThrd processAlive) us''
173 return us3
174
175only3 :: forall t t1 t2 t3. (t1, t2, t3, t) -> (t1, t2, t3)
176only3 (a,b,c,_) = (a,b,c)
177
178data UtmpRecord = UtmpRecord
179 { utmpType :: UT_Type
180 , utmpUser :: Text
181 , utmpTty :: Text
182 , utmpPid :: CPid
183 , utmpHost :: Text
184 , utmpSession :: Int32
185 , utmpRemoteAddr :: Maybe SockAddr
186 }
187 deriving ( Show, Eq, Ord )
188
189toText :: C.ByteString -> Text
190toText bs = Text.decodeUtf8 $ C.takeWhile (/='\0') bs
191
192interp_utmp_record2 ::
193 forall t t1 t2 t3 a.
194 Integral a =>
195 (a,
196 Word32,
197 C.ByteString,
198 t,
199 C.ByteString,
200 C.ByteString,
201 t1,
202 t2,
203 Word32,
204 t3,
205 Word32,
206 Word32,
207 Word32,
208 Word32)
209 -> UtmpRecord
210interp_utmp_record2 (typ,pid,tty,inittab,user,hostv4
211 ,term,exit,session,time,addr0,addr1,addr2,addr3) =
212 UtmpRecord
213 { utmpType = toEnum (fromIntegral typ) :: UT_Type
214 , utmpUser = toText user
215 , utmpTty = toText tty
216 , utmpPid = processId pid
217 , utmpHost = toText hostv4
218 , utmpSession = coerceToSigned session
219 , utmpRemoteAddr =
220 if all (==0) [addr1,addr2,addr3]
221 then do guard (addr0/=0)
222 Just $ SockAddrInet6 0 0 (0,0,0xFFFF,addr0) 0
223 else Just $ SockAddrInet6 0 0 (addr0,addr1,addr2,addr3) 0
224 }
225 where
226 processId = CPid . coerceToSigned
227
228users2 :: IO [UtmpRecord]
229users2 = do
230 us <- utmp
231 let us' = map interp_utmp_record2 us
232 us3 <- filterM (processAlive . utmpPid) us'
233 return us3
234
235{-
236 - This is how the w command reports idle time:
237/* stat the device file to get an idle time */
238static time_t idletime(const char *restrict const tty)
239{
240 struct stat sbuf;
241 if (stat(tty, &sbuf) != 0)
242 return 0;
243 return time(NULL) - sbuf.st_atime;
244}
245 - THis might be useful fo rimplementing
246 - xep-0012 Last Activity
247 - iq get {jabber:iq:last}query
248 -
249 -}
diff --git a/Presence/Util.hs b/Presence/Util.hs
new file mode 100644
index 00000000..8d9a9494
--- /dev/null
+++ b/Presence/Util.hs
@@ -0,0 +1,59 @@
1{-# LANGUAGE OverloadedStrings #-}
2module Util where
3
4import qualified Data.ByteString.Lazy as L
5import Data.Monoid
6import qualified Data.Text as Text
7 ;import Data.Text (Text)
8import qualified Data.Text.Encoding as Text
9import qualified Network.BSD as BSD
10import Network.Socket
11
12import Network.Address (setPort)
13
14type UserName = Text
15type ResourceName = Text
16
17
18unsplitJID :: (Maybe UserName,Text,Maybe ResourceName) -> Text
19unsplitJID (n,h,r) = username <> h <> resource
20 where
21 username = maybe "" (<>"@") n
22 resource = maybe "" ("/"<>) r
23
24splitJID :: Text -> (Maybe UserName,Text,Maybe ResourceName)
25splitJID bjid =
26 let xs = splitAll '@' bjid
27 ys = splitAll '/' (last xs)
28 splitAll c bjid = take 1 xs0 ++ map (Text.drop 1) (drop 1 xs0)
29 where xs0 = Text.groupBy (\x y-> y/=c) bjid
30 server = head ys
31 name = case xs of
32 (n:s:_) -> Just n
33 (s:_) -> Nothing
34 rsrc = case ys of
35 (s:_:_) -> Just $ last ys
36 _ -> Nothing
37 in (name,server,rsrc)
38
39
40textHostName :: IO Text
41textHostName = fmap Text.pack BSD.getHostName
42
43textToLazyByteString :: Text -> L.ByteString
44textToLazyByteString s = L.fromChunks [Text.encodeUtf8 s]
45
46lazyByteStringToText :: L.ByteString -> Text
47lazyByteStringToText = (foldr1 (<>) . map Text.decodeUtf8 . L.toChunks)
48
49-- | for example: 2001-db8-85a3-8d3-1319-8a2e-370-7348.ipv6-literal.net
50ip6literal :: Text -> Text
51ip6literal addr = Text.map dash addr <> ".ipv6-literal.net"
52 where
53 dash ':' = '-'
54 dash x = x
55
56sameAddress :: SockAddr -> SockAddr -> Bool
57sameAddress laddr addr = setPort 0 laddr == setPort 0 addr
58
59
diff --git a/Presence/XMPP.hs b/Presence/XMPP.hs
new file mode 100644
index 00000000..eab57da5
--- /dev/null
+++ b/Presence/XMPP.hs
@@ -0,0 +1,1461 @@
1{-# LANGUAGE OverloadedStrings #-}
2{-# LANGUAGE FlexibleContexts #-}
3{-# LANGUAGE ViewPatterns #-}
4{-# LANGUAGE TypeFamilies #-}
5{-# LANGUAGE CPP #-}
6module XMPP
7 ( module XMPPTypes
8 , listenForXmppClients
9 , listenForRemotePeers
10 , newServerConnections
11 , seekRemotePeers
12 , quitListening
13 , OutBoundMessage(..)
14 , OutgoingConnections
15 , CachedMessages
16 , toPeer
17 , newOutgoingConnections
18 , sendMessage
19 ) where
20
21import ServerC
22import XMPPTypes
23import ByteStringOperators
24import ControlMaybe
25import XMLToByteStrings
26import SendMessage
27import Logging
28import Todo
29
30import Data.Maybe (catMaybes)
31import Data.HList hiding (hHead)
32import Network.Socket ( Family )
33import Control.Concurrent.STM
34import Control.Concurrent.STM.Delay
35import Data.Conduit
36import Data.Maybe
37import Data.ByteString (ByteString)
38import qualified Data.ByteString.Lazy.Char8 as L
39 ( fromChunks
40 )
41import Control.Concurrent.Async
42import Control.Exception as E ( finally )
43import System.IO.Error (isDoesNotExistError)
44import Control.Monad.IO.Class
45import Control.Monad.Trans.Class
46import Control.Monad.Trans.Maybe
47import Text.XML.Stream.Parse (def,parseBytes,content)
48import Data.XML.Types as XML
49import qualified Data.Text as S (Text,takeWhile)
50import Data.Text.Encoding as S (decodeUtf8,encodeUtf8)
51import Data.Text.Lazy.Encoding as L (decodeUtf8)
52import Data.Text.Lazy (toStrict)
53import qualified Data.Sequence as Seq
54import Data.Foldable (toList)
55import Data.List (find)
56import qualified Text.Show.ByteString as L
57import NestingXML
58import Data.Set as Set (Set,(\\))
59import qualified Data.Set as Set
60import qualified Data.Map as Map
61import Data.Map as Map (Map)
62
63#if MIN_VERSION_HList(0,3,0)
64#define HCONS HCons'
65#else
66#define HCONS HCons
67#endif
68
69hHead (HCONS x _) = x
70
71textToByteString x = L.fromChunks [S.encodeUtf8 x]
72
73
74
75xmlifyPresenceForClient :: Presence -> IO [XML.Event]
76xmlifyPresenceForClient (Presence jid stat) = do
77 let n = name jid
78 rsc = resource jid
79 names <- getNamesForPeer (peer jid)
80 let tostr p = L.decodeUtf8 $ n <$++> "@" <?++> L.fromChunks [p] <++?> "/" <++$> rsc
81 jidstrs = fmap (toStrict . tostr) names
82 return (concatMap presenceEvents jidstrs)
83 where
84 presenceEvents jidstr =
85 [ EventBeginElement "{jabber:client}presence" (("from",[ContentText jidstr]):typ stat) ]
86 ++ ( shw stat >>= jabberShow ) ++
87 [ EventEndElement "{jabber:client}presence" ]
88 typ Offline = [("type",[ContentText "unavailable"])]
89 typ _ = []
90 shw ExtendedAway = ["xa"]
91 shw Chatty = ["chat"]
92 shw Away = ["away"]
93 shw DoNotDisturb = ["dnd"]
94 shw _ = []
95 jabberShow stat =
96 [ EventBeginElement "{jabber:client}show" []
97 , EventContent (ContentText stat)
98 , EventEndElement "{jabber:client}show" ]
99
100prefix ## name = Name name Nothing (Just prefix)
101
102streamP name = Name name (Just "http://etherx.jabber.org/streams") (Just "stream")
103
104greet host =
105 [ EventBeginDocument
106 , EventBeginElement (streamP "stream")
107 [("from",[ContentText host])
108 ,("id",[ContentText "someid"])
109 ,("xmlns",[ContentText "jabber:client"])
110 ,("xmlns:stream",[ContentText "http://etherx.jabber.org/streams"])
111 ,("version",[ContentText "1.0"])
112 ]
113 , EventBeginElement (streamP "features") []
114 , EventBeginElement "{urn:ietf:params:xml:ns:xmpp-bind}bind" []
115 , EventEndElement "{urn:ietf:params:xml:ns:xmpp-bind}bind"
116
117 {-
118 -- , " <session xmlns='urn:ietf:params:xml:ns:xmpp-session'/>"
119 , " <mechanisms xmlns='urn:ietf:params:xml:ns:xmpp-sasl'>"
120 -- , " <mechanism>DIGEST-MD5</mechanism>"
121 , " <mechanism>PLAIN</mechanism>"
122 , " </mechanisms> "
123 -}
124
125 , EventEndElement (streamP "features")
126 ]
127
128
129-- type Consumer i m r = forall o. ConduitM i o m r
130mawait :: Monad m => MaybeT (ConduitM i o m) i
131mawait = MaybeT await
132
133-- Note: This function ignores name space qualification
134elementAttrs expected (EventBeginElement name attrs)
135 | nameLocalName name==expected
136 = return attrs
137elementAttrs _ _ = mzero
138
139eventIsBeginElement (EventBeginElement _ _) = True
140eventIsBeginElement _ = False
141
142eventIsEndElement (EventEndElement _) = True
143eventIsEndElement _ = False
144
145filterMapElement::
146 (Monad m, MonadPlus mp) =>
147 (Event -> mp a) -> Event -> mp a -> MaybeT (ConduitM Event o m) (mp a)
148filterMapElement ret opentag empty = loop (empty `mplus` ret opentag) 1
149 where
150 loop ts 0 = return ts
151 loop ts cnt = do
152 tag <- mawait
153 let ts' = mplus ts (ret tag)
154 case () of
155 _ | eventIsEndElement tag -> loop ts' (cnt-1)
156 _ | eventIsBeginElement tag -> loop ts' (cnt+1)
157 _ -> loop ts' cnt
158
159gatherElement ::
160 (Monad m, MonadPlus mp) =>
161 Event -> mp Event -> NestingXML o m (mp Event)
162gatherElement opentag empty = loop (empty `mplus` return opentag) 1
163 where
164 loop ts 0 = return ts
165 loop ts cnt = do
166 maybeXML (return ts) $ \tag -> do
167 let ts' = mplus ts (return tag)
168 case () of
169 _ | eventIsEndElement tag -> loop ts' (cnt-1)
170 _ | eventIsBeginElement tag -> loop ts' (cnt+1)
171 _ -> loop ts' cnt
172
173
174voidMaybeT body = (>> return ()) . runMaybeT $ body
175fixMaybeT f = (>> return ()) . runMaybeT . fix $ f
176
177iq_bind_reply id jid =
178 [ EventBeginElement "{jabber:client}iq" [("type",[ContentText "result"]),("id",[ContentText id])]
179
180 , EventBeginElement "{urn:ietf:params:xml:ns:xmpp-bind}bind"
181 [("xmlns",[ContentText "urn:ietf:params:xml:ns:xmpp-bind"])]
182 , EventBeginElement "{urn:ietf:params:xml:ns:xmpp-bind}jid" []
183 , EventContent (ContentText jid)
184 , EventEndElement "{urn:ietf:params:xml:ns:xmpp-bind}jid"
185 , EventEndElement "{urn:ietf:params:xml:ns:xmpp-bind}bind"
186 , EventEndElement "{jabber:client}iq"
187 ]
188
189uncontent cs = head $ map getText cs
190 where
191 getText (ContentText x) = x
192 getText (ContentEntity x ) = x
193
194tagAttrs (EventBeginElement _ xs) = xs
195tagAttrs _ = []
196
197tagName (EventBeginElement n _) = n
198tagName _ = ""
199
200handleIQSetBind session cmdChan stanza_id = do
201 mchild <- nextElement
202 rsc <- case mchild of
203 Just child -> do
204 let unhandledBind = do
205 liftIO $ debugStr $ "unhandled-bind: "++show child
206 return ""
207 case tagName child of
208 "{urn:ietf:params:xml:ns:xmpp-bind}resource"
209 -> do
210 rsc <- lift content
211 return . textToByteString $ rsc
212 _ -> unhandledBind
213 Nothing -> do
214 liftIO $ debugStr $ "empty bind request!"
215 return ""
216 liftIO $ do
217 debugL $ "iq-set-bind-resource " <++> rsc
218 setResource session rsc
219 jid <- getJID session
220 atomically $ do
221 writeTChan cmdChan (Send $ iq_bind_reply stanza_id (toStrict $ L.decodeUtf8 $ L.show jid) )
222 writeTChan cmdChan BoundToResource
223 forCachedPresence session $ \presence -> do
224 xs <- xmlifyPresenceForClient presence
225 atomically . writeTChan cmdChan . Send $ xs
226
227
228iq_session_reply host stanza_id =
229 [ EventBeginElement "{jabber:client}iq"
230 [("id",[ContentText stanza_id])
231 ,("from",[ContentText host])
232 ,("type",[ContentText "result"])
233 ]
234 , EventEndElement "{jabber:client}iq"
235 ]
236
237handleIQSetSession session cmdChan stanza_id = do
238 host <- liftIO $ do
239 jid <- getJID session
240 names <- getNamesForPeer (peer jid)
241 return (S.decodeUtf8 . head $ names)
242 liftIO . atomically . writeTChan cmdChan . Send $ iq_session_reply host stanza_id
243
244handleIQSet session cmdChan tag = do
245 withJust (lookupAttrib "id" (tagAttrs tag)) $ \stanza_id -> do
246 whenJust nextElement $ \child -> do
247 let unhandledSet = liftIO $ debugStr ("iq-set: "++show (stanza_id,child))
248 case tagName child of
249 "{urn:ietf:params:xml:ns:xmpp-bind}bind"
250 -> handleIQSetBind session cmdChan stanza_id
251 "{urn:ietf:params:xml:ns:xmpp-session}session"
252 -> handleIQSetSession session cmdChan stanza_id
253 _ -> unhandledSet
254
255matchAttrib name value attrs =
256 case find ( (==name) . fst) attrs of
257 Just (_,[ContentText x]) | x==value -> True
258 Just (_,[ContentEntity x]) | x==value -> True
259 _ -> False
260
261lookupAttrib name attrs =
262 case find ( (==name) . fst) attrs of
263 Just (_,[ContentText x]) -> Just x
264 Just (_,[ContentEntity x]) -> Just x
265 _ -> Nothing
266
267iqTypeSet = "set"
268iqTypeGet = "get"
269iqTypeResult = "result"
270iqTypeError = "error"
271
272isIQOf (EventBeginElement name attrs) testType
273 | name=="{jabber:client}iq"
274 && matchAttrib "type" testType attrs
275 = True
276isIQOf _ _ = False
277
278isServerIQOf (EventBeginElement name attrs) testType
279 | name=="{jabber:server}iq"
280 && matchAttrib "type" testType attrs
281 = True
282isServerIQOf _ _ = False
283
284iq_service_unavailable host iq_id mjid req =
285 [ EventBeginElement "{jabber:client}iq"
286 [("type",[ContentText "error"])
287 ,("id",[ContentText iq_id])
288 -- , TODO: set "from" if isJust mjid
289 ]
290 , EventBeginElement req []
291 , EventEndElement req
292 , EventBeginElement "{jabber:client}error" [("type",[ContentText "cancel"])]
293 , EventBeginElement "{urn:ietf:params:xml:ns:xmpp-stanzas}service-unavailable" []
294 , EventEndElement "{urn:ietf:params:xml:ns:xmpp-stanzas}service-unavailable"
295 , EventEndElement "{jabber:client}error"
296 , EventEndElement "{jabber:client}iq"
297 ]
298
299attr name value = (name,[ContentText value])
300attrbs name value = (name,[ContentText (toStrict . L.decodeUtf8 $ value)])
301
302
303getRoster session iqid = do
304 let getlist f = do
305 bs <- f session
306 -- js <- mapM parseHostNameJID bs
307 return (Set.fromList bs) -- js)
308 buddies <- getlist getMyBuddies
309 subscribers <- getlist getMySubscribers
310 solicited <- getlist getMySolicited
311 subnone0 <- getlist getMyOthers
312 let subnone = subnone0 \\ (Set.union buddies subscribers)
313 let subto = buddies \\ subscribers
314 let subfrom = subscribers \\ buddies
315 let subboth = Set.intersection buddies subscribers
316 -- solicited -> ask='subscribe'
317 jid <- getJID session
318 let dest = toStrict . L.decodeUtf8 . bshow $ jid
319 let items= (xmlify solicited "to" subto)
320 ++(xmlify solicited "from" subfrom)
321 ++(xmlify solicited "both" subboth)
322 ++(xmlify solicited "none" subnone)
323 openiq = [EventBeginElement "{jabber:client}iq"
324 [ attr "id" iqid
325 , attr "to" dest
326 , attr "type" "result" ]
327 ,EventBeginElement "{jabber:iq:roster}query"
328 [] -- todo: ver?
329 ]
330 closeiq = [EventEndElement "{jabber:iq:roster}query"
331 ,EventEndElement "{jabber:client}iq"]
332 return $ openiq ++ items ++ closeiq
333 where
334 xmlify solicited stype set = flip concatMap (Set.toList set)
335 $ \jid ->
336 [ EventBeginElement "item"
337 ([ attr "jid" (toStrict . L.decodeUtf8 $ jid)
338 , attr "subscription" stype
339 ]++if Set.member jid solicited
340 then [attr "ask" "subscribe"]
341 else [] )
342 , EventEndElement "item"
343 ]
344
345handleIQGet session cmdChan tag = do
346 withJust (lookupAttrib "id" (tagAttrs tag)) $ \stanza_id -> do
347 whenJust nextElement $ \child -> do
348 host <- liftIO $ do
349 jid <- getJID session
350 names <- getNamesForPeer (peer jid)
351 return (S.decodeUtf8 . head $ names)
352 let unhandledGet req = do
353 liftIO $ debugStr ("iq-get: "++show (stanza_id,child))
354 liftIO . atomically . writeTChan cmdChan . Send $ iq_service_unavailable host stanza_id Nothing req
355 case tagName child of
356 -- "{http://jabber.org/protocol/disco#items}query" -> liftIO $ debugStr "iq-get-query-items"
357 "{urn:xmpp:ping}ping" -> liftIO $ do
358 let mjid = lookupAttrib "from" (tagAttrs tag)
359 let pong = [ EventBeginElement "{jabber:client}iq"
360 $ (case mjid of
361 Just jid -> (attr "to" jid :)
362 _ -> id )
363 [ attr "type" "result"
364 , attr "id" stanza_id
365 , attr "from" host
366 ]
367 , EventEndElement "{jabber:client}iq"
368 ]
369 atomically . writeTChan cmdChan . Send $ pong
370 "{jabber:iq:roster}query" -> liftIO $ do
371 debugStr $ "REQUESTED ROSTER " ++ show tag
372 roster <- getRoster session stanza_id
373 atomically $ do
374 writeTChan cmdChan InterestedInRoster
375 writeTChan cmdChan . Send $ roster
376 sendPending session
377 req -> unhandledGet req
378
379
380handleClientPresence session stanza = do
381 -- online (Available or Away)
382 let log = liftIO . debugL . ("(C) " <++>)
383 log $ "handleClientPresence "<++>bshow stanza
384 jid <- liftIO $ getJID session
385 -- cjid <- liftIO $ parseAddressJID (textToByteString jid)
386 let parseChildren stat = do
387 child <- nextElement
388 log $ " child: "<++> bshow child
389 case child of
390 Just tag | tagName tag=="{jabber:client}show"
391 -> fmap toStat (lift content)
392 Just tag | otherwise -> parseChildren stat
393 Nothing -> return stat
394 toStat "away" = Away
395 toStat "xa" = ExtendedAway
396 toStat "dnd" = DoNotDisturb
397 toStat "chat" = Chatty
398
399 stat' <- parseChildren Available
400 liftIO $ setPresence session stat'
401 log $ "requesting presence: "<++>bshow stat'
402 return ()
403
404
405fromClient :: (MonadThrow m,MonadIO m, JabberClientSession session) =>
406 session -> TChan ClientCommands -> Sink XML.Event m ()
407fromClient session cmdChan = doNestingXML $ do
408 let log = liftIO . debugL . ("(C) " <++>)
409 send = liftIO . atomically . writeTChan cmdChan . Send
410 withXML $ \begindoc -> do
411 when (begindoc==EventBeginDocument) $ do
412 log "begin-doc"
413 withXML $ \xml -> do
414 withJust (elementAttrs "stream" xml) $ \stream_attrs -> do
415 log $ "stream atributes: " <++> bshow stream_attrs
416 host <- liftIO $ do
417 jid <- getJID session
418 names <- getNamesForPeer (peer jid)
419 return (S.decodeUtf8 . head $ names)
420 send $ greet host
421
422 fix $ \loop -> do
423 log "waiting for stanza."
424 whenJust nextElement $ \stanza -> do
425 stanza_lvl <- nesting
426
427 liftIO . debugStr $ "stanza: "++show stanza
428
429 let unhandledStanza = do
430 xs <- gatherElement stanza Seq.empty
431 prettyPrint "unhandled-C: " (toList xs)
432 case () of
433 _ | stanza `isIQOf` iqTypeSet -> handleIQSet session cmdChan stanza
434 _ | stanza `isIQOf` iqTypeGet -> handleIQGet session cmdChan stanza
435 _ | stanza `isClientPresenceOf` presenceTypeSubscribe
436 -> clientRequestsSubscription session cmdChan stanza
437 _ | stanza `isClientPresenceOf` presenceTypeSubscribed
438 -> clientApprovesSubscription session stanza
439 _ | stanza `isClientPresenceOf` presenceTypeUnsubscribed
440 -> clientRejectsSubscription session stanza
441 _ | stanza `isClientPresenceOf` presenceTypeOnline
442 -> handleClientPresence session stanza
443 _ | isMessageStanza stanza -> handleClientMessage session stanza
444 _ | otherwise -> unhandledStanza
445
446 awaitCloser stanza_lvl
447 loop
448
449 log $ "end of stream"
450 withXML $ \xml -> do
451 log $ "end-of-document: " <++> bshow xml
452
453
454rosterPush to contact attrs = do
455 let n = name to
456 rsc = resource to
457 names <- getNamesForPeer (peer to)
458 let tostr p = L.decodeUtf8 $ n <$++> "@" <?++> L.fromChunks [p] <++?> "/" <++$> rsc
459 jidstrs = fmap (toStrict . tostr) names
460 tojid = head jidstrs
461 return
462 [ EventBeginElement "{jabber:client}iq"
463 [ attr "to" tojid
464 , attr "id" "someid"
465 , attr "type" "set"
466 ]
467 , EventBeginElement "{jabber:iq:roster}query" []
468 , EventBeginElement "{jabber:iq:roster}item" (attr "jid" contact : attrs)
469 , EventEndElement "{jabber:iq:roster}item"
470 , EventEndElement "{jabber:iq:roster}query"
471 , EventEndElement "{jabber:client}iq"
472 ]
473
474data EventsForClient = CmdChan ClientCommands
475 | PChan Presence
476 | RChan RosterEvent
477
478toClient :: (MonadIO m, JabberClientSession session ) =>
479 session -> TChan Presence -> TChan ClientCommands -> TChan RosterEvent -> Source m [XML.Event]
480toClient session pchan cmdChan rchan = toClient' False False
481 where
482 toClient' isBound isInterested = do
483 let loop = toClient' isBound isInterested
484 send xs = yield xs >> prettyPrint ">C: " xs
485 event <- liftIO . atomically $
486 foldr1 orElse [fmap CmdChan $ readTChan cmdChan
487 ,fmap RChan $ readTChan rchan
488 ,fmap PChan $ readTChan pchan
489 ]
490 case event of
491 CmdChan QuitThread -> return ()
492 CmdChan (Send xs) -> send xs >> loop
493 CmdChan BoundToResource -> toClient' True isInterested
494 CmdChan InterestedInRoster -> do
495 liftIO . debugStr $ "Roster: interested"
496 toClient' isBound True
497 CmdChan (Chat msg) -> do
498 xs <- liftIO $ xmlifyMessageForClient msg
499 send xs
500 loop
501 -- CmdChan cmd -> liftIO (debugStr $ "unhandled event: "++show cmd) >> loop
502 RChan (RequestedSubscription who contact) -> do
503 jid <- liftIO $ getJID session
504 when (isInterested && Just who==name jid) $ do
505 r <- liftIO $ rosterPush jid (toStrict . L.decodeUtf8 $ contact) [attr "ask" "subscribe"]
506 send r
507 loop
508 RChan (NewBuddy who contact) -> do
509 liftIO . debugStr $ "Roster push: NewBuddy "++show (isInterested,who,contact)
510 (jid,me) <- liftIO $ do
511 jid <- getJID session
512 me <- asHostNameJID jid
513 return (jid,me)
514 withJust me $ \me -> do
515 when (isInterested && Just who==name jid) $ do
516 send [ EventBeginElement "{jabber:client}presence"
517 [ attrbs "from" contact
518 , attrbs "to" me
519 , attr "type" "subscribed"
520 ]
521 , EventEndElement "{jabber:client}presence" ]
522 let f True = "both"
523 f False = "to"
524 subscription <- fmap f (liftIO $ isSubscribed session contact)
525 r <- liftIO . handleIO (\e -> debugStr ("Roster NewBuddy error: "++show e) >> return []) $ do
526 rosterPush jid
527 (toStrict . L.decodeUtf8 $ contact)
528 [attr "subscription" subscription]
529 send r
530 loop
531 RChan (RemovedBuddy who contact) -> do
532 liftIO . debugStr $ "Roster push: RemovedBuddy "++show (isInterested,who,contact)
533 (jid,me) <- liftIO $ do
534 jid <- getJID session
535 me <- asHostNameJID jid
536 return (jid,me)
537 withJust me $ \me -> do
538 when (isInterested && Just who==name jid) $ do
539 send [ EventBeginElement "{jabber:client}presence"
540 [ attrbs "from" contact
541 , attrbs "to" me
542 , attr "type" "unsubscribed"
543 ]
544 , EventEndElement "{jabber:client}presence" ]
545 let f True = "from"
546 f False = "none"
547 subscription <- fmap f (liftIO $ isSubscribed session contact)
548 r <- liftIO . handleIO (\e -> debugStr ("Roster RemovedBuddy error: "++show e) >> return []) $ do
549 rosterPush jid
550 (toStrict . L.decodeUtf8 $ contact)
551 [attr "subscription" subscription]
552 send r
553 loop
554 RChan (NewSubscriber who contact) -> do
555 liftIO . debugStr $ "Roster push: NewSubscriber "++show (isInterested,who,contact)
556 (jid,me) <- liftIO $ do
557 jid <- getJID session
558 me <- asHostNameJID jid
559 return (jid,me)
560 withJust me $ \me -> do
561 when (isInterested && Just who==name jid) $ do
562 let f True = "both"
563 f False = "from"
564 subscription <- fmap f (liftIO $ isBuddy session contact)
565 r <- liftIO . handleIO (\e -> debugStr ("Roster NewSubscriber error: "++show e) >> return []) $ do
566 rosterPush jid
567 (toStrict . L.decodeUtf8 $ contact)
568 [attr "subscription" subscription]
569 send r
570 loop
571 RChan (RejectSubscriber who contact) -> do
572 liftIO . debugStr $ "Roster push: RejectSubscriber "++show (isInterested,who,contact)
573 (jid,me) <- liftIO $ do
574 jid <- getJID session
575 me <- asHostNameJID jid
576 return (jid,me)
577 withJust me $ \me -> do
578 when (isInterested && Just who==name jid) $ do
579 let f True = "to"
580 f False = "none"
581 subscription <- fmap f (liftIO $ isBuddy session contact)
582 r <- liftIO . handleIO (\e -> debugStr ("Roster RejectSubscriber error: "++show e) >> return []) $ do
583 rosterPush jid
584 (toStrict . L.decodeUtf8 $ contact)
585 [attr "subscription" subscription]
586 send r
587 loop
588 RChan (PendingSubscriber who contact) -> do
589 liftIO . debugStr $ "Roster: Pending buddy "++show (isInterested,who,contact)
590 (jid,me) <- liftIO $ do
591 jid <- getJID session
592 me <- asHostNameJID jid
593 return (jid,me)
594 withJust me $ \me -> do
595 when (isInterested && Just who==name jid) $ do
596 send [ EventBeginElement "{jabber:client}presence"
597 [ attrbs "from" contact
598 , attrbs "to" me
599 , attr "type" "subscribe"
600 ]
601 , EventEndElement "{jabber:client}presence" ]
602 loop
603 PChan presence -> do
604 when isBound $ do
605 xs <- liftIO $ xmlifyPresenceForClient presence
606 send xs
607 loop
608
609
610{-
611handleClient
612 :: (SocketLike sock, HHead l (XMPPClass session),
613 JabberClientSession session) =>
614 HCONS sock (HCONS t l) -> Source IO ByteString -> Sink ByteString IO () -> IO ()
615-}
616handleClient st src snk = do
617#if MIN_VERSION_HList(0,3,0)
618 let HCons' sock (HCons' _ st') = st
619#else
620 let HCons sock (HCons _ st') = st
621#endif
622 session_factory = hHead st'
623 pname <- getPeerName sock
624 session <- newSession session_factory sock
625 debugStr $ "PEER NAME: "++Prelude.show pname
626 pchan <- subscribe session Nothing
627 rchan <- subscribeToRoster session
628 let cmdChan = clientChannel session
629
630 writer <- async ( toClient session pchan cmdChan rchan `xmlToByteStrings` snk )
631 finally ( src $= parseBytes def $$ fromClient session cmdChan )
632 $ do
633 atomically $ writeTChan cmdChan QuitThread
634 wait writer
635 closeSession session
636
637{-
638listenForXmppClients ::
639 (HList l, HHead l (XMPPClass session), HExtend e1 l2 l1,
640 HExtend e l1 (HCONS PortNumber l), JabberClientSession session) =>
641 Family -> e1 -> e -> l2 -> IO ServerHandle
642-}
643listenForXmppClients addr_family session_factory port st = do
644#if MIN_VERSION_HList(0,3,0)
645 doServer (HCons' addr_family $ HCons' port $ HCons' session_factory st) handleClient
646#else
647 doServer (HCons addr_family $ HCons port $ HCons session_factory st) handleClient
648#endif
649
650
651{-
652listenForRemotePeers
653 :: (HList l, HHead l (XMPPPeerClass session),
654 HExtend e l1 (HCONS PortNumber l), HExtend e1 l2 l1,
655 JabberPeerSession session) =>
656 Family -> e1 -> e -> l2 -> IO ServerHandle
657-}
658listenForRemotePeers addrfamily session_factory port st = do
659#if MIN_VERSION_HList(0,3,0)
660 doServer (HCons' addrfamily $ HCons' port $ HCons' session_factory st) handlePeer
661#else
662 doServer (HCons addrfamily $ HCons port $ HCons session_factory st) handlePeer
663#endif
664
665{-
666handlePeer
667 :: (HHead l (XMPPPeerClass session),
668 JabberPeerSession session) =>
669 HCONS RestrictedSocket (HCONS t1 l) -> Source IO ByteString -> t -> IO ()
670-}
671handlePeer st src snk = do
672#if MIN_VERSION_HList(0,3,0)
673 let HCons' sock (HCons' _ st') = st
674#else
675 let HCons sock (HCons _ st') = st
676#endif
677 session_factory = hHead st'
678 name <- fmap bshow $ getPeerName sock
679 debugL $ "(P) connected " <++> name
680 session <- newPeerSession session_factory sock
681
682 didClose <- newTVarIO False
683 finally ( src $= parseBytes def $$ fromPeer sock session didClose )
684 $ do
685 debugL $ "(P) disconnected " <++> name
686 didc <- readTVarIO didClose
687 when (not didc) $ closePeerSession session
688
689
690handlePeerPresence session stanza False = do
691 -- Offline
692 liftIO . debugStr $ "PEER-OFFLINE: "++show stanza
693 withJust (lookupAttrib "from" (tagAttrs stanza)) $ \jid -> do
694 peer_jid <- liftIO $ parseAddressJID (textToByteString jid)
695 liftIO . debugStr $ "PEER-OFFLINE-JID: "++show peer_jid
696 liftIO $ announcePresence session (Presence peer_jid Offline)
697handlePeerPresence session stanza True = do
698 -- online (Available or Away)
699 let log = liftIO . debugL . ("(P) " <++>)
700 withJust (lookupAttrib "from" (tagAttrs stanza)) $ \jid -> do
701 pjid <- liftIO $ parseAddressJID (textToByteString jid)
702 -- stat <- show element content
703 let parseChildren stat = do
704 child <- nextElement
705 case child of
706 Just tag | tagName tag=="{jabber:server}show"
707 -> fmap toStat (lift content)
708 Just tag | otherwise -> parseChildren stat
709 Nothing -> return stat
710 toStat "away" = Away
711 toStat "xa" = ExtendedAway
712 toStat "dnd" = DoNotDisturb
713 toStat "chat" = Chatty
714
715 stat' <- parseChildren Available
716 liftIO . debugStr $ "announcing peer online: "++show (pjid,stat')
717 liftIO $ announcePresence session (Presence pjid stat')
718 log $ bshow (Presence pjid stat')
719
720handlePeerMessage session stanza = do
721 withJust (lookupAttrib "from" (tagAttrs stanza)) $ \fromstr-> do
722 withJust (lookupAttrib "to" (tagAttrs stanza)) $ \tostr -> do
723 fromjid <- liftIO $ parseAddressJID (textToByteString fromstr)
724 tojid <- liftIO $ parseAddressJID (textToByteString tostr)
725 let log = liftIO . debugL . ("(P) " <++>)
726 log $ "handlePeerMessage "<++>bshow stanza
727 msg <- parseMessage ("{jabber:server}body"
728 ,"{jabber:server}subject"
729 ,"{jabber:server}thread"
730 )
731 log
732 fromjid
733 tojid
734 stanza
735 liftIO $ sendChatToClient session msg
736
737matchAttribMaybe name (Just value) attrs =
738 case find ( (==name) . fst) attrs of
739 Just (_,[ContentText x]) | x==value -> True
740 Just (_,[ContentEntity x]) | x==value -> True
741 _ -> False
742matchAttribMaybe name Nothing attrs
743 | find ( (==name) . fst) attrs==Nothing
744 = True
745matchAttribMaybe name Nothing attrs
746 | otherwise
747 = False
748
749presenceTypeOffline = Just "unavailable"
750presenceTypeOnline = Nothing
751presenceTypeProbe = Just "probe"
752presenceTypeSubscribe = Just "subscribe"
753presenceTypeSubscribed = Just "subscribed"
754presenceTypeUnsubscribed = Just "unsubscribed"
755
756isPresenceOf (EventBeginElement name attrs) testType
757 | name=="{jabber:server}presence"
758 && matchAttribMaybe "type" testType attrs
759 = True
760isPresenceOf _ _ = False
761
762isMessageStanza (EventBeginElement name attrs)
763 | name=="{jabber:client}message"
764 = True
765isMessageStanza (EventBeginElement name attrs)
766 | name=="{jabber:server}message"
767 = True
768isMessageStanza _ = False
769
770isClientPresenceOf (EventBeginElement name attrs) testType
771 | name=="{jabber:client}presence"
772 && matchAttribMaybe "type" testType attrs
773 = True
774isClientPresenceOf _ _ = False
775
776
777handlePresenceProbe session stanza = do
778 withJust (lookupAttrib "to" (tagAttrs stanza)) $ \to -> do
779 -- withJust (lookupAttrib "from" (tagAttrs stanza)) $ \from -> do
780 jid <- liftIO $ parseAddressJID $ textToByteString to
781 withJust (name jid) $ \user -> do
782 liftIO $ debugL $ "RECEIVED PROBE "<++>bshow (peerAddress session,to)
783 liftIO $ do
784 subs <- getSubscribers (peerSessionFactory session) user
785 liftIO $ debugL $ "subscribers for "<++>bshow user<++>": " <++>bshow subs
786 forM_ subs $ \jidstr -> do
787 handleIO_ (return ()) $ do
788 debugL $ "parsing " <++>jidstr
789 sub <- parseHostNameJID jidstr
790 debugStr $ "comparing " ++show (peer sub , peerAddress session)
791 when (peer sub == discardPort (peerAddress session)) $ do
792 ps <- userStatus session user
793 -- todo: Consider making this a directed presence
794 forM_ ps $ \p -> do
795 debugStr ("PROBE-REPLY: "++show p)
796 mapM_ (sendPeerMessage session . OutBoundPresence) ps
797 return ()
798
799subscribeToPresence subscribers peer_jid user = do
800 pjid <- parseAddressJID peer_jid
801 if Set.member pjid subscribers
802 then return ()
803 else return ()
804
805bare (JID n host _) = JID n host Nothing
806
807presenceErrorRemoteNotFound iqid from to = return
808 [ EventBeginElement "{stream:client}presence"
809 ( case iqid of { Nothing -> id; Just iqid -> ( attr "id" iqid :) }
810 $ [ attr "from" to
811 , attr "type" "error"
812 ] )
813 , EventBeginElement "{stream:client}error"
814 [ attr "type" "modify"]
815 , EventBeginElement "{urn:ietf:params:xml:ns:xmpp-stanzas}remote-server-not-found"
816 []
817 , EventEndElement "{urn:ietf:params:xml:ns:xmpp-stanzas}remote-server-not-found"
818 , EventEndElement "{stream:client}error"
819 , EventEndElement "{stream:client}presence"
820 ]
821
822presenceSubscribed from = return
823 [ EventBeginElement "{stream:client}presence"
824 [ attr "from" from
825 , attr "type" "subscribed"
826 ]
827 , EventEndElement "{stream:client}presence"
828 ]
829
830clientRequestsSubscription session cmdChan stanza = do
831 liftIO $ do
832 debugStr $ "CLIENT PRESENCE SUBSCRIBE " ++ show stanza
833 withJust (lookupAttrib "to" (tagAttrs stanza)) $ \to_str0 -> do
834 let to_str = S.takeWhile (/='/') to_str0
835 from = lookupAttrib "from" (tagAttrs stanza)
836 iqid = lookupAttrib "id" (tagAttrs stanza)
837 let handleError e | isDoesNotExistError e = do
838 debugStr $ "remote-server-not-found"
839 r <- presenceErrorRemoteNotFound iqid from to_str
840 atomically $ writeTChan cmdChan (Send r)
841 handleError e = do
842 debugStr $ "ERROR: "++ show e
843 handleIO handleError $ do
844 let to_str' = textToByteString to_str
845 to_jid <- fmap bare $ parseHostNameJID to_str'
846 if (is_remote . peer) to_jid
847 then do
848 addSolicited session to_str' to_jid
849 debugStr $ "added to solicited: " ++ show to_jid
850 else do
851 -- addLocalSubscriber session to_str
852 -- self <- getJID session
853 r <- presenceSubscribed to_str -- self
854 atomically $ writeTChan cmdChan (Send r)
855 return ()
856
857
858stanzaFromTo ::
859 JabberPeerSession session =>
860 session -> Event -> IO (Maybe (JID, JID))
861stanzaFromTo session stanza =
862 let lookup key = fmap textToByteString (lookupAttrib key (tagAttrs stanza))
863 parse jidstr = handleIO_ (return Nothing) (fmap Just $ parseAddressJID jidstr)
864 in case liftM2 (,) (lookup "from") (lookup "to") of
865 Nothing -> return Nothing
866 Just (from,to) -> do
867 mfrom <- parse from
868 mto <- parse to
869 case liftM2 (,) mfrom mto of
870 Nothing -> return Nothing
871 Just (from,to) -> do
872 let fromjid = JID (name from) (peerAddress session) Nothing
873 return $ Just (fromjid,to)
874
875peerRequestsSubsription session stanza = do
876 liftIO $ debugStr $ "PEER PRESENCE SUBSCRIBE " ++ show stanza
877
878 whenJust (liftIO . handleIO (\e -> debugStr ("peerRequestsSubsription: "++show e) >> return Nothing)
879 $ stanzaFromTo session stanza) $ \(fromjid,tojid) -> do
880 withJust (name tojid) $ \user -> do
881
882 subs <- liftIO $ do
883 subs <- getSubscribers (peerSessionFactory session) user
884 msubs <- flip mapM subs $ \str -> do
885 handleIO_ (return Nothing)
886 (fmap Just $ parseHostNameJID str)
887 return (catMaybes msubs)
888 if elem fromjid subs
889 then do
890 liftIO . debugL $ bshow fromjid <++> " already subscribed to " <++> user
891 -- if already subscribed, reply
892 liftIO $ do
893 sendPeerMessage session (Approval tojid fromjid)
894 ps <- userStatus session user
895 -- todo: consider making this a directed presence
896 mapM_ (sendPeerMessage session . OutBoundPresence) ps
897 else
898 liftIO $ processRequest session user fromjid
899
900clientApprovesSubscription session stanza = do
901 liftIO $ debugStr $ "CLIENT APPROVES SUBSCRIPTION"
902 withJust (lookupAttrib "to" (tagAttrs stanza)) $ \to_str -> do
903 liftIO $ approveSubscriber session (textToByteString to_str)
904
905clientRejectsSubscription session stanza = do
906 liftIO $ debugStr $ "CLIENT REJECTS SUBSCRIPTION"
907 withJust (lookupAttrib "to" (tagAttrs stanza)) $ \to_str -> do
908 liftIO $ rejectSubscriber session (textToByteString to_str)
909
910peerApprovesSubscription session stanza = do
911 liftIO $ debugStr $ "PEER APPROVES SUBSCRIPTION"
912 whenJust (liftIO . handleIO (\e -> debugStr ("peerApprovesSubscription: "++show e) >> return Nothing)
913 $ stanzaFromTo session stanza) $ \(fromjid,tojid) -> do
914 withJust (name tojid) $ \user -> do
915 liftIO $ processApproval session user fromjid
916
917peerRejectsSubscription session stanza = do
918 liftIO $ debugStr $ "PEER REJECTS SUBSCRIPTION"
919 whenJust (liftIO . handleIO (\e -> debugStr ("peerRejectsSubscription: "++show e) >> return Nothing)
920 $ stanzaFromTo session stanza) $ \(fromjid,tojid) -> do
921 withJust (name tojid) $ \user -> do
922 liftIO $ processRejection session user fromjid
923
924handlePeerIQGet :: (JabberPeerSession session, MonadIO m) =>
925 session -> XML.Event -> NestingXML o m ()
926handlePeerIQGet session tag = do
927 -- TODO: Pings should not require an id field.
928 withJust (lookupAttrib "id" (tagAttrs tag)) $ \stanza_id -> do
929 whenJust nextElement $ \child -> do
930 let unhandledGet req = do
931 liftIO $ debugStr ("iq-peer-get: "++show (stanza_id,child))
932 liftIO $
933 sendPeerMessage session (Unsupported (JID Nothing LocalHost Nothing)
934 (JID Nothing (peerAddress session) Nothing)
935 (Just (ContentText stanza_id))
936 req)
937 -- Client equiv: liftIO . atomically . writeTChan cmdChan . Send $ iq_service_unavailable host stanza_id Nothing req
938 case tagName child of
939 -- "{http://jabber.org/protocol/disco#items}query" -> liftIO $ debugStr "iq-get-query-items"
940 "{urn:xmpp:ping}ping" -> liftIO $ do
941 sendPeerMessage session (Pong (JID Nothing LocalHost Nothing)
942 (JID Nothing (peerAddress session) Nothing)
943 (Just (ContentText stanza_id)))
944 -- Client equiv: atomically . writeTChan cmdChan . Send $ pong
945 return ()
946
947 req -> unhandledGet req
948
949fromPeer :: (MonadThrow m,MonadIO m, JabberPeerSession session) =>
950 RestrictedSocket -> session -> TVar Bool -> Sink XML.Event m ()
951fromPeer sock session didClose = doNestingXML $ do
952 let log = liftIO . debugL . ("(P) " <++>)
953 withXML $ \begindoc -> do
954 when (begindoc==EventBeginDocument) $ do
955 log "begin-doc"
956 withXML $ \xml -> do
957 withJust (elementAttrs "stream" xml) $ \stream_attrs -> do
958 log $ "stream atributes: " <++> bshow stream_attrs
959
960 let doTimeout = Thunk $ do
961 atomically $ writeTVar didClose True
962 closePeerSession session
963
964 fix $ \loop -> do
965 log "waiting for stanza."
966 whenJust nextElement $ \stanza -> do
967 stanza_lvl <- nesting
968
969 liftIO $ sendPeerMessage session (ActivityBump doTimeout) -- reset ping timer
970
971 let unhandledStanza = do
972 xs <- gatherElement stanza Seq.empty
973 prettyPrint "P: " (toList xs)
974 case () of
975 _ | stanza `isServerIQOf` iqTypeGet -> handlePeerIQGet session stanza
976 _ | stanza `isPresenceOf` presenceTypeOnline
977 -> handlePeerPresence session stanza True
978 _ | stanza `isPresenceOf` presenceTypeOffline
979 -> handlePeerPresence session stanza False
980 _ | stanza `isPresenceOf` presenceTypeProbe
981 -> handlePresenceProbe session stanza
982 _ | stanza `isPresenceOf` presenceTypeSubscribe
983 -> peerRequestsSubsription session stanza
984 _ | stanza `isPresenceOf` presenceTypeSubscribed
985 -> peerApprovesSubscription session stanza
986 _ | stanza `isPresenceOf` presenceTypeUnsubscribed
987 -> peerRejectsSubscription session stanza
988 _ | isMessageStanza stanza
989 -> handlePeerMessage session stanza
990 _ -> unhandledStanza
991
992 awaitCloser stanza_lvl
993 loop
994
995 log $ "end of stream"
996 withXML $ \xml -> do
997 log $ "end-of-document: " <++> bshow xml
998
999
1000
1001
1002newServerConnections = newTVar Map.empty
1003
1004data CachedMessages = CachedMessages
1005 { presences :: Map JID JabberShow
1006 , probes :: Map JID (Set (Bool,JID)) -- False means solicitation rather than probe
1007 , approvals :: Map JID (Set (Bool,JID) ) -- False means rejection rather than approval
1008 }
1009
1010instance CommandCache CachedMessages where
1011 type CacheableCommand CachedMessages = OutBoundMessage
1012 emptyCache = CachedMessages Map.empty Map.empty Map.empty
1013
1014 updateCache (OutBoundPresence (Presence jid Offline)) cache =
1015 cache { presences=Map.delete jid . presences $ cache }
1016 updateCache (OutBoundPresence p@(Presence jid st)) cache =
1017 cache { presences=Map.insert jid st . presences $ cache }
1018 updateCache (PresenceProbe from to) cache =
1019 cache { probes = mmInsert (True,from) to $ probes cache }
1020 updateCache (Solicitation from to) cache =
1021 cache { probes= mmInsert (False,from) to $ probes cache }
1022 updateCache (Approval from to) cache =
1023 cache { approvals= mmInsert (True,from) to $ approvals cache }
1024 updateCache (Rejection from to) cache =
1025 cache { approvals= mmInsert (False,from) to $ approvals cache }
1026 updateCache (OutBoundMessage msg) cache = cache -- TODO: cache chat?
1027 updateCache (Pong _ _ _) cache = trace "(DISCARDING Pong)" cache -- pings are not cached
1028 updateCache (Unsupported _ _ _ _) cache = cache -- error messages are not cached
1029 updateCache (ActivityBump sock) cache = cache
1030
1031instance ThreadChannelCommand OutBoundMessage where
1032 isQuitCommand Disconnect = True
1033 isQuitCommand _ = False
1034
1035mmInsert val key mm = Map.alter f key mm
1036 where
1037 f Nothing = Just $ Set.singleton val
1038 f (Just set) = Just $ Set.insert val set
1039
1040
1041greetPeer =
1042 [ EventBeginDocument
1043 , EventBeginElement (streamP "stream")
1044 [ attr "xmlns" "jabber:server"
1045 , attr "version" "1.0"
1046 ]
1047 ]
1048
1049goodbyePeer =
1050 [ EventEndElement (streamP "stream")
1051 , EventEndDocument
1052 ]
1053
1054peerJidTextLocal sock jid = do
1055 addr <- getSocketName sock
1056 return . toStrict . L.decodeUtf8
1057 $ name jid <$++> "@"
1058 <?++> showPeer (RemotePeer addr)
1059 <++?> "/" <++$> resource jid
1060
1061peerJidTextRemote sock jid = do
1062 addr <- getPeerName sock
1063 return . toStrict . L.decodeUtf8
1064 $ name jid <$++> "@"
1065 <?++> showPeer (RemotePeer addr)
1066 <++?> "/" <++$> resource jid
1067
1068presenceStanza sock fromjid tojid typ = do
1069 from <- peerJidTextLocal sock fromjid
1070 let to = toStrict . L.decodeUtf8
1071 $ name tojid <$++> "@"
1072 <?++> showPeer (peer tojid)
1073 return
1074 [ EventBeginElement "{jabber:server}presence"
1075 [ attr "from" from
1076 , attr "to" to
1077 , attr "type" typ
1078 ]
1079 , EventEndElement "{jabber:server}presence"
1080 ]
1081
1082
1083toPeer
1084 :: SocketLike sock =>
1085 sock
1086 -> CachedMessages
1087 -> TChan OutBoundMessage
1088 -> (Maybe OutBoundMessage -> IO ())
1089 -> ConduitM i [Event] IO ()
1090toPeer sock cache chan fail = do
1091 let -- log = liftIO . debugL . ("(>P) " <++>)
1092 send xs = yield xs >> prettyPrint ">P: " xs -- >> return (3::Int)
1093 checkConnection cmd = do
1094 liftIO $ catchIO (getPeerName sock >> return ())
1095 (\_ -> fail . Just $ cmd)
1096 sendOrFail getXML cmd = do
1097 checkConnection cmd
1098 r <- liftIO $ getXML
1099 -- handleIO (\e -> debugStr ("ERROR: "++show e) >> return []) getXML
1100 yieldOr r (fail . Just $ cmd)
1101 prettyPrint ">P: " r
1102 sendPresence presence =
1103 sendOrFail (xmlifyPresenceForPeer sock presence)
1104 (OutBoundPresence presence)
1105 sendProbe from to =
1106 sendOrFail (presenceStanza sock from to "probe")
1107 (PresenceProbe from to)
1108 sendSolicitation from to =
1109 sendOrFail (presenceStanza sock from to "subscribe")
1110 (Solicitation from to)
1111 sendApproval approve from to =
1112 sendOrFail (presenceStanza sock from to
1113 (if approve then "subscribed" else "unsubscribed"))
1114 (if approve then Approval from to
1115 else Rejection from to)
1116 sendMessage msg =
1117 sendOrFail (xmlifyMessageForPeer sock msg)
1118 (OutBoundMessage msg)
1119
1120 sendPong from to mid = do
1121 liftIO . debugL $ "SEND PONG"
1122 sendOrFail (xmlifyPong sock from to mid)
1123 (Pong from to mid)
1124 where
1125 xmlifyPong sock from to mid = do
1126 fromjid <- peerJidTextLocal sock to
1127 tojid <- peerJidTextRemote sock to
1128 return $ [ EventBeginElement "{jabber:server}iq"
1129 $ (case mid of
1130 Just c -> (("id",[c]):)
1131 _ -> id )
1132 [ attr "type" "result"
1133 , attr "to" tojid
1134 , attr "from" fromjid
1135 ]
1136 , EventEndElement "{jabber:server}iq"
1137 ]
1138 sendUnsupported from to mid tag =
1139 sendOrFail (xmlifyUnsupported sock from to mid tag)
1140 (Unsupported from to mid tag)
1141 where
1142 xmlifyUnsupported sock from to mid req = do
1143 fromjid <- peerJidTextLocal sock to
1144 tojid <- peerJidTextRemote sock to
1145 return $
1146 [ EventBeginElement "{jabber:server}iq"
1147 $ (case mid of
1148 Just c -> (("id",[c]):)
1149 _ -> id )
1150 [("type",[ContentText "error"])
1151 , attr "to" tojid
1152 , attr "from" fromjid
1153 ]
1154 , EventBeginElement req []
1155 , EventEndElement req
1156 , EventBeginElement "{jabber:server}error" [("type",[ContentText "cancel"])]
1157 , EventBeginElement "{urn:ietf:params:xml:ns:xmpp-stanzas}service-unavailable" []
1158 , EventEndElement "{urn:ietf:params:xml:ns:xmpp-stanzas}service-unavailable"
1159 , EventEndElement "{jabber:server}error"
1160 , EventEndElement "{jabber:server}iq"
1161 ]
1162
1163
1164 send greetPeer
1165 forM_ (Map.assocs . approvals $ cache) $ \(to,froms) -> do
1166 forM_ (Set.toList froms) $ \(approve,from) -> do
1167 liftIO $ debugL "sending cached approval/rejection..."
1168 sendApproval approve from to
1169 forM_ (Map.assocs . presences $ cache) $ \(jid,st) -> do
1170 sendPresence (Presence jid st)
1171 forM_ (Map.assocs . probes $ cache) $ \(to,froms) -> do
1172 forM_ (Set.toList froms) $ \(got,from) -> do
1173 if got
1174 then do
1175 liftIO $ debugL "sending cached probe..."
1176 sendProbe from to
1177 else do
1178 liftIO $ debugL "sending cached solicitation..."
1179 sendSolicitation from to
1180
1181
1182 let five_sec = 5 * 1000000 :: Int
1183 pingref <- liftIO $ do
1184 ping_timer <- liftIO $ newDelay five_sec
1185 newTVarIO (ping_timer,0::Int)
1186
1187 sockref <- liftIO $ atomically newEmptyTMVar
1188 let bump fromsock = do
1189 remote <- liftIO $ catchIO (fmap Just $ getPeerName sock)
1190 (\_ -> return Nothing)
1191 debugL $ "PING BUMP" <++?> fmap (showPeer . RemotePeer) remote
1192 timer <- atomically $ do
1193 tryTakeTMVar sockref
1194 putTMVar sockref fromsock
1195 (timer,v) <- readTVar pingref
1196 writeTVar pingref (timer,0)
1197 return timer
1198 updateDelay timer five_sec
1199 waitPing = do
1200 (timer,v) <- readTVar pingref
1201 waitDelay timer
1202 return v
1203
1204 fix $ \loop -> do
1205 liftIO . debugStr $ "LOOP waiting..."
1206 event <- lift . atomically $ orElse (Left `fmap` readTChan chan)
1207 (Right `fmap` waitPing)
1208 liftIO . debugStr $ "LOOP event = " ++ show event
1209 let sendPing n = do
1210 case n of
1211 0 -> do
1212 ping <- liftIO makePing
1213 yield ping
1214 liftIO . debugL $ "SEND PING"
1215 prettyPrint ">P: " ping
1216 ping_timer <- liftIO $ newDelay five_sec
1217 liftIO . atomically $ writeTVar pingref (ping_timer,1)
1218 loop
1219 1 -> do
1220 remote <- liftIO $ getPeerName sock
1221 liftIO . debugL $ "PING TIMEOUT: " <++> showPeer (RemotePeer remote)
1222 fromsock <- liftIO $ atomically $ readTMVar sockref
1223 -- liftIO $ sClose fromsock
1224 liftIO $ runThunk fromsock
1225
1226 return () -- PING TIMEOUT (loop quits)
1227 x -> error ("What? "++show x)
1228 where makePing = do
1229 addr <- getSocketName sock
1230 remote <- getPeerName sock
1231 let from = toStrict . L.decodeUtf8 . showPeer $ RemotePeer addr
1232 to = toStrict . L.decodeUtf8 . showPeer $ RemotePeer remote
1233 mid = Just (ContentText "iduno")
1234 return $
1235 [ EventBeginElement "{jabber:server}iq"
1236 $ (case mid of
1237 Just c -> (("id",[c]):)
1238 _ -> id )
1239 [ ("type",[ContentText "get"])
1240 , attr "to" to
1241 , attr "from" from
1242 ]
1243 , EventBeginElement "{urn:xmpp:ping}ping" []
1244 , EventEndElement "{urn:xmpp:ping}ping"
1245 , EventEndElement "{jabber:server}iq" ]
1246 chanEvent event = do
1247 case event of
1248 OutBoundPresence p -> sendPresence p
1249 PresenceProbe from to -> do
1250 liftIO $ debugL "sending live probe..."
1251 sendProbe from to
1252 Solicitation from to -> do
1253 liftIO $ debugL "sending live solicitation..."
1254 sendSolicitation from to
1255 Approval from to -> do
1256 liftIO . debugL $ "sending approval "<++>bshow (from,to)
1257 sendApproval True from to
1258 Rejection from to -> do
1259 liftIO . debugL $ "sending rejection "<++>bshow (from,to)
1260 sendApproval False from to
1261 OutBoundMessage msg -> sendMessage msg
1262 Pong from to mid -> do
1263 liftIO . debugL $ "sending pong "<++>bshow (from,to)
1264 sendPong from to mid
1265 Unsupported from to mid tag -> sendUnsupported from to mid tag
1266 Disconnect -> return ()
1267 ActivityBump fromsock -> liftIO (bump fromsock)
1268 when (not . isQuitCommand $ event) loop
1269 either chanEvent sendPing event
1270 return ()
1271 -- send goodbyePeer -- TODO: why does this cause an exception?
1272 -- Text/XML/Stream/Render.hs:169:5-15:
1273 -- Irrefutable pattern failed for pattern (sl : s')
1274
1275
1276
1277
1278seekRemotePeers :: JabberPeerSession config =>
1279 XMPPPeerClass config -> TChan Presence -> OutgoingConnections CachedMessages -> IO b0
1280seekRemotePeers config chan server_connections = do
1281 fix $ \loop -> do
1282 event <- atomically $ readTChan chan
1283 case event of
1284 p@(Presence jid stat) | not (is_remote (peer jid)) -> do
1285 -- debugL $ "seekRemotePeers: " <++> L.show jid <++> " " <++> bshow stat
1286 runMaybeT $ do
1287 u <- MaybeT . return $ name jid
1288 subscribers <- liftIO $ do
1289 subs <- getSubscribers config u
1290 mapM parseHostNameJID subs
1291 -- liftIO . debugL $ "subscribers: " <++> bshow subscribers
1292 let peers = Set.map peer (Set.fromList subscribers)
1293 forM_ (Set.toList peers) $ \peer -> do
1294 when (is_remote peer) $
1295 liftIO $ sendMessage server_connections (OutBoundPresence p) peer
1296 _ -> return (Just ())
1297 loop
1298
1299xmlifyPresenceForPeer sock (Presence jid stat) = do
1300 addr <- getSocketName sock
1301 let n = name jid
1302 rsc = resource jid
1303 jidstr = toStrict . L.decodeUtf8
1304 $ n <$++> "@" <?++> showPeer (RemotePeer addr) <++?> "/" <++$> rsc
1305 return $
1306 [ EventBeginElement "{jabber:server}presence"
1307 (attr "from" jidstr:typ stat) ]
1308 ++ ( shw stat >>= jabberShow ) ++
1309 [ EventEndElement "{jabber:server}presence" ]
1310 where
1311 typ Offline = [attr "type" "unavailable"]
1312 typ _ = []
1313
1314 shw ExtendedAway = ["xa"]
1315 shw Chatty = ["chat"]
1316 shw Away = ["away"]
1317 shw DoNotDisturb = ["dnd"]
1318 shw _ = []
1319 jabberShow stat =
1320 [ EventBeginElement "{jabber:server}show" []
1321 , EventContent (ContentText stat)
1322 , EventEndElement "{jabber:server}show" ]
1323
1324xmlifyMessageForClient msg = do
1325 let tojid = msgTo msg
1326 fromjid = msgFrom msg
1327 tonames <- getNamesForPeer (peer tojid)
1328 fromnames <- getNamesForPeer (peer fromjid)
1329 let mk_str ns jid = toStrict . L.decodeUtf8 $ name jid <$++> "@" <?++> L.fromChunks [head ns] <++?> "/" <++$> resource jid
1330 to_str = mk_str tonames tojid
1331 from_str = mk_str fromnames fromjid
1332 tags = ( "{jabber:client}subject"
1333 , "{jabber:client}body"
1334 )
1335 return $
1336 [ EventBeginElement "{jabber:client}message"
1337 [ attr "from" from_str
1338 , attr "to" to_str
1339 ]
1340 ]
1341 ++ xmlifyMsgElements tags (msgLangMap msg) ++
1342 [ EventEndElement "{jabber:client}message" ]
1343
1344
1345xmlifyMessageForPeer sock msg = do
1346 addr <- getSocketName sock
1347 remote <- getPeerName sock
1348 let n = name (msgFrom msg)
1349 rsc = resource (msgFrom msg)
1350 jidstr = toStrict . L.decodeUtf8
1351 $ n <$++> "@" <?++> showPeer (RemotePeer addr) <++?> "/" <++$> rsc
1352 tostr = toStrict . L.decodeUtf8
1353 $ name (msgTo msg) <$++> "@"
1354 <?++> showPeer (RemotePeer remote) <++?> "/"
1355 <++$> resource (msgTo msg)
1356 tags = ( "{jabber:server}subject"
1357 , "{jabber:server}body"
1358 )
1359 return $
1360 [ EventBeginElement "{jabber:server}message"
1361 [ attr "from" jidstr
1362 , attr "to" tostr
1363 ]
1364 ]
1365 ++ xmlifyMsgElements tags (msgLangMap msg) ++
1366 [ EventEndElement "{jabber:server}message" ]
1367
1368xmlifyMsgElements tags langmap = concatMap (uncurry (langElements tags)) . Map.toList $ langmap
1369
1370langElements (subjecttag,bodytag) lang msg =
1371 ( maybeToList (msgSubject msg)
1372 >>= wrap subjecttag )
1373 ++ ( maybeToList (msgBody msg)
1374 >>= wrap bodytag )
1375 ++ ( Set.toList (msgElements msg)
1376 >>= wrapTriple )
1377 where
1378 wrap name content =
1379 [ EventBeginElement name
1380 ( if lang/="" then [attr "xml:lang" lang]
1381 else [] )
1382 , EventContent (ContentText content)
1383 , EventEndElement name
1384 ]
1385 wrapTriple (name,attrs,content) =
1386 [ EventBeginElement name attrs -- Note: we assume lang specified in attrs
1387 , EventContent (ContentText content)
1388 , EventEndElement name
1389 ]
1390
1391
1392handleClientMessage session stanza = do
1393 let log = liftIO . debugL . ("(C) " <++>)
1394 log $ "handleClientMessage "<++>bshow stanza
1395 from <- liftIO $ getJID session
1396 withJust (lookupAttrib "to" (tagAttrs stanza)) $ \to_str -> do
1397 log $ " to = "<++>bshow to_str
1398 tojid <- liftIO $ parseHostNameJID (textToByteString to_str)
1399 msg <- parseMessage ("{jabber:client}body"
1400 ,"{jabber:client}subject"
1401 ,"{jabber:client}thread"
1402 )
1403 log
1404 from
1405 tojid
1406 stanza
1407 liftIO $ sendChat session msg
1408
1409{-
1410unhandled-C: <message
1411unhandled-C: type="chat"
1412unhandled-C: id="purplea0a7fd24"
1413unhandled-C: to="user@vm2"
1414unhandled-C: xmlns="jabber:client">
1415unhandled-C: <active xmlns="http://jabber.org/protocol/chatstates"/>
1416unhandled-C: <body>
1417unhandled-C: hello dude
1418unhandled-C: </body>
1419unhandled-C: </message>
1420-}
1421parseMessage (bodytag,subjecttag,threadtag) log from tojid stanza = do
1422 let emptyMsg = LangSpecificMessage { msgBody=Nothing, msgSubject=Nothing, msgElements=Set.empty }
1423 parseChildren (th,cmap) = do
1424 child <- nextElement
1425 lvl <- nesting
1426 xmllang <- xmlLang
1427 let lang = maybe "" id xmllang
1428 let c = maybe emptyMsg id (Map.lookup lang cmap)
1429 log $ " child: "<++> bshow child
1430 case child of
1431 Just tag | tagName tag==bodytag
1432 -> do
1433 txt <- lift content
1434 awaitCloser lvl
1435 parseChildren (th,Map.insert lang (c { msgBody=Just txt }) cmap)
1436 Just tag | tagName tag==subjecttag
1437 -> do
1438 txt <- lift content
1439 awaitCloser lvl
1440 parseChildren (th,Map.insert lang (c { msgSubject=Just txt }) cmap)
1441 Just tag | tagName tag==threadtag
1442 -> do
1443 txt <- lift content
1444 awaitCloser lvl
1445 parseChildren (th {msgThreadContent=txt},cmap)
1446 Just tag -> do
1447 let nm = tagName tag
1448 attrs = tagAttrs tag
1449 elems = msgElements c
1450 txt <- lift content
1451 awaitCloser lvl
1452 parseChildren (th,Map.insert lang (c {msgElements=Set.insert (nm,attrs,txt) elems}) cmap)
1453 Nothing -> return (th,cmap)
1454 (th,langmap) <- parseChildren ( MessageThread {msgThreadParent=Nothing, msgThreadContent=""}
1455 , Map.empty )
1456 return Message {
1457 msgTo = tojid,
1458 msgFrom = from,
1459 msgLangMap = langmap,
1460 msgThread = if msgThreadContent th/="" then Just th else Nothing
1461 }
diff --git a/Presence/XMPPServer.hs b/Presence/XMPPServer.hs
new file mode 100644
index 00000000..c81cb9ce
--- /dev/null
+++ b/Presence/XMPPServer.hs
@@ -0,0 +1,1856 @@
1{-# LANGUAGE CPP #-}
2{-# LANGUAGE OverloadedStrings #-}
3{-# LANGUAGE RankNTypes #-}
4{-# LANGUAGE FlexibleInstances #-} -- instance for TChan Event
5{-# LANGUAGE DoAndIfThenElse #-}
6module XMPPServer
7 ( xmppServer
8 , ConnectionKey(..)
9 , XMPPServerParameters(..)
10 , XMPPServer
11 , xmppConnections
12 , StanzaWrap(..)
13 , Stanza(..)
14 , StanzaType(..)
15 , StanzaOrigin(..)
16 , cloneStanza
17 , LangSpecificMessage(..)
18 , peerKeyToText
19 , addrToText
20 , sendModifiedStanzaToPeer
21 , sendModifiedStanzaToClient
22 , presenceProbe
23 , presenceSolicitation
24 , makePresenceStanza
25 , makeInformSubscription
26 , makeRosterUpdate
27 , makeMessage
28 , JabberShow(..)
29 , Server
30 ) where
31
32import ConnectionKey
33import qualified Control.Concurrent.STM.UpdateStream as Slotted
34import Nesting
35import Server
36import EventUtil
37import ControlMaybe
38import LockedChan
39import PeerResolve
40import Blaze.ByteString.Builder (Builder)
41
42import Debug.Trace
43import System.IO (hFlush,stdout)
44import Control.Monad.Trans.Resource
45import Control.Monad.Trans (lift)
46import Control.Monad.IO.Class (MonadIO, liftIO)
47import Control.Monad.Fix (fix)
48import Control.Monad
49#ifdef THREAD_DEBUG
50import Control.Concurrent.Lifted.Instrument (forkIO,myThreadId,labelThread)
51#else
52import Control.Concurrent.Lifted (forkIO,myThreadId)
53import GHC.Conc (labelThread)
54#endif
55import Control.Concurrent.STM
56-- import Control.Concurrent.STM.TChan
57import Network.SocketLike
58import Text.Printf
59import System.Posix.Signals
60import Data.ByteString (ByteString)
61import qualified Data.ByteString.Char8 as Strict8
62-- import qualified Data.ByteString.Lazy.Char8 as Lazy8
63import Data.Int (Int8)
64
65import Data.Conduit
66import qualified Data.Conduit.List as CL
67import qualified Data.Conduit.Binary as CB
68import Data.Conduit.Blaze (builderToByteStringFlush)
69
70import qualified Text.XML.Stream.Render as XML hiding (content)
71import qualified Text.XML.Stream.Parse as XML
72import Data.XML.Types as XML
73import Data.Maybe
74import Data.List (nub)
75import Data.Monoid ( (<>) )
76import Data.Text (Text)
77import qualified Data.Text as Text (pack,unpack,words,intercalate)
78import Data.Char (toUpper,chr,ord)
79import Data.Map (Map)
80import qualified Data.Map as Map
81import Data.Set (Set, (\\) )
82import qualified Data.Set as Set
83import Data.String ( IsString(..) )
84import qualified System.Random
85import Data.Void (Void)
86import System.Endian (toBE32)
87import Control.Applicative
88import System.IO
89import qualified Connection
90
91peerport :: PortNumber
92peerport = 5269
93clientport :: PortNumber
94clientport = 5222
95
96my_uuid :: Text
97my_uuid = "154ae29f-98f2-4af4-826d-a40c8a188574"
98
99data JabberShow = Offline
100 | ExtendedAway
101 | Away
102 | DoNotDisturb
103 | Available
104 | Chatty
105 deriving (Show,Enum,Ord,Eq,Read)
106
107data MessageThread = MessageThread {
108 msgThreadParent :: Maybe Text,
109 msgThreadContent :: Text
110 }
111 deriving (Show,Eq)
112
113data LangSpecificMessage =
114 LangSpecificMessage { msgBody :: Maybe Text
115 , msgSubject :: Maybe Text
116 }
117 deriving (Show,Eq)
118
119data RosterEventType
120 = RequestedSubscription
121 | NewBuddy -- preceded by PresenceInformSubscription True
122 | RemovedBuddy -- preceded by PresenceInformSubscription False
123 | PendingSubscriber -- same as PresenceRequestSubscription
124 | NewSubscriber
125 | RejectSubscriber
126 deriving (Show,Read,Ord,Eq,Enum)
127
128data ClientHack = SimulatedChatErrors
129 deriving (Show,Read,Ord,Eq,Enum)
130
131data StanzaType
132 = Unrecognized
133 | Ping
134 | Pong
135 | RequestResource (Maybe Text)
136 | SetResource
137 | SessionRequest
138 | UnrecognizedQuery Name
139 | RequestRoster
140 | Roster
141 | RosterEvent { rosterEventType :: RosterEventType
142 , rosterUser :: Text
143 , rosterContact :: Text }
144 | Error StanzaError XML.Event
145 | PresenceStatus { presenceShow :: JabberShow
146 , presencePriority :: Maybe Int8
147 , presenceStatus :: [(Lang,Text)]
148 , presenceWhiteList :: [Text]
149 }
150 | PresenceInformError
151 | PresenceInformSubscription Bool
152 | PresenceRequestStatus
153 | PresenceRequestSubscription Bool
154 | Message { msgThread :: Maybe MessageThread
155 , msgLangMap :: [(Lang,LangSpecificMessage)]
156 }
157 | NotifyClientVersion { versionName :: Text
158 , versionVersion :: Text }
159 | InternalEnableHack ClientHack
160 | InternalCacheId Text
161 deriving (Show,Eq)
162
163data StanzaOrigin = LocalPeer | NetworkOrigin ConnectionKey (TChan Stanza)
164
165data StanzaWrap a = Stanza
166 { stanzaType :: StanzaType
167 , stanzaId :: Maybe Text
168 , stanzaTo :: Maybe Text
169 , stanzaFrom :: Maybe Text
170 , stanzaChan :: a
171 , stanzaClosers :: TVar (Maybe [XML.Event])
172 , stanzaInterrupt :: TMVar ()
173 , stanzaOrigin :: StanzaOrigin
174 }
175
176type Stanza = StanzaWrap (LockedChan XML.Event)
177
178data XMPPServerParameters =
179 XMPPServerParameters
180 { -- | Called when a client requests a resource id. The Maybe value is the
181 -- client's preference.
182 xmppChooseResourceName :: ConnectionKey -> SockAddr -> Maybe Text -> IO Text
183 , -- | This should indicate the server's hostname that all client's see.
184 xmppTellMyNameToClient :: IO Text
185 , xmppTellMyNameToPeer :: SockAddr -> IO Text
186 , xmppTellClientHisName :: ConnectionKey -> IO Text
187 , xmppTellPeerHisName :: ConnectionKey -> IO Text
188 , xmppNewConnection :: ConnectionKey -> SockAddr -> TChan Stanza -> IO ()
189 , xmppEOF :: ConnectionKey -> IO ()
190 , xmppRosterBuddies :: ConnectionKey -> IO [Text]
191 , xmppRosterSubscribers :: ConnectionKey -> IO [Text]
192 , xmppRosterSolicited :: ConnectionKey -> IO [Text]
193 , xmppRosterOthers :: ConnectionKey -> IO [Text]
194 , -- | Called when after sending a roster to a client. Usually this means
195 -- the client status should change from "available" to "interested".
196 xmppSubscribeToRoster :: ConnectionKey -> IO ()
197 -- , xmppLookupClientJID :: ConnectionKey -> IO Text
198 , xmppTellClientNameOfPeer :: ConnectionKey -> [Text] -> IO Text
199 , xmppDeliverMessage :: (IO ()) -> Stanza -> IO ()
200 -- | Called whenever a local client's presence changes.
201 , xmppInformClientPresence :: ConnectionKey -> Stanza -> IO ()
202 -- | Called whenever a remote peer's presence changes.
203 , xmppInformPeerPresence :: ConnectionKey -> Stanza -> IO ()
204 , -- | Called when a remote peer requests our status.
205 xmppAnswerProbe :: ConnectionKey -> Stanza -> TChan Stanza -> IO ()
206 , xmppClientSubscriptionRequest :: IO () -> ConnectionKey -> Stanza -> TChan Stanza -> IO ()
207 , -- | Called when a remote peer sends subscription request.
208 xmppPeerSubscriptionRequest :: IO () -> ConnectionKey -> Stanza -> TChan Stanza -> IO ()
209 , xmppClientInformSubscription :: IO () -> ConnectionKey -> Stanza -> IO ()
210 , -- | Called when a remote peer informs us of our subscription status.
211 xmppPeerInformSubscription :: IO () -> ConnectionKey -> Stanza -> IO ()
212 , xmppVerbosity :: IO Int
213 }
214
215
216enableClientHacks ::
217 forall t a.
218 (Eq a, IsString a) =>
219 a -> t -> TChan Stanza -> IO ()
220enableClientHacks "Pidgin" version replyto = do
221 wlog "Enabling hack SimulatedChatErrors for client Pidgin"
222 donevar <- atomically newEmptyTMVar
223 sendReply donevar
224 (InternalEnableHack SimulatedChatErrors)
225 []
226 replyto
227enableClientHacks "irssi-xmpp" version replyto = do
228 wlog "Enabling hack SimulatedChatErrors for client irssi-xmpp"
229 donevar <- atomically newEmptyTMVar
230 sendReply donevar
231 (InternalEnableHack SimulatedChatErrors)
232 []
233 replyto
234enableClientHacks _ _ _ = return ()
235
236cacheMessageId :: Text -> TChan Stanza -> IO ()
237cacheMessageId id' replyto = do
238 wlog $ "Caching id " ++ Text.unpack id'
239 donevar <- atomically newEmptyTMVar
240 sendReply donevar
241 (InternalCacheId id')
242 []
243 replyto
244
245
246-- TODO: http://xmpp.org/rfcs/rfc6120.html#rules-remote-error
247-- client connection
248-- socat script to send stanza fragment
249-- copyToChannel can keep a stack of closers to append to finish-off a stanza
250-- the TMVar () from forkConnection can be passed and with a stanza to detect interruption
251
252addrToText :: SockAddr -> Text
253addrToText (addr@(SockAddrInet _ _)) = Text.pack $ stripColon (show addr)
254 where stripColon s = pre where (pre,port) = break (==':') s
255addrToText (addr@(SockAddrInet6 _ _ _ _)) = Text.pack $ stripColon (show addr)
256 where stripColon s = if null bracket then pre else pre ++ "]"
257 where
258 (pre,bracket) = break (==']') s
259
260peerKeyToText :: ConnectionKey -> Text
261peerKeyToText (PeerKey { callBackAddress=addr }) = addrToText addr
262peerKeyToText (ClientKey { localAddress=addr }) = "ErrorClIeNt0"
263
264
265wlog :: String -> IO ()
266wlog s = putStrLn s >> hFlush stdout
267
268wlogb :: ByteString -> IO ()
269wlogb s = Strict8.putStrLn s >> hFlush stdout
270
271flushPassThrough :: Monad m => Conduit a m b -> Conduit (Flush a) m (Flush b)
272flushPassThrough c = getZipConduit $ ZipConduit (onlyChunks =$= mapOutput Chunk c) <* ZipConduit onlyFlushes
273 where
274 onlyChunks :: Monad m => Conduit (Flush a) m a
275 onlyFlushes :: Monad m => Conduit (Flush a) m (Flush b)
276 onlyChunks = awaitForever yieldChunk
277 onlyFlushes = awaitForever yieldFlush
278 yieldFlush Flush = yield Flush
279 yieldFlush _ = return ()
280 yieldChunk (Chunk x) = yield x
281 yieldChunk _ = return ()
282
283xmlStream :: ReadCommand -> WriteCommand -> ( Source IO XML.Event
284 , Sink (Flush XML.Event) IO () )
285xmlStream conread conwrite = (xsrc,xsnk)
286 where
287 xsrc = src $= XML.parseBytes XML.def
288 xsnk :: Sink (Flush Event) IO ()
289 xsnk = -- XML.renderBytes XML.def =$ snk
290 flushPassThrough (XML.renderBuilder XML.def)
291 =$= builderToByteStringFlush
292 =$= discardFlush
293 =$ snk
294 where
295 discardFlush :: Monad m => ConduitM (Flush a) a m ()
296 discardFlush = awaitForever yieldChunk
297 yieldChunk (Chunk x) = yield x
298 yieldChunk _ = return ()
299
300 src = do
301 v <- lift conread
302 maybe (return ()) -- lift . wlog $ "conread: Nothing")
303 (yield >=> const src)
304 v
305 snk = awaitForever $ liftIO . conwrite
306
307
308type FlagCommand = STM Bool
309type ReadCommand = IO (Maybe ByteString)
310type WriteCommand = ByteString -> IO Bool
311
312cloneStanza :: StanzaWrap (LockedChan a) -> IO (StanzaWrap (LockedChan a))
313cloneStanza stanza = do
314 dupped <- cloneLChan (stanzaChan stanza)
315 return stanza { stanzaChan = dupped }
316
317copyToChannel
318 :: MonadIO m =>
319 (Event -> a) -> LockedChan a -> TVar (Maybe [Event]) -> ConduitM Event Event m ()
320copyToChannel f chan closer_stack = awaitForever copy
321 where
322 copy x = do
323 liftIO . atomically $ writeLChan chan (f x)
324 case x of
325 EventBeginDocument {} -> do
326 let clsr = closerFor x
327 liftIO . atomically $
328 modifyTVar' closer_stack (fmap (clsr:))
329 EventEndDocument {} -> do
330 liftIO . atomically $
331 modifyTVar' closer_stack (fmap (drop 1))
332 _ -> return ()
333 yield x
334
335
336prettyPrint :: ByteString -> ConduitM Event Void IO ()
337prettyPrint prefix =
338 XML.renderBytes (XML.def { XML.rsPretty=True })
339 =$= CB.lines
340 =$ CL.mapM_ (wlogb . (prefix <>))
341
342swapNamespace :: Monad m => Text -> Text -> ConduitM Event Event m ()
343swapNamespace old new = awaitForever (yield . swapit old new)
344
345swapit :: Text -> Text -> Event -> Event
346swapit old new (EventBeginElement n as) | nameNamespace n==Just old =
347 EventBeginElement (n { nameNamespace = Just new }) as
348swapit old new (EventEndElement n) | nameNamespace n==Just old =
349 EventEndElement (n { nameNamespace = Just new })
350swapit old new x = x
351
352fixHeaders :: Monad m => Stanza -> ConduitM Event Event m ()
353fixHeaders Stanza { stanzaType=typ, stanzaTo=mto, stanzaFrom=mfrom } = do
354 x <- await
355 maybe (return ()) f x
356 where
357 f (EventBeginElement n as) = do yield $ EventBeginElement n (update n as)
358 awaitForever yield
359 f x = yield x >> awaitForever yield
360 update n as = as3
361 where
362 as' = maybe as (setAttrib "to" as) mto
363 as'' = maybe as' (setAttrib "from" as') mfrom
364 as3 = case typ of
365 PresenceStatus {} | nameNamespace n == Just "jabber:client"
366 -> delAttrib "whitelist" as''
367 PresenceStatus {} | otherwise
368 -> case presenceWhiteList typ of
369 [] -> delAttrib "whitelist" as''
370 ws -> setAttrib "whitelist" as'' (Text.intercalate " " ws)
371 _ -> as''
372
373 setAttrib akey as aval = attr akey aval:filter ((/=akey) . fst) as
374 delAttrib akey as = filter ((/=akey) . fst) as
375
376conduitToChan
377 :: Conduit () IO Event
378 -> IO (LockedChan Event, TVar (Maybe [Event]), TMVar a)
379conduitToChan c = do
380 chan <- atomically newLockedChan
381 clsrs <- atomically $ newTVar (Just [])
382 quitvar <- atomically $ newEmptyTMVar
383 forkIO $ do
384 c =$= copyToChannel id chan clsrs $$ awaitForever (const $ return ())
385 atomically $ writeTVar clsrs Nothing
386 return (chan,clsrs,quitvar)
387
388conduitToStanza
389 :: StanzaType
390 -> Maybe Text -- ^ id
391 -> Maybe Text -- ^ from
392 -> Maybe Text -- ^ to
393 -> Conduit () IO Event
394 -> IO Stanza
395conduitToStanza stype mid from to c = do
396 (chan,clsrs,quitvar) <- conduitToChan c
397 return
398 Stanza { stanzaType = stype
399 , stanzaId = mid
400 , stanzaTo = to
401 , stanzaFrom = from
402 , stanzaChan = chan
403 , stanzaClosers = clsrs
404 , stanzaInterrupt = quitvar
405 , stanzaOrigin = LocalPeer
406 }
407
408
409ioWriteChan :: MonadIO m => TChan a -> a -> m ()
410ioWriteChan c v = liftIO . atomically $ writeTChan c v
411
412stanzaToConduit :: MonadIO m => Stanza -> ConduitM i Event m ()
413stanzaToConduit stanza = do
414 let xchan = stanzaChan stanza
415 xfin = stanzaClosers stanza
416 rdone = stanzaInterrupt stanza
417 loop = return ()
418 xchan <- liftIO $ unlockChan xchan
419 fix $ \inner -> do
420 what <- liftIO . atomically $ foldr1 orElse
421 [readTChan xchan >>= \xml -> return $ do
422 yield xml -- atomically $ Slotted.push slots Nothing xml
423 inner
424 ,do mb <- readTVar xfin
425 cempty <- isEmptyTChan xchan
426 if isNothing mb
427 then if cempty then return loop else retry
428 else do done <- tryReadTMVar rdone
429 check (isJust done)
430 trace "todo: send closers" retry
431 ,do isEmptyTChan xchan >>= check
432 readTMVar rdone
433 return (return ())]
434 what
435
436
437sendModifiedStanzaToPeer :: Stanza -> TChan Stanza -> IO ()
438sendModifiedStanzaToPeer stanza chan = do
439 (echan,clsrs,quitvar) <- conduitToChan c
440 ioWriteChan chan
441 stanza { stanzaChan = echan
442 , stanzaClosers = clsrs
443 , stanzaInterrupt = quitvar
444 , stanzaType = processedType (stanzaType stanza)
445 -- TODO id? origin?
446 }
447 where
448 old = "jabber:client"
449 new = "jabber:server"
450 c = stanzaToConduit stanza =$= swapNamespace old new =$= fixHeaders stanza
451 processedType (Error cond tag) = Error cond (swapit old new tag)
452 processedType x = x
453
454
455sendModifiedStanzaToClient :: Stanza -> TChan Stanza -> IO ()
456sendModifiedStanzaToClient stanza chan = do
457 (echan,clsrs,quitvar) <- conduitToChan c
458 -- wlog $ "send-to-client " ++ show (stanzaId stanza)
459 ioWriteChan chan
460 stanza { stanzaChan = echan
461 , stanzaClosers = clsrs
462 , stanzaInterrupt = quitvar
463 , stanzaType = processedType (stanzaType stanza)
464 -- TODO id? origin?
465 }
466 where
467 old = "jabber:server"
468 new = "jabber:client"
469 c = stanzaToConduit stanza =$= swapNamespace old new =$= fixHeaders stanza
470 processedType (Error cond tag) = Error cond (swapit old new tag)
471 processedType x = x
472
473
474-- id,to, and from are taken as-is from reply list
475-- todo: this should probably be restricted to IO monad
476sendReply :: (Functor m, MonadIO m) => TMVar () -> StanzaType -> [Event] -> TChan Stanza -> m ()
477sendReply donevar stype reply replychan = do
478 let stanzaTag = listToMaybe reply
479 mid = stanzaTag >>= lookupAttrib "id" . tagAttrs
480 mfrom = stanzaTag >>= lookupAttrib "from" . tagAttrs
481 mto = stanzaTag >>= lookupAttrib "to" . tagAttrs
482 isInternal (InternalEnableHack {}) = True
483 isInternal (InternalCacheId {}) = True
484 isInternal _ = False
485 flip (maybe $ return ())
486 (fmap (const ()) stanzaTag `mplus` guard (isInternal stype))
487 . const $ do
488 replyStanza <- liftIO . atomically $ do
489 replyChan <- newLockedChan
490 replyClsrs <- newTVar (Just [])
491 return Stanza { stanzaType = stype
492 , stanzaId = mid
493 , stanzaTo = mto -- as-is from reply list
494 , stanzaFrom = mfrom -- as-is from reply list
495 , stanzaChan = replyChan
496 , stanzaClosers = replyClsrs
497 , stanzaInterrupt = donevar
498 , stanzaOrigin = LocalPeer
499 }
500 ioWriteChan replychan replyStanza
501 void . liftIO . forkIO $ do
502 mapM_ (liftIO . atomically . writeLChan (stanzaChan replyStanza)) reply
503 liftIO . atomically $ writeTVar (stanzaClosers replyStanza) Nothing
504 -- liftIO $ wlog "finished reply stanza"
505
506stanzaFromList :: StanzaType -> [Event] -> IO Stanza
507stanzaFromList stype reply = do
508 let stanzaTag = listToMaybe reply
509 mid = stanzaTag >>= lookupAttrib "id" . tagAttrs
510 mfrom = stanzaTag >>= lookupAttrib "from" . tagAttrs
511 mto = stanzaTag >>= lookupAttrib "to" . tagAttrs
512 {-
513 isInternal (InternalEnableHack {}) = True
514 isInternal (InternalCacheId {}) = True
515 isInternal _ = False
516 -}
517 (donevar,replyChan,replyClsrs) <- atomically $ do
518 donevar <- newEmptyTMVar -- TMVar ()
519 replyChan <- newLockedChan
520 replyClsrs <- newTVar (Just [])
521 return (donevar,replyChan, replyClsrs)
522 forkIO $ do
523 forM_ reply $ atomically . writeLChan replyChan
524 atomically $ do putTMVar donevar ()
525 writeTVar replyClsrs Nothing
526 return Stanza { stanzaType = stype
527 , stanzaId = mid
528 , stanzaTo = mto -- as-is from reply list
529 , stanzaFrom = mfrom -- as-is from reply list
530 , stanzaChan = replyChan
531 , stanzaClosers = replyClsrs
532 , stanzaInterrupt = donevar
533 , stanzaOrigin = LocalPeer
534 }
535
536grokStanzaIQGet :: Monad m => XML.Event -> NestingXML o m (Maybe StanzaType)
537grokStanzaIQGet stanza = do
538 mtag <- nextElement
539 flip (maybe $ return Nothing) mtag $ \tag -> do
540 case tagName tag of
541 "{urn:xmpp:ping}ping" -> return $ Just Ping
542 "{jabber:iq:roster}query" -> return $ Just RequestRoster
543 name -> return . Just $ UnrecognizedQuery name
544
545parseClientVersion :: NestingXML o IO (Maybe StanzaType)
546parseClientVersion = parseit Nothing Nothing
547 where
548 reportit mname mver = return $ do
549 name <- mname
550 ver <- mver
551 return NotifyClientVersion { versionName=name, versionVersion=ver }
552 parseit :: Maybe Text -> Maybe Text -> NestingXML o IO (Maybe StanzaType)
553 parseit mname mver = do
554 mtag <- nextElement
555 flip (maybe $ reportit mname mver) mtag $ \tag -> do
556 case tagName tag of
557 "{jabber:iq:version}name" -> do
558 x <- XML.content
559 parseit (Just x) mver
560 "{jabber:iq:version}version" -> do
561 x <- XML.content
562 parseit mname (Just x)
563 _ -> parseit mname mver
564
565
566grokStanzaIQResult :: XML.Event -> NestingXML o IO (Maybe StanzaType)
567grokStanzaIQResult stanza = do
568 mtag <- nextElement
569 flip (maybe $ return (Just Pong)) mtag $ \tag -> do
570 case tagName tag of
571 "{jabber:iq:version}query" | nameNamespace (tagName stanza)==Just "jabber:client"
572 -> parseClientVersion
573 _ -> return Nothing
574
575grokStanzaIQSet :: XML.Event -> NestingXML o IO (Maybe StanzaType)
576grokStanzaIQSet stanza = do
577 mtag <- nextElement
578 flip (maybe $ return Nothing) mtag $ \tag -> do
579 case tagName tag of
580 "{urn:ietf:params:xml:ns:xmpp-bind}bind" -> do
581 mchild <- nextElement
582 case fmap tagName mchild of
583 Just "{urn:ietf:params:xml:ns:xmpp-bind}resource" -> do
584 rsc <- XML.content -- TODO: MonadThrow???
585 return . Just $ RequestResource (Just rsc)
586 Just _ -> return Nothing
587 Nothing -> return . Just $ RequestResource Nothing
588 "{urn:ietf:params:xml:ns:xmpp-session}session" -> do
589 return $ Just SessionRequest
590 _ -> return Nothing
591
592
593{-
594C->Unrecognized <iq
595C->Unrecognized type="set"
596C->Unrecognized id="purpleae62d88f"
597C->Unrecognized xmlns="jabber:client">
598C->Unrecognized <bind xmlns="urn:ietf:params:xml:ns:xmpp-bind"/>
599C->Unrecognized </iq>
600-}
601chanContents :: TChan x -> IO [x]
602chanContents ch = do
603 x <- atomically $ do
604 bempty <- isEmptyTChan ch
605 if bempty
606 then return Nothing
607 else fmap Just $ readTChan ch
608 maybe (return [])
609 (\x -> do
610 xs <- chanContents ch
611 return (x:xs))
612 x
613
614
615parsePresenceStatus
616 :: ( MonadThrow m
617 , MonadIO m
618 ) => Text -> XML.Event -> NestingXML o m (Maybe StanzaType)
619parsePresenceStatus ns stanzaTag = do
620
621 let toStat "away" = Away
622 toStat "xa" = ExtendedAway
623 toStat "dnd" = DoNotDisturb
624 toStat "chat" = Chatty
625
626 showv <- liftIO . atomically $ newTVar Available
627 priov <- liftIO . atomically $ newTVar Nothing
628 statusv <- liftIO . atomically $ newTChan
629 fix $ \loop -> do
630 mtag <- nextElement
631 flip (maybe $ return ()) mtag $ \tag -> do
632 when (nameNamespace (tagName tag) == Just ns) $ do
633 case nameLocalName (tagName tag) of
634 "show" -> do t <- XML.content
635 liftIO . atomically $ writeTVar showv (toStat t)
636 "priority" -> do t <- XML.content
637 liftIO . handleIO_ (return ()) $ do
638 prio <- readIO (Text.unpack t)
639 atomically $ writeTVar priov (Just prio)
640 "status" -> do t <- XML.content
641 lang <- xmlLang
642 ioWriteChan statusv (maybe "" id lang,t)
643 _ -> return ()
644 loop
645 show <- liftIO . atomically $ readTVar showv
646 prio <- liftIO . atomically $ readTVar priov
647 status <- liftIO $ chanContents statusv -- Could use unsafeInterleaveIO to
648 -- avoid multiple passes, but whatever.
649 let wlist = do
650 w <- maybeToList $ lookupAttrib "whitelist" (tagAttrs stanzaTag)
651 Text.words w
652 return . Just $ PresenceStatus { presenceShow = show
653 , presencePriority = prio
654 , presenceStatus = status
655 , presenceWhiteList = wlist
656 }
657grokPresence
658 :: ( MonadThrow m
659 , MonadIO m
660 ) => Text -> XML.Event -> NestingXML o m (Maybe StanzaType)
661grokPresence ns stanzaTag = do
662 let typ = lookupAttrib "type" (tagAttrs stanzaTag)
663 case typ of
664 Nothing -> parsePresenceStatus ns stanzaTag
665 Just "unavailable" -> fmap (fmap (\p -> p {presenceShow=Offline}))
666 $ parsePresenceStatus ns stanzaTag
667 Just "error" -> return . Just $ PresenceInformError
668 Just "unsubscribed" -> return . Just $ PresenceInformSubscription False
669 Just "subscribed" -> return . Just $ PresenceInformSubscription True
670 Just "probe" -> return . Just $ PresenceRequestStatus
671 Just "unsubscribe" -> return . Just $ PresenceRequestSubscription False
672 Just "subscribe" -> return . Just $ PresenceRequestSubscription True
673 _ -> return Nothing
674
675parseMessage
676 :: ( MonadThrow m
677 , MonadIO m
678 ) => Text -> XML.Event -> NestingXML o m StanzaType
679parseMessage ns stanza = do
680 let bodytag = Name { nameNamespace = Just ns
681 , nameLocalName = "body"
682 , namePrefix = Nothing }
683 subjecttag = Name { nameNamespace = Just ns
684 , nameLocalName = "subject"
685 , namePrefix = Nothing }
686 threadtag = Name { nameNamespace = Just ns
687 , nameLocalName = "thread"
688 , namePrefix = Nothing }
689 let emptyMsg = LangSpecificMessage { msgBody=Nothing, msgSubject=Nothing }
690 parseChildren (th,cmap) = do
691 child <- nextElement
692 lvl <- nesting
693 xmllang <- xmlLang
694 let lang = maybe "" id xmllang
695 let c = maybe emptyMsg id (Map.lookup lang cmap)
696 -- log $ " child: "<> bshow child
697 case child of
698 Just tag | tagName tag==bodytag
699 -> do
700 txt <- XML.content
701 awaitCloser lvl
702 parseChildren (th,Map.insert lang (c { msgBody=Just txt }) cmap)
703 Just tag | tagName tag==subjecttag
704 -> do
705 txt <- XML.content
706 awaitCloser lvl
707 parseChildren (th,Map.insert lang (c { msgSubject=Just txt }) cmap)
708 Just tag | tagName tag==threadtag
709 -> do
710 txt <- XML.content
711 awaitCloser lvl
712 parseChildren (th {msgThreadContent=txt},cmap)
713 Just tag -> do
714 -- let nm = tagName tag
715 -- attrs = tagAttrs tag
716 -- -- elems = msgElements c
717 -- txt <- XML.content
718 awaitCloser lvl
719 parseChildren (th,Map.insert lang c cmap)
720 Nothing -> return (th,cmap)
721 (th,langmap) <- parseChildren ( MessageThread {msgThreadParent=Nothing, msgThreadContent=""}
722 , Map.empty )
723 return Message {
724 msgLangMap = Map.toList langmap,
725 msgThread = if msgThreadContent th/="" then Just th else Nothing
726 }
727
728findConditionTag :: Monad m => NestingXML o m (Maybe XML.Event)
729findConditionTag = do
730 x <- nextElement
731 flip (maybe $ return Nothing) x $ \x -> do
732 case nameNamespace (tagName x) of
733 Just "urn:ietf:params:xml:ns:xmpp-stanzas" -> return (Just x)
734 _ -> findConditionTag
735
736conditionFromText :: Text -> Maybe StanzaError
737conditionFromText t = fmap fst $ listToMaybe ss
738 where
739 es = [BadRequest .. UnexpectedRequest]
740 ts = map (\e->(e,errorTagLocalName e)) es
741 ss = dropWhile ((/=t) . snd) ts
742
743findErrorTag :: Monad m => Text -> NestingXML o m (Maybe StanzaError)
744findErrorTag ns = do
745 x <- nextElement
746 flip (maybe $ return Nothing) x $ \x -> do
747 case tagName x of
748 n | nameNamespace n==Just ns && nameLocalName n=="error"
749 -> do
750 mtag <- findConditionTag
751 return $ do
752 tag <- {- trace ("mtag = "++show mtag) -} mtag
753 let t = nameLocalName (tagName tag)
754 conditionFromText t
755 _ -> findErrorTag ns
756
757grokMessage
758 :: ( MonadThrow m
759 , MonadIO m
760 ) => Text -> XML.Event -> NestingXML o m (Maybe StanzaType)
761grokMessage ns stanzaTag = do
762 let typ = lookupAttrib "type" (tagAttrs stanzaTag)
763 case typ of
764 Just "error" -> do
765 mb <- findErrorTag ns
766 return $ do
767 e <- mb
768 return $ Error e stanzaTag
769 _ -> do t <- parseMessage ns stanzaTag
770 return $ Just t
771
772
773
774grokStanza
775 :: Text -> XML.Event -> NestingXML o IO (Maybe StanzaType)
776grokStanza "jabber:server" stanzaTag =
777 case () of
778 _ | stanzaTag `isServerIQOf` "get" -> grokStanzaIQGet stanzaTag
779 _ | stanzaTag `isServerIQOf` "result" -> grokStanzaIQResult stanzaTag
780 _ | tagName stanzaTag == "{jabber:server}presence" -> grokPresence "jabber:server" stanzaTag
781 _ | tagName stanzaTag == "{jabber:server}message" -> grokMessage "jabber:server" stanzaTag
782 _ -> return $ Just Unrecognized
783
784grokStanza "jabber:client" stanzaTag =
785 case () of
786 _ | stanzaTag `isClientIQOf` "get" -> grokStanzaIQGet stanzaTag
787 _ | stanzaTag `isClientIQOf` "set" -> grokStanzaIQSet stanzaTag
788 _ | stanzaTag `isClientIQOf` "result" -> grokStanzaIQResult stanzaTag
789 _ | tagName stanzaTag == "{jabber:client}presence" -> grokPresence "jabber:client" stanzaTag
790 _ | tagName stanzaTag == "{jabber:client}message" -> grokMessage "jabber:client" stanzaTag
791 _ -> return $ Just Unrecognized
792
793mkname :: Text -> Text -> XML.Name
794mkname namespace name = (Name name (Just namespace) Nothing)
795
796makeMessage :: Text -> Text -> Text -> Text -> IO Stanza
797makeMessage namespace from to bod =
798 stanzaFromList typ
799 $ [ EventBeginElement (mkname namespace "message")
800 [ attr "from" from
801 , attr "to" to
802 ]
803 , EventBeginElement (mkname namespace "body") []
804 , EventContent (ContentText bod)
805 , EventEndElement (mkname namespace "body")
806 , EventEndElement (mkname namespace "message") ]
807 where
808 typ = Message { msgThread = Nothing
809 , msgLangMap = [("", lsm)]
810 }
811 lsm = LangSpecificMessage
812 { msgBody = Just bod
813 , msgSubject = Nothing }
814
815makeInformSubscription :: Text -> Text -> Text -> Bool -> IO Stanza
816makeInformSubscription namespace from to approved =
817 stanzaFromList (PresenceInformSubscription approved)
818 $ [ EventBeginElement (mkname namespace "presence")
819 [ attr "from" from
820 , attr "to" to
821 , attr "type" $ if approved then "subscribed"
822 else "unsubscribed" ]
823 , EventEndElement (mkname namespace "presence")]
824
825makePresenceStanza :: Text -> Maybe Text -> JabberShow -> IO Stanza
826makePresenceStanza namespace mjid pstat = do
827 stanzaFromList PresenceStatus { presenceShow = pstat
828 , presencePriority = Nothing
829 , presenceStatus = []
830 , presenceWhiteList = []
831 }
832 $ [ EventBeginElement (mkname namespace "presence")
833 (setFrom $ typ pstat) ]
834 ++ (shw pstat >>= jabberShow) ++
835 [ EventEndElement (mkname namespace "presence")]
836 where
837 setFrom = maybe id
838 (\jid -> (attr "from" jid :) )
839 mjid
840 typ Offline = [attr "type" "unavailable"]
841 typ _ = []
842 shw ExtendedAway = ["xa"]
843 shw Chatty = ["chat"]
844 shw Away = ["away"]
845 shw DoNotDisturb = ["dnd"]
846 shw _ = []
847 jabberShow stat =
848 [ EventBeginElement "{jabber:client}show" []
849 , EventContent (ContentText stat)
850 , EventEndElement "{jabber:client}show" ]
851
852makeRosterUpdate :: Text -> Text -> [(Name, Text)] -> IO Stanza
853makeRosterUpdate tojid contact as = do
854 let attrs = map (uncurry attr) as
855 stanzaFromList Unrecognized
856 [ EventBeginElement "{jabber:client}iq"
857 [ attr "to" tojid
858 , attr "id" "someid"
859 , attr "type" "set"
860 ]
861 , EventBeginElement "{jabber:iq:roster}query" []
862 , EventBeginElement "{jabber:iq:roster}item" (attr "jid" contact : attrs)
863 , EventEndElement "{jabber:iq:roster}item"
864 , EventEndElement "{jabber:iq:roster}query"
865 , EventEndElement "{jabber:client}iq"
866 ]
867
868makePong :: Text -> Maybe Text -> Text -> Text -> [XML.Event]
869makePong namespace mid to from =
870 -- Note: similar to session reply
871 [ EventBeginElement (mkname namespace "iq")
872 $(case mid of
873 Just c -> (("id",[ContentText c]):)
874 _ -> id)
875 [ attr "type" "result"
876 , attr "to" to
877 , attr "from" from
878 ]
879 , EventEndElement (mkname namespace "iq")
880 ]
881
882
883xmppInbound :: Server ConnectionKey SockAddr ReleaseKey XML.Event
884 -> XMPPServerParameters
885 -> ConnectionKey
886 -> SockAddr
887 -> FlagCommand -- ^ action to check whether the connection needs a ping
888 -> TChan Stanza -- ^ channel to announce incomming stanzas on
889 -> TChan Stanza -- ^ channel used to send stanzas
890 -> TMVar () -- ^ mvar that is filled when the connection quits
891 -> Sink XML.Event IO ()
892xmppInbound sv xmpp k laddr pingflag stanzas output donevar = doNestingXML $ do
893 let (namespace,tellmyname,tellyourname) = case k of
894 ClientKey {} -> ( "jabber:client"
895 , xmppTellMyNameToClient xmpp
896 , xmppTellClientHisName xmpp k
897 )
898 PeerKey {} -> ( "jabber:server"
899 , xmppTellMyNameToPeer xmpp laddr
900 , xmppTellPeerHisName xmpp k
901 )
902 me <- liftIO tellmyname
903 withXML $ \begindoc -> do
904 when (begindoc==EventBeginDocument) $ do
905 whenJust nextElement $ \xml -> do
906 withJust (elementAttrs "stream" xml) $ \stream_attrs -> do
907 fix $ \loop -> do
908 -- liftIO . wlog $ "waiting for stanza."
909 (chan,clsrs) <- liftIO . atomically $
910 liftM2 (,) newLockedChan (newTVar (Just []))
911 whenJust nextElement $ \stanzaTag -> do
912 stanza_lvl <- nesting
913 liftIO . atomically $ do
914 writeLChan chan stanzaTag
915 modifyTVar' clsrs (fmap (closerFor stanzaTag:))
916 copyToChannel id chan clsrs =$= do
917 let mid = lookupAttrib "id" (tagAttrs stanzaTag)
918 mfrom = lookupAttrib "from" (tagAttrs stanzaTag)
919 mto = lookupAttrib "to" (tagAttrs stanzaTag)
920 dispatch <- grokStanza namespace stanzaTag
921 let unrecog = do
922 let stype = Unrecognized
923 s <- liftIO . atomically $ do
924 return Stanza
925 { stanzaType = stype
926 , stanzaId = mid
927 , stanzaTo = mto
928 , stanzaFrom = mfrom
929 , stanzaChan = chan
930 , stanzaClosers = clsrs
931 , stanzaInterrupt = donevar
932 , stanzaOrigin = NetworkOrigin k output
933 }
934 ioWriteChan stanzas s
935 you <- liftIO tellyourname
936 flip (maybe $ unrecog) dispatch $ \dispatch ->
937 case dispatch of
938 -- Checking that the to-address matches this server.
939 -- Otherwise it could be a client-to-client ping or a
940 -- client-to-server for some other server.
941 -- For now, assuming its for the immediate connection.
942 Ping | mto==Just me || mto==Nothing -> do
943 let pongto = maybe you id mfrom
944 pongfrom = maybe me id mto
945 pong = makePong namespace mid pongto pongfrom
946 sendReply donevar Pong pong output
947#ifdef PINGNOISE
948 -- TODO: Remove this, it is only to generate a debug print
949 ioWriteChan stanzas Stanza
950 { stanzaType = Ping
951 , stanzaId = mid
952 , stanzaTo = mto
953 , stanzaFrom = mfrom
954 , stanzaChan = chan
955 , stanzaClosers = clsrs
956 , stanzaInterrupt = donevar
957 , stanzaOrigin = NetworkOrigin k output
958 }
959#endif
960 stype -> ioWriteChan stanzas Stanza
961 { stanzaType = stype
962 , stanzaId = mid
963 , stanzaTo = mto
964 , stanzaFrom = mfrom
965 , stanzaChan = chan
966 , stanzaClosers = clsrs
967 , stanzaInterrupt = donevar
968 , stanzaOrigin = NetworkOrigin k output
969 }
970 awaitCloser stanza_lvl
971 liftIO . atomically $ writeTVar clsrs Nothing
972 loop
973
974
975while :: IO Bool -> IO a -> IO [a]
976while cond body = do
977 b <- cond
978 if b then do x <- body
979 xs <- while cond body
980 return (x:xs)
981 else return []
982
983readUntilNothing :: TChan (Maybe x) -> IO [x]
984readUntilNothing ch = do
985 x <- atomically $ readTChan ch
986 maybe (return [])
987 (\x -> do
988 xs <- readUntilNothing ch
989 return (x:xs))
990 x
991
992
993streamFeatures :: Text -> [XML.Event]
994streamFeatures "jabber:client" =
995 [ EventBeginElement (streamP "features") []
996 , EventBeginElement "{urn:ietf:params:xml:ns:xmpp-bind}bind" []
997 , EventEndElement "{urn:ietf:params:xml:ns:xmpp-bind}bind"
998
999 {-
1000 -- , " <session xmlns='urn:ietf:params:xml:ns:xmpp-session'/>"
1001 , " <mechanisms xmlns='urn:ietf:params:xml:ns:xmpp-sasl'>"
1002 -- , " <mechanism>DIGEST-MD5</mechanism>"
1003 , " <mechanism>PLAIN</mechanism>"
1004 , " </mechanisms> "
1005 -}
1006
1007 , EventEndElement (streamP "features")
1008 ]
1009streamFeatures "jabber:server" =
1010 []
1011
1012
1013greet' :: Text -> Text -> [XML.Event]
1014greet' namespace host = EventBeginDocument : greet'' namespace host
1015
1016greet'' :: Text -> Text -> [Event]
1017greet'' namespace host =
1018 [ EventBeginElement (streamP "stream")
1019 [("from",[ContentText host])
1020 ,("id",[ContentText "someid"])
1021 ,("xmlns",[ContentText namespace])
1022 ,("xmlns:stream",[ContentText "http://etherx.jabber.org/streams"])
1023 ,("version",[ContentText "1.0"])
1024 ]
1025 ] ++ streamFeatures namespace
1026
1027consid :: Maybe Text -> [(Name, [Content])] -> [(Name, [Content])]
1028consid Nothing = id
1029consid (Just sid) = (("id",[ContentText sid]):)
1030
1031
1032data XMPPState
1033 = PingSlot
1034 deriving (Eq,Ord)
1035
1036makePing :: Text -> Maybe Text -> Text -> Text -> [XML.Event]
1037makePing namespace mid to from =
1038 [ EventBeginElement (mkname namespace "iq")
1039 $ (case mid of
1040 Just c -> (("id",[ContentText c]):)
1041 _ -> id )
1042 [ ("type",[ContentText "get"])
1043 , attr "to" to
1044 , attr "from" from
1045 ]
1046 , EventBeginElement "{urn:xmpp:ping}ping" []
1047 , EventEndElement "{urn:xmpp:ping}ping"
1048 , EventEndElement $ mkname namespace "iq"]
1049
1050iq_bind_reply :: Maybe Text -> Text -> [XML.Event]
1051iq_bind_reply mid jid =
1052 [ EventBeginElement "{jabber:client}iq" (consid mid [("type",[ContentText "result"])])
1053 , EventBeginElement "{urn:ietf:params:xml:ns:xmpp-bind}bind"
1054 [("xmlns",[ContentText "urn:ietf:params:xml:ns:xmpp-bind"])]
1055 , EventBeginElement "{urn:ietf:params:xml:ns:xmpp-bind}jid" []
1056 , EventContent (ContentText jid)
1057 , EventEndElement "{urn:ietf:params:xml:ns:xmpp-bind}jid"
1058 , EventEndElement "{urn:ietf:params:xml:ns:xmpp-bind}bind"
1059 , EventEndElement "{jabber:client}iq"
1060
1061 {-
1062 -- query for client version
1063 , EventBeginElement "{jabber:client}iq"
1064 [ attr "to" jid
1065 , attr "from" hostname
1066 , attr "type" "get"
1067 , attr "id" "version"]
1068 , EventBeginElement "{jabber:iq:version}query" []
1069 , EventEndElement "{jabber:iq:version}query"
1070 , EventEndElement "{jabber:client}iq"
1071 -}
1072 ]
1073
1074iq_session_reply :: Maybe Text -> Text -> [XML.Event]
1075iq_session_reply mid host =
1076 -- Note: similar to Pong
1077 [ EventBeginElement "{jabber:client}iq"
1078 (consid mid [("from",[ContentText host])
1079 ,("type",[ContentText "result"])
1080 ])
1081 , EventEndElement "{jabber:client}iq"
1082 ]
1083
1084iq_service_unavailable :: Maybe Text -> Text -> XML.Name -> [XML.Event]
1085iq_service_unavailable mid host {- mjid -} req =
1086 [ EventBeginElement "{jabber:client}iq"
1087 (consid mid [attr "type" "error"
1088 ,attr "from" host])
1089 , EventBeginElement req []
1090 , EventEndElement req
1091 , EventBeginElement "{jabber:client}error"
1092 [ attr "type" "cancel"
1093 , attr "code" "503" ]
1094 , EventBeginElement "{urn:ietf:params:xml:ns:xmpp-stanzas}service-unavailable" []
1095 , EventEndElement "{urn:ietf:params:xml:ns:xmpp-stanzas}service-unavailable"
1096 , EventEndElement "{jabber:client}error"
1097 , EventEndElement "{jabber:client}iq"
1098 ]
1099
1100
1101wrapStanzaList :: [XML.Event] -> STM [Either (StanzaWrap XML.Event) XML.Event]
1102wrapStanzaList xs = do
1103 wrap <- do
1104 clsrs <- newTVar Nothing
1105 donev <- newTMVar ()
1106 return $ \ x ->
1107 Stanza { stanzaType = Unrecognized
1108 , stanzaId = mid
1109 , stanzaTo = mto
1110 , stanzaFrom = mfrom
1111 , stanzaClosers = clsrs
1112 , stanzaInterrupt = donev
1113 , stanzaOrigin = LocalPeer
1114 , stanzaChan = x
1115 }
1116 return $ map (Left . wrap) (take 1 xs) ++ map Right (drop 1 xs)
1117 where
1118 m = listToMaybe xs
1119 mto = m >>= lookupAttrib "to" . tagAttrs
1120 mfrom = m >>= lookupAttrib "from" . tagAttrs
1121 mid = m >>= lookupAttrib "id" . tagAttrs
1122
1123wrapStanzaConduit :: Monad m => StanzaWrap a -> ConduitM Event (Either (StanzaWrap Event) Event) m ()
1124wrapStanzaConduit stanza = do
1125 mfirst <- await
1126 flip (maybe $ return ()) mfirst $ \first -> do
1127 yield . Left $ stanza { stanzaChan = first }
1128 awaitForever $ yield . Right
1129
1130
1131
1132{-
1133greet namespace =
1134 [ EventBeginDocument
1135 , EventBeginElement (streamP "stream")
1136 [ attr "xmlns" namespace
1137 , attr "version" "1.0"
1138 ]
1139 ]
1140-}
1141
1142goodbye :: [XML.Event]
1143goodbye =
1144 [ EventEndElement (streamP "stream")
1145 , EventEndDocument
1146 ]
1147
1148simulateChatError :: StanzaError -> Maybe Text -> [Event]
1149simulateChatError err mfrom =
1150 [ EventBeginElement "{jabber:client}message"
1151 ((maybe id (\t->(attr "from" t:)) mfrom)
1152 [attr "type" "normal" ])
1153 , EventBeginElement "{jabber:client}body" []
1154 , EventContent $ ContentText ("/me " <> errorText err)
1155 , EventEndElement "{jabber:client}body"
1156 , EventBeginElement "{http://jabber.org/protocol/xhtml-im}html" []
1157 , EventBeginElement "{http://www.w3.org/1999/xhtml}body" []
1158 , EventBeginElement "{http://www.w3.org/1999/xhtml}p"
1159 [ attr "style" "font-weight:bold; color:red"
1160 ]
1161 , EventContent $ ContentText ("/me " <> errorText err)
1162 , EventEndElement "{http://www.w3.org/1999/xhtml}p"
1163 , EventEndElement "{http://www.w3.org/1999/xhtml}body"
1164 , EventEndElement "{http://jabber.org/protocol/xhtml-im}html"
1165 , EventEndElement "{jabber:client}message"
1166 ]
1167
1168
1169presenceSolicitation :: Text -> Text -> IO Stanza
1170presenceSolicitation = presenceStanza (PresenceRequestSubscription True) "subscribe"
1171
1172presenceProbe :: Text -> Text -> IO Stanza
1173presenceProbe = presenceStanza PresenceRequestStatus "probe"
1174
1175presenceStanza :: StanzaType -> Text -> Text -> Text -> IO Stanza
1176presenceStanza stanza_type type_attr me jid =
1177 stanzaFromList stanza_type
1178 [ EventBeginElement "{jabber:server}presence"
1179 [ attr "to" jid
1180 , attr "from" me
1181 , attr "type" type_attr
1182 ]
1183 , EventEndElement "{jabber:server}presence" ]
1184
1185slotsToSource ::
1186 Slotted.UpdateStream XMPPState (Either (StanzaWrap XML.Event) XML.Event)
1187 -> TVar Int
1188 -> TVar (Maybe (StanzaWrap XML.Event))
1189 -> TVar Bool
1190 -> TMVar ()
1191 -> Source IO (Flush XML.Event)
1192slotsToSource slots nesting lastStanza needsFlush rdone =
1193 fix $ \slot_src -> join . lift . atomically $ foldr1 orElse
1194 [Slotted.pull slots >>= \x -> do
1195 x <- case x of
1196 Left wrapped -> do
1197 writeTVar nesting 1
1198 writeTVar lastStanza (Just wrapped)
1199 return $ stanzaChan wrapped
1200 Right x -> do
1201 when (isEventBeginElement x)
1202 $ modifyTVar' nesting (+1)
1203 when (isEventEndElement x) $ do
1204 n <- readTVar nesting
1205 when (n==1) $ writeTVar lastStanza Nothing
1206 modifyTVar' nesting (subtract 1)
1207 return x
1208 writeTVar needsFlush True
1209 return $ do
1210 -- liftIO $ wlog $ "yielding Chunk: " ++ show x
1211 yield (Chunk x)
1212 slot_src
1213 ,do Slotted.isEmpty slots >>= check
1214 readTVar needsFlush >>= check
1215 writeTVar needsFlush False
1216 return $ do
1217 -- liftIO $ wlog "yielding Flush"
1218 yield Flush
1219 slot_src
1220 ,readTMVar rdone >> return (return ())
1221 ]
1222
1223forkConnection :: Server ConnectionKey SockAddr ReleaseKey XML.Event
1224 -> XMPPServerParameters
1225 -> ConnectionKey
1226 -> SockAddr
1227 -> FlagCommand
1228 -> Source IO XML.Event
1229 -> Sink (Flush XML.Event) IO ()
1230 -> TChan Stanza
1231 -> IO (TChan Stanza)
1232forkConnection sv xmpp k laddr pingflag src snk stanzas = do
1233 let (namespace,tellmyname) = case k of
1234 ClientKey {} -> ("jabber:client", xmppTellMyNameToClient xmpp)
1235 PeerKey {} -> ("jabber:server",xmppTellMyNameToPeer xmpp laddr)
1236 me <- tellmyname
1237 rdone <- atomically newEmptyTMVar
1238 let isStarter (Left _) = True
1239 isStarter (Right e) | isEventBeginElement e = True
1240 isStarter _ = False
1241 isStopper (Left _) = False
1242 isStopper (Right e) | isEventEndElement e = True
1243 isStopper _ = False
1244 slots <- atomically $ Slotted.new isStarter isStopper
1245 needsFlush <- atomically $ newTVar False
1246 lastStanza <- atomically $ newTVar Nothing
1247 nesting <- atomically $ newTVar 0
1248 let _ = slots :: Slotted.UpdateStream XMPPState (Either (StanzaWrap XML.Event) XML.Event)
1249 let greet_src = do
1250 CL.sourceList (greet' namespace me) =$= CL.map Chunk
1251 yield Flush
1252 slot_src = slotsToSource slots nesting lastStanza needsFlush rdone
1253 forkIO $ do myThreadId >>= flip labelThread ("post-queue."++show k)
1254 (greet_src >> slot_src) $$ snk
1255 last <- atomically $ readTVar lastStanza
1256 es <- while (atomically . fmap not $ Slotted.isEmpty slots)
1257 (atomically . Slotted.pull $ slots)
1258 let es' = mapMaybe metadata es
1259 metadata (Left s) = Just s
1260 metadata _ = Nothing
1261 -- TODO: Issuing RecipientUnavailable for all errors is a presence leak
1262 -- and protocol violation
1263 -- TODO: IDMangler can be used for better targetted error delivery.
1264 let fail stanza = do
1265 wlog $ "failed delivery: " ++ show (stanzaId stanza)
1266 quitVar <- atomically newEmptyTMVar
1267 reply <- makeErrorStanza stanza
1268 tag <- stanzaFirstTag stanza
1269 -- sendReply quitVar (Error RecipientUnavailable tag) reply replyto
1270 replystanza <- stanzaFromList (Error RecipientUnavailable tag) reply
1271 xmppDeliverMessage xmpp (wlog $ "discarded error delivery fail") replystanza
1272 notError s = case stanzaType s of
1273 Error {} -> False
1274 _ -> True
1275 -- TODO: Probably some stanzas should be queued or saved for re-connect.
1276 mapM_ fail $ filter notError (maybeToList last ++ es')
1277 wlog $ "end post-queue fork: " ++ show k
1278
1279 output <- atomically newTChan
1280 hacks <- atomically $ newTVar Map.empty
1281 msgids <- atomically $ newTVar []
1282 forkIO $ do
1283 -- mapM_ (atomically . Slotted.push slots Nothing) greetPeer
1284 myThreadId >>= flip labelThread ("pre-queue."++show k)
1285 verbosity <- xmppVerbosity xmpp
1286 fix $ \loop -> do
1287 what <- atomically $ foldr1 orElse
1288 [readTChan output >>= \stanza -> return $ do
1289 let notping f
1290 | (verbosity==1) = case stanzaType stanza of Pong -> return ()
1291 _ -> f
1292 | (verbosity>=2) = f
1293 | otherwise = return ()
1294 -- isempty <- atomically $ isEmptyTChan (stanzaChan stanza)
1295 -- kwlog $ "queuing: "++show (isempty, stanzaId stanza)
1296 notping $ do
1297 dup <- cloneStanza stanza
1298 let typ = Strict8.pack $ c ++ "<-"++(concat . take 1 . words $ show (stanzaType dup))++" "
1299 c = case k of
1300 ClientKey {} -> "C"
1301 PeerKey {} -> "P"
1302 wlog ""
1303 stanzaToConduit dup $$ prettyPrint typ
1304 -- wlog $ "hacks: "++show (stanzaId stanza)
1305 case stanzaType stanza of
1306 InternalEnableHack hack -> do
1307 -- wlog $ "enable hack: " ++ show hack
1308 atomically $ modifyTVar' hacks (Map.insert hack ())
1309 InternalCacheId x -> do
1310 -- wlog $ "cache id thread: " ++ show x
1311 atomically $ modifyTVar' msgids (take 3 . (x:))
1312 _ -> return ()
1313 stanzaToConduit stanza =$= wrapStanzaConduit stanza
1314 $$ awaitForever
1315 -- TODO: PresenceStatus stanzas should be pushed to appropriate slots
1316 $ liftIO . atomically . Slotted.push slots Nothing
1317 case stanzaType stanza of
1318 Error err tag | tagName tag=="{jabber:client}message" -> do
1319 wlog $ "handling Error hacks"
1320 b <- atomically $ do m <- readTVar hacks
1321 cached <- readTVar msgids
1322 flip (maybe $ return False) (stanzaId stanza) $ \id' -> do
1323 return $ Map.member SimulatedChatErrors m
1324 && elem id' cached
1325 ids <- atomically $ readTVar msgids
1326 wlog $ "ids = " ++ show (b,stanzaId stanza, ids)
1327 when b $ do
1328 let sim = simulateChatError err (stanzaFrom stanza)
1329 wlog $ "sending simulated chat for error message."
1330 CL.sourceList sim =$= wrapStanzaConduit stanza -- not quite right, but whatever
1331 $$ awaitForever
1332 $ liftIO . atomically . Slotted.push slots Nothing
1333 Error e _ -> do
1334 wlog $ "no hacks for error: " ++ show e
1335 _ -> return ()
1336 loop
1337 ,do pingflag >>= check
1338 return $ do
1339 to <- xmppTellPeerHisName xmpp k -- addrToText (callBackAddress k)
1340 let from = me -- Look it up from Server object
1341 -- or pass it with Connection event.
1342 mid = Just "ping"
1343 ping0 = makePing namespace mid to from
1344 ping <- atomically $ wrapStanzaList ping0
1345 mapM_ (atomically . Slotted.push slots (Just $ PingSlot))
1346 ping
1347#ifdef PINGNOISE
1348 wlog ""
1349 CL.sourceList ping0 $$ prettyPrint $ case k of
1350 ClientKey {} -> "C<-Ping"
1351 PeerKey {} -> "P<-Ping "
1352#endif
1353 loop
1354 ,readTMVar rdone >> return (return ())
1355 ]
1356 what
1357 wlog $ "end pre-queue fork: " ++ show k
1358 forkIO $ do
1359 myThreadId >>= flip labelThread ("reader."++show k)
1360 -- src $$ awaitForever (lift . putStrLn . takeWhile (/=' ') . show)
1361 src $$ xmppInbound sv xmpp k laddr pingflag stanzas output rdone
1362 atomically $ putTMVar rdone ()
1363 wlog $ "end reader fork: " ++ show k
1364 return output
1365
1366{-
1367data Peer = Peer
1368 { peerWanted :: TVar Bool -- ^ False when this peer is on a you-call-me basis
1369 , peerState :: TVar PeerState
1370 }
1371data PeerState
1372 = PeerPendingConnect UTCTime
1373 | PeerPendingAccept UTCTime
1374 | PeerConnected (TChan Stanza)
1375-}
1376
1377peerKey :: SocketLike sock => sock -> IO (ConnectionKey,SockAddr)
1378peerKey sock = do
1379 addr <- getSocketName sock
1380 peer <-
1381 sIsConnected sock >>= \c ->
1382 if c then getPeerName sock -- addr is normally socketName
1383 else return addr -- Weird hack: addr is would-be peer name
1384 laddr <- getSocketName sock
1385 return $ (PeerKey (peer `withPort` fromIntegral peerport),laddr)
1386
1387clientKey :: SocketLike sock => sock -> IO (ConnectionKey,SockAddr)
1388clientKey sock = do
1389 addr <- getSocketName sock
1390 paddr <- getPeerName sock
1391 return $ (ClientKey addr,paddr)
1392
1393xmlifyRosterItems :: Monad m => Set Text -> Text -> Set Text -> ConduitM i Event m ()
1394xmlifyRosterItems solicited stype set = mapM_ item (Set.toList set)
1395 where
1396 item jid = do yield $ EventBeginElement "{jabber:iq:roster}item"
1397 ([ attr "jid" jid
1398 , attr "subscription" stype
1399 ]++if Set.member jid solicited
1400 then [attr "ask" "subscribe"]
1401 else [] )
1402 yield $ EventEndElement "{jabber:iq:roster}item"
1403
1404sendRoster ::
1405 StanzaWrap a
1406 -> XMPPServerParameters
1407 -> TChan Stanza
1408 -> IO ()
1409sendRoster query xmpp replyto = do
1410 let k = case stanzaOrigin query of
1411 NetworkOrigin k _ -> Just k
1412 LocalPeer -> Nothing -- local peer requested roster?
1413 flip (maybe $ return ()) k $ \k -> do
1414 hostname <- xmppTellMyNameToClient xmpp
1415 let getlist f = do
1416 bs <- f xmpp k
1417 return (Set.fromList bs) -- js)
1418 buddies <- getlist xmppRosterBuddies
1419 subscribers <- getlist xmppRosterSubscribers
1420 solicited <- getlist xmppRosterSolicited
1421 subnone0 <- getlist xmppRosterOthers
1422 jid <- case k of
1423 ClientKey {} -> xmppTellClientHisName xmpp k -- LookupClientJID xmpp k
1424 PeerKey {} -> xmppTellClientNameOfPeer xmpp k (Set.toList buddies)
1425 let subnone = Set.union solicited subnone0 \\ Set.union buddies subscribers
1426 let subto = buddies \\ subscribers
1427 let subfrom = subscribers \\ buddies
1428 let subboth = Set.intersection buddies subscribers
1429 let roster = do
1430 yield $ EventBeginElement "{jabber:client}iq"
1431 (consid (stanzaId query)
1432 [ attr "to" jid
1433 , attr "type" "result" ])
1434 yield $ EventBeginElement "{jabber:iq:roster}query" [] -- todo: ver?
1435 xmlifyRosterItems solicited "to" subto
1436 xmlifyRosterItems solicited "from" subfrom
1437 xmlifyRosterItems solicited "both" subboth
1438 xmlifyRosterItems solicited "none" subnone
1439 yield $ EventEndElement "{jabber:iq:roster}query"
1440 yield $ EventEndElement "{jabber:client}iq"
1441
1442 conduitToStanza Roster
1443 (stanzaId query)
1444 Nothing
1445 (Just jid)
1446 roster >>= ioWriteChan replyto
1447 {-
1448 let debugpresence =
1449 [ EventBeginElement "{jabber:client}presence"
1450 [ attr "from" "guest@oxio4inifatsetlx.onion"
1451 , attr "to" jid]
1452 , EventEndElement "{jabber:client}presence"
1453 ]
1454 quitvar <- atomically newEmptyTMVar
1455 sendReply quitvar Unrecognized debugpresence replyto
1456 -}
1457
1458
1459socketFromKey :: Server ConnectionKey SockAddr ReleaseKey XML.Event -> ConnectionKey -> IO SockAddr
1460socketFromKey sv k = do
1461 map <- atomically $ readTVar (conmap sv)
1462 let mcd = Map.lookup k map
1463 case mcd of
1464 Nothing -> case k of
1465 ClientKey addr -> return addr
1466 PeerKey addr -> return addr
1467 -- XXX: ? wrong address
1468 -- Shouldnt happen anyway.
1469 Just cd -> return $ cdata cd
1470
1471class StanzaFirstTag a where
1472 stanzaFirstTag :: StanzaWrap a -> IO XML.Event
1473instance StanzaFirstTag (TChan XML.Event) where
1474 stanzaFirstTag stanza = do
1475 e <-atomically $ peekTChan (stanzaChan stanza)
1476 return e
1477instance StanzaFirstTag (LockedChan XML.Event) where
1478 stanzaFirstTag stanza = do
1479 e <-atomically $ peekLChan (stanzaChan stanza)
1480 return e
1481instance StanzaFirstTag XML.Event where
1482 stanzaFirstTag stanza = return (stanzaChan stanza)
1483
1484data StanzaError
1485 = BadRequest
1486 | Conflict
1487 | FeatureNotImplemented
1488 | Forbidden
1489 | Gone
1490 | InternalServerError
1491 | ItemNotFound
1492 | JidMalformed
1493 | NotAcceptable
1494 | NotAllowed
1495 | NotAuthorized
1496 | PaymentRequired
1497 | RecipientUnavailable
1498 | Redirect
1499 | RegistrationRequired
1500 | RemoteServerNotFound
1501 | RemoteServerTimeout
1502 | ResourceConstraint
1503 | ServiceUnavailable
1504 | SubscriptionRequired
1505 | UndefinedCondition
1506 | UnexpectedRequest
1507 deriving (Show,Enum,Ord,Eq)
1508
1509xep0086 ::
1510 forall t t1. (Num t1, IsString t) => StanzaError -> (t, t1)
1511xep0086 e =
1512 case e of
1513 BadRequest -> ("modify", 400)
1514 Conflict -> ("cancel", 409)
1515 FeatureNotImplemented -> ("cancel", 501)
1516 Forbidden -> ("auth", 403)
1517 Gone -> ("modify", 302)
1518 InternalServerError -> ("wait", 500)
1519 ItemNotFound -> ("cancel", 404)
1520 JidMalformed -> ("modify", 400)
1521 NotAcceptable -> ("modify", 406)
1522 NotAllowed -> ("cancel", 405)
1523 NotAuthorized -> ("auth", 401)
1524 PaymentRequired -> ("auth", 402)
1525 RecipientUnavailable -> ("wait", 404)
1526 Redirect -> ("modify", 302)
1527 RegistrationRequired -> ("auth", 407)
1528 RemoteServerNotFound -> ("cancel", 404)
1529 RemoteServerTimeout -> ("wait", 504)
1530 ResourceConstraint -> ("wait", 500)
1531 ServiceUnavailable -> ("cancel", 503)
1532 SubscriptionRequired -> ("auth", 407)
1533 UndefinedCondition -> ("", 500)
1534 UnexpectedRequest -> ("wait", 400)
1535
1536errorText :: StanzaError -> Text
1537errorText e =
1538 case e of
1539 BadRequest -> "Bad request"
1540 Conflict -> "Conflict"
1541 FeatureNotImplemented -> "This feature is not implemented"
1542 Forbidden -> "Forbidden"
1543 Gone -> "Recipient can no longer be contacted"
1544 InternalServerError -> "Internal server error"
1545 ItemNotFound -> "Item not found"
1546 JidMalformed -> "JID Malformed"
1547 NotAcceptable -> "Message was rejected"
1548 NotAllowed -> "Not allowed"
1549 NotAuthorized -> "Not authorized"
1550 PaymentRequired -> "Payment is required"
1551 RecipientUnavailable -> "Recipient is unavailable"
1552 Redirect -> "Redirect"
1553 RegistrationRequired -> "Registration required"
1554 RemoteServerNotFound -> "Recipient's server not found"
1555 RemoteServerTimeout -> "Remote server timeout"
1556 ResourceConstraint -> "The server is low on resources"
1557 ServiceUnavailable -> "The service is unavailable"
1558 SubscriptionRequired -> "A subscription is required"
1559 UndefinedCondition -> "Undefined condition"
1560 UnexpectedRequest -> "Unexpected request"
1561
1562eventContent :: Maybe [Content] -> Text
1563eventContent cs = maybe "" (foldr1 (<>) . map content1) cs
1564 where content1 (ContentText t) = t
1565 content1 (ContentEntity t) = t
1566
1567errorTagLocalName :: forall a. Show a => a -> Text
1568errorTagLocalName e = Text.pack . drop 1 $ do
1569 c <- show e
1570 if 'A' <= c && c <= 'Z'
1571 then [ '-', chr( ord c - ord 'A' + ord 'a') ]
1572 else return c
1573
1574makeErrorStanza :: StanzaFirstTag a => StanzaWrap a -> IO [XML.Event]
1575makeErrorStanza stanza = do
1576 startTag <- stanzaFirstTag stanza
1577 let n = tagName startTag
1578 endTag = EventEndElement n
1579 amap0 = Map.fromList (tagAttrs startTag)
1580 mto = Map.lookup "to" amap0
1581 mfrom = Map.lookup "from" amap0
1582 mtype = Map.lookup "type" amap0
1583 mid = Map.lookup "id" amap0
1584 amap1 = Map.alter (const mto) "from" amap0
1585 -- amap2 = Map.alter (const $ Just $ [ContentText "blackbird"]) {-mfrom)-} "to" amap1
1586 amap2 = Map.alter (const mfrom) "to" amap1
1587 amap3 = Map.insert "type" [XML.ContentText "error"] amap2
1588 startTag' = EventBeginElement
1589 (tagName startTag)
1590 (Map.toList amap3)
1591 -- err = Gone -- FeatureNotImplemented -- UndefinedCondition -- RecipientUnavailable
1592 err = RecipientUnavailable
1593 errname = n { nameLocalName = "error" }
1594 -- errattrs = [attr "type" "wait"] -- "modify"]
1595 errorAttribs e xs = ys ++ xs -- todo replace instead of append
1596 where (typ,code) = xep0086 e
1597 ys = [attr "type" typ, attr "code" (Text.pack . show $ code)]
1598 errorTagName = Name { nameNamespace = Just "urn:ietf:params:xml:ns:xmpp-stanzas"
1599 , nameLocalName = errorTagLocalName err
1600 , namePrefix = Nothing }
1601 errattrs = errorAttribs err []
1602 let wlogd v s = do
1603 wlog $ "error "++show (lookupAttrib "id" $ tagAttrs startTag)++" " ++ v ++ " = " ++ show s
1604 {-
1605 wlogd "amap0" amap0
1606 wlogd "mto" mto
1607 wlogd "mfrom" mfrom
1608 wlogd "amap3" amap3
1609 -}
1610 if eventContent mtype=="error" then return [] else do
1611 return [ startTag'
1612 , EventBeginElement errname errattrs
1613 , EventBeginElement errorTagName []
1614 , EventEndElement errorTagName
1615 , EventEndElement errname
1616 {-
1617 , EventBeginElement "{jabber:client}body" []
1618 , EventContent (ContentText "what?")
1619 , EventEndElement "{jabber:client}body"
1620 -}
1621 {-
1622 , EventBeginElement "{154ae29f-98f2-4af4-826d-a40c8a188574}dummy" []
1623 , EventEndElement "{154ae29f-98f2-4af4-826d-a40c8a188574}dummy"
1624 -}
1625 , endTag
1626 ]
1627
1628monitor ::
1629 Server ConnectionKey SockAddr ReleaseKey XML.Event
1630 -> ConnectionParameters ConnectionKey SockAddr
1631 -> XMPPServerParameters
1632 -> IO b
1633monitor sv params xmpp = do
1634 chan <- return $ serverEvent sv
1635 stanzas <- atomically newTChan
1636 quitVar <- atomically newEmptyTMVar
1637 fix $ \loop -> do
1638 action <- atomically $ foldr1 orElse
1639 [ readTChan chan >>= \((k,u),e) -> return $ do
1640 case e of
1641 Connection pingflag xsrc xsnk -> do
1642 wlog $ tomsg k "Connection"
1643 outs <- forkConnection sv xmpp k u pingflag xsrc xsnk stanzas
1644 xmppNewConnection xmpp k u outs
1645 ConnectFailure addr -> return () -- wlog $ tomsg k "ConnectFailure"
1646 EOF -> do wlog $ tomsg k "EOF"
1647 xmppEOF xmpp k
1648 HalfConnection In -> do
1649 wlog $ tomsg k "ReadOnly"
1650 control sv (Connect (callBackAddress k) params)
1651 HalfConnection Out -> wlog $ tomsg k "WriteOnly"
1652 RequiresPing -> return () -- wlog $ tomsg k "RequiresPing"
1653 , readTChan stanzas >>= \stanza -> return $ do
1654 {-
1655 dup <- case stanzaType stanza of
1656 -- Must dup anything that is going to be delivered...
1657 Message {} -> do
1658 dup <- cloneStanza stanza -- dupped so we can make debug print
1659 return dup
1660 Error {} -> do
1661 dup <- cloneStanza stanza -- dupped so we can make debug print
1662 return dup
1663 _ -> return stanza
1664 -}
1665 dup <- cloneStanza stanza
1666
1667 forkIO $ do
1668 case stanzaOrigin stanza of
1669 NetworkOrigin k@(ClientKey {}) replyto ->
1670 case stanzaType stanza of
1671 RequestResource wanted -> do
1672 sockaddr <- socketFromKey sv k
1673 rsc <- xmppChooseResourceName xmpp k sockaddr wanted
1674 let reply = iq_bind_reply (stanzaId stanza) rsc
1675 -- sendReply quitVar SetResource reply replyto
1676 hostname <- xmppTellMyNameToClient xmpp
1677 let requestVersion :: Producer IO XML.Event
1678 requestVersion = do
1679 yield $ EventBeginElement "{jabber:client}iq"
1680 [ attr "to" rsc
1681 , attr "from" hostname
1682 , attr "type" "get"
1683 , attr "id" "version"]
1684 yield $ EventBeginElement "{jabber:iq:version}query" []
1685 yield $ EventEndElement "{jabber:iq:version}query"
1686 yield $ EventEndElement "{jabber:client}iq"
1687 {-
1688 -- XXX Debug chat:
1689 yield $ EventBeginElement "{jabber:client}message"
1690 [ attr "from" $ eventContent (Just [ContentText rsc])
1691 , attr "type" "normal" ] -- "blackbird" ]
1692 yield $ EventBeginElement "{jabber:client}body" []
1693 yield $ EventContent $ ContentText ("hello?")
1694 yield $ EventEndElement "{jabber:client}body"
1695 yield $ EventEndElement "{jabber:client}message"
1696 -}
1697 sendReply quitVar SetResource reply replyto
1698 conduitToStanza (UnrecognizedQuery "{jabber:iq:version}query")
1699 Nothing -- id
1700 (Just hostname) -- from
1701 (Just rsc) -- to
1702 requestVersion
1703 >>= ioWriteChan replyto
1704 SessionRequest -> do
1705 me <- xmppTellMyNameToClient xmpp
1706 let reply = iq_session_reply (stanzaId stanza) me
1707 sendReply quitVar Pong reply replyto
1708 RequestRoster -> do
1709 sendRoster stanza xmpp replyto
1710 xmppSubscribeToRoster xmpp k
1711 PresenceStatus {} -> do
1712 xmppInformClientPresence xmpp k stanza
1713 PresenceRequestSubscription {} -> do
1714 let fail = return () -- todo
1715 xmppClientSubscriptionRequest xmpp fail k stanza replyto
1716 PresenceInformSubscription {} -> do
1717 let fail = return () -- todo
1718 xmppClientInformSubscription xmpp fail k stanza
1719 NotifyClientVersion name version -> do
1720 enableClientHacks name version replyto
1721 UnrecognizedQuery query -> do
1722 me <- xmppTellMyNameToClient xmpp
1723 let reply = iq_service_unavailable (stanzaId stanza) me query
1724 sendReply quitVar (Error ServiceUnavailable (head reply)) reply replyto
1725 Message {} -> do
1726 -- wlog $ "LANGMAP "++show (stanzaId stanza, msgLangMap (stanzaType stanza))
1727 maybe (return ()) (flip cacheMessageId replyto) $ do
1728 guard . not . null . mapMaybe (msgBody . snd) $ msgLangMap (stanzaType stanza)
1729 stanzaId stanza
1730 _ -> return ()
1731 NetworkOrigin k@(PeerKey {}) replyto ->
1732 case stanzaType stanza of
1733 PresenceRequestStatus {} -> do
1734 xmppAnswerProbe xmpp k stanza replyto
1735 PresenceStatus {} -> do
1736 xmppInformPeerPresence xmpp k stanza
1737 PresenceRequestSubscription {} -> do
1738 let fail = return () -- todo
1739 xmppPeerSubscriptionRequest xmpp fail k stanza replyto
1740 PresenceInformSubscription {} -> do
1741 let fail = return () -- todo
1742 xmppPeerInformSubscription xmpp fail k stanza
1743 _ -> return ()
1744 _ -> return ()
1745 let deliver replyto = do
1746 -- TODO: Issuing RecipientUnavailable for all errors is a presence leak
1747 -- and protocol violation
1748 let fail = do
1749 wlog $ "Failed delivery id="++show (stanzaId stanza) -- TODO
1750 reply <- makeErrorStanza stanza
1751 tag <- stanzaFirstTag stanza
1752 sendReply quitVar (Error RecipientUnavailable tag) reply replyto
1753 xmppDeliverMessage xmpp fail stanza
1754 -- -- bad idea:
1755 -- let newStream = greet'' "jabber:client" "blackbird"
1756 -- sendReply quitVar Error newStream replyto
1757 case stanzaType stanza of
1758 Message {} -> do
1759 case stanzaOrigin stanza of
1760 LocalPeer {} -> return ()
1761 NetworkOrigin _ replyto -> deliver replyto
1762 Error {} -> do
1763 case stanzaOrigin stanza of
1764 LocalPeer {} -> return ()
1765 NetworkOrigin k replyto -> do
1766 -- wlog $ "delivering error: " ++show (stanzaId stanza)
1767 -- wlog $ " from: " ++ show k
1768 deliver replyto
1769 _ -> return ()
1770 -- We need to clone in the case the stanza is passed on as for Message.
1771 verbosity <- xmppVerbosity xmpp
1772 let notping f | (verbosity==1) = case stanzaType stanza of Pong -> return ()
1773 _ -> f
1774 | (verbosity>=2) = f
1775 | otherwise = return ()
1776 notping $ do
1777 let typ = Strict8.pack $ c ++ "->"++(concat . take 1 . words $ show (stanzaType stanza))++" "
1778 c = case stanzaOrigin stanza of
1779 LocalPeer -> "*"
1780 NetworkOrigin (ClientKey {}) _ -> "C"
1781 NetworkOrigin (PeerKey {}) _ -> "P"
1782 wlog ""
1783 stanzaToConduit dup $$ prettyPrint typ
1784
1785 ]
1786 action
1787 loop
1788 where
1789 tomsg k str = printf "%12s %s" str (show k)
1790 where
1791 _ = str :: String
1792
1793data XMPPServer
1794 = XMPPServer { _xmpp_sv :: Server ConnectionKey SockAddr ReleaseKey XML.Event
1795 , _xmpp_peer_params :: ConnectionParameters ConnectionKey SockAddr
1796 }
1797
1798grokPeer :: XMPPServer -> ConnectionKey -> (SockAddr, ConnectionParameters ConnectionKey SockAddr, Miliseconds)
1799grokPeer sv (PeerKey addr) = (addr, _xmpp_peer_params sv, 10000)
1800
1801xmppConnections :: XMPPServer -> IO (Connection.Manager TCPStatus Text)
1802xmppConnections sv = tcpManager (grokPeer sv) (Just . Text.pack) resolvPeer (_xmpp_sv sv)
1803 where
1804 resolvPeer :: Text -> IO (Maybe ConnectionKey)
1805 resolvPeer str = fmap PeerKey <$> listToMaybe <$> resolvePeer str
1806
1807xmppServer :: ( MonadResource m
1808 , MonadIO m
1809 ) => XMPPServerParameters -> m XMPPServer
1810xmppServer xmpp = do
1811 sv <- server allocate xmlStream
1812 -- some fuzz helps avoid simultaneity
1813 pingfuzz <- liftIO $ do
1814 gen <- System.Random.getStdGen
1815 let (r,gen') = System.Random.next gen
1816 return $ r `mod` 2000 -- maximum 2 seconds of fuzz
1817 liftIO . wlog $ "pingfuzz = " ++ show pingfuzz
1818 let peer_params = (connectionDefaults peerKey)
1819 { pingInterval = 15000 + pingfuzz
1820 , timeout = 2000
1821 , duplex = False }
1822 client_params = (connectionDefaults clientKey)
1823 { pingInterval = 0
1824 , timeout = 0
1825 }
1826 liftIO $ do
1827 forkIO $ do
1828 myThreadId >>= flip labelThread ("XMPP.monitor")
1829 monitor sv peer_params xmpp
1830 hPutStrLn stderr $ "Starting peer listen"
1831 control sv (Listen peerport peer_params)
1832 hPutStrLn stderr $ "Starting client listen"
1833 control sv (Listen clientport client_params)
1834 return XMPPServer { _xmpp_sv = sv, _xmpp_peer_params = peer_params }
1835
1836#if MIN_VERSION_stm(2,4,0)
1837#else
1838-- |Clone a 'TChan': similar to dupTChan, but the cloned channel starts with the
1839-- same content available as the original channel.
1840--
1841-- Terrible inefficient implementation provided to build against older libraries.
1842cloneTChan :: TChan a -> STM (TChan a)
1843cloneTChan chan = do
1844 contents <- chanContents' chan
1845 chan2 <- dupTChan chan
1846 mapM_ (writeTChan chan) contents
1847 return chan2
1848 where
1849 chanContents' chan = do
1850 b <- isEmptyTChan chan
1851 if b then return [] else do
1852 x <- readTChan chan
1853 xs <- chanContents' chan
1854 return (x:xs)
1855#endif
1856
diff --git a/Presence/monitortty.c b/Presence/monitortty.c
new file mode 100644
index 00000000..7582aa56
--- /dev/null
+++ b/Presence/monitortty.c
@@ -0,0 +1,182 @@
1// monitortty.c
2
3#include <unistd.h>
4#include <pthread.h>
5#include <stdio.h>
6#include <string.h>
7#include <stdint.h>
8#include <errno.h>
9#include <linux/vt.h>
10#include <sys/ioctl.h>
11#include <fcntl.h>
12#include <linux/kd.h>
13#include <stdlib.h>
14
15static char *conspath[] = {
16 "/proc/self/fd/0",
17 "/dev/tty",
18 "/dev/tty0",
19 "/dev/vc/0",
20 "/dev/systty",
21 "/dev/console",
22 NULL
23};
24
25static int
26is_a_console(int fd) {
27 char arg;
28
29 arg = 0;
30 return (isatty (fd)
31 && ioctl(fd, KDGKBTYPE, &arg) == 0
32 && ((arg == KB_101) || (arg == KB_84)));
33}
34
35static int
36open_a_console(const char *fnam) {
37 int fd;
38
39 /*
40 * For ioctl purposes we only need some fd and permissions
41 * do not matter. But setfont:activatemap() does a write.
42 */
43 fd = open(fnam, O_RDWR);
44 if (fd < 0)
45 fd = open(fnam, O_WRONLY);
46 if (fd < 0)
47 fd = open(fnam, O_RDONLY);
48 if (fd < 0)
49 return -1;
50 return fd;
51}
52
53int ttyfd() {
54 // We try several things because opening /dev/console will fail
55 // if someone else used X (which does a chown on /dev/console).
56 int i;
57 int fd;
58 for (i = 0; conspath[i]; i++) {
59 if ((fd = open_a_console(conspath[i])) >= 0) {
60 if (is_a_console(fd)) {
61 printf("using %s\n",conspath[i]);
62 return fd;
63 }
64 close(fd);
65 }
66 }
67 for (fd = 0; fd < 3; fd++)
68 if (is_a_console(fd))
69 return fd;
70 printf("failed to find console fd\n");
71 return -1;
72}
73
74void vt_wait(int tty_fd) {
75 struct vt_event vt;
76 memset(&vt,'\0',sizeof(vt));
77 vt.event = VT_EVENT_SWITCH;
78 int res;
79 // printf("started wait\n");
80 res = ioctl (tty_fd, VT_WAITEVENT, &vt);
81 if (res==-1) {
82 printf("vt_wait error fd=%i\n",tty_fd);
83 perror("vt_wait");
84 // printf("vt_wait: %u - %s\n", errno, errmsg(errno));
85 sleep(1);
86 }
87 // printf("finished wait\n");
88}
89
90int8_t get_active(int tty_fd) {
91 struct vt_stat vtstat;
92 memset(&vtstat,'\0',sizeof(vtstat));
93 if (ioctl(tty_fd, VT_GETSTATE, &vtstat)) {
94 perror ("get_active: VT_GETSTATE");
95 return 7;
96 }
97 return vtstat.v_active;
98}
99
100void chvt(int tty_fd, int n) {
101 if (ioctl(tty_fd, VT_ACTIVATE, n)) {
102 perror ("chvt: VT_ACTIVATE");
103 }
104
105}
106
107pthread_mutex_t mu;
108pthread_t mt;
109int tty = -1;
110
111void *write_vtch(void *pfd) {
112 int fd = (int)(intptr_t)pfd;
113 printf("started VT_WAITEVENT loop fd=%i\n",fd);
114 pthread_mutex_lock(&mu);
115 tty = ttyfd();
116 pthread_mutex_unlock(&mu);
117 int8_t active_tty = get_active(tty);
118 int8_t reported_tty;
119 ssize_t e;
120
121 pthread_setcancelstate(PTHREAD_CANCEL_ENABLE, NULL);
122 for (;;) {
123 // ssize_t write(int fd, const void *buf, size_t count);
124 e = write(fd, &active_tty, 1);
125 if (e<0 ) {
126 if( errno==EAGAIN) continue;
127 break;
128 }
129 else if(e==1) {
130 reported_tty = active_tty;
131 }
132 do {
133 vt_wait(tty);
134 // printf("vt_wait() finished. tty=%d fd=%d\n",tty,fd);
135 active_tty = get_active(tty);
136 } while (active_tty==reported_tty);
137 }
138
139 // TODO:
140 // use VT_GETSTATE
141 // use VT_WAITEVENT
142 printf("stopped VT_WAITEVENT loop\n");
143 tty = -1;
144 pthread_mutex_destroy(&mu);
145 return NULL;
146}
147
148
149// Returns 0 on success.
150int monitorTTY(int fd) {
151 int er = -1, dev = -1;
152 pthread_mutex_init(&mu,NULL);
153 // Ensure we can open a device before we bother forking a thread.
154 dev = ttyfd();
155 if( dev != -1 ) {
156 er = pthread_create (&mt, NULL, write_vtch, (void*)(intptr_t)fd);
157 return er;
158 }
159 else {
160 return -1;
161 }
162}
163
164void closeTTY() {
165 int fd = -1;
166 int active = 7;
167 pthread_mutex_lock(&mu);
168 active = get_active(tty);
169 fd = tty;
170 pthread_mutex_unlock(&mu);
171#ifndef VTHACK
172 pthread_cancel(mt);
173#endif
174 char cmd[40]; cmd[39] = '\0';
175 // Hack to wake up from VT_WAITEVENT ioctl
176#ifdef VTHACK
177 snprintf(cmd,39,"chvt %i;chvt %i",active+1,active);
178 system(cmd);
179 pthread_join(mt,NULL);
180#endif
181 close(fd);
182}
diff --git a/Setup.hs b/Setup.hs
index 9a994af6..d07decd4 100644
--- a/Setup.hs
+++ b/Setup.hs
@@ -1,2 +1,96 @@
1import Control.Monad
2import Data.List
1import Distribution.Simple 3import Distribution.Simple
2main = defaultMain 4import Distribution.Simple.LocalBuildInfo
5import Distribution.Simple.Setup
6import Distribution.Simple.Utils
7import System.Directory
8
9main = defaultMainWithHooks hooks
10
11hooks :: UserHooks
12hooks = simpleUserHooks
13 { buildHook = \pkgDesc localBuildInfo hooks flags -> do
14 let paths = (absoluteInstallDirs pkgDesc localBuildInfo dest)
15 {- libsubdir = "<undef>"
16 , datasubdir = "<undef>"
17 -}
18 dest = maybe NoCopyDest CopyTo $
19 flagToMaybe $ buildDistPref flags
20 buildSystemDConfig localBuildInfo paths
21 buildHook simpleUserHooks pkgDesc localBuildInfo hooks flags
22 , copyHook = \pkgDesc localBuildInfo hooks flags -> do
23 let paths = (absoluteInstallDirs pkgDesc localBuildInfo (fromFlag $ copyDest flags))
24 {- libsubdir = "<undef>"
25 , datasubdir = "<undef>"
26 -}
27 dest = maybe NoCopyDest CopyTo $
28 flagToMaybe $ copyDistPref flags
29 copySystemDConfig localBuildInfo paths flags
30 copyHook simpleUserHooks pkgDesc localBuildInfo hooks flags
31 }
32
33-- Drop a /-terminated prefix from a Filepath. The / is not dropped.
34dropPrefix :: String -> FilePath -> FilePath
35dropPrefix prefix s | prefix `isPrefixOf` s = drop (length prefix - 1) s
36 | otherwise = s
37
38exestart :: FilePath -> InstallDirs FilePath -> String -> String
39exestart buildprefix paths cmd
40 | "ExecStart=" `isPrefixOf` cmd = "ExecStart="++(dropPrefix buildprefix $ bindir paths) ++ "/presence"
41 | otherwise = cmd
42
43buildSystemDConfig :: LocalBuildInfo -> InstallDirs FilePath -> IO ()
44buildSystemDConfig buildInfo paths = do
45 template <- lines <$> readFile "presence.service"
46 let buildprefix = takeWhile (/='/') (buildDir buildInfo) ++ "/"
47 service = map (exestart buildprefix paths) template
48 createDirectoryIfMissing True (buildDir buildInfo)
49 writeFile (buildDir buildInfo ++ "/presence.service") $ unlines service
50
51preferredSystemDPath prefix =
52 case removeSlashes prefix of
53 "" -> "/lib/systemd/system"
54 "usr" -> "/lib/systemd/system"
55 _ -> "/etc/systemd/system"
56
57removeSlashes prefix = reverse $ dropWhile (=='/') $ reverse $ dropWhile (=='/') prefix
58
59-- InstallDirs {prefix = "dest/usr/local"
60-- , bindir = "dest/usr/local/bin"
61-- , libdir = "dest/usr/local/lib/x86_64-linux-ghc-8.0.2/presence-0.0.1-1fqjx0Frxyf1ESoA9cNUiZ"
62-- , libsubdir = "<undef>"
63-- , dynlibdir = "dest/usr/local/lib/x86_64-linux-ghc-8.0.2"
64-- , libexecdir = "dest/usr/local/libexec"
65-- , includedir = "dest/usr/local/lib/x86_64-linux-ghc-8.0.2/presence-0.0.1-1fqjx0Frxyf1ESoA9cNUiZ/include"
66-- , datadir = "dest/usr/local/share/x86_64-linux-ghc-8.0.2/presence-0.0.1"
67-- , datasubdir = "<undef>"
68-- , docdir = "dest/usr/local/share/doc/x86_64-linux-ghc-8.0.2/presence-0.0.1"
69-- , mandir = "dest/usr/local/share/man"
70-- , htmldir = "dest/usr/local/share/doc/x86_64-linux-ghc-8.0.2/presence-0.0.1/html"
71-- , haddockdir = "dest/usr/local/share/doc/x86_64-linux-ghc-8.0.2/presence-0.0.1/html"
72-- , sysconfdir = "dest/usr/local/etc"}
73-- CopyFlags
74-- { copyDest = Flag (CopyTo "dest/")
75-- , copyDistPref = Flag "dist"
76-- , copyVerbosity = Flag Verbose}
77-- realprefix = dest/usr/local
78
79copySystemDConfig :: LocalBuildInfo -> InstallDirs FilePath -> CopyFlags -> IO ()
80copySystemDConfig buildInfo paths flags = do
81 -- print paths
82 -- print flags
83 let verbosity = fromFlag (copyVerbosity flags)
84 built = buildDir buildInfo ++ "/presence.service"
85 realprefix = dropPrefix dest (prefix paths)
86 dest = case fromFlag (copyDest flags) of
87 NoCopyDest -> ""
88 CopyTo p -> p
89 sysddir = dest ++ drop 1 (preferredSystemDPath realprefix)
90 sysdpath = sysddir ++ "/presence.service"
91 -- putStrLn $ "realprefix = " ++ realprefix
92 -- putStrLn $ "no slashes = " ++ removeSlashes realprefix
93 -- putStrLn $ "sysdpath = " ++ sysdpath
94 createDirectoryIfMissing True sysddir
95 installOrdinaryFile verbosity built sysdpath
96
diff --git a/TraversableT.hs b/TraversableT.hs
new file mode 100644
index 00000000..c0e40853
--- /dev/null
+++ b/TraversableT.hs
@@ -0,0 +1,94 @@
1module TraversableT where
2
3import Data.Traversable
4import Control.Monad (join,MonadPlus(..))
5import Control.Monad.Trans.Class (MonadTrans(..))
6import Control.Applicative
7import Data.Foldable (Foldable(foldMap), toList)
8import Data.Maybe (maybeToList)
9
10-- |
11--
12-- /Note:/ this does not yield a monad unless the argument monad is commutative.
13newtype TraversableT t m a = TraversableT { runTraversableT :: m (t a) }
14
15-- | Map between 'TraversableT' computations.
16--
17-- * @'runTraversableT' ('mapTraversableT' f m) = f ('runTraversableT' m)@
18mapTraversableT :: (m (t a) -> n (t b)) -> TraversableT t m a -> TraversableT t n b
19mapTraversableT f m = TraversableT $ f (runTraversableT m)
20
21
22instance (Functor m, Functor t) => Functor (TraversableT t m) where
23 fmap f = mapTraversableT $ fmap $ fmap f
24
25instance (Foldable f, Foldable t) => Foldable (TraversableT t f) where
26 foldMap f (TraversableT a) = foldMap (foldMap f) a
27
28instance (Traversable f, Traversable t) => Traversable (TraversableT t f) where
29 traverse f (TraversableT a) = TraversableT <$> traverse (traverse f) a
30
31instance (Applicative m,Applicative t) => Applicative (TraversableT t m) where
32 pure a = TraversableT $ pure (pure a)
33 f <*> v = TraversableT $ (<*>) <$> runTraversableT f <*> runTraversableT v
34
35instance (Applicative m, Alternative t) => Alternative (TraversableT t m) where
36 empty = TraversableT $ pure empty
37 m <|> n = TraversableT $ (<|>) <$> runTraversableT m <*> runTraversableT n
38
39instance (Monad m, Traversable t, Monad t) => Monad (TraversableT t m) where
40 return = TraversableT . return . return
41 m >>= k = TraversableT $ do
42 a <- runTraversableT m
43 b <- forM a $ runTraversableT . k
44 return (join b)
45 fail s = TraversableT $ return (fail s)
46
47instance (Monad m, Traversable t, MonadPlus t) => MonadPlus (TraversableT t m) where
48 mzero = TraversableT $ return mzero
49 m `mplus` n = TraversableT $ do
50 a <- runTraversableT m
51 b <- runTraversableT n
52 return (a `mplus` b)
53
54instance Applicative t => MonadTrans (TraversableT t) where
55 lift m = TraversableT $ do
56 a <- m
57 return (pure a)
58
59liftT :: Monad m => t a -> TraversableT t m a
60liftT = TraversableT . return
61
62liftMT :: m (t a) -> TraversableT t m a
63liftMT = TraversableT
64
65-- | Lift a @callCC@ operation to the new monad.
66liftCallCC :: Applicative t =>
67 ((( (t a) -> m (t b)) -> m (t a)) -> m (t a)) ->
68 ((a -> TraversableT t m b) -> TraversableT t m a) -> TraversableT t m a
69liftCallCC callCC f = TraversableT $
70 callCC $ \c ->
71 runTraversableT (f (\a -> TraversableT $ c (pure a)))
72
73-- | Lift a @catchError@ operation to the new monad.
74liftCatch :: (m (t a) -> (e -> m (t a)) -> m (t a)) ->
75 TraversableT t m a -> (e -> TraversableT t m a) -> TraversableT t m a
76liftCatch catchError m h = TraversableT $ runTraversableT m
77 `catchError` \e -> runTraversableT (h e)
78
79liftMaybe :: Monad m => Maybe a -> TraversableT [] m a
80liftMaybe = liftT . maybeToList
81
82liftIOMaybe :: IO (Maybe a) -> TraversableT [] IO a
83liftIOMaybe = liftMT . fmap maybeToList
84
85handleT :: ( Monad m
86 , Traversable t ) =>
87 (t a -> TraversableT t m a)
88 -> TraversableT t m a
89 -> TraversableT t m a
90handleT catcher body = TraversableT $ do
91 tx <- runTraversableT body
92 if null (toList tx)
93 then runTraversableT $ catcher tx
94 else return tx
diff --git a/b b/b
new file mode 100755
index 00000000..a116163e
--- /dev/null
+++ b/b
@@ -0,0 +1,16 @@
1#!/bin/bash
2args="-fwarn-unused-imports -rtsopts -DRENDERFLUSH"
3
4root=${0%/*}
5cd "$root"
6
7me=${0##*/}
8me=${me%.*}
9ghc \
10 -hidir build/$me -odir build/$me \
11 -iPresence \
12 $args \
13 -o presence \
14 Presence/monitortty.c \
15 Presence/main \
16 "$@"
diff --git a/bp b/bp
new file mode 100755
index 00000000..8d3335d4
--- /dev/null
+++ b/bp
@@ -0,0 +1,20 @@
1#!/bin/bash
2args="-rtsopts -hisuf p_hi -osuf p_o -prof -fprof-auto -fprof-auto-exported"
3
4root=${0%/*}
5cd "$root"
6
7me=${0##*/}
8me=${me%.*}
9ghc \
10 -hidir build/$me -odir build/$me \
11 -iPresence \
12 Data/BitSyntax.hs
13ghc \
14 -hidir build/$me -odir build/$me \
15 -iPresence \
16 $args \
17 -o presence \
18 build/b/Presence/monitortty.o \
19 Presence/main \
20 "$@"
diff --git a/consolation.hs b/consolation.hs
new file mode 100644
index 00000000..0c576dfc
--- /dev/null
+++ b/consolation.hs
@@ -0,0 +1,186 @@
1{-# LANGUAGE OverloadedStrings #-}
2module Main where
3
4import Control.Monad
5import Control.Applicative
6import Control.Concurrent
7import Control.Concurrent.STM
8import Data.Monoid
9import Data.Char
10import System.INotify ( initINotify, EventVariety(Modify), addWatch )
11import Data.Word ( Word8 )
12import Data.Text ( Text )
13import Data.Map ( Map )
14import Data.List ( foldl' )
15import qualified Data.Map as Map
16import qualified Data.Traversable as Traversable
17import qualified Data.Text as Text
18import qualified Data.Text.IO as Text
19import qualified Network.BSD as BSD
20
21import WaitForSignal ( waitForTermSignal )
22import UTmp ( users2, utmp_file, UtmpRecord(..), UT_Type(..) )
23import FGConsole ( monitorTTY )
24
25data ConsoleState = ConsoleState
26 { csActiveTTY :: TVar Word8
27 , csUtmp :: TVar (Map Text (TVar (Maybe UtmpRecord)))
28 }
29
30newConsoleState = atomically $
31 ConsoleState <$> newTVar 0 <*> newTVar Map.empty
32
33
34onLogin cs start = \e -> do
35 us <- UTmp.users2
36 let (m,cruft) =
37 foldl' (\(m,cruft) x ->
38 case utmpType x of
39 USER_PROCESS
40 -> (Map.insert (utmpTty x) x m,cruft)
41 DEAD_PROCESS | utmpPid x /= 0
42 -> (m,Map.insert (utmpTty x) x cruft)
43 _ -> (m,cruft))
44 (Map.empty,Map.empty)
45 us
46 forM_ (Map.elems cruft) $ \c -> do
47 putStrLn $ "cruft " ++ show (utmpTty c, utmpPid c,utmpHost c, utmpRemoteAddr c)
48 newborn <- atomically $ do
49 old <- readTVar (csUtmp cs) -- swapTVar (csUtmp cs) m
50 newborn <- flip Traversable.mapM (m Map.\\ old)
51 $ newTVar . Just
52 updated <- let upd v u = writeTVar v $ Just u
53 in Traversable.sequence $ Map.intersectionWith upd old m
54 let dead = old Map.\\ m
55 Traversable.mapM (flip writeTVar Nothing) dead
56 writeTVar (csUtmp cs) $ (old `Map.union` newborn) Map.\\ dead
57 return newborn
58 let getActive = do
59 tty <- readTVar $ csActiveTTY cs
60 utmp <- readTVar $ csUtmp cs
61 flip (maybe $ return (tty,Nothing))
62 (Map.lookup ("tty"<>tshow tty) utmp)
63 $ \tuvar -> do
64 tu <- readTVar tuvar
65 return (tty,tu)
66
67 forM_ (Map.elems newborn) $
68 forkIO . start getActive
69 -- forM_ (Map.elems dead ) $ putStrLn . ("gone: "++) . show
70
71onTTY outvar cs vtnum = do
72 logit outvar $ "switch: " <> tshow vtnum
73 atomically $ writeTVar (csActiveTTY cs) vtnum
74
75retryWhen var pred = do
76 value <- var
77 if pred value then retry
78 else return value
79
80tshow x = Text.pack . show $ x
81
82resource :: UtmpRecord -> Text
83resource u =
84 case utmpTty u of
85 s | Text.take 3 s == "tty" -> s
86 s | Text.take 4 s == "pts/" -> "pty" <> Text.drop 4 s <> ":" <> utmpHost u
87 s -> escapeR s <> ":" <> utmpHost u
88 where
89 escapeR s = s
90
91textHostName = fmap Text.pack BSD.getHostName
92
93ujid u = do
94 h <- textHostName
95 return $ utmpUser u <> "@" <> h <> "/" <> resource u
96
97newCon :: (Text -> IO ()) -> STM (Word8,Maybe UtmpRecord) -> TVar (Maybe UtmpRecord) -> IO ()
98newCon log activeTTY utmp = do
99 ((tty,tu),u) <- atomically $
100 liftM2 (,) activeTTY
101 (readTVar utmp)
102 flip (maybe $ return ()) u $ \u -> do
103 jid <- ujid u
104 log $ status (resource u) tty tu <> " " <> jid <> " pid=" <> tshow (utmpPid u)
105 <> (if istty (resource u)
106 then " host=" <> tshow (utmpHost u)
107 else "")
108 <> " session=" <> tshow (utmpSession u)
109 <> " addr=" <> tshow (utmpRemoteAddr u)
110 loop tty tu (Just u)
111 where
112 bstatus r ttynum mtu
113 = r == ttystr
114 || match mtu
115 where ttystr = "tty" <> tshow ttynum
116 searchstr mtu = maybe ttystr utmpHost $ do
117 tu <- mtu
118 guard (not $ Text.null $ utmpHost tu)
119 return tu
120 match mtu = searchstr mtu `Text.isInfixOf` Text.dropWhile (/=':') r
121 status r ttynum tu =
122 if bstatus r ttynum tu
123 then "Available"
124 else "Away "
125
126 istty r = fst3 == "tty" && Text.all isDigit rst
127 where
128 (fst3,rst) = Text.splitAt 3 r
129
130 loop tty tu u = do
131 what <- atomically $ foldr1 orElse
132 [ do (tty',tu') <- retryWhen activeTTY
133 (\ttyu -> bstatus r tty tu == uncurry (bstatus r) ttyu)
134 return $ ttyChanged tty' tu'
135 , do u' <- retryWhen (readTVar utmp) (==u)
136 return $ utmpChanged u'
137 ]
138 what
139 where
140 r = maybe "" resource u
141
142 ttyChanged tty' tu' = do
143 jid <- maybe (return "") ujid u
144 log $ status r tty' tu' <> " " <> jid
145 loop tty' tu' u
146
147 utmpChanged u' = maybe dead changed u'
148 where
149 changed u' = do
150 jid0 <- maybe (return "") ujid u
151 jid <- ujid u'
152 log $ "changed: " <> jid0 <> " --> " <> jid
153 loop tty tu (Just u')
154 dead = do
155 jid <- maybe (return "") ujid u
156 log $ "Offline " <> jid
157
158logit outvar s = do
159 atomically $ takeTMVar outvar
160 Text.putStrLn s
161 atomically $ putTMVar outvar ()
162
163
164main = do
165 outvar <- atomically $ newTMVar ()
166
167 cs <- newConsoleState
168 inotify <- initINotify
169
170 -- get active tty
171 mtty <- monitorTTY (onTTY outvar cs)
172 atomically $ retryWhen (readTVar $ csActiveTTY cs) (==0)
173
174 -- read utmp
175 onLogin cs (newCon $ logit outvar) Modify
176
177 -- monitor utmp
178 wd <- addWatch
179 inotify
180 [Modify] -- [CloseWrite,Open,Close,Access,Modify,Move]
181 utmp_file
182 (onLogin cs (newCon $ logit outvar))
183
184 waitForTermSignal
185
186 putStrLn "goodbye."
diff --git a/dht-client.cabal b/dht-client.cabal
index aa4de64c..b17ceb14 100644
--- a/dht-client.cabal
+++ b/dht-client.cabal
@@ -58,7 +58,7 @@ library
58 , OverloadedStrings 58 , OverloadedStrings
59 , RecordWildCards 59 , RecordWildCards
60 , NondecreasingIndentation 60 , NondecreasingIndentation
61 hs-source-dirs: src, cryptonite-backport, . 61 hs-source-dirs: src, cryptonite-backport, ., Presence
62 exposed-modules: Network.SocketLike 62 exposed-modules: Network.SocketLike
63 Data.Digest.CRC32C 63 Data.Digest.CRC32C
64 Data.Bits.ByteString 64 Data.Bits.ByteString
@@ -99,6 +99,34 @@ library
99 Roster 99 Roster
100 Announcer 100 Announcer
101 InterruptibleDelay 101 InterruptibleDelay
102 ByteStringOperators
103 ClientState
104 ConfigFiles
105 ConnectionKey
106 ConsoleWriter
107 Control.Concurrent.STM.StatusCache
108 Control.Concurrent.STM.UpdateStream
109 ControlMaybe
110 Data.BitSyntax
111 DNSCache
112 EventUtil
113 FGConsole
114 GetHostByAddr
115 LocalPeerCred
116 LockedChan
117 Logging
118 Nesting
119 Paths
120 PeerResolve
121 Server
122 SockAddr
123 TraversableT
124 UTmp
125 XMPPServer
126 Util
127 Presence
128 PingMachine
129 Connection
102 130
103 build-depends: base 131 build-depends: base
104 , containers 132 , containers
@@ -117,6 +145,7 @@ library
117 , directory 145 , directory
118 , bencoding 146 , bencoding
119 , contravariant 147 , contravariant
148 , xml-types
120 149
121 , cryptonite 150 , cryptonite
122 , memory 151 , memory
@@ -144,6 +173,15 @@ library
144 , ghc-prim 173 , ghc-prim
145 , sensible-directory 174 , sensible-directory
146 , temporary 175 , temporary
176 , transformers
177 , conduit
178 , conduit-extra
179 , xml-conduit
180 , unix
181 , template-haskell
182 , resourcet
183 , blaze-builder
184 , hinotify
147 185
148 if impl(ghc < 8) 186 if impl(ghc < 8)
149 Build-depends: transformers 187 Build-depends: transformers
@@ -168,11 +206,12 @@ library
168 Crypto.Internal.Imports 206 Crypto.Internal.Imports
169 Crypto.PubKey.Curve25519 207 Crypto.PubKey.Curve25519
170 208
171 C-sources: cbits/cryptonite_xsalsa.c, cbits/cryptonite_salsa.c 209 C-sources: cbits/cryptonite_xsalsa.c, cbits/cryptonite_salsa.c,
210 Presence/monitortty.c
172 211
173 -- if flag(aeson) 212 -- if flag(aeson)
174 build-depends: aeson, aeson-pretty, unordered-containers, vector 213 build-depends: aeson, aeson-pretty, unordered-containers, vector
175 cpp-options: -DBENCODE_AESON 214 cpp-options: -DBENCODE_AESON -DRENDERFLUSH
176 if flag(thread-debug) 215 if flag(thread-debug)
177 exposed-modules: Control.Concurrent.Lifted.Instrument 216 exposed-modules: Control.Concurrent.Lifted.Instrument
178 Control.Concurrent.Async.Lifted.Instrument 217 Control.Concurrent.Async.Lifted.Instrument
@@ -208,9 +247,10 @@ executable dhtd
208 , unordered-containers 247 , unordered-containers
209 , vector 248 , vector
210 , text 249 , text
250 , resourcet
211 251
212 if flag(thread-debug) 252 if flag(thread-debug)
213 build-depends: time 253 build-depends: time
214 cpp-options: -DTHREAD_DEBUG 254 cpp-options: -DTHREAD_DEBUG -DRENDERFLUSH
215 ghc-options: -rtsopts -fdefer-typed-holes 255 ghc-options: -rtsopts -fdefer-typed-holes -threaded
216 256
diff --git a/doc/rfc6120.html b/doc/rfc6120.html
new file mode 100644
index 00000000..fa7ef081
--- /dev/null
+++ b/doc/rfc6120.html
@@ -0,0 +1,9372 @@
1<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
2<html lang="en"><head><title>Extensible Messaging and Presence Protocol (XMPP): Core</title>
3<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
4<meta name="description" content="Extensible Messaging and Presence Protocol (XMPP): Core">
5<meta name="keywords" content="XMPP, Extensible Messaging and Presence Protocol, Jabber, Messaging, Instant Messaging, Presence, Extensible Markup Language, XML">
6<meta name="generator" content="xml2rfc v1.36 (http://xml.resource.org/)">
7<style type='text/css'><!--
8 body {
9 font-family: verdana, charcoal, helvetica, arial, sans-serif;
10 font-size: small; color: #000; background-color: #FFF;
11 margin: 2em;
12 }
13 h1, h2, h3, h4, h5, h6 {
14 font-family: helvetica, monaco, "MS Sans Serif", arial, sans-serif;
15 font-weight: bold; font-style: normal;
16 }
17 h1 { color: #900; background-color: transparent; text-align: right; }
18 h3 { color: #333; background-color: transparent; }
19
20 td.RFCbug {
21 font-size: x-small; text-decoration: none;
22 width: 30px; height: 30px; padding-top: 2px;
23 text-align: justify; vertical-align: middle;
24 background-color: #000;
25 }
26 td.RFCbug span.RFC {
27 font-family: monaco, charcoal, geneva, "MS Sans Serif", helvetica, verdana, sans-serif;
28 font-weight: bold; color: #666;
29 }
30 td.RFCbug span.hotText {
31 font-family: charcoal, monaco, geneva, "MS Sans Serif", helvetica, verdana, sans-serif;
32 font-weight: normal; text-align: center; color: #FFF;
33 }
34
35 table.TOCbug { width: 30px; height: 15px; }
36 td.TOCbug {
37 text-align: center; width: 30px; height: 15px;
38 color: #FFF; background-color: #900;
39 }
40 td.TOCbug a {
41 font-family: monaco, charcoal, geneva, "MS Sans Serif", helvetica, sans-serif;
42 font-weight: bold; font-size: x-small; text-decoration: none;
43 color: #FFF; background-color: transparent;
44 }
45
46 td.header {
47 font-family: arial, helvetica, sans-serif; font-size: x-small;
48 vertical-align: top; width: 33%;
49 color: #FFF; background-color: #666;
50 }
51 td.author { font-weight: bold; font-size: x-small; margin-left: 4em; }
52 td.author-text { font-size: x-small; }
53
54 /* info code from SantaKlauss at http://www.madaboutstyle.com/tooltip2.html */
55 a.info {
56 /* This is the key. */
57 position: relative;
58 z-index: 24;
59 text-decoration: none;
60 }
61 a.info:hover {
62 z-index: 25;
63 color: #FFF; background-color: #900;
64 }
65 a.info span { display: none; }
66 a.info:hover span.info {
67 /* The span will display just on :hover state. */
68 display: block;
69 position: absolute;
70 font-size: smaller;
71 top: 2em; left: -5em; width: 15em;
72 padding: 2px; border: 1px solid #333;
73 color: #900; background-color: #EEE;
74 text-align: left;
75 }
76
77 a { font-weight: bold; }
78 a:link { color: #900; background-color: transparent; }
79 a:visited { color: #633; background-color: transparent; }
80 a:active { color: #633; background-color: transparent; }
81
82 p { margin-left: 2em; margin-right: 2em; }
83 p.copyright { font-size: x-small; }
84 p.toc { font-size: small; font-weight: bold; margin-left: 3em; }
85 table.toc { margin: 0 0 0 3em; padding: 0; border: 0; vertical-align: text-top; }
86 td.toc { font-size: small; font-weight: bold; vertical-align: text-top; }
87
88 ol.text { margin-left: 2em; margin-right: 2em; }
89 ul.text { margin-left: 2em; margin-right: 2em; }
90 li { margin-left: 3em; }
91
92 /* RFC-2629 <spanx>s and <artwork>s. */
93 em { font-style: italic; }
94 strong { font-weight: bold; }
95 dfn { font-weight: bold; font-style: normal; }
96 cite { font-weight: normal; font-style: normal; }
97 tt { color: #036; }
98 tt, pre, pre dfn, pre em, pre cite, pre span {
99 font-family: "Courier New", Courier, monospace; font-size: small;
100 }
101 pre {
102 text-align: left; padding: 4px;
103 color: #000; background-color: #CCC;
104 }
105 pre dfn { color: #900; }
106 pre em { color: #66F; background-color: #FFC; font-weight: normal; }
107 pre .key { color: #33C; font-weight: bold; }
108 pre .id { color: #900; }
109 pre .str { color: #000; background-color: #CFF; }
110 pre .val { color: #066; }
111 pre .rep { color: #909; }
112 pre .oth { color: #000; background-color: #FCF; }
113 pre .err { background-color: #FCC; }
114
115 /* RFC-2629 <texttable>s. */
116 table.all, table.full, table.headers, table.none {
117 font-size: small; text-align: center; border-width: 2px;
118 vertical-align: top; border-collapse: collapse;
119 }
120 table.all, table.full { border-style: solid; border-color: black; }
121 table.headers, table.none { border-style: none; }
122 th {
123 font-weight: bold; border-color: black;
124 border-width: 2px 2px 3px 2px;
125 }
126 table.all th, table.full th { border-style: solid; }
127 table.headers th { border-style: none none solid none; }
128 table.none th { border-style: none; }
129 table.all td {
130 border-style: solid; border-color: #333;
131 border-width: 1px 2px;
132 }
133 table.full td, table.headers td, table.none td { border-style: none; }
134
135 hr { height: 1px; }
136 hr.insert {
137 width: 80%; border-style: none; border-width: 0;
138 color: #CCC; background-color: #CCC;
139 }
140--></style>
141</head>
142<body>
143
144<table border="0" cellpadding="0" cellspacing="2" width="30" align="right">
145 <tr>
146 <td class="RFCbug">
147 <span class="RFC">&nbsp;RFC&nbsp;</span><br /><span class="hotText">&nbsp;6120&nbsp;</span>
148 </td>
149 </tr>
150 <tr><td class="TOCbug"><a href="#toc">&nbsp;TOC&nbsp;</a><br /></td></tr>
151</table>
152<table summary="layout" width="66%" border="0" cellpadding="0" cellspacing="0"><tr><td><table summary="layout" width="100%" border="0" cellpadding="2" cellspacing="1">
153<tr><td class="header">Internet Engineering Task Force (IETF)</td><td class="header">P. Saint-Andre</td></tr>
154<tr><td class="header">Request for Comments: 6120</td><td class="header">Cisco</td></tr>
155<tr><td class="header">Obsoletes: <a href='http://tools.ietf.org/html/rfc3920'>3920</a></td><td class="header">March 2011</td></tr>
156<tr><td class="header">Category: Standards Track</td><td class="header">&nbsp;</td></tr>
157<tr><td class="header">ISSN: 2070-1721</td><td class="header">&nbsp;</td></tr>
158</table></td></tr></table>
159<h1><br />Extensible Messaging and Presence Protocol (XMPP): Core</h1>
160
161<h3>Abstract</h3>
162
163<p>The Extensible Messaging and Presence Protocol (XMPP) is an application profile of the Extensible Markup Language (XML) that enables the near-real-time exchange of structured yet extensible data between any two or more network entities. This document defines XMPP's core protocol methods: setup and teardown of XML streams, channel encryption, authentication, error handling, and communication primitives for messaging, network availability ("presence"), and request-response interactions. This document obsoletes RFC 3920.
164</p>
165<h3>Status of This Memo</h3>
166<p>
167This is an Internet Standards Track document.</p>
168<p>
169This document is a product of the Internet Engineering Task Force (IETF). It represents the consensus of the IETF community. It has received public review and has been approved for publication by the Internet Engineering Steering Group (IESG). Further information on Internet Standards is available in Section 2 of RFC 5741.</p>
170<p>
171Information about the current status of this document, any errata, and how to provide feedback on it may be obtained at http://www.rfc-editor.org/info/rfc6120.</p>
172
173<h3>Copyright Notice</h3>
174<p>
175Copyright (c) 2011 IETF Trust and the persons identified as the
176document authors. All rights reserved.</p>
177<p>
178This document is subject to BCP 78 and the IETF Trust's Legal
179Provisions Relating to IETF Documents
180(http://trustee.ietf.org/license-info) in effect on the date of
181publication of this document. Please review these documents
182carefully, as they describe your rights and restrictions with respect
183to this document. Code Components extracted from this document must
184include Simplified BSD License text as described in Section 4.e of
185the Trust Legal Provisions and are provided without warranty as
186described in the Simplified BSD License.</p>
187<a name="toc"></a><hr />
188
189<table border="0" cellpadding="0" cellspacing="2" width="30" align="right">
190 <tr>
191 <td class="RFCbug">
192 <span class="RFC">&nbsp;RFC&nbsp;</span><br /><span class="hotText">&nbsp;6120&nbsp;</span>
193 </td>
194 </tr>
195 <tr><td class="TOCbug"><a href="#toc">&nbsp;TOC&nbsp;</a><br /></td></tr>
196</table>
197<h3>Table of Contents</h3>
198<p class="toc">
199<a href="#intro">1.</a>&nbsp;
200Introduction<br />
201&nbsp;&nbsp;&nbsp;&nbsp;<a href="#intro-overview">1.1.</a>&nbsp;
202Overview<br />
203&nbsp;&nbsp;&nbsp;&nbsp;<a href="#intro-history">1.2.</a>&nbsp;
204History<br />
205&nbsp;&nbsp;&nbsp;&nbsp;<a href="#intro-summary">1.3.</a>&nbsp;
206Functional Summary<br />
207&nbsp;&nbsp;&nbsp;&nbsp;<a href="#intro-terms">1.4.</a>&nbsp;
208Terminology<br />
209<a href="#arch">2.</a>&nbsp;
210Architecture<br />
211&nbsp;&nbsp;&nbsp;&nbsp;<a href="#arch-addresses">2.1.</a>&nbsp;
212Global Addresses<br />
213&nbsp;&nbsp;&nbsp;&nbsp;<a href="#arch-presence">2.2.</a>&nbsp;
214Presence<br />
215&nbsp;&nbsp;&nbsp;&nbsp;<a href="#arch-streams">2.3.</a>&nbsp;
216Persistent Streams<br />
217&nbsp;&nbsp;&nbsp;&nbsp;<a href="#arch-data">2.4.</a>&nbsp;
218Structured Data<br />
219&nbsp;&nbsp;&nbsp;&nbsp;<a href="#arch-network">2.5.</a>&nbsp;
220Distributed Network of Clients and Servers<br />
221<a href="#tcp">3.</a>&nbsp;
222TCP Binding<br />
223&nbsp;&nbsp;&nbsp;&nbsp;<a href="#tcp-scope">3.1.</a>&nbsp;
224Scope<br />
225&nbsp;&nbsp;&nbsp;&nbsp;<a href="#tcp-resolution">3.2.</a>&nbsp;
226Resolution of Fully Qualified Domain Names<br />
227&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<a href="#tcp-resolution-prefer">3.2.1.</a>&nbsp;
228Preferred Process: SRV Lookup<br />
229&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<a href="#tcp-resolution-fallback">3.2.2.</a>&nbsp;
230Fallback Processes<br />
231&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<a href="#tcp-resolution-srvnot">3.2.3.</a>&nbsp;
232When Not to Use SRV<br />
233&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<a href="#tcp-resolution-srvadd">3.2.4.</a>&nbsp;
234Use of SRV Records with Add-On Services<br />
235&nbsp;&nbsp;&nbsp;&nbsp;<a href="#tcp-reconnect">3.3.</a>&nbsp;
236Reconnection<br />
237&nbsp;&nbsp;&nbsp;&nbsp;<a href="#streams-reliability">3.4.</a>&nbsp;
238Reliability<br />
239<a href="#streams">4.</a>&nbsp;
240XML Streams<br />
241&nbsp;&nbsp;&nbsp;&nbsp;<a href="#streams-fundamentals">4.1.</a>&nbsp;
242Stream Fundamentals<br />
243&nbsp;&nbsp;&nbsp;&nbsp;<a href="#streams-open">4.2.</a>&nbsp;
244Opening a Stream<br />
245&nbsp;&nbsp;&nbsp;&nbsp;<a href="#streams-negotiation">4.3.</a>&nbsp;
246Stream Negotiation<br />
247&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<a href="#streams-negotiation-basics">4.3.1.</a>&nbsp;
248Basic Concepts<br />
249&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<a href="#streams-negotiation-features">4.3.2.</a>&nbsp;
250Stream Features Format<br />
251&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<a href="#streams-negotiation-restart">4.3.3.</a>&nbsp;
252Restarts<br />
253&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<a href="#streams-negotiation-resend">4.3.4.</a>&nbsp;
254Resending Features<br />
255&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<a href="#streams-negotiation-complete">4.3.5.</a>&nbsp;
256Completion of Stream Negotiation<br />
257&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<a href="#streams-negotiation-address">4.3.6.</a>&nbsp;
258Determination of Addresses<br />
259&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<a href="#streams-negotiation-flowchart">4.3.7.</a>&nbsp;
260Flow Chart<br />
261&nbsp;&nbsp;&nbsp;&nbsp;<a href="#streams-close">4.4.</a>&nbsp;
262Closing a Stream<br />
263&nbsp;&nbsp;&nbsp;&nbsp;<a href="#streams-direction">4.5.</a>&nbsp;
264Directionality<br />
265&nbsp;&nbsp;&nbsp;&nbsp;<a href="#streams-silence">4.6.</a>&nbsp;
266Handling of Silent Peers<br />
267&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<a href="#streams-silence-dead">4.6.1.</a>&nbsp;
268Dead Connection<br />
269&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<a href="#streams-silence-broken">4.6.2.</a>&nbsp;
270Broken Stream<br />
271&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<a href="#streams-silence-idle">4.6.3.</a>&nbsp;
272Idle Peer<br />
273&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<a href="#streams-silence-check">4.6.4.</a>&nbsp;
274Use of Checking Methods<br />
275&nbsp;&nbsp;&nbsp;&nbsp;<a href="#streams-attr">4.7.</a>&nbsp;
276Stream Attributes<br />
277&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<a href="#streams-attr-from">4.7.1.</a>&nbsp;
278from<br />
279&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<a href="#streams-attr-to">4.7.2.</a>&nbsp;
280to<br />
281&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<a href="#streams-attr-id">4.7.3.</a>&nbsp;
282id<br />
283&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<a href="#streams-attr-xmllang">4.7.4.</a>&nbsp;
284xml:lang<br />
285&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<a href="#streams-attr-version">4.7.5.</a>&nbsp;
286version<br />
287&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<a href="#streams-attr-summary">4.7.6.</a>&nbsp;
288Summary of Stream Attributes<br />
289&nbsp;&nbsp;&nbsp;&nbsp;<a href="#streams-ns">4.8.</a>&nbsp;
290XML Namespaces<br />
291&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<a href="#streams-ns-stream">4.8.1.</a>&nbsp;
292Stream Namespace<br />
293&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<a href="#streams-ns-content">4.8.2.</a>&nbsp;
294Content Namespace<br />
295&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<a href="#streams-ns-xmpp">4.8.3.</a>&nbsp;
296XMPP Content Namespaces<br />
297&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<a href="#streams-ns-other">4.8.4.</a>&nbsp;
298Other Namespaces<br />
299&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<a href="#streams-ns-declarations">4.8.5.</a>&nbsp;
300Namespace Declarations and Prefixes<br />
301&nbsp;&nbsp;&nbsp;&nbsp;<a href="#streams-error">4.9.</a>&nbsp;
302Stream Errors<br />
303&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<a href="#streams-error-rules">4.9.1.</a>&nbsp;
304Rules<br />
305&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<a href="#streams-error-rules-unrecoverable">4.9.1.1.</a>&nbsp;
306Stream Errors Are Unrecoverable<br />
307&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<a href="#streams-error-rules-setup">4.9.1.2.</a>&nbsp;
308Stream Errors Can Occur During Setup<br />
309&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<a href="#streams-error-rules-host">4.9.1.3.</a>&nbsp;
310Stream Errors When the Host Is Unspecified or Unknown<br />
311&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<a href="#streams-error-rules-where">4.9.1.4.</a>&nbsp;
312Where Stream Errors Are Sent<br />
313&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<a href="#streams-error-syntax">4.9.2.</a>&nbsp;
314Syntax<br />
315&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<a href="#streams-error-conditions">4.9.3.</a>&nbsp;
316Defined Stream Error Conditions<br />
317&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<a href="#streams-error-conditions-bad-format">4.9.3.1.</a>&nbsp;
318bad-format<br />
319&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<a href="#streams-error-conditions-bad-namespace-prefix">4.9.3.2.</a>&nbsp;
320bad-namespace-prefix<br />
321&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<a href="#streams-error-conditions-conflict">4.9.3.3.</a>&nbsp;
322conflict<br />
323&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<a href="#streams-error-conditions-connection-timeout">4.9.3.4.</a>&nbsp;
324connection-timeout<br />
325&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<a href="#streams-error-conditions-host-gone">4.9.3.5.</a>&nbsp;
326host-gone<br />
327&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<a href="#streams-error-conditions-host-unknown">4.9.3.6.</a>&nbsp;
328host-unknown<br />
329&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<a href="#streams-error-conditions-improper-addressing">4.9.3.7.</a>&nbsp;
330improper-addressing<br />
331&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<a href="#streams-error-conditions-internal-server-error">4.9.3.8.</a>&nbsp;
332internal-server-error<br />
333&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<a href="#streams-error-conditions-invalid-from">4.9.3.9.</a>&nbsp;
334invalid-from<br />
335&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<a href="#streams-error-conditions-invalid-namespace">4.9.3.10.</a>&nbsp;
336invalid-namespace<br />
337&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<a href="#streams-error-conditions-invalid-xml">4.9.3.11.</a>&nbsp;
338invalid-xml<br />
339&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<a href="#streams-error-conditions-not-authorized">4.9.3.12.</a>&nbsp;
340not-authorized<br />
341&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<a href="#streams-error-conditions-not-well-formed">4.9.3.13.</a>&nbsp;
342not-well-formed<br />
343&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<a href="#streams-error-conditions-policy-violation">4.9.3.14.</a>&nbsp;
344policy-violation<br />
345&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<a href="#streams-error-conditions-remote-connection-failed">4.9.3.15.</a>&nbsp;
346remote-connection-failed<br />
347&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<a href="#streams-error-conditions-reset">4.9.3.16.</a>&nbsp;
348reset<br />
349&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<a href="#streams-error-conditions-resource-constraint">4.9.3.17.</a>&nbsp;
350resource-constraint<br />
351&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<a href="#streams-error-conditions-restricted-xml">4.9.3.18.</a>&nbsp;
352restricted-xml<br />
353&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<a href="#streams-error-conditions-see-other-host">4.9.3.19.</a>&nbsp;
354see-other-host<br />
355&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<a href="#streams-error-conditions-system-shutdown">4.9.3.20.</a>&nbsp;
356system-shutdown<br />
357&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<a href="#streams-error-conditions-undefined-condition">4.9.3.21.</a>&nbsp;
358undefined-condition<br />
359&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<a href="#streams-error-conditions-unsupported-encoding">4.9.3.22.</a>&nbsp;
360unsupported-encoding<br />
361&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<a href="#streams-error-conditions-unsupported-feature">4.9.3.23.</a>&nbsp;
362unsupported-feature<br />
363&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<a href="#streams-error-conditions-unsupported-stanza-type">4.9.3.24.</a>&nbsp;
364unsupported-stanza-type<br />
365&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<a href="#streams-error-conditions-unsupported-version">4.9.3.25.</a>&nbsp;
366unsupported-version<br />
367&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<a href="#streams-error-app">4.9.4.</a>&nbsp;
368Application-Specific Conditions<br />
369&nbsp;&nbsp;&nbsp;&nbsp;<a href="#streams-example">4.10.</a>&nbsp;
370Simplified Stream Examples<br />
371<a href="#tls">5.</a>&nbsp;
372STARTTLS Negotiation<br />
373&nbsp;&nbsp;&nbsp;&nbsp;<a href="#tls-fundamentals">5.1.</a>&nbsp;
374Fundamentals<br />
375&nbsp;&nbsp;&nbsp;&nbsp;<a href="#tls-support">5.2.</a>&nbsp;
376Support<br />
377&nbsp;&nbsp;&nbsp;&nbsp;<a href="#tls-rules">5.3.</a>&nbsp;
378Stream Negotiation Rules<br />
379&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<a href="#tls-rules-mtn">5.3.1.</a>&nbsp;
380Mandatory-to-Negotiate<br />
381&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<a href="#tls-rules-restart">5.3.2.</a>&nbsp;
382Restart<br />
383&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<a href="#tls-rules-data">5.3.3.</a>&nbsp;
384Data Formatting<br />
385&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<a href="#tls-rules-order">5.3.4.</a>&nbsp;
386Order of TLS and SASL Negotiations<br />
387&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<a href="#tls-rules-renegotiation">5.3.5.</a>&nbsp;
388TLS Renegotiation<br />
389&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<a href="#tls-rules-extensions">5.3.6.</a>&nbsp;
390TLS Extensions<br />
391&nbsp;&nbsp;&nbsp;&nbsp;<a href="#tls-process">5.4.</a>&nbsp;
392Process<br />
393&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<a href="#tls-process-stream">5.4.1.</a>&nbsp;
394Exchange of Stream Headers and Stream Features<br />
395&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<a href="#tls-process-initiate">5.4.2.</a>&nbsp;
396Initiation of STARTTLS Negotiation<br />
397&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<a href="#tls-process-initiate-command">5.4.2.1.</a>&nbsp;
398STARTTLS Command<br />
399&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<a href="#tls-process-initiate-failure">5.4.2.2.</a>&nbsp;
400Failure Case<br />
401&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<a href="#tls-process-initiate-proceed">5.4.2.3.</a>&nbsp;
402Proceed Case<br />
403&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<a href="#tls-process-neg">5.4.3.</a>&nbsp;
404TLS Negotiation<br />
405&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<a href="#tls-process-neg-rules">5.4.3.1.</a>&nbsp;
406Rules<br />
407&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<a href="#tls-process-neg-failure">5.4.3.2.</a>&nbsp;
408TLS Failure<br />
409&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<a href="#tls-process-neg-success">5.4.3.3.</a>&nbsp;
410TLS Success<br />
411<a href="#sasl">6.</a>&nbsp;
412SASL Negotiation<br />
413&nbsp;&nbsp;&nbsp;&nbsp;<a href="#sasl-fundamentals">6.1.</a>&nbsp;
414Fundamentals<br />
415&nbsp;&nbsp;&nbsp;&nbsp;<a href="#sasl-support">6.2.</a>&nbsp;
416Support<br />
417&nbsp;&nbsp;&nbsp;&nbsp;<a href="#sasl-rules">6.3.</a>&nbsp;
418Stream Negotiation Rules<br />
419&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<a href="#sasl-rules-mtn">6.3.1.</a>&nbsp;
420Mandatory-to-Negotiate<br />
421&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<a href="#sasl-rules-restart">6.3.2.</a>&nbsp;
422Restart<br />
423&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<a href="#sasl-rules-preferences">6.3.3.</a>&nbsp;
424Mechanism Preferences<br />
425&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<a href="#sasl-rules-offers">6.3.4.</a>&nbsp;
426Mechanism Offers<br />
427&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<a href="#sasl-rules-data">6.3.5.</a>&nbsp;
428Data Formatting<br />
429&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<a href="#sasl-rules-layers">6.3.6.</a>&nbsp;
430Security Layers<br />
431&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<a href="#sasl-rules-username">6.3.7.</a>&nbsp;
432Simple User Name<br />
433&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<a href="#sasl-rules-authzid">6.3.8.</a>&nbsp;
434Authorization Identity<br />
435&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<a href="#sasl-rules-realms">6.3.9.</a>&nbsp;
436Realms<br />
437&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<a href="#sasl-rules-roundtrips">6.3.10.</a>&nbsp;
438Round Trips<br />
439&nbsp;&nbsp;&nbsp;&nbsp;<a href="#sasl-process">6.4.</a>&nbsp;
440Process<br />
441&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<a href="#sasl-process-stream">6.4.1.</a>&nbsp;
442Exchange of Stream Headers and Stream Features<br />
443&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<a href="#sasl-process-neg-initiate">6.4.2.</a>&nbsp;
444Initiation<br />
445&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<a href="#sasl-process-neg-challengeresponse">6.4.3.</a>&nbsp;
446Challenge-Response Sequence<br />
447&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<a href="#sasl-process-neg-abort">6.4.4.</a>&nbsp;
448Abort<br />
449&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<a href="#sasl-process-neg-failure">6.4.5.</a>&nbsp;
450SASL Failure<br />
451&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<a href="#sasl-process-neg-success">6.4.6.</a>&nbsp;
452SASL Success<br />
453&nbsp;&nbsp;&nbsp;&nbsp;<a href="#sasl-errors">6.5.</a>&nbsp;
454SASL Errors<br />
455&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<a href="#sasl-errors-aborted">6.5.1.</a>&nbsp;
456aborted<br />
457&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<a href="#sasl-errors-account-disabled">6.5.2.</a>&nbsp;
458account-disabled<br />
459&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<a href="#sasl-errors-credentials-expired">6.5.3.</a>&nbsp;
460credentials-expired<br />
461&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<a href="#sasl-errors-encryption-required">6.5.4.</a>&nbsp;
462encryption-required<br />
463&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<a href="#sasl-errors-incorrect-encoding">6.5.5.</a>&nbsp;
464incorrect-encoding<br />
465&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<a href="#sasl-errors-invalid-authzid">6.5.6.</a>&nbsp;
466invalid-authzid<br />
467&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<a href="#sasl-errors-invalid-mechanism">6.5.7.</a>&nbsp;
468invalid-mechanism<br />
469&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<a href="#sasl-errors-malformed-request">6.5.8.</a>&nbsp;
470malformed-request<br />
471&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<a href="#sasl-errors-mechanism-too-weak">6.5.9.</a>&nbsp;
472mechanism-too-weak<br />
473&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<a href="#sasl-errors-not-authorized">6.5.10.</a>&nbsp;
474not-authorized<br />
475&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<a href="#sasl-errors-temporary-auth-failure">6.5.11.</a>&nbsp;
476temporary-auth-failure<br />
477&nbsp;&nbsp;&nbsp;&nbsp;<a href="#sasl-def">6.6.</a>&nbsp;
478SASL Definition<br />
479<a href="#bind">7.</a>&nbsp;
480Resource Binding<br />
481&nbsp;&nbsp;&nbsp;&nbsp;<a href="#bind-fundamentals">7.1.</a>&nbsp;
482Fundamentals<br />
483&nbsp;&nbsp;&nbsp;&nbsp;<a href="#bind-support">7.2.</a>&nbsp;
484Support<br />
485&nbsp;&nbsp;&nbsp;&nbsp;<a href="#bind-rules">7.3.</a>&nbsp;
486Stream Negotiation Rules<br />
487&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<a href="#bind-rules-mtn">7.3.1.</a>&nbsp;
488Mandatory-to-Negotiate<br />
489&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<a href="#bind-rules-restart">7.3.2.</a>&nbsp;
490Restart<br />
491&nbsp;&nbsp;&nbsp;&nbsp;<a href="#bind-feature">7.4.</a>&nbsp;
492Advertising Support<br />
493&nbsp;&nbsp;&nbsp;&nbsp;<a href="#bind-generation">7.5.</a>&nbsp;
494Generation of Resource Identifiers<br />
495&nbsp;&nbsp;&nbsp;&nbsp;<a href="#bind-servergen">7.6.</a>&nbsp;
496Server-Generated Resource Identifier<br />
497&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<a href="#bind-servergen-success">7.6.1.</a>&nbsp;
498Success Case<br />
499&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<a href="#bind-servergen-error">7.6.2.</a>&nbsp;
500Error Cases<br />
501&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<a href="#bind-servergen-error-resourceconstraint">7.6.2.1.</a>&nbsp;
502Resource Constraint<br />
503&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<a href="#bind-servergen-error-notallowed">7.6.2.2.</a>&nbsp;
504Not Allowed<br />
505&nbsp;&nbsp;&nbsp;&nbsp;<a href="#bind-clientsubmit">7.7.</a>&nbsp;
506Client-Submitted Resource Identifier<br />
507&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<a href="#bind-clientsubmit-success">7.7.1.</a>&nbsp;
508Success Case<br />
509&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<a href="#bind-clientsubmit-error">7.7.2.</a>&nbsp;
510Error Cases<br />
511&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<a href="#bind-clientsubmit-error-badrequest">7.7.2.1.</a>&nbsp;
512Bad Request<br />
513&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<a href="#bind-clientsubmit-error-conflict">7.7.2.2.</a>&nbsp;
514Conflict<br />
515&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<a href="#bind-clientsubmit-retries">7.7.3.</a>&nbsp;
516Retries<br />
517<a href="#stanzas">8.</a>&nbsp;
518XML Stanzas<br />
519&nbsp;&nbsp;&nbsp;&nbsp;<a href="#stanzas-attributes">8.1.</a>&nbsp;
520Common Attributes<br />
521&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<a href="#stanzas-attributes-to">8.1.1.</a>&nbsp;
522to<br />
523&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<a href="#stanzas-attributes-to-c2s">8.1.1.1.</a>&nbsp;
524Client-to-Server Streams<br />
525&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<a href="#stanzas-attributes-to-s2s">8.1.1.2.</a>&nbsp;
526Server-to-Server Streams<br />
527&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<a href="#stanzas-attributes-from">8.1.2.</a>&nbsp;
528from<br />
529&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<a href="#stanzas-attributes-from-c2s">8.1.2.1.</a>&nbsp;
530Client-to-Server Streams<br />
531&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<a href="#stanzas-attributes-from-s2s">8.1.2.2.</a>&nbsp;
532Server-to-Server Streams<br />
533&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<a href="#stanzas-attributes-id">8.1.3.</a>&nbsp;
534id<br />
535&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<a href="#stanzas-attributes-type">8.1.4.</a>&nbsp;
536type<br />
537&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<a href="#stanzas-attributes-lang">8.1.5.</a>&nbsp;
538xml:lang<br />
539&nbsp;&nbsp;&nbsp;&nbsp;<a href="#stanzas-semantics">8.2.</a>&nbsp;
540Basic Semantics<br />
541&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<a href="#stanzas-semantics-message">8.2.1.</a>&nbsp;
542Message Semantics<br />
543&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<a href="#stanzas-semantics-presence">8.2.2.</a>&nbsp;
544Presence Semantics<br />
545&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<a href="#stanzas-semantics-iq">8.2.3.</a>&nbsp;
546IQ Semantics<br />
547&nbsp;&nbsp;&nbsp;&nbsp;<a href="#stanzas-error">8.3.</a>&nbsp;
548Stanza Errors<br />
549&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<a href="#stanzas-error-rules">8.3.1.</a>&nbsp;
550Rules<br />
551&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<a href="#stanzas-error-syntax">8.3.2.</a>&nbsp;
552Syntax<br />
553&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<a href="#stanzas-error-conditions">8.3.3.</a>&nbsp;
554Defined Conditions<br />
555&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<a href="#stanzas-error-conditions-bad-request">8.3.3.1.</a>&nbsp;
556bad-request<br />
557&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<a href="#stanzas-error-conditions-conflict">8.3.3.2.</a>&nbsp;
558conflict<br />
559&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<a href="#stanzas-error-conditions-feature-not-implemented">8.3.3.3.</a>&nbsp;
560feature-not-implemented<br />
561&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<a href="#stanzas-error-conditions-forbidden">8.3.3.4.</a>&nbsp;
562forbidden<br />
563&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<a href="#stanzas-error-conditions-gone">8.3.3.5.</a>&nbsp;
564gone<br />
565&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<a href="#stanzas-error-conditions-internal-server-error">8.3.3.6.</a>&nbsp;
566internal-server-error<br />
567&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<a href="#stanzas-error-conditions-item-not-found">8.3.3.7.</a>&nbsp;
568item-not-found<br />
569&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<a href="#stanzas-error-conditions-jid-malformed">8.3.3.8.</a>&nbsp;
570jid-malformed<br />
571&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<a href="#stanzas-error-conditions-not-acceptable">8.3.3.9.</a>&nbsp;
572not-acceptable<br />
573&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<a href="#stanzas-error-conditions-not-allowed">8.3.3.10.</a>&nbsp;
574not-allowed<br />
575&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<a href="#stanzas-error-conditions-not-authorized">8.3.3.11.</a>&nbsp;
576not-authorized<br />
577&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<a href="#stanzas-error-conditions-policy-violation">8.3.3.12.</a>&nbsp;
578policy-violation<br />
579&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<a href="#stanzas-error-conditions-recipient-unavailable">8.3.3.13.</a>&nbsp;
580recipient-unavailable<br />
581&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<a href="#stanzas-error-conditions-redirect">8.3.3.14.</a>&nbsp;
582redirect<br />
583&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<a href="#stanzas-error-conditions-registration-required">8.3.3.15.</a>&nbsp;
584registration-required<br />
585&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<a href="#stanzas-error-conditions-remote-server-not-found">8.3.3.16.</a>&nbsp;
586remote-server-not-found<br />
587&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<a href="#stanzas-error-conditions-remote-server-timeout">8.3.3.17.</a>&nbsp;
588remote-server-timeout<br />
589&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<a href="#stanzas-error-conditions-resource-constraint">8.3.3.18.</a>&nbsp;
590resource-constraint<br />
591&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<a href="#stanzas-error-conditions-service-unavailable">8.3.3.19.</a>&nbsp;
592service-unavailable<br />
593&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<a href="#stanzas-error-conditions-subscription-required">8.3.3.20.</a>&nbsp;
594subscription-required<br />
595&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<a href="#stanzas-error-conditions-undefined-condition">8.3.3.21.</a>&nbsp;
596undefined-condition<br />
597&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<a href="#stanzas-error-conditions-unexpected-request">8.3.3.22.</a>&nbsp;
598unexpected-request<br />
599&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<a href="#stanzas-error-app">8.3.4.</a>&nbsp;
600Application-Specific Conditions<br />
601&nbsp;&nbsp;&nbsp;&nbsp;<a href="#stanzas-extended">8.4.</a>&nbsp;
602Extended Content<br />
603<a href="#examples">9.</a>&nbsp;
604Detailed Examples<br />
605&nbsp;&nbsp;&nbsp;&nbsp;<a href="#examples-c2s">9.1.</a>&nbsp;
606Client-to-Server Examples<br />
607&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<a href="#examples-c2s-tls">9.1.1.</a>&nbsp;
608TLS<br />
609&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<a href="#examples-c2s-sasl">9.1.2.</a>&nbsp;
610SASL<br />
611&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<a href="#examples-c2s-bind">9.1.3.</a>&nbsp;
612Resource Binding<br />
613&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<a href="#examples-c2s-stanzas">9.1.4.</a>&nbsp;
614Stanza Exchange<br />
615&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<a href="#examples-c2s-close">9.1.5.</a>&nbsp;
616Close<br />
617&nbsp;&nbsp;&nbsp;&nbsp;<a href="#examples-s2s">9.2.</a>&nbsp;
618Server-to-Server Examples<br />
619&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<a href="#examples-s2s-tls">9.2.1.</a>&nbsp;
620TLS<br />
621&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<a href="#examples-s2s-sasl">9.2.2.</a>&nbsp;
622SASL<br />
623&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<a href="#examples-s2s-stanzas">9.2.3.</a>&nbsp;
624Stanza Exchange<br />
625&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<a href="#examples-s2s-close">9.2.4.</a>&nbsp;
626Close<br />
627<a href="#rules">10.</a>&nbsp;
628Server Rules for Processing XML Stanzas<br />
629&nbsp;&nbsp;&nbsp;&nbsp;<a href="#rules-order">10.1.</a>&nbsp;
630In-Order Processing<br />
631&nbsp;&nbsp;&nbsp;&nbsp;<a href="#rules-gen">10.2.</a>&nbsp;
632General Considerations<br />
633&nbsp;&nbsp;&nbsp;&nbsp;<a href="#rules-noto">10.3.</a>&nbsp;
634No 'to' Address<br />
635&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<a href="#rules-noto-message">10.3.1.</a>&nbsp;
636Message<br />
637&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<a href="#rules-noto-presence">10.3.2.</a>&nbsp;
638Presence<br />
639&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<a href="#rules-noto-IQ">10.3.3.</a>&nbsp;
640IQ<br />
641&nbsp;&nbsp;&nbsp;&nbsp;<a href="#rules-remote">10.4.</a>&nbsp;
642Remote Domain<br />
643&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<a href="#rules-remote-existing">10.4.1.</a>&nbsp;
644Existing Stream<br />
645&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<a href="#rules-remote-nostream">10.4.2.</a>&nbsp;
646No Existing Stream<br />
647&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<a href="#rules-remote-error">10.4.3.</a>&nbsp;
648Error Handling<br />
649&nbsp;&nbsp;&nbsp;&nbsp;<a href="#rules-local">10.5.</a>&nbsp;
650Local Domain<br />
651&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<a href="#rules-local-domain">10.5.1.</a>&nbsp;
652domainpart<br />
653&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<a href="#rules-local-domainresource">10.5.2.</a>&nbsp;
654domainpart/resourcepart<br />
655&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<a href="#rules-local-barejid">10.5.3.</a>&nbsp;
656localpart@domainpart<br />
657&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<a href="#rules-local-barejid-nosuchuser">10.5.3.1.</a>&nbsp;
658No Such User<br />
659&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<a href="#rules-local-barejid-userexists">10.5.3.2.</a>&nbsp;
660User Exists<br />
661&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<a href="#rules-local-fulljid">10.5.4.</a>&nbsp;
662localpart@domainpart/resourcepart<br />
663<a href="#xml">11.</a>&nbsp;
664XML Usage<br />
665&nbsp;&nbsp;&nbsp;&nbsp;<a href="#xml-restrictions">11.1.</a>&nbsp;
666XML Restrictions<br />
667&nbsp;&nbsp;&nbsp;&nbsp;<a href="#xml-ns">11.2.</a>&nbsp;
668XML Namespace Names and Prefixes<br />
669&nbsp;&nbsp;&nbsp;&nbsp;<a href="#xml-wellformed">11.3.</a>&nbsp;
670Well-Formedness<br />
671&nbsp;&nbsp;&nbsp;&nbsp;<a href="#xml-validation">11.4.</a>&nbsp;
672Validation<br />
673&nbsp;&nbsp;&nbsp;&nbsp;<a href="#xml-declaration">11.5.</a>&nbsp;
674Inclusion of XML Declaration<br />
675&nbsp;&nbsp;&nbsp;&nbsp;<a href="#xml-encoding">11.6.</a>&nbsp;
676Character Encoding<br />
677&nbsp;&nbsp;&nbsp;&nbsp;<a href="#xml-whitespace">11.7.</a>&nbsp;
678Whitespace<br />
679&nbsp;&nbsp;&nbsp;&nbsp;<a href="#xml-versions">11.8.</a>&nbsp;
680XML Versions<br />
681<a href="#i18n">12.</a>&nbsp;
682Internationalization Considerations<br />
683<a href="#security">13.</a>&nbsp;
684Security Considerations<br />
685&nbsp;&nbsp;&nbsp;&nbsp;<a href="#security-fundamentals">13.1.</a>&nbsp;
686Fundamentals<br />
687&nbsp;&nbsp;&nbsp;&nbsp;<a href="#security-threats">13.2.</a>&nbsp;
688Threat Model<br />
689&nbsp;&nbsp;&nbsp;&nbsp;<a href="#security-layers">13.3.</a>&nbsp;
690Order of Layers<br />
691&nbsp;&nbsp;&nbsp;&nbsp;<a href="#security-confidentiality">13.4.</a>&nbsp;
692Confidentiality and Integrity<br />
693&nbsp;&nbsp;&nbsp;&nbsp;<a href="#security-authentication">13.5.</a>&nbsp;
694Peer Entity Authentication<br />
695&nbsp;&nbsp;&nbsp;&nbsp;<a href="#security-strong">13.6.</a>&nbsp;
696Strong Security<br />
697&nbsp;&nbsp;&nbsp;&nbsp;<a href="#security-certificates">13.7.</a>&nbsp;
698Certificates<br />
699&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<a href="#security-certificates-generation">13.7.1.</a>&nbsp;
700Certificate Generation<br />
701&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<a href="#security-certificates-generation-general">13.7.1.1.</a>&nbsp;
702General Considerations<br />
703&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<a href="#security-certificates-generation-server">13.7.1.2.</a>&nbsp;
704Server Certificates<br />
705&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<a href="#security-certificates-generation-client">13.7.1.3.</a>&nbsp;
706Client Certificates<br />
707&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<a href="#security-certificates-generation-xmppaddr">13.7.1.4.</a>&nbsp;
708XmppAddr Identifier Type<br />
709&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<a href="#security-certificates-validation">13.7.2.</a>&nbsp;
710Certificate Validation<br />
711&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<a href="#security-certificates-validation-server">13.7.2.1.</a>&nbsp;
712Server Certificates<br />
713&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<a href="#security-certificates-validation-client">13.7.2.2.</a>&nbsp;
714Client Certificates<br />
715&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<a href="#security-certificates-validation-streams">13.7.2.3.</a>&nbsp;
716Checking of Certificates in Long-Lived Streams<br />
717&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<a href="#security-certificates-validation-extensions">13.7.2.4.</a>&nbsp;
718Use of Certificates in XMPP Extensions<br />
719&nbsp;&nbsp;&nbsp;&nbsp;<a href="#security-mti">13.8.</a>&nbsp;
720Mandatory-to-Implement TLS and SASL Technologies<br />
721&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<a href="#security-mti-auth">13.8.1.</a>&nbsp;
722For Authentication Only<br />
723&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<a href="#security-mti-conf">13.8.2.</a>&nbsp;
724For Confidentiality Only<br />
725&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<a href="#security-mti-bothpass">13.8.3.</a>&nbsp;
726For Confidentiality and Authentication with Passwords<br />
727&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<a href="#security-mti-bothnopass">13.8.4.</a>&nbsp;
728For Confidentiality and Authentication without Passwords<br />
729&nbsp;&nbsp;&nbsp;&nbsp;<a href="#security-reuse">13.9.</a>&nbsp;
730Technology Reuse<br />
731&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<a href="#security-reuse-base64">13.9.1.</a>&nbsp;
732Use of Base 64 in SASL<br />
733&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<a href="#security-reuse-dns">13.9.2.</a>&nbsp;
734Use of DNS<br />
735&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<a href="#security-reuse-hash">13.9.3.</a>&nbsp;
736Use of Hash Functions<br />
737&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<a href="#security-reuse-sasl">13.9.4.</a>&nbsp;
738Use of SASL<br />
739&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<a href="#security-reuse-tls">13.9.5.</a>&nbsp;
740Use of TLS<br />
741&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<a href="#security-reuse-utf8">13.9.6.</a>&nbsp;
742Use of UTF-8<br />
743&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<a href="#security-reuse-xml">13.9.7.</a>&nbsp;
744Use of XML<br />
745&nbsp;&nbsp;&nbsp;&nbsp;<a href="#security-leaks">13.10.</a>&nbsp;
746Information Leaks<br />
747&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<a href="#security-leaks-ipaddress">13.10.1.</a>&nbsp;
748IP Addresses<br />
749&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<a href="#security-leaks-presence">13.10.2.</a>&nbsp;
750Presence Information<br />
751&nbsp;&nbsp;&nbsp;&nbsp;<a href="#security-harvesting">13.11.</a>&nbsp;
752Directory Harvesting<br />
753&nbsp;&nbsp;&nbsp;&nbsp;<a href="#security-dos">13.12.</a>&nbsp;
754Denial of Service<br />
755&nbsp;&nbsp;&nbsp;&nbsp;<a href="#security-firewalls">13.13.</a>&nbsp;
756Firewalls<br />
757&nbsp;&nbsp;&nbsp;&nbsp;<a href="#security-federation">13.14.</a>&nbsp;
758Interdomain Federation<br />
759&nbsp;&nbsp;&nbsp;&nbsp;<a href="#security-nonrepudiation">13.15.</a>&nbsp;
760Non-Repudiation<br />
761<a href="#iana">14.</a>&nbsp;
762IANA Considerations<br />
763&nbsp;&nbsp;&nbsp;&nbsp;<a href="#iana-ns-tls">14.1.</a>&nbsp;
764XML Namespace Name for TLS Data<br />
765&nbsp;&nbsp;&nbsp;&nbsp;<a href="#iana-ns-sasl">14.2.</a>&nbsp;
766XML Namespace Name for SASL Data<br />
767&nbsp;&nbsp;&nbsp;&nbsp;<a href="#iana-ns-streams">14.3.</a>&nbsp;
768XML Namespace Name for Stream Errors<br />
769&nbsp;&nbsp;&nbsp;&nbsp;<a href="#iana-ns-bind">14.4.</a>&nbsp;
770XML Namespace Name for Resource Binding<br />
771&nbsp;&nbsp;&nbsp;&nbsp;<a href="#iana-ns-stanzas">14.5.</a>&nbsp;
772XML Namespace Name for Stanza Errors<br />
773&nbsp;&nbsp;&nbsp;&nbsp;<a href="#iana-gssapi">14.6.</a>&nbsp;
774GSSAPI Service Name<br />
775&nbsp;&nbsp;&nbsp;&nbsp;<a href="#iana-ports">14.7.</a>&nbsp;
776Port Numbers and Service Names<br />
777<a href="#conformance">15.</a>&nbsp;
778Conformance Requirements<br />
779<a href="#rfc.references1">16.</a>&nbsp;
780References<br />
781&nbsp;&nbsp;&nbsp;&nbsp;<a href="#rfc.references1">16.1.</a>&nbsp;
782Normative References<br />
783&nbsp;&nbsp;&nbsp;&nbsp;<a href="#rfc.references2">16.2.</a>&nbsp;
784Informative References<br />
785<a href="#schema">Appendix&nbsp;A.</a>&nbsp;
786XML Schemas<br />
787&nbsp;&nbsp;&nbsp;&nbsp;<a href="#schemas-stream">A.1.</a>&nbsp;
788Stream Namespace<br />
789&nbsp;&nbsp;&nbsp;&nbsp;<a href="#schemas-streamerror">A.2.</a>&nbsp;
790Stream Error Namespace<br />
791&nbsp;&nbsp;&nbsp;&nbsp;<a href="#schemas-starttls">A.3.</a>&nbsp;
792STARTTLS Namespace<br />
793&nbsp;&nbsp;&nbsp;&nbsp;<a href="#schemas-sasl">A.4.</a>&nbsp;
794SASL Namespace<br />
795&nbsp;&nbsp;&nbsp;&nbsp;<a href="#schemas-client">A.5.</a>&nbsp;
796Client Namespace<br />
797&nbsp;&nbsp;&nbsp;&nbsp;<a href="#schemas-server">A.6.</a>&nbsp;
798Server Namespace<br />
799&nbsp;&nbsp;&nbsp;&nbsp;<a href="#schemas-bind">A.7.</a>&nbsp;
800Resource Binding Namespace<br />
801&nbsp;&nbsp;&nbsp;&nbsp;<a href="#schemas-stanzaerror">A.8.</a>&nbsp;
802Stanza Error Namespace<br />
803<a href="#contact">Appendix&nbsp;B.</a>&nbsp;
804Contact Addresses<br />
805<a href="#provisioning">Appendix&nbsp;C.</a>&nbsp;
806Account Provisioning<br />
807<a href="#diffs">Appendix&nbsp;D.</a>&nbsp;
808Differences from RFC 3920<br />
809<a href="#intro-ack">Appendix&nbsp;E.</a>&nbsp;
810Acknowledgements<br />
811</p>
812<br clear="all" />
813
814<a name="intro"></a><br /><hr />
815<table summary="layout" cellpadding="0" cellspacing="2" class="TOCbug" align="right"><tr><td class="TOCbug"><a href="#toc">&nbsp;TOC&nbsp;</a></td></tr></table>
816<a name="rfc.section.1"></a><h3>1.&nbsp;
817Introduction</h3>
818
819<a name="intro-overview"></a><br /><hr />
820<table summary="layout" cellpadding="0" cellspacing="2" class="TOCbug" align="right"><tr><td class="TOCbug"><a href="#toc">&nbsp;TOC&nbsp;</a></td></tr></table>
821<a name="rfc.section.1.1"></a><h3>1.1.&nbsp;
822Overview</h3>
823
824<p>The Extensible Messaging and Presence Protocol (XMPP) is an application profile of the Extensible Markup Language <a class='info' href='#XML'>[XML]<span> (</span><span class='info'>Maler, E., Yergeau, F., Sperberg-McQueen, C., Paoli, J., and T. Bray, &ldquo;Extensible Markup Language (XML) 1.0 (Fifth Edition),&rdquo; November&nbsp;2008.</span><span>)</span></a> that enables the near-real-time exchange of structured yet extensible data between any two or more network entities. This document defines XMPP's core protocol methods: setup and teardown of XML streams, channel encryption, authentication, error handling, and communication primitives for messaging, network availability ("presence"), and request-response interactions.
825</p>
826<a name="intro-history"></a><br /><hr />
827<table summary="layout" cellpadding="0" cellspacing="2" class="TOCbug" align="right"><tr><td class="TOCbug"><a href="#toc">&nbsp;TOC&nbsp;</a></td></tr></table>
828<a name="rfc.section.1.2"></a><h3>1.2.&nbsp;
829History</h3>
830
831<p>The basic syntax and semantics of XMPP were developed originally within the Jabber open-source community, mainly in 1999. In late 2002, the XMPP Working Group was chartered with developing an adaptation of the base Jabber protocol that would be suitable as an IETF instant messaging (IM) and presence technology in accordance with <a class='info' href='#IMP-REQS'>[IMP&#8209;REQS]<span> (</span><span class='info'>Day, M., Aggarwal, S., and J. Vincent, &ldquo;Instant Messaging / Presence Protocol Requirements,&rdquo; February&nbsp;2000.</span><span>)</span></a>. In October 2004, <a class='info' href='#RFC3920'>[RFC3920]<span> (</span><span class='info'>Saint-Andre, P., Ed., &ldquo;Extensible Messaging and Presence Protocol (XMPP): Core,&rdquo; October&nbsp;2004.</span><span>)</span></a> and <a class='info' href='#RFC3921'>[RFC3921]<span> (</span><span class='info'>Saint-Andre, P., Ed., &ldquo;Extensible Messaging and Presence Protocol (XMPP): Instant Messaging and Presence,&rdquo; October&nbsp;2004.</span><span>)</span></a> were published, representing the most complete definition of XMPP at that time.
832</p>
833<p>Since 2004 the Internet community has gained extensive implementation and deployment experience with XMPP, including formal interoperability testing carried out under the auspices of the XMPP Standards Foundation (XSF). This document incorporates comprehensive feedback from software developers and XMPP service providers, including a number of backward-compatible modifications summarized under <a class='info' href='#diffs'>Appendix&nbsp;D<span> (</span><span class='info'>Differences from RFC 3920</span><span>)</span></a>. As a result, this document reflects the rough consensus of the Internet community regarding the core features of XMPP 1.0, thus obsoleting RFC 3920.
834</p>
835<a name="intro-summary"></a><br /><hr />
836<table summary="layout" cellpadding="0" cellspacing="2" class="TOCbug" align="right"><tr><td class="TOCbug"><a href="#toc">&nbsp;TOC&nbsp;</a></td></tr></table>
837<a name="rfc.section.1.3"></a><h3>1.3.&nbsp;
838Functional Summary</h3>
839
840<p>This non-normative section provides a developer-friendly, functional summary of XMPP; refer to the sections that follow for a normative definition of XMPP.
841</p>
842<p>The purpose of XMPP is to enable the exchange of relatively small pieces of structured data (called "XML stanzas") over a network between any two (or more) entities. XMPP is typically implemented using a distributed client-server architecture, wherein a client needs to connect to a server in order to gain access to the network and thus be allowed to exchange XML stanzas with other entities (which can be associated with other servers). The process whereby a client connects to a server, exchanges XML stanzas, and ends the connection is:
843</p>
844<p>
845 </p>
846<ol class="text">
847<li>Determine the IP address and port at which to connect,
848 typically based on resolution of a fully qualified domain name (<a class='info' href='#tcp-resolution'>Section&nbsp;3.2<span> (</span><span class='info'>Resolution of Fully Qualified Domain Names</span><span>)</span></a>)
849</li>
850<li>Open a Transmission Control Protocol <a class='info' href='#TCP'>[TCP]<span> (</span><span class='info'>Postel, J., &ldquo;Transmission Control Protocol,&rdquo; September&nbsp;1981.</span><span>)</span></a> connection
851</li>
852<li>Open an XML stream over TCP (<a class='info' href='#streams-open'>Section&nbsp;4.2<span> (</span><span class='info'>Opening a Stream</span><span>)</span></a>)
853</li>
854<li>Preferably negotiate Transport Layer Security <a class='info' href='#TLS'>[TLS]<span> (</span><span class='info'>Dierks, T. and E. Rescorla, &ldquo;The Transport Layer Security (TLS) Protocol Version 1.2,&rdquo; August&nbsp;2008.</span><span>)</span></a> for channel encryption (<a class='info' href='#tls'>Section&nbsp;5<span> (</span><span class='info'>STARTTLS Negotiation</span><span>)</span></a>)
855</li>
856<li>Authenticate using a Simple Authentication and Security Layer <a class='info' href='#SASL'>[SASL]<span> (</span><span class='info'>Melnikov, A. and K. Zeilenga, &ldquo;Simple Authentication and Security Layer (SASL),&rdquo; June&nbsp;2006.</span><span>)</span></a> mechanism (<a class='info' href='#sasl'>Section&nbsp;6<span> (</span><span class='info'>SASL Negotiation</span><span>)</span></a>)
857</li>
858<li>Bind a resource to the stream (<a class='info' href='#bind'>Section&nbsp;7<span> (</span><span class='info'>Resource Binding</span><span>)</span></a>)
859</li>
860<li>Exchange an unbounded number of XML stanzas with other entities on the network (<a class='info' href='#stanzas'>Section&nbsp;8<span> (</span><span class='info'>XML Stanzas</span><span>)</span></a>)
861</li>
862<li>Close the XML stream (<a class='info' href='#streams-close'>Section&nbsp;4.4<span> (</span><span class='info'>Closing a Stream</span><span>)</span></a>)
863</li>
864<li>Close the TCP connection
865</li>
866</ol><p>
867
868</p>
869<p>Within XMPP, one server can optionally connect to another server to enable inter-domain or inter-server communication. For this to happen, the two servers need to negotiate a connection between themselves and then exchange XML stanzas; the process for doing so is:
870</p>
871<p>
872 </p>
873<ol class="text">
874<li>Determine the IP address and port at which to connect,
875 typically based on resolution of a fully qualified domain name (<a class='info' href='#tcp-resolution'>Section&nbsp;3.2<span> (</span><span class='info'>Resolution of Fully Qualified Domain Names</span><span>)</span></a>)
876</li>
877<li>Open a TCP connection
878</li>
879<li>Open an XML stream (<a class='info' href='#streams-open'>Section&nbsp;4.2<span> (</span><span class='info'>Opening a Stream</span><span>)</span></a>)
880</li>
881<li>Preferably negotiate TLS for channel encryption (<a class='info' href='#tls'>Section&nbsp;5<span> (</span><span class='info'>STARTTLS Negotiation</span><span>)</span></a>)
882</li>
883<li>Authenticate using a Simple Authentication and Security Layer <a class='info' href='#SASL'>[SASL]<span> (</span><span class='info'>Melnikov, A. and K. Zeilenga, &ldquo;Simple Authentication and Security Layer (SASL),&rdquo; June&nbsp;2006.</span><span>)</span></a> mechanism (<a class='info' href='#sasl'>Section&nbsp;6<span> (</span><span class='info'>SASL Negotiation</span><span>)</span></a>) *
884</li>
885<li>Exchange an unbounded number of XML stanzas both directly for the servers and indirectly on behalf of entities associated with each server, such as connected clients (<a class='info' href='#stanzas'>Section&nbsp;8<span> (</span><span class='info'>XML Stanzas</span><span>)</span></a>)
886</li>
887<li>Close the XML stream (<a class='info' href='#streams-close'>Section&nbsp;4.4<span> (</span><span class='info'>Closing a Stream</span><span>)</span></a>)
888</li>
889<li>Close the TCP connection
890</li>
891</ol><p>
892
893</p>
894<p></p>
895<blockquote class="text">
896<p>* Interoperability Note: At the time of writing, most deployed servers still use the Server Dialback protocol <a class='info' href='#XEP-0220'>[XEP&#8209;0220]<span> (</span><span class='info'>Miller, J., Saint-Andre, P., and P. Hancke, &ldquo;Server Dialback,&rdquo; March&nbsp;2010.</span><span>)</span></a> to provide weak identity verification instead of using SASL with PKIX certificates to provide strong authentication, especially in cases where SASL negotiation would not result in strong authentication anyway (e.g., because TLS negotiation was not mandated by the peer server, or because the PKIX certificate presented by the peer server during TLS negotiation is self-signed and has not been previously accepted); for details, see <a class='info' href='#XEP-0220'>[XEP&#8209;0220]<span> (</span><span class='info'>Miller, J., Saint-Andre, P., and P. Hancke, &ldquo;Server Dialback,&rdquo; March&nbsp;2010.</span><span>)</span></a>. The solutions specified in this document offer a significantly stronger level of security (see also <a class='info' href='#security-strong'>Section&nbsp;13.6<span> (</span><span class='info'>Strong Security</span><span>)</span></a>).
897</p>
898</blockquote>
899
900<p>This document specifies how clients connect to servers and specifies the basic semantics of XML stanzas. However, this document does not define the "payloads" of the XML stanzas that might be exchanged once a connection is successfully established; instead, those payloads are defined by various XMPP extensions. For example, <a class='info' href='#XMPP-IM'>[XMPP&#8209;IM]<span> (</span><span class='info'>Saint-Andre, P., &ldquo;Extensible Messaging and Presence Protocol (XMPP): Instant Messaging and Presence,&rdquo; March&nbsp;2011.</span><span>)</span></a> defines extensions for basic instant messaging and presence functionality. In addition, various specifications produced in the XSF's XEP series <a class='info' href='#XEP-0001'>[XEP&#8209;0001]<span> (</span><span class='info'>Saint-Andre, P., &ldquo;XMPP Extension Protocols,&rdquo; March&nbsp;2010.</span><span>)</span></a> define extensions for a wide range of applications.
901</p>
902<a name="intro-terms"></a><br /><hr />
903<table summary="layout" cellpadding="0" cellspacing="2" class="TOCbug" align="right"><tr><td class="TOCbug"><a href="#toc">&nbsp;TOC&nbsp;</a></td></tr></table>
904<a name="rfc.section.1.4"></a><h3>1.4.&nbsp;
905Terminology</h3>
906
907<p>The key words "MUST", "MUST NOT", "REQUIRED", "SHALL", "SHALL NOT", "SHOULD", "SHOULD NOT", "RECOMMENDED", "NOT RECOMMENDED", "MAY", and "OPTIONAL" in this document are to be interpreted as described in RFC 2119 <a class='info' href='#KEYWORDS'>[KEYWORDS]<span> (</span><span class='info'>Bradner, S., &ldquo;Key words for use in RFCs to Indicate Requirement Levels,&rdquo; March&nbsp;1997.</span><span>)</span></a>.
908</p>
909<p>Certain security-related terms are to be understood in the sense defined in <a class='info' href='#SEC-TERMS'>[SEC&#8209;TERMS]<span> (</span><span class='info'>Shirey, R., &ldquo;Internet Security Glossary, Version 2,&rdquo; August&nbsp;2007.</span><span>)</span></a>; such terms include, but are not limited to, "assurance", "attack", "authentication", "authorization", "certificate", "certification authority", "certification path", "confidentiality", "credential", "downgrade", "encryption", "hash value", "identity", "integrity", "signature", "self-signed certificate", "sign", "spoof", "tamper", "trust", "trust anchor", "validate", and "verify".
910</p>
911<p>Certain terms related to certificates, domains, and application service identity are to be understood in the sense defined in <a class='info' href='#TLS-CERTS'>[TLS&#8209;CERTS]<span> (</span><span class='info'>Saint-Andre, P. and J. Hodges, &ldquo;Representation and Verification of Domain-Based Application Service Identity within Internet Public Key Infrastructure Using X.509 (PKIX) Certificates in the Context of Transport Layer Security (TLS),&rdquo; March&nbsp;2011.</span><span>)</span></a>; these include, but are not limited to, "PKIX certificate", "source domain", "derived domain", and the identifier types "CN-ID", "DNS-ID", and "SRV-ID".
912</p>
913<p>Other security-related terms are to be understood in the sense defined in the referenced specifications (for example, "denial of service" as described in <a class='info' href='#DOS'>[DOS]<span> (</span><span class='info'>Handley, M., Rescorla, E., and IAB, &ldquo;Internet Denial-of-Service Considerations,&rdquo; December&nbsp;2006.</span><span>)</span></a> or "end entity certificate" as described in <a class='info' href='#PKIX'>[PKIX]<span> (</span><span class='info'>Cooper, D., Santesson, S., Farrell, S., Boeyen, S., Housley, R., and W. Polk, &ldquo;Internet X.509 Public Key Infrastructure Certificate and Certificate Revocation List (CRL) Profile,&rdquo; May&nbsp;2008.</span><span>)</span></a>).
914</p>
915<p>The term "whitespace" is used to refer to any character or characters matching the "S" production from <a class='info' href='#XML'>[XML]<span> (</span><span class='info'>Maler, E., Yergeau, F., Sperberg-McQueen, C., Paoli, J., and T. Bray, &ldquo;Extensible Markup Language (XML) 1.0 (Fifth Edition),&rdquo; November&nbsp;2008.</span><span>)</span></a>, i.e., one or more instances of the SP, HTAB, CR, or LF rules defined in <a class='info' href='#ABNF'>[ABNF]<span> (</span><span class='info'>Crocker, D. and P. Overell, &ldquo;Augmented BNF for Syntax Specifications: ABNF,&rdquo; January&nbsp;2008.</span><span>)</span></a>.
916</p>
917<p>The terms "localpart", "domainpart", and "resourcepart" are defined in <a class='info' href='#XMPP-ADDR'>[XMPP&#8209;ADDR]<span> (</span><span class='info'>Saint-Andre, P., &ldquo;Extensible Messaging and Presence Protocol (XMPP): Address Format,&rdquo; March&nbsp;2011.</span><span>)</span></a>.
918</p>
919<p>The term "bare JID" refers to an XMPP address of the form &lt;localpart@domainpart&gt; (for an account at a server) or of the form &lt;domainpart&gt; (for a server).
920</p>
921<p>The term "full JID" refers to an XMPP address of the form &lt;localpart@domainpart/resourcepart&gt; (for a particular authorized client or device associated with an account) or of the form &lt;domainpart/resourcepart&gt; (for a particular resource or script associated with a server).
922</p>
923<p>The term "XML stream" (also "stream") is defined under <a class='info' href='#streams-fundamentals'>Section&nbsp;4.1<span> (</span><span class='info'>Stream Fundamentals</span><span>)</span></a>.
924</p>
925<p>The term "XML stanza" (also "stanza") is defined under <a class='info' href='#streams-fundamentals'>Section&nbsp;4.1<span> (</span><span class='info'>Stream Fundamentals</span><span>)</span></a>. There are three kinds of stanzas: message,
926presence, and IQ (short for "Info/Query"). These communication primitives are
927defined under Sections <a class='info' href='#stanzas-semantics-message'>8.2.1<span> (</span><span class='info'>Message Semantics</span><span>)</span></a>, <a class='info' href='#stanzas-semantics-presence'>8.2.2<span> (</span><span class='info'>Presence Semantics</span><span>)</span></a>, and <a class='info' href='#stanzas-semantics-iq'>8.2.3<span> (</span><span class='info'>IQ Semantics</span><span>)</span></a>, respectively.
928</p>
929<p>The term "originating entity" refers to the entity that first generates a stanza that is sent over an XMPP network (e.g., a connected client, an add-on service, or a server). The term "generated stanza" refers to the stanza so generated.
930</p>
931<p>The term "input stream" designates an XML stream over which a server receives data from a connected client or remote server, and the term "output stream" designates an XML stream over which a server sends data to a connected client or remote server. The following terms designate some of the actions that a server can perform when processing data received over an input stream:
932</p>
933<p>
934 </p>
935<blockquote class="text">
936<p>
937 </p>
938<blockquote class="text"><dl>
939<dt>route:</dt>
940<dd>pass the data to a remote server for direct processing by the remote server or eventual delivery to a client associated with the remote server
941</dd>
942<dt>deliver:</dt>
943<dd>pass the data to a connected client
944</dd>
945<dt>ignore:</dt>
946<dd>discard the data without acting upon it or returning an error to the sender
947</dd>
948</dl></blockquote>
949
950
951</blockquote><p>
952
953</p>
954<p>When the term "ignore" is used with regard to client processing of data it receives, the phrase "without acting upon it" explicitly includes not presenting the data to a human user.
955</p>
956<p>Following the "XML Notation" used in <a class='info' href='#IRI'>[IRI]<span> (</span><span class='info'>Duerst, M. and M. Suignard, &ldquo;Internationalized Resource Identifiers (IRIs),&rdquo; January&nbsp;2005.</span><span>)</span></a> to represent characters that cannot be rendered in ASCII-only documents, some examples in this document use the form "&amp;#x...." as a notational device to represent <a class='info' href='#UNICODE'>[UNICODE]<span> (</span><span class='info'>The Unicode Consortium, &ldquo;The Unicode Standard, Version 6.0,&rdquo; 2010.</span><span>)</span></a> characters (e.g., the string "&amp;#x0159;" stands for the Unicode character LATIN SMALL LETTER R WITH CARON); this form is definitely not to be sent over the wire in XMPP systems.
957</p>
958<p>Consistent with the convention used in <a class='info' href='#URI'>[URI]<span> (</span><span class='info'>Berners-Lee, T., Fielding, R., and L. Masinter, &ldquo;Uniform Resource Identifier (URI): Generic Syntax,&rdquo; January&nbsp;2005.</span><span>)</span></a>
959 to represent Uniform Resource Identifiers, XMPP addresses in running text are enclosed between '&lt;' and '&gt;' (although natively they are not URIs).
960</p>
961<p>In examples, lines have been wrapped for improved readability, "[...]" means elision, and the following prepended strings are used (these prepended strings are not to be sent over the wire):
962</p>
963<p>
964 </p>
965<ul class="text">
966<li>C: = a client
967</li>
968<li>E: = any XMPP entity
969</li>
970<li>I: = an initiating entity
971</li>
972<li>P: = a peer server
973</li>
974<li>R: = a receiving entity
975</li>
976<li>S: = a server
977</li>
978<li>S1: = server1
979</li>
980<li>S2: = server2
981</li>
982</ul><p>
983
984</p>
985<p>Readers need to be aware that the examples are not exhaustive and that, in examples for some protocol flows, the alternate steps shown would not necessarily be triggered by the exact data sent in the previous step; in all cases the protocol definitions specified in this document or in normatively referenced documents rule over any examples provided here. All examples are fictional and the information exchanged (e.g., usernames and passwords) does not represent any existing users or servers.
986</p>
987<a name="arch"></a><br /><hr />
988<table summary="layout" cellpadding="0" cellspacing="2" class="TOCbug" align="right"><tr><td class="TOCbug"><a href="#toc">&nbsp;TOC&nbsp;</a></td></tr></table>
989<a name="rfc.section.2"></a><h3>2.&nbsp;
990Architecture</h3>
991
992<p>XMPP provides a technology for the asynchronous, end-to-end
993 exchange of structured data by means of direct, persistent XML
994 streams among a distributed network of globally addressable, presence-aware clients and servers. Because this architectural style involves ubiquitous knowledge of network availability and a conceptually unlimited number of concurrent information transactions in the context of a given client-to-server or server-to-server session, we label it "Availability for Concurrent Transactions" (ACT) to distinguish it from the "Representational State Transfer" <a class='info' href='#REST'>[REST]<span> (</span><span class='info'>Fielding, R., &ldquo;Architectural Styles and the Design of Network-based Software Architectures,&rdquo; .</span><span>)</span></a> architectural style familiar from the World Wide Web. &nbsp;Although the architecture of XMPP is similar in important ways to that of email (see <a class='info' href='#EMAIL-ARCH'>[EMAIL&#8209;ARCH]<span> (</span><span class='info'>Crocker, D., &ldquo;Internet Mail Architecture,&rdquo; July&nbsp;2009.</span><span>)</span></a>), it introduces several modifications to facilitate communication in close to real time. The salient features of this ACTive architectural style are as follows.
995</p>
996<a name="arch-addresses"></a><br /><hr />
997<table summary="layout" cellpadding="0" cellspacing="2" class="TOCbug" align="right"><tr><td class="TOCbug"><a href="#toc">&nbsp;TOC&nbsp;</a></td></tr></table>
998<a name="rfc.section.2.1"></a><h3>2.1.&nbsp;
999Global Addresses</h3>
1000
1001<p>As with email, XMPP uses globally unique addresses (based on the Domain Name System) in order to route and deliver messages over the network. All XMPP entities are addressable on the network, most particularly clients and servers but also various additional services that can be accessed by clients and servers. In general, server addresses are of the form &lt;domainpart&gt; (e.g., &lt;im.example.com&gt;), accounts hosted at a server are of the form &lt;localpart@domainpart&gt; (e.g., &lt;juliet@im.example.com&gt;, called a "bare JID"), and a particular connected device or resource that is currently authorized for interaction on behalf of an account is of the form &lt;localpart@domainpart/resourcepart&gt; (e.g., &lt;juliet@im.example.com/balcony&gt;, called a "full JID"). For historical reasons, XMPP addresses are often called Jabber IDs or JIDs. Because the formal specification of the XMPP address format depends on internationalization technologies that are in flux at the time of writing, the format is defined in <a class='info' href='#XMPP-ADDR'>[XMPP&#8209;ADDR]<span> (</span><span class='info'>Saint-Andre, P., &ldquo;Extensible Messaging and Presence Protocol (XMPP): Address Format,&rdquo; March&nbsp;2011.</span><span>)</span></a> instead of this document. The terms "localpart", "domainpart", and "resourcepart" are defined more formally in <a class='info' href='#XMPP-ADDR'>[XMPP&#8209;ADDR]<span> (</span><span class='info'>Saint-Andre, P., &ldquo;Extensible Messaging and Presence Protocol (XMPP): Address Format,&rdquo; March&nbsp;2011.</span><span>)</span></a>.
1002</p>
1003<a name="arch-presence"></a><br /><hr />
1004<table summary="layout" cellpadding="0" cellspacing="2" class="TOCbug" align="right"><tr><td class="TOCbug"><a href="#toc">&nbsp;TOC&nbsp;</a></td></tr></table>
1005<a name="rfc.section.2.2"></a><h3>2.2.&nbsp;
1006Presence</h3>
1007
1008<p>XMPP includes the ability for an entity to advertise its network availability or "presence" to other entities. In XMPP, this availability for communication is signaled end-to-end by means of a dedicated communication primitive: the &lt;presence/&gt; stanza. Although knowledge of network availability is not strictly necessary for the exchange of XMPP messages, it facilitates real-time interaction because the originator of a message can know before initiating communication that the intended recipient is online and available. End-to-end presence is defined in <a class='info' href='#XMPP-IM'>[XMPP&#8209;IM]<span> (</span><span class='info'>Saint-Andre, P., &ldquo;Extensible Messaging and Presence Protocol (XMPP): Instant Messaging and Presence,&rdquo; March&nbsp;2011.</span><span>)</span></a>.
1009</p>
1010<a name="arch-streams"></a><br /><hr />
1011<table summary="layout" cellpadding="0" cellspacing="2" class="TOCbug" align="right"><tr><td class="TOCbug"><a href="#toc">&nbsp;TOC&nbsp;</a></td></tr></table>
1012<a name="rfc.section.2.3"></a><h3>2.3.&nbsp;
1013Persistent Streams</h3>
1014
1015<p>Availability for communication is also built into each point-to-point "hop" through the use of persistent XML streams over long-lived TCP connections. These "always-on" client-to-server and server-to-server streams enable each party to push data to the other party at any time for immediate routing or delivery. XML streams are defined under <a class='info' href='#streams'>Section&nbsp;4<span> (</span><span class='info'>XML Streams</span><span>)</span></a>.
1016</p>
1017<a name="arch-data"></a><br /><hr />
1018<table summary="layout" cellpadding="0" cellspacing="2" class="TOCbug" align="right"><tr><td class="TOCbug"><a href="#toc">&nbsp;TOC&nbsp;</a></td></tr></table>
1019<a name="rfc.section.2.4"></a><h3>2.4.&nbsp;
1020Structured Data</h3>
1021
1022<p>The basic protocol data unit in XMPP is not an XML stream (which simply provides the transport for point-to-point communication) but an XML "stanza", which is essentially a fragment of XML that is sent over a stream. The root element of a stanza includes routing attributes (such as "from" and "to" addresses), and the child elements of the stanza contain a payload for delivery to the intended recipient. XML stanzas are defined under <a class='info' href='#stanzas'>Section&nbsp;8<span> (</span><span class='info'>XML Stanzas</span><span>)</span></a>.
1023</p>
1024<a name="arch-network"></a><br /><hr />
1025<table summary="layout" cellpadding="0" cellspacing="2" class="TOCbug" align="right"><tr><td class="TOCbug"><a href="#toc">&nbsp;TOC&nbsp;</a></td></tr></table>
1026<a name="rfc.section.2.5"></a><h3>2.5.&nbsp;
1027Distributed Network of Clients and Servers</h3>
1028
1029<p>In practice, XMPP consists of a network of clients and servers that inter-communicate (however, communication between any two given deployed servers is strictly discretionary and a matter of local service policy). Thus, for example, the user &lt;juliet@im.example.com&gt; associated with the server &lt;im.example.com&gt; might be able to exchange messages, presence, and other structured data with the user &lt;romeo@example.net&gt; associated with the server &lt;example.net&gt;. This pattern is familiar from messaging protocols that make use of global addresses, such as the email network (see <a class='info' href='#SMTP'>[SMTP]<span> (</span><span class='info'>Klensin, J., &ldquo;Simple Mail Transfer Protocol,&rdquo; October&nbsp;2008.</span><span>)</span></a> and <a class='info' href='#EMAIL-ARCH'>[EMAIL&#8209;ARCH]<span> (</span><span class='info'>Crocker, D., &ldquo;Internet Mail Architecture,&rdquo; July&nbsp;2009.</span><span>)</span></a>). As a result, end-to-end communication in XMPP is logically peer-to-peer but physically client-to-server-to-server-to-client, as illustrated in the following diagram.
1030</p><br /><hr class="insert" />
1031<a name="figure-1"></a>
1032<div style='display: table; width: 0; margin-left: 3em; margin-right: auto'><pre>
1033 example.net &lt;--------------&gt; im.example.com
1034 ^ ^
1035 | |
1036 v v
1037romeo@example.net juliet@im.example.com
1038
1039</pre></div><table border="0" cellpadding="0" cellspacing="2" align="center"><tr><td align="center"><font face="monaco, MS Sans Serif" size="1"><b>&nbsp;Figure&nbsp;1: Distributed Client-Server Architecture&nbsp;</b></font><br /></td></tr></table><hr class="insert" />
1040
1041<p></p>
1042<blockquote class="text">
1043<p>Informational Note: Architectures that employ <a class='info' href='#streams'>XML streams<span> (</span><span class='info'>XML Streams</span><span>)</span></a> and <a class='info' href='#stanzas'>XML stanzas<span> (</span><span class='info'>XML Stanzas</span><span>)</span></a> but that establish peer-to-peer connections directly between clients using technologies based on <a class='info' href='#LINKLOCAL'>[LINKLOCAL]<span> (</span><span class='info'>Cheshire, S., Aboba, B., and E. Guttman, &ldquo;Dynamic Configuration of IPv4 Link-Local Addresses,&rdquo; May&nbsp;2005.</span><span>)</span></a> have been deployed, but such architectures are not defined in this specification and are best described as "XMPP-like"; for details, see <a class='info' href='#XEP-0174'>[XEP&#8209;0174]<span> (</span><span class='info'>Saint-Andre, P., &ldquo;Link-Local Messaging,&rdquo; November&nbsp;2008.</span><span>)</span></a>. In addition, XML streams can be established end-to-end over any reliable transport, including extensions to XMPP itself; however, such methods are out of scope for this specification.
1044</p>
1045</blockquote>
1046
1047<p>The following paragraphs describe the responsibilities of clients and servers on the network.
1048</p>
1049<p>A client is an entity that establishes an XML stream with a server by authenticating using the credentials of a registered account (via <a class='info' href='#sasl'>SASL negotiation<span> (</span><span class='info'>SASL Negotiation</span><span>)</span></a>) and that then completes <a class='info' href='#bind'>resource binding<span> (</span><span class='info'>Resource Binding</span><span>)</span></a> in order to enable delivery of XML stanzas between the server and the client over the negotiated stream. The client then uses XMPP to communicate with its server, other clients, and any other entities on the network, where the server is responsible for delivering stanzas to other connected clients at the same server or routing them to remote servers. Multiple clients can connect simultaneously to a server on behalf of the same registered account, where each client is differentiated by the resourcepart of an XMPP address (e.g., &lt;juliet@im.example.com/balcony&gt; vs. &lt;juliet@im.example.com/chamber&gt;), as defined under <a class='info' href='#XMPP-ADDR'>[XMPP&#8209;ADDR]<span> (</span><span class='info'>Saint-Andre, P., &ldquo;Extensible Messaging and Presence Protocol (XMPP): Address Format,&rdquo; March&nbsp;2011.</span><span>)</span></a> and <a class='info' href='#bind'>Section&nbsp;7<span> (</span><span class='info'>Resource Binding</span><span>)</span></a>.
1050</p>
1051<p>A server is an entity whose primary responsibilities are to:
1052</p>
1053<p>
1054 </p>
1055<ul class="text">
1056<li>Manage <a class='info' href='#streams'>XML streams<span> (</span><span class='info'>XML Streams</span><span>)</span></a> with connected clients and deliver <a class='info' href='#stanzas'>XML stanzas<span> (</span><span class='info'>XML Stanzas</span><span>)</span></a> to those clients over the negotiated streams; this includes responsibility for ensuring that a client authenticates with the server before being granted access to the XMPP network.
1057</li>
1058<li>Subject to local service policies on server-to-server communication, manage <a class='info' href='#streams'>XML streams<span> (</span><span class='info'>XML Streams</span><span>)</span></a> with remote servers and route <a class='info' href='#stanzas'>XML stanzas<span> (</span><span class='info'>XML Stanzas</span><span>)</span></a> to those servers over the negotiated streams.
1059</li>
1060</ul><p>
1061
1062</p>
1063<p>Depending on the application, the secondary responsibilities of an XMPP server can include:
1064</p>
1065<p>
1066 </p>
1067<ul class="text">
1068<li>Storing data that is used by clients (e.g., contact lists for users of XMPP-based instant messaging and presence applications as defined in <a class='info' href='#XMPP-IM'>[XMPP&#8209;IM]<span> (</span><span class='info'>Saint-Andre, P., &ldquo;Extensible Messaging and Presence Protocol (XMPP): Instant Messaging and Presence,&rdquo; March&nbsp;2011.</span><span>)</span></a>); in this case, the relevant XML stanza is handled directly by the server itself on behalf of the client and is not routed to a remote server or delivered to a connected client.
1069</li>
1070<li>Hosting add-on services that also use XMPP as the basis for communication but that provide additional functionality beyond that defined in this document or in <a class='info' href='#XMPP-IM'>[XMPP&#8209;IM]<span> (</span><span class='info'>Saint-Andre, P., &ldquo;Extensible Messaging and Presence Protocol (XMPP): Instant Messaging and Presence,&rdquo; March&nbsp;2011.</span><span>)</span></a>; examples include multi-user conferencing services as specified in <a class='info' href='#XEP-0045'>[XEP&#8209;0045]<span> (</span><span class='info'>Saint-Andre, P., &ldquo;Multi-User Chat,&rdquo; July&nbsp;2007.</span><span>)</span></a> and publish-subscribe services as specified in <a class='info' href='#XEP-0060'>[XEP&#8209;0060]<span> (</span><span class='info'>Millard, P., Saint-Andre, P., and R. Meijer, &ldquo;Publish-Subscribe,&rdquo; July&nbsp;2010.</span><span>)</span></a>.
1071</li>
1072</ul><p>
1073
1074</p>
1075<a name="tcp"></a><br /><hr />
1076<table summary="layout" cellpadding="0" cellspacing="2" class="TOCbug" align="right"><tr><td class="TOCbug"><a href="#toc">&nbsp;TOC&nbsp;</a></td></tr></table>
1077<a name="rfc.section.3"></a><h3>3.&nbsp;
1078TCP Binding</h3>
1079
1080<a name="tcp-scope"></a><br /><hr />
1081<table summary="layout" cellpadding="0" cellspacing="2" class="TOCbug" align="right"><tr><td class="TOCbug"><a href="#toc">&nbsp;TOC&nbsp;</a></td></tr></table>
1082<a name="rfc.section.3.1"></a><h3>3.1.&nbsp;
1083Scope</h3>
1084
1085<p>As XMPP is defined in this specification, an initiating entity (client or server) MUST open a Transmission Control Protocol <a class='info' href='#TCP'>[TCP]<span> (</span><span class='info'>Postel, J., &ldquo;Transmission Control Protocol,&rdquo; September&nbsp;1981.</span><span>)</span></a> connection to the receiving entity (server) before it negotiates XML streams with the receiving entity. The parties then maintain that TCP connection for as long as the XML streams are in use. The rules specified in the following sections apply to the TCP binding.
1086</p>
1087<p></p>
1088<blockquote class="text">
1089<p>Informational Note: There is no necessary coupling of XML streams to TCP, and other transports are possible. For example, two entities could connect to each other by means of <a class='info' href='#HTTP'>[HTTP]<span> (</span><span class='info'>Fielding, R., Gettys, J., Mogul, J., Frystyk, H., Masinter, L., Leach, P., and T. Berners-Lee, &ldquo;Hypertext Transfer Protocol -- HTTP/1.1,&rdquo; June&nbsp;1999.</span><span>)</span></a> as specified in <a class='info' href='#XEP-0124'>[XEP&#8209;0124]<span> (</span><span class='info'>Paterson, I., Smith, D., and P. Saint-Andre, &ldquo;Bidirectional-streams Over Synchronous HTTP (BOSH),&rdquo; July&nbsp;2010.</span><span>)</span></a> and <a class='info' href='#XEP-0206'>[XEP&#8209;0206]<span> (</span><span class='info'>Paterson, I. and P. Saint-Andre, &ldquo;XMPP Over BOSH,&rdquo; July&nbsp;2010.</span><span>)</span></a>. However, this specification defines only a binding of XMPP to TCP.
1090</p>
1091</blockquote>
1092
1093<a name="tcp-resolution"></a><br /><hr />
1094<table summary="layout" cellpadding="0" cellspacing="2" class="TOCbug" align="right"><tr><td class="TOCbug"><a href="#toc">&nbsp;TOC&nbsp;</a></td></tr></table>
1095<a name="rfc.section.3.2"></a><h3>3.2.&nbsp;
1096Resolution of Fully Qualified Domain Names</h3>
1097
1098<p>Because XML streams are sent over TCP, the initiating entity
1099 needs to determine the IPv4 or IPv6 address (and port) of the
1100 receiving entity before it can attempt to open an XML stream.
1101 Typically this is done by resolving the receiving entity's fully
1102 qualified domain name or FQDN (see <a class='info' href='#DNS-CONCEPTS'>[DNS&#8209;CONCEPTS]<span> (</span><span class='info'>Mockapetris, P., &ldquo;Domain names - concepts and facilities,&rdquo; November&nbsp;1987.</span><span>)</span></a>).
1103</p>
1104<a name="tcp-resolution-prefer"></a><br /><hr />
1105<table summary="layout" cellpadding="0" cellspacing="2" class="TOCbug" align="right"><tr><td class="TOCbug"><a href="#toc">&nbsp;TOC&nbsp;</a></td></tr></table>
1106<a name="rfc.section.3.2.1"></a><h3>3.2.1.&nbsp;
1107Preferred Process: SRV Lookup</h3>
1108
1109<p>The preferred process for FQDN resolution is to use <a class='info' href='#DNS-SRV'>[DNS&#8209;SRV]<span> (</span><span class='info'>Gulbrandsen, A., Vixie, P., and L. Esibov, &ldquo;A DNS RR for specifying the location of services (DNS SRV),&rdquo; February&nbsp;2000.</span><span>)</span></a> records as follows:
1110</p>
1111<p>
1112 </p>
1113<ol class="text">
1114<li>The initiating entity constructs a DNS SRV query whose inputs are:
1115
1116<ul class="text">
1117<li>a Service of "xmpp-client" (for client-to-server connections) or "xmpp-server" (for server-to-server connections)
1118</li>
1119<li>a Proto of "tcp"
1120</li>
1121<li>a Name corresponding to the "origin domain" <a class='info' href='#TLS-CERTS'>[TLS&#8209;CERTS]<span> (</span><span class='info'>Saint-Andre, P. and J. Hodges, &ldquo;Representation and Verification of Domain-Based Application Service Identity within Internet Public Key Infrastructure Using X.509 (PKIX) Certificates in the Context of Transport Layer Security (TLS),&rdquo; March&nbsp;2011.</span><span>)</span></a> of the XMPP service to which the initiating entity wishes to connect (e.g., "example.net" or "im.example.com")
1122</li>
1123</ul>
1124
1125</li>
1126<li>The result is a query such as "_xmpp-client._tcp.example.net." or "_xmpp-server._tcp.im.example.com.".
1127</li>
1128<li>
1129 If a response is received, it will contain one or more combinations of a port and FDQN, each of which is weighted and prioritized as described in <a class='info' href='#DNS-SRV'>[DNS&#8209;SRV]<span> (</span><span class='info'>Gulbrandsen, A., Vixie, P., and L. Esibov, &ldquo;A DNS RR for specifying the location of services (DNS SRV),&rdquo; February&nbsp;2000.</span><span>)</span></a>.
1130
1131 (However, if the result of the SRV lookup is a single resource record with a Target of ".", i.e., the root domain, then the initiating entity MUST abort SRV processing at this point because according to <a class='info' href='#DNS-SRV'>[DNS&#8209;SRV]<span> (</span><span class='info'>Gulbrandsen, A., Vixie, P., and L. Esibov, &ldquo;A DNS RR for specifying the location of services (DNS SRV),&rdquo; February&nbsp;2000.</span><span>)</span></a> such a Target "means that the service is decidedly not available at this domain".)
1132
1133</li>
1134<li>The initiating entity chooses at least one of the returned FQDNs to resolve (following the rules in <a class='info' href='#DNS-SRV'>[DNS&#8209;SRV]<span> (</span><span class='info'>Gulbrandsen, A., Vixie, P., and L. Esibov, &ldquo;A DNS RR for specifying the location of services (DNS SRV),&rdquo; February&nbsp;2000.</span><span>)</span></a>), which it does by performing DNS "A" or "AAAA" lookups on the FDQN; this will result in an IPv4 or IPv6 address.
1135</li>
1136<li>The initiating entity uses the IP address(es) from the successfully resolved FDQN (with the corresponding port number returned by the SRV lookup) as the connection address for the receiving entity.
1137</li>
1138<li>If the initiating entity fails to connect using that IP address but the "A" or "AAAA" lookups returned more than one IP address, then the initiating entity uses the next resolved IP address for that FDQN as the connection address.
1139</li>
1140<li>If the initiating entity fails to connect using all resolved IP addresses for a given FDQN, then it repeats the process of resolution and connection for the next FQDN returned by the SRV lookup based on the priority and weight as defined in <a class='info' href='#DNS-SRV'>[DNS&#8209;SRV]<span> (</span><span class='info'>Gulbrandsen, A., Vixie, P., and L. Esibov, &ldquo;A DNS RR for specifying the location of services (DNS SRV),&rdquo; February&nbsp;2000.</span><span>)</span></a>.
1141</li>
1142<li>If the initiating entity receives a response to its SRV query but it is not able to establish an XMPP connection using the data received in the response, it SHOULD NOT attempt the fallback process described in the next section (this helps to prevent a state mismatch between inbound and outbound connections).
1143</li>
1144<li>If the initiating entity does not receive a response to its SRV query, it SHOULD attempt the fallback process described in the next section.
1145</li>
1146</ol><p>
1147
1148</p>
1149<a name="tcp-resolution-fallback"></a><br /><hr />
1150<table summary="layout" cellpadding="0" cellspacing="2" class="TOCbug" align="right"><tr><td class="TOCbug"><a href="#toc">&nbsp;TOC&nbsp;</a></td></tr></table>
1151<a name="rfc.section.3.2.2"></a><h3>3.2.2.&nbsp;
1152Fallback Processes</h3>
1153
1154<p>The fallback process SHOULD be a normal "A" or "AAAA" address record resolution to determine the IPv4 or IPv6 address of the origin domain, where the port used is the "xmpp-client" port of 5222 for client-to-server connections or the "xmpp-server" port of 5269 for server-to-server connections (these are the default ports as registered with the IANA as described under <a class='info' href='#iana-ports'>Section&nbsp;14.7<span> (</span><span class='info'>Port Numbers and Service Names</span><span>)</span></a>).
1155</p>
1156<p>If connections via TCP are unsuccessful, the initiating entity might attempt to find and use alternative connection methods such as the HTTP binding (see <a class='info' href='#XEP-0124'>[XEP&#8209;0124]<span> (</span><span class='info'>Paterson, I., Smith, D., and P. Saint-Andre, &ldquo;Bidirectional-streams Over Synchronous HTTP (BOSH),&rdquo; July&nbsp;2010.</span><span>)</span></a> and <a class='info' href='#XEP-0206'>[XEP&#8209;0206]<span> (</span><span class='info'>Paterson, I. and P. Saint-Andre, &ldquo;XMPP Over BOSH,&rdquo; July&nbsp;2010.</span><span>)</span></a>), which might be discovered using <a class='info' href='#DNS-TXT'>[DNS&#8209;TXT]<span> (</span><span class='info'>Rosenbaum, R., &ldquo;Using the Domain Name System To Store Arbitrary String Attributes,&rdquo; May&nbsp;1993.</span><span>)</span></a> records as described in <a class='info' href='#XEP-0156'>[XEP&#8209;0156]<span> (</span><span class='info'>Hildebrand, J. and P. Saint-Andre, &ldquo;Discovering Alternative XMPP Connection Methods,&rdquo; June&nbsp;2007.</span><span>)</span></a>.
1157</p>
1158<a name="tcp-resolution-srvnot"></a><br /><hr />
1159<table summary="layout" cellpadding="0" cellspacing="2" class="TOCbug" align="right"><tr><td class="TOCbug"><a href="#toc">&nbsp;TOC&nbsp;</a></td></tr></table>
1160<a name="rfc.section.3.2.3"></a><h3>3.2.3.&nbsp;
1161When Not to Use SRV</h3>
1162
1163<p>If the initiating entity has been explicitly configured to associate a particular FQDN (and potentially port) with the origin domain of the receiving entity (say, to "hardcode" an association from an origin domain of example.net to a configured FQDN of apps.example.com), the initiating entity is encouraged to use the configured name instead of performing the preferred SRV resolution process on the origin domain.
1164</p>
1165<a name="tcp-resolution-srvadd"></a><br /><hr />
1166<table summary="layout" cellpadding="0" cellspacing="2" class="TOCbug" align="right"><tr><td class="TOCbug"><a href="#toc">&nbsp;TOC&nbsp;</a></td></tr></table>
1167<a name="rfc.section.3.2.4"></a><h3>3.2.4.&nbsp;
1168Use of SRV Records with Add-On Services</h3>
1169
1170<p>Many XMPP servers are implemented in such a way that they can host add-on services (beyond those defined in this specification and <a class='info' href='#XMPP-IM'>[XMPP&#8209;IM]<span> (</span><span class='info'>Saint-Andre, P., &ldquo;Extensible Messaging and Presence Protocol (XMPP): Instant Messaging and Presence,&rdquo; March&nbsp;2011.</span><span>)</span></a>) at DNS domain names that typically are "subdomains" of the main XMPP service (e.g., conference.example.net for a <a class='info' href='#XEP-0045'>[XEP&#8209;0045]<span> (</span><span class='info'>Saint-Andre, P., &ldquo;Multi-User Chat,&rdquo; July&nbsp;2007.</span><span>)</span></a> service associated with the example.net XMPP service) or "subdomains" of the first-level domain of the underlying service (e.g., muc.example.com for a <a class='info' href='#XEP-0045'>[XEP&#8209;0045]<span> (</span><span class='info'>Saint-Andre, P., &ldquo;Multi-User Chat,&rdquo; July&nbsp;2007.</span><span>)</span></a> service associated with the im.example.com XMPP service). If an entity associated with a remote XMPP server wishes to communicate with such an add-on service, it would generate an appropriate XML stanza and the remote server would attempt to resolve the add-on service's DNS domain name via an SRV lookup on resource records such as "_xmpp-server._tcp.conference.example.net." or "_xmpp-server._tcp.muc.example.com.". Therefore, if the administrators of an XMPP service wish to enable entities associated with remote servers to access such add-on services, they need to advertise the appropriate "_xmpp-server" SRV records in addition to the "_xmpp-server" record for their main XMPP service. In case SRV records are not available, the fallback methods described under <a class='info' href='#tcp-resolution-fallback'>Section&nbsp;3.2.2<span> (</span><span class='info'>Fallback Processes</span><span>)</span></a> can be used to resolve the DNS domain names of add-on services.
1171</p>
1172<a name="tcp-reconnect"></a><br /><hr />
1173<table summary="layout" cellpadding="0" cellspacing="2" class="TOCbug" align="right"><tr><td class="TOCbug"><a href="#toc">&nbsp;TOC&nbsp;</a></td></tr></table>
1174<a name="rfc.section.3.3"></a><h3>3.3.&nbsp;
1175Reconnection</h3>
1176
1177<p>It can happen that an XMPP server goes offline unexpectedly while servicing TCP connections from connected clients and remote servers. Because the number of such connections can be quite large, the reconnection algorithm employed by entities that seek to reconnect can have a significant impact on software performance and network congestion. If an entity chooses to reconnect, it:
1178</p>
1179<p>
1180 </p>
1181<ul class="text">
1182<li>SHOULD set the number of seconds that expire before reconnecting to an unpredictable number between 0 and 60 (this helps to ensure that not all entities attempt to reconnect at exactly the same number of seconds after being disconnected).
1183</li>
1184<li>SHOULD back off increasingly on the time between subsequent reconnection attempts (e.g., in accordance with "truncated binary exponential backoff" as described in <a class='info' href='#ETHERNET'>[ETHERNET]<span> (</span><span class='info'>, &ldquo;Information technology - Telecommunications and information exchange between systems - Local and metropolitan area networks - Specific requirements - Part 3: Carrier sense multiple access with collision detection (CSMA/CD) access method and physical layer specifications,&rdquo; September&nbsp;1998.</span><span>)</span></a>) if the first reconnection attempt does not succeed.
1185</li>
1186</ul><p>
1187
1188</p>
1189<p>It is RECOMMENDED to make use of TLS session resumption <a class='info' href='#TLS-RESUME'>[TLS&#8209;RESUME]<span> (</span><span class='info'>Salowey, J., Zhou, H., Eronen, P., and H. Tschofenig, &ldquo;Transport Layer Security (TLS) Session Resumption without Server-Side State,&rdquo; January&nbsp;2008.</span><span>)</span></a> when reconnecting. A future version of this document, or a separate specification, might provide more detailed guidelines regarding methods for speeding the reconnection process.
1190</p>
1191<a name="streams-reliability"></a><br /><hr />
1192<table summary="layout" cellpadding="0" cellspacing="2" class="TOCbug" align="right"><tr><td class="TOCbug"><a href="#toc">&nbsp;TOC&nbsp;</a></td></tr></table>
1193<a name="rfc.section.3.4"></a><h3>3.4.&nbsp;
1194Reliability</h3>
1195
1196<p>The use of long-lived TCP connections in XMPP implies that the sending of XML stanzas over XML streams can be unreliable, since the parties to a long-lived TCP connection might not discover a connectivity disruption in a timely manner. At the XMPP application layer, long connectivity disruptions can result in undelivered stanzas. Although the core XMPP technology defined in this specification does not contain features to overcome this lack of reliability, there exist XMPP extensions for doing so (e.g., <a class='info' href='#XEP-0198'>[XEP&#8209;0198]<span> (</span><span class='info'>Karneges, J., Hildebrand, J., Saint-Andre, P., Forno, F., Cridland, D., and M. Wild, &ldquo;Stream Management,&rdquo; February&nbsp;2011.</span><span>)</span></a>).
1197</p>
1198<a name="streams"></a><br /><hr />
1199<table summary="layout" cellpadding="0" cellspacing="2" class="TOCbug" align="right"><tr><td class="TOCbug"><a href="#toc">&nbsp;TOC&nbsp;</a></td></tr></table>
1200<a name="rfc.section.4"></a><h3>4.&nbsp;
1201XML Streams</h3>
1202
1203<a name="streams-fundamentals"></a><br /><hr />
1204<table summary="layout" cellpadding="0" cellspacing="2" class="TOCbug" align="right"><tr><td class="TOCbug"><a href="#toc">&nbsp;TOC&nbsp;</a></td></tr></table>
1205<a name="rfc.section.4.1"></a><h3>4.1.&nbsp;
1206Stream Fundamentals</h3>
1207
1208<p>Two fundamental concepts make possible the rapid, asynchronous exchange of relatively small payloads of structured information between XMPP entities: XML streams and XML stanzas. These terms are defined as follows.
1209</p>
1210<p>
1211 </p>
1212<blockquote class="text"><dl>
1213<dt>Definition of XML Stream:</dt>
1214<dd>An XML stream is a container for the exchange of XML elements between any two entities over a network. The start of an XML stream is denoted unambiguously by an opening "stream header" (i.e., an XML &lt;stream&gt; tag with appropriate attributes and namespace declarations), while the end of the XML stream is denoted unambiguously by a closing XML &lt;/stream&gt; tag. During the life of the stream, the entity that initiated it can send an unbounded number of XML elements over the stream, either elements used to negotiate the stream (e.g., to complete <a class='info' href='#tls'>TLS negotiation<span> (</span><span class='info'>STARTTLS Negotiation</span><span>)</span></a> or <a class='info' href='#sasl'>SASL negotiation<span> (</span><span class='info'>SASL Negotiation</span><span>)</span></a>) or XML stanzas. The "initial stream" is negotiated from the initiating entity (typically a client or server) to the receiving entity (typically a server), and can be seen as corresponding to the initiating entity's "connection to" or "session with" the receiving entity. The initial stream enables unidirectional communication from the initiating entity to the receiving entity; in order to enable exchange of stanzas from the receiving entity to the initiating entity, the receiving entity MUST negotiate a stream in the opposite direction (the "response stream").
1215</dd>
1216<dt>Definition of XML Stanza:</dt>
1217<dd>An XML stanza is the basic unit of meaning in XMPP. A stanza is a first-level element (at depth=1 of the stream) whose element name is "message", "presence", or "iq" and whose qualifying namespace is 'jabber:client' or 'jabber:server'. By contrast, a first-level element qualified by any other namespace is not an XML stanza (stream errors, stream features, TLS-related elements, SASL-related elements, etc.), nor is a &lt;message/&gt;, &lt;presence/&gt;, or &lt;iq/&gt; element that is qualified by the 'jabber:client' or 'jabber:server' namespace but that occurs at a depth other than one (e.g., a &lt;message/&gt; element contained within an extension element (<a class='info' href='#stanzas-extended'>Section&nbsp;8.4<span> (</span><span class='info'>Extended Content</span><span>)</span></a>) for reporting purposes), nor is a &lt;message/&gt;, &lt;presence/&gt;, or &lt;iq/&gt; element that is qualified by a namespace other than 'jabber:client' or 'jabber:server'. An XML stanza typically contains one or more child elements (with accompanying attributes, elements, and XML character data) as necessary in order to convey the desired information, which MAY be qualified by any XML namespace (see <a class='info' href='#XML-NAMES'>[XML&#8209;NAMES]<span> (</span><span class='info'>Thompson, H., Hollander, D., Layman, A., Bray, T., and R. Tobin, &ldquo;Namespaces in XML 1.0 (Third Edition),&rdquo; December&nbsp;2009.</span><span>)</span></a> as well as <a class='info' href='#stanzas-extended'>Section&nbsp;8.4<span> (</span><span class='info'>Extended Content</span><span>)</span></a> in this specification).
1218</dd>
1219</dl></blockquote><p>
1220
1221</p>
1222<p>There are three kinds of stanzas: message, presence, and IQ (short for
1223"Info/Query"). These stanza types provide three different communication
1224primitives: a "push" mechanism for generalized messaging, a specialized
1225"publish-subscribe" mechanism for broadcasting information about network
1226availability, and a "request-response" mechanism for more structured exchanges
1227of data (similar to <a class='info' href='#HTTP'>[HTTP]<span> (</span><span class='info'>Fielding, R., Gettys, J., Mogul, J., Frystyk, H., Masinter, L., Leach, P., and T. Berners-Lee, &ldquo;Hypertext Transfer Protocol -- HTTP/1.1,&rdquo; June&nbsp;1999.</span><span>)</span></a>). Further explanations are provided
1228under Sections <a class='info' href='#stanzas-semantics-message'>8.2.1<span> (</span><span class='info'>Message Semantics</span><span>)</span></a>,
1229<a class='info' href='#stanzas-semantics-presence'>8.2.2<span> (</span><span class='info'>Presence Semantics</span><span>)</span></a>, and <a class='info' href='#stanzas-semantics-iq'>8.2.3<span> (</span><span class='info'>IQ Semantics</span><span>)</span></a>, respectively.
1230</p>
1231<p>Consider the example of a client's connection to a server. The client initiates an XML stream by sending a stream header to the server, preferably preceded by an XML declaration specifying the XML version and the character encoding supported (see <a class='info' href='#xml-declaration'>Section&nbsp;11.5<span> (</span><span class='info'>Inclusion of XML Declaration</span><span>)</span></a> and <a class='info' href='#xml-encoding'>Section&nbsp;11.6<span> (</span><span class='info'>Character Encoding</span><span>)</span></a>). Subject to local policies and service provisioning, the server then replies with a second XML stream back to the client, again preferably preceded by an XML declaration. Once the client has completed <a class='info' href='#sasl'>SASL negotiation<span> (</span><span class='info'>SASL Negotiation</span><span>)</span></a> and <a class='info' href='#bind'>resource binding<span> (</span><span class='info'>Resource Binding</span><span>)</span></a>, the client can send an unbounded number of XML stanzas over the stream. When the client desires to close the stream, it simply sends a closing &lt;/stream&gt; tag to the server as further described under <a class='info' href='#streams-close'>Section&nbsp;4.4<span> (</span><span class='info'>Closing a Stream</span><span>)</span></a>.
1232</p>
1233<p>In essence, then, one XML stream functions as an envelope for the XML stanzas sent during a session and another XML stream functions as an envelope for the XML stanzas received during a session. We can represent this in a simplistic fashion as follows.
1234</p><br /><hr class="insert" />
1235<a name="figure-2"></a>
1236<div style='display: table; width: 0; margin-left: 3em; margin-right: auto'><pre>
1237+--------------------+--------------------+
1238| INITIAL STREAM | RESPONSE STREAM |
1239+--------------------+--------------------+
1240| &lt;stream&gt; | |
1241|--------------------|--------------------|
1242| | &lt;stream&gt; |
1243|--------------------|--------------------|
1244| &lt;presence&gt; | |
1245| &lt;show/&gt; | |
1246| &lt;/presence&gt; | |
1247|--------------------|--------------------|
1248| &lt;message to='foo'&gt; | |
1249| &lt;body/&gt; | |
1250| &lt;/message&gt; | |
1251|--------------------|--------------------|
1252| &lt;iq to='bar' | |
1253| type='get'&gt; | |
1254| &lt;query/&gt; | |
1255| &lt;/iq&gt; | |
1256|--------------------|--------------------|
1257| | &lt;iq from='bar' |
1258| | type='result'&gt; |
1259| | &lt;query/&gt; |
1260| | &lt;/iq&gt; |
1261|--------------------|--------------------|
1262| [ ... ] | |
1263|--------------------|--------------------|
1264| | [ ... ] |
1265|--------------------|--------------------|
1266| &lt;/stream&gt; | |
1267|--------------------|--------------------|
1268| | &lt;/stream&gt; |
1269+--------------------+--------------------+
1270</pre></div><table border="0" cellpadding="0" cellspacing="2" align="center"><tr><td align="center"><font face="monaco, MS Sans Serif" size="1"><b>&nbsp;Figure&nbsp;2: A Simplistic View of Two Streams&nbsp;</b></font><br /></td></tr></table><hr class="insert" />
1271
1272<p>Those who are accustomed to thinking of XML in a document-centric manner might find the following analogies useful:
1273</p>
1274<p>
1275 </p>
1276<ul class="text">
1277<li>The two XML streams are like two "documents" (matching the "document" production from <a class='info' href='#XML'>[XML]<span> (</span><span class='info'>Maler, E., Yergeau, F., Sperberg-McQueen, C., Paoli, J., and T. Bray, &ldquo;Extensible Markup Language (XML) 1.0 (Fifth Edition),&rdquo; November&nbsp;2008.</span><span>)</span></a>) that are built up through the accumulation of XML stanzas.
1278</li>
1279<li>The root &lt;stream/&gt; element is like the "document entity" for each "document" (as described in Section 4.8 of <a class='info' href='#XML'>[XML]<span> (</span><span class='info'>Maler, E., Yergeau, F., Sperberg-McQueen, C., Paoli, J., and T. Bray, &ldquo;Extensible Markup Language (XML) 1.0 (Fifth Edition),&rdquo; November&nbsp;2008.</span><span>)</span></a>).
1280</li>
1281<li>The XML stanzas sent over the streams are like "fragments" of the "documents" (as described in <a class='info' href='#XML-FRAG'>[XML&#8209;FRAG]<span> (</span><span class='info'>Grosso, P. and D. Veillard, &ldquo;XML Fragment Interchange,&rdquo; February&nbsp;2001.</span><span>)</span></a>).
1282</li>
1283</ul><p>
1284
1285</p>
1286<p>However, these descriptions are merely analogies, because XMPP does not deal in documents and fragments but in streams and stanzas.
1287</p>
1288<p>The remainder of this section defines the following aspects of XML streams (along with related topics):
1289</p>
1290<p>
1291 </p>
1292<ul class="text">
1293<li>How to open a stream (<a class='info' href='#streams-open'>Section&nbsp;4.2<span> (</span><span class='info'>Opening a Stream</span><span>)</span></a>)
1294</li>
1295<li>The stream negotiation process (<a class='info' href='#streams-negotiation'>Section&nbsp;4.3<span> (</span><span class='info'>Stream Negotiation</span><span>)</span></a>)
1296</li>
1297<li>How to close a stream (<a class='info' href='#streams-close'>Section&nbsp;4.4<span> (</span><span class='info'>Closing a Stream</span><span>)</span></a>)
1298</li>
1299<li>The directionality of XML streams (<a class='info' href='#streams-direction'>Section&nbsp;4.5<span> (</span><span class='info'>Directionality</span><span>)</span></a>)
1300</li>
1301<li>How to handle peers that are silent (<a class='info' href='#streams-silence'>Section&nbsp;4.6<span> (</span><span class='info'>Handling of Silent Peers</span><span>)</span></a>)
1302</li>
1303<li>The XML attributes of a stream (<a class='info' href='#streams-attr'>Section&nbsp;4.7<span> (</span><span class='info'>Stream Attributes</span><span>)</span></a>)
1304</li>
1305<li>The XML namespaces of a stream (<a class='info' href='#streams-ns'>Section&nbsp;4.8<span> (</span><span class='info'>XML Namespaces</span><span>)</span></a>)
1306</li>
1307<li>Error handling related to XML streams (<a class='info' href='#streams-error'>Section&nbsp;4.9<span> (</span><span class='info'>Stream Errors</span><span>)</span></a>)
1308</li>
1309</ul><p>
1310
1311</p>
1312<a name="streams-open"></a><br /><hr />
1313<table summary="layout" cellpadding="0" cellspacing="2" class="TOCbug" align="right"><tr><td class="TOCbug"><a href="#toc">&nbsp;TOC&nbsp;</a></td></tr></table>
1314<a name="rfc.section.4.2"></a><h3>4.2.&nbsp;
1315Opening a Stream</h3>
1316
1317<p>After connecting to the appropriate IP address and port of the receiving entity, the initiating entity opens a stream by sending a stream header (the "initial stream header") to the receiving entity.
1318</p><div style='display: table; width: 0; margin-left: 3em; margin-right: auto'><pre>
1319I: &lt;?xml version='1.0'?&gt;
1320 &lt;stream:stream
1321 from='juliet@im.example.com'
1322 to='im.example.com'
1323 version='1.0'
1324 xml:lang='en'
1325 xmlns='jabber:client'
1326 xmlns:stream='http://etherx.jabber.org/streams'&gt;
1327</pre></div>
1328<p>The receiving entity then replies by sending a stream header of its own (the "response stream header") to the initiating entity.
1329</p><div style='display: table; width: 0; margin-left: 3em; margin-right: auto'><pre>
1330R: &lt;?xml version='1.0'?&gt;
1331 &lt;stream:stream
1332 from='im.example.com'
1333 id='++TR84Sm6A3hnt3Q065SnAbbk3Y='
1334 to='juliet@im.example.com'
1335 version='1.0'
1336 xml:lang='en'
1337 xmlns='jabber:client'
1338 xmlns:stream='http://etherx.jabber.org/streams'&gt;
1339</pre></div>
1340<p>The entities can then proceed with the remainder of the stream negotiation process.
1341</p>
1342<a name="streams-negotiation"></a><br /><hr />
1343<table summary="layout" cellpadding="0" cellspacing="2" class="TOCbug" align="right"><tr><td class="TOCbug"><a href="#toc">&nbsp;TOC&nbsp;</a></td></tr></table>
1344<a name="rfc.section.4.3"></a><h3>4.3.&nbsp;
1345Stream Negotiation</h3>
1346
1347<a name="streams-negotiation-basics"></a><br /><hr />
1348<table summary="layout" cellpadding="0" cellspacing="2" class="TOCbug" align="right"><tr><td class="TOCbug"><a href="#toc">&nbsp;TOC&nbsp;</a></td></tr></table>
1349<a name="rfc.section.4.3.1"></a><h3>4.3.1.&nbsp;
1350Basic Concepts</h3>
1351
1352<p>Because the receiving entity for a stream acts as a gatekeeper to the domains it services, it imposes certain conditions for connecting as a client or as a peer server. At a minimum, the initiating entity needs to authenticate with the receiving entity before it is allowed to send stanzas to the receiving entity (for client-to-server streams this means using SASL as described under <a class='info' href='#sasl'>Section&nbsp;6<span> (</span><span class='info'>SASL Negotiation</span><span>)</span></a>). However, the receiving entity can consider conditions other than authentication to be mandatory-to-negotiate, such as encryption using TLS as described under <a class='info' href='#tls'>Section&nbsp;5<span> (</span><span class='info'>STARTTLS Negotiation</span><span>)</span></a>. The receiving entity informs the initiating entity about such conditions by communicating "stream features": the set of particular protocol interactions that the initiating entity needs to complete before the receiving entity will accept XML stanzas from the initiating entity, as well as any protocol interactions that are voluntary-to-negotiate but that might improve the handling of an XML stream (e.g., establishment of application-layer compression as described in <a class='info' href='#XEP-0138'>[XEP&#8209;0138]<span> (</span><span class='info'>Hildebrand, J. and P. Saint-Andre, &ldquo;Stream Compression,&rdquo; May&nbsp;2009.</span><span>)</span></a>).
1353</p>
1354<p>The existence of conditions for connecting implies that
1355 streams need to be negotiated. The order of layers (TCP, then
1356 TLS, then SASL, then XMPP as described under
1357 <a class='info' href='#security-layers'>Section&nbsp;13.3<span> (</span><span class='info'>Order of Layers</span><span>)</span></a>) implies that stream
1358 negotiation is a multi-stage process. Further structure is
1359 imposed by two factors: (1) a given stream feature might be
1360 offered only to certain entities or only after certain other
1361 features have been negotiated (e.g., resource binding is
1362 offered only after SASL authentication), and (2) stream
1363 features can be either mandatory-to-negotiate or
1364 voluntary-to-negotiate. Finally, for security reasons the
1365 parties to a stream need to discard knowledge that they gained
1366 during the negotiation process after successfully completing
1367 the protocol interactions defined for certain features (e.g.,
1368 TLS in all cases and SASL in the case when a security layer
1369 might be established, as defined in the specification for the
1370 relevant SASL mechanism). This is done by flushing the old stream context and exchanging new stream headers over the existing TCP connection.
1371</p>
1372<a name="streams-negotiation-features"></a><br /><hr />
1373<table summary="layout" cellpadding="0" cellspacing="2" class="TOCbug" align="right"><tr><td class="TOCbug"><a href="#toc">&nbsp;TOC&nbsp;</a></td></tr></table>
1374<a name="rfc.section.4.3.2"></a><h3>4.3.2.&nbsp;
1375Stream Features Format</h3>
1376
1377<p>If the initiating entity includes in the initial stream header the 'version' attribute set to a value of at least "1.0" (see <a class='info' href='#streams-attr-version'>Section&nbsp;4.7.5<span> (</span><span class='info'>version</span><span>)</span></a>), after sending the response stream header the receiving entity MUST send a &lt;features/&gt; child element (typically prefixed by the stream namespace prefix as described under <a class='info' href='#streams-ns-declarations'>Section&nbsp;4.8.5<span> (</span><span class='info'>Namespace Declarations and Prefixes</span><span>)</span></a>) to the initiating entity in order to announce any conditions for continuation of the stream negotiation process. Each condition takes the form of a child element of the &lt;features/&gt; element, qualified by a namespace that is different from the stream namespace and the content namespace. The &lt;features/&gt; element can contain one child, contain multiple children, or be empty.
1378</p>
1379<p></p>
1380<blockquote class="text">
1381<p>Implementation Note: The order of child elements contained in any given &lt;features/&gt; element is not significant.
1382</p>
1383</blockquote>
1384
1385<p>If a particular stream feature is or can be mandatory-to-negotiate, the definition of that feature needs to do one of the following:
1386</p>
1387<p>
1388 </p>
1389<ol class="text">
1390<li>Declare that the feature is always mandatory-to-negotiate (e.g., this is true of resource binding for XMPP clients); or
1391</li>
1392<li>Specify a way for the receiving entity to flag the feature as mandatory-to-negotiate for this interaction (e.g., for STARTTLS, this is done by including an empty &lt;required/&gt; element in the advertisement for that stream feature, but that is not a generic format for all stream features); it is RECOMMENDED that stream feature definitions for new mandatory-to-negotiate features do so by including an empty &lt;required/&gt; element as is done for STARTTLS.
1393</li>
1394</ol><p>
1395
1396</p>
1397<p></p>
1398<blockquote class="text">
1399<p>Informational Note: Because there is no generic format for indicating that a feature is mandatory-to-negotiate, it is possible that a feature that is not understood by the initiating entity might be considered mandatory-to-negotiate by the receiving entity, resulting in failure of the stream negotiation process. Although such an outcome would be undesirable, the working group deemed it rare enough that a generic format was not needed.
1400</p>
1401</blockquote>
1402
1403<p>For security reasons, certain stream features necessitate the initiating entity to send a new initial stream header upon successful negotiation of the feature (e.g., TLS in all cases and SASL in the case when a security layer might be established). If this is true of a given stream feature, the definition of that feature needs to specify that a stream restart is expected after negotiation of the feature.
1404</p>
1405<p>A &lt;features/&gt; element that contains at least one mandatory-to-negotiate feature indicates that the stream negotiation is not complete and that the initiating entity MUST negotiate further features.
1406</p><div style='display: table; width: 0; margin-left: 3em; margin-right: auto'><pre>
1407R: &lt;stream:features&gt;
1408 &lt;starttls xmlns='urn:ietf:params:xml:ns:xmpp-tls'&gt;
1409 &lt;required/&gt;
1410 &lt;/starttls&gt;
1411 &lt;/stream:features&gt;
1412</pre></div>
1413<p>A &lt;features/&gt; element MAY contain more than one mandatory-to-negotiate feature. This means that the initiating entity can choose among the mandatory-to-negotiate features at this stage of the stream negotiation process. As an example, perhaps a future technology will perform roughly the same function as TLS, so the receiving entity might advertise support for both TLS and the future technology at the same stage of the stream negotiation process. However, this applies only at a given stage of the stream negotiation process and does not apply to features that are mandatory-to-negotiate at different stages (e.g., the receiving entity would not advertise both STARTTLS and SASL as mandatory-to-negotiate, or both SASL and resource binding as mandatory-to-negotiate, because TLS would need to be negotiated before SASL and because SASL would need to be negotiated before resource binding).
1414</p>
1415<p>A &lt;features/&gt; element that contains both mandatory-to-negotiate and voluntary-to-negotiate features indicates that the negotiation is not complete but that the initiating entity MAY complete the voluntary-to-negotiate feature(s) before it attempts to negotiate the mandatory-to-negotiate feature(s).
1416</p><div style='display: table; width: 0; margin-left: 3em; margin-right: auto'><pre>
1417R: &lt;stream:features&gt;
1418 &lt;bind xmlns='urn:ietf:params:xml:ns:xmpp-bind'/&gt;
1419 &lt;compression xmlns='http://jabber.org/features/compress'&gt;
1420 &lt;method&gt;zlib&lt;/method&gt;
1421 &lt;method&gt;lzw&lt;/method&gt;
1422 &lt;/compression&gt;
1423 &lt;/stream:features&gt;
1424</pre></div>
1425<p>A &lt;features/&gt; element that contains only voluntary-to-negotiate features indicates that the stream negotiation is complete and that the initiating entity is cleared to send XML stanzas, but that the initiating entity MAY negotiate further features if desired.
1426</p><div style='display: table; width: 0; margin-left: 3em; margin-right: auto'><pre>
1427R: &lt;stream:features&gt;
1428 &lt;compression xmlns='http://jabber.org/features/compress'&gt;
1429 &lt;method&gt;zlib&lt;/method&gt;
1430 &lt;method&gt;lzw&lt;/method&gt;
1431 &lt;/compression&gt;
1432 &lt;/stream:features&gt;
1433</pre></div>
1434<p>An empty &lt;features/&gt; element indicates that the stream negotiation is complete and that the initiating entity is cleared to send XML stanzas.
1435</p><div style='display: table; width: 0; margin-left: 3em; margin-right: auto'><pre>
1436R: &lt;stream:features/&gt;
1437</pre></div>
1438<a name="streams-negotiation-restart"></a><br /><hr />
1439<table summary="layout" cellpadding="0" cellspacing="2" class="TOCbug" align="right"><tr><td class="TOCbug"><a href="#toc">&nbsp;TOC&nbsp;</a></td></tr></table>
1440<a name="rfc.section.4.3.3"></a><h3>4.3.3.&nbsp;
1441Restarts</h3>
1442
1443<p>On successful negotiation of a feature that necessitates a stream restart, both parties MUST consider the previous stream to be replaced but MUST NOT send a closing &lt;/stream&gt; tag and MUST NOT terminate the underlying TCP connection; instead, the parties MUST reuse the existing connection, which might be in a new state (e.g., encrypted as a result of TLS negotiation). The initiating entity then MUST send a new initial stream header, which SHOULD be preceded by an XML declaration as described under <a class='info' href='#xml-declaration'>Section&nbsp;11.5<span> (</span><span class='info'>Inclusion of XML Declaration</span><span>)</span></a>. When the receiving entity receives the new initial stream header, it MUST generate a new stream ID (instead of reusing the old stream ID) before sending a new response stream header (which SHOULD be preceded by an XML declaration as described under <a class='info' href='#xml-declaration'>Section&nbsp;11.5<span> (</span><span class='info'>Inclusion of XML Declaration</span><span>)</span></a>).
1444</p>
1445<a name="streams-negotiation-resend"></a><br /><hr />
1446<table summary="layout" cellpadding="0" cellspacing="2" class="TOCbug" align="right"><tr><td class="TOCbug"><a href="#toc">&nbsp;TOC&nbsp;</a></td></tr></table>
1447<a name="rfc.section.4.3.4"></a><h3>4.3.4.&nbsp;
1448Resending Features</h3>
1449
1450<p>The receiving entity MUST send an updated list of stream features to the initiating entity after a stream restart. The list of updated features MAY be empty if there are no further features to be advertised or MAY include any combination of features.
1451</p>
1452<a name="streams-negotiation-complete"></a><br /><hr />
1453<table summary="layout" cellpadding="0" cellspacing="2" class="TOCbug" align="right"><tr><td class="TOCbug"><a href="#toc">&nbsp;TOC&nbsp;</a></td></tr></table>
1454<a name="rfc.section.4.3.5"></a><h3>4.3.5.&nbsp;
1455Completion of Stream Negotiation</h3>
1456
1457<p>The receiving entity indicates completion of the stream negotiation process by sending to the initiating entity either an empty &lt;features/&gt; element or a &lt;features/&gt; element that contains only voluntary-to-negotiate features. After doing so, the receiving entity MAY send an empty &lt;features/&gt; element (e.g., after negotiation of such voluntary-to-negotiate features) but MUST NOT send additional stream features to the initiating entity (if the receiving entity has new features to offer, preferably limited to mandatory-to-negotiate or security-critical features, it can simply close the stream with a &lt;reset/&gt; stream error (<a class='info' href='#streams-error-conditions-reset'>Section&nbsp;4.9.3.16<span> (</span><span class='info'>reset</span><span>)</span></a>) and then advertise the new features when the initiating entity reconnects, preferably closing existing streams in a staggered way so that not all of the initiating entities reconnect at once). Once stream negotiation is complete, the initiating entity is cleared to send XML stanzas over the stream for as long as the stream is maintained by both parties.
1458</p>
1459<p></p>
1460<blockquote class="text">
1461<p>Informational Note: Resource binding as specified under <a class='info' href='#bind'>Section&nbsp;7<span> (</span><span class='info'>Resource Binding</span><span>)</span></a> is an historical exception to the foregoing rule, since it is mandatory-to-negotiate for clients but uses XML stanzas for negotiation purposes.
1462</p>
1463</blockquote>
1464
1465<p>The initiating entity MUST NOT attempt to send <a class='info' href='#stanzas'>XML stanzas<span> (</span><span class='info'>XML Stanzas</span><span>)</span></a> to entities other than itself (i.e., the client's connected resource or any other authenticated resource of the client's account) or the server to which it is connected until stream negotiation has been completed. Even if the initiating entity does attempt to do so, the receiving entity MUST NOT accept such stanzas and MUST close the stream with a &lt;not-authorized/&gt; stream error (<a class='info' href='#streams-error-conditions-not-authorized'>Section&nbsp;4.9.3.12<span> (</span><span class='info'>not-authorized</span><span>)</span></a>). This rule applies to XML stanzas only (i.e., &lt;message/&gt;, &lt;presence/&gt;, and &lt;iq/&gt; elements qualified by the content namespace) and not to XML elements used for stream negotiation (e.g., elements used to complete <a class='info' href='#tls'>TLS negotiation<span> (</span><span class='info'>STARTTLS Negotiation</span><span>)</span></a> or <a class='info' href='#sasl'>SASL negotiation<span> (</span><span class='info'>SASL Negotiation</span><span>)</span></a>).
1466</p>
1467<a name="streams-negotiation-address"></a><br /><hr />
1468<table summary="layout" cellpadding="0" cellspacing="2" class="TOCbug" align="right"><tr><td class="TOCbug"><a href="#toc">&nbsp;TOC&nbsp;</a></td></tr></table>
1469<a name="rfc.section.4.3.6"></a><h3>4.3.6.&nbsp;
1470Determination of Addresses</h3>
1471
1472<p>After the parties to an XML stream have completed the appropriate aspects of stream negotiation, the receiving entity for a stream MUST determine the initiating entity's JID.
1473</p>
1474<p>For client-to-server communication, both <a class='info' href='#sasl'>SASL negotiation<span> (</span><span class='info'>SASL Negotiation</span><span>)</span></a> and <a class='info' href='#bind'>resource binding<span> (</span><span class='info'>Resource Binding</span><span>)</span></a> MUST be completed before the server can determine the client's address. The client's bare JID (&lt;localpart@domainpart&gt;) MUST be the authorization identity (as defined by <a class='info' href='#SASL'>[SASL]<span> (</span><span class='info'>Melnikov, A. and K. Zeilenga, &ldquo;Simple Authentication and Security Layer (SASL),&rdquo; June&nbsp;2006.</span><span>)</span></a>), either (1) as directly communicated by the client during <a class='info' href='#sasl'>SASL negotiation<span> (</span><span class='info'>SASL Negotiation</span><span>)</span></a> or (2) as derived by the server from the authentication identity if no authorization identity was specified during SASL negotiation. The resourcepart of the full JID (&lt;localpart@domainpart/resourcepart&gt;) MUST be the resource negotiated by the client and server during <a class='info' href='#bind'>resource binding<span> (</span><span class='info'>Resource Binding</span><span>)</span></a>. A client MUST NOT attempt to guess at its JID but instead MUST consider its JID to be whatever the server returns to it during resource binding. The server MUST ensure that the resulting JID (including localpart, domainpart, resourcepart, and separator characters) conforms to the canonical format for XMPP addresses defined in <a class='info' href='#XMPP-ADDR'>[XMPP&#8209;ADDR]<span> (</span><span class='info'>Saint-Andre, P., &ldquo;Extensible Messaging and Presence Protocol (XMPP): Address Format,&rdquo; March&nbsp;2011.</span><span>)</span></a>; to meet this restriction, the server MAY replace the JID sent by the client with the canonicalized JID as determined by the server and communicate that JID to the client during resource binding.
1475</p>
1476<p>For server-to-server communication, the initiating server's bare JID (&lt;domainpart&gt;) MUST be the authorization identity (as defined by <a class='info' href='#SASL'>[SASL]<span> (</span><span class='info'>Melnikov, A. and K. Zeilenga, &ldquo;Simple Authentication and Security Layer (SASL),&rdquo; June&nbsp;2006.</span><span>)</span></a>), either (1) as directly communicated by the initiating server during <a class='info' href='#sasl'>SASL negotiation<span> (</span><span class='info'>SASL Negotiation</span><span>)</span></a> or (2) as derived by the receiving server from the authentication identity if no authorization identity was specified during SASL negotiation. In the absence of SASL negotiation, the receiving server MAY consider the authorization identity to be an identity negotiated within the relevant verification protocol (e.g., the 'from' attribute of the &lt;result/&gt; element in Server Dialback <a class='info' href='#XEP-0220'>[XEP&#8209;0220]<span> (</span><span class='info'>Miller, J., Saint-Andre, P., and P. Hancke, &ldquo;Server Dialback,&rdquo; March&nbsp;2010.</span><span>)</span></a>).
1477</p>
1478<p></p>
1479<blockquote class="text">
1480<p>Security Warning: Because it is possible for a third party to tamper with information that is sent over the stream before a security layer such as TLS is successfully negotiated, it is advisable for the receiving server to treat any such unprotected information with caution; this applies especially to the 'from' and 'to' addresses on the first initial stream header sent by the initiating entity.
1481</p>
1482</blockquote>
1483
1484<a name="streams-negotiation-flowchart"></a><br /><hr />
1485<table summary="layout" cellpadding="0" cellspacing="2" class="TOCbug" align="right"><tr><td class="TOCbug"><a href="#toc">&nbsp;TOC&nbsp;</a></td></tr></table>
1486<a name="rfc.section.4.3.7"></a><h3>4.3.7.&nbsp;
1487Flow Chart</h3>
1488
1489<p>We summarize the foregoing rules in the following non-normative flow chart for the stream negotiation process, presented from the perspective of the initiating entity.
1490</p><br /><hr class="insert" />
1491<a name="figure-3"></a>
1492<div style='display: table; width: 0; margin-left: 3em; margin-right: auto'><pre>
1493 +---------------------+
1494 | open TCP connection |
1495 +---------------------+
1496 |
1497 v
1498 +---------------+
1499 | send initial |&lt;-------------------------+
1500 | stream header | ^
1501 +---------------+ |
1502 | |
1503 v |
1504 +------------------+ |
1505 | receive response | |
1506 | stream header | |
1507 +------------------+ |
1508 | |
1509 v |
1510 +----------------+ |
1511 | receive stream | |
1512+------------------&gt;| features | |
1513^ {OPTIONAL} +----------------+ |
1514| | |
1515| v |
1516| +&lt;-----------------+ |
1517| | |
1518| {empty?} ----&gt; {all voluntary?} ----&gt; {some mandatory?} |
1519| | no | no | |
1520| | yes | yes | yes |
1521| | v v |
1522| | +---------------+ +----------------+ |
1523| | | MAY negotiate | | MUST negotiate | |
1524| | | any or none | | one feature | |
1525| | +---------------+ +----------------+ |
1526| v | | |
1527| +---------+ v | |
1528| | DONE |&lt;----- {negotiate?} | |
1529| +---------+ no | | |
1530| yes | | |
1531| v v |
1532| +---------&gt;+&lt;---------+ |
1533| | |
1534| v |
1535+&lt;-------------------------- {restart mandatory?} ------------&gt;+
1536 no yes
1537
1538</pre></div><table border="0" cellpadding="0" cellspacing="2" align="center"><tr><td align="center"><font face="monaco, MS Sans Serif" size="1"><b>&nbsp;Figure&nbsp;3: Stream Negotiation Flow Chart&nbsp;</b></font><br /></td></tr></table><hr class="insert" />
1539
1540<a name="streams-close"></a><br /><hr />
1541<table summary="layout" cellpadding="0" cellspacing="2" class="TOCbug" align="right"><tr><td class="TOCbug"><a href="#toc">&nbsp;TOC&nbsp;</a></td></tr></table>
1542<a name="rfc.section.4.4"></a><h3>4.4.&nbsp;
1543Closing a Stream</h3>
1544
1545<p>An XML stream from one entity to another can be closed at any time, either because a specific stream error (<a class='info' href='#streams-error'>Section&nbsp;4.9<span> (</span><span class='info'>Stream Errors</span><span>)</span></a>) has occurred or in the absence of an error (e.g., when a client simply ends its session).
1546</p>
1547<p>A stream is closed by sending a closing &lt;/stream&gt; tag.
1548</p><div style='display: table; width: 0; margin-left: 3em; margin-right: auto'><pre>
1549E: &lt;/stream:stream&gt;
1550</pre></div>
1551<p>If the parties are using either two streams over a single TCP connection or two streams over two TCP connections, the entity that sends the closing stream tag MUST behave as follows:
1552</p>
1553<p>
1554 </p>
1555<ol class="text">
1556<li>Wait for the other party to also close its outbound
1557 stream before terminating the underlying TCP connection(s);
1558 this gives the other party an opportunity to finish
1559 transmitting any outbound data to the closing entity before
1560 the termination of the TCP connection(s).
1561</li>
1562<li>Refrain from sending any further data over its outbound stream to the other entity, but continue to process data received from the other entity (and, if necessary, process such data).
1563</li>
1564<li>Consider both streams to be void if the other party does not send its closing stream tag within a reasonable amount of time (where the definition of "reasonable" is a matter of implementation or deployment).
1565</li>
1566<li>After receiving a reciprocal closing stream tag from the other party or waiting a reasonable amount of time with no response, terminate the underlying TCP connection(s).
1567</li>
1568</ol><p>
1569
1570</p>
1571<p></p>
1572<blockquote class="text">
1573<p>Security Warning: In accordance with Section 7.2.1 of <a class='info' href='#TLS'>[TLS]<span> (</span><span class='info'>Dierks, T. and E. Rescorla, &ldquo;The Transport Layer Security (TLS) Protocol Version 1.2,&rdquo; August&nbsp;2008.</span><span>)</span></a>, to help prevent a truncation attack the party that is closing the stream MUST send a TLS close_notify alert and MUST receive a responding close_notify alert from the other party before terminating the underlying TCP connection(s).
1574</p>
1575</blockquote>
1576
1577<p>If the parties are using multiple streams over multiple TCP connections, there is no defined pairing of streams and therefore the behavior is a matter for implementation.
1578</p>
1579<a name="streams-direction"></a><br /><hr />
1580<table summary="layout" cellpadding="0" cellspacing="2" class="TOCbug" align="right"><tr><td class="TOCbug"><a href="#toc">&nbsp;TOC&nbsp;</a></td></tr></table>
1581<a name="rfc.section.4.5"></a><h3>4.5.&nbsp;
1582Directionality</h3>
1583
1584<p>An XML stream is always unidirectional, by which is meant that XML stanzas can be sent in only one direction over the stream (either from the initiating entity to the receiving entity or from the receiving entity to the initiating entity).
1585</p>
1586<p>Depending on the type of session that has been negotiated and the nature of the entities involved, the entities might use:
1587</p>
1588<p>
1589 </p>
1590<ul class="text">
1591<li>Two streams over a single TCP connection, where the security context negotiated for the first stream is applied to the second stream. This is typical for client-to-server sessions, and a server MUST allow a client to use the same TCP connection for both streams.
1592</li>
1593<li>Two streams over two TCP connections, where each stream is separately secured. In this approach, one TCP connection is used for the stream in which stanzas are sent from the initiating entity to the receiving entity, and the other TCP connection is used for the stream in which stanzas are sent from the receiving entity to the initiating entity. This is typical for server-to-server sessions.
1594</li>
1595<li>Multiple streams over two or more TCP connections, where each stream is separately secured. This approach is sometimes used for server-to-server communication between two large XMPP service providers; however, this can make it difficult to maintain coherence of data received over multiple streams in situations described under <a class='info' href='#rules-order'>Section&nbsp;10.1<span> (</span><span class='info'>In-Order Processing</span><span>)</span></a>, which is why a server MAY close the stream with a &lt;conflict/&gt; stream error (<a class='info' href='#streams-error-conditions-conflict'>Section&nbsp;4.9.3.3<span> (</span><span class='info'>conflict</span><span>)</span></a>) if a remote server attempts to negotiate more than one stream (as described under <a class='info' href='#streams-error-conditions-conflict'>Section&nbsp;4.9.3.3<span> (</span><span class='info'>conflict</span><span>)</span></a>).
1596</li>
1597</ul><p>
1598
1599</p>
1600<p>This concept of directionality applies only to stanzas and explicitly does not apply to first-level children of the stream root that are used to bootstrap or manage the stream (e.g., first-level elements used for TLS negotiation, SASL negotiation, Server Dialback <a class='info' href='#XEP-0220'>[XEP&#8209;0220]<span> (</span><span class='info'>Miller, J., Saint-Andre, P., and P. Hancke, &ldquo;Server Dialback,&rdquo; March&nbsp;2010.</span><span>)</span></a>, and Stream Management <a class='info' href='#XEP-0198'>[XEP&#8209;0198]<span> (</span><span class='info'>Karneges, J., Hildebrand, J., Saint-Andre, P., Forno, F., Cridland, D., and M. Wild, &ldquo;Stream Management,&rdquo; February&nbsp;2011.</span><span>)</span></a>).
1601</p>
1602<p>The foregoing considerations imply that while completing <a class='info' href='#tls'>STARTTLS negotiation<span> (</span><span class='info'>STARTTLS Negotiation</span><span>)</span></a> and <a class='info' href='#sasl'>SASL negotiation<span> (</span><span class='info'>SASL Negotiation</span><span>)</span></a> two servers would use one TCP connection, but after the stream negotiation process is done that original TCP connection would be used only for the initiating server to send XML stanzas to the receiving server. In order for the receiving server to send XML stanzas to the initiating server, the receiving server would need to reverse the roles and negotiate an XML stream from the receiving server to the initiating server over a separate TCP connection. This separate TCP connection is then secured using a new round of TLS and/or SASL negotiation.
1603</p>
1604<p></p>
1605<blockquote class="text">
1606<p>Implementation Note: For historical reasons, a server-to-server session always uses two TCP connections. While that approach remains the standard behavior described in this document, extensions such as <a class='info' href='#XEP-0288'>[XEP&#8209;0288]<span> (</span><span class='info'>Hancke, P. and D. Cridland, &ldquo;Bidirectional Server-to-Server Connections,&rdquo; October&nbsp;2010.</span><span>)</span></a> enable servers to negotiate the use of a single TCP connection for bidirectional stanza exchange.
1607</p>
1608</blockquote>
1609
1610<p></p>
1611<blockquote class="text">
1612<p>Informational Note: Although XMPP developers sometimes apply the terms "unidirectional" and "bidirectional" to the underlying TCP connection (e.g., calling the TCP connection for a client-to-server session "bidirectional" and the TCP connection for a server-to-server session "unidirectional"), strictly speaking a stream is always unidirectional (because the initiating entity and receiving entity always have a minimum of two streams, one in each direction) and a TCP connection is always bidirectional (because TCP traffic can be sent in both directions). Directionality applies to the application-layer traffic sent over the TCP connection, not to the transport-layer traffic sent over the TCP connection itself.
1613</p>
1614</blockquote>
1615
1616<a name="streams-silence"></a><br /><hr />
1617<table summary="layout" cellpadding="0" cellspacing="2" class="TOCbug" align="right"><tr><td class="TOCbug"><a href="#toc">&nbsp;TOC&nbsp;</a></td></tr></table>
1618<a name="rfc.section.4.6"></a><h3>4.6.&nbsp;
1619Handling of Silent Peers</h3>
1620
1621<p>When an entity that is a party to a stream has not received any XMPP traffic from its stream peer for some period of time, the peer might appear to be silent. There are several reasons why this might happen:
1622</p>
1623<p>
1624 </p>
1625<ol class="text">
1626<li>The underlying TCP connection is dead.
1627</li>
1628<li>The XML stream is broken despite the fact that the underlying TCP connection is alive.
1629</li>
1630<li>The peer is idle and simply has not sent any XMPP traffic over its XML stream to the entity.
1631</li>
1632</ol><p>
1633
1634</p>
1635<p>These three conditions are best handled separately, as described in the following sections.
1636</p>
1637<p></p>
1638<blockquote class="text">
1639<p>Implementation Note: For the purpose of handling silent peers, we treat a two unidirectional TCP connections as conceptually equivalent to a single bidirectional TCP connection (see <a class='info' href='#streams-direction'>Section&nbsp;4.5<span> (</span><span class='info'>Directionality</span><span>)</span></a>); however, implementers need to be aware that, in the case of two unidirectional TCP connections, responses to traffic at the XMPP application layer will come back from the peer on the second TCP connection. In addition, the use of multiple streams in each direction (which is a somewhat frequent deployment choice for server-to-server connectivity among large XMPP service providers) further complicates application-level checking of XMPP streams and their underlying TCP connections, because there is no necessary correlation between any given initial stream and any given response stream.
1640</p>
1641</blockquote>
1642
1643<a name="streams-silence-dead"></a><br /><hr />
1644<table summary="layout" cellpadding="0" cellspacing="2" class="TOCbug" align="right"><tr><td class="TOCbug"><a href="#toc">&nbsp;TOC&nbsp;</a></td></tr></table>
1645<a name="rfc.section.4.6.1"></a><h3>4.6.1.&nbsp;
1646Dead Connection</h3>
1647
1648<p>If the underlying TCP connection is dead, stream-level checks (e.g., <a class='info' href='#XEP-0199'>[XEP&#8209;0199]<span> (</span><span class='info'>Saint-Andre, P., &ldquo;XMPP Ping,&rdquo; June&nbsp;2009.</span><span>)</span></a> and <a class='info' href='#XEP-0198'>[XEP&#8209;0198]<span> (</span><span class='info'>Karneges, J., Hildebrand, J., Saint-Andre, P., Forno, F., Cridland, D., and M. Wild, &ldquo;Stream Management,&rdquo; February&nbsp;2011.</span><span>)</span></a>) are ineffective. Therefore, it is unnecessary to close the stream with or without an error, and it is appropriate instead to simply terminate the TCP connection.
1649</p>
1650<p>One common method for checking the TCP connection is to send a space character (U+0020) between XML stanzas, which is allowed for XML streams as described under <a class='info' href='#xml-whitespace'>Section&nbsp;11.7<span> (</span><span class='info'>Whitespace</span><span>)</span></a>; the sending of such a space character is properly called a "whitespace keepalive" (the term "whitespace ping" is often used, despite the fact that it is not a ping since no "pong" is possible). However, this is not allowed during TLS negotiation or SASL negotiation, as described under <a class='info' href='#tls-rules-data'>Section&nbsp;5.3.3<span> (</span><span class='info'>Data Formatting</span><span>)</span></a> and <a class='info' href='#sasl-rules-data'>Section&nbsp;6.3.5<span> (</span><span class='info'>Data Formatting</span><span>)</span></a>.
1651</p>
1652<a name="streams-silence-broken"></a><br /><hr />
1653<table summary="layout" cellpadding="0" cellspacing="2" class="TOCbug" align="right"><tr><td class="TOCbug"><a href="#toc">&nbsp;TOC&nbsp;</a></td></tr></table>
1654<a name="rfc.section.4.6.2"></a><h3>4.6.2.&nbsp;
1655Broken Stream</h3>
1656
1657<p>Even if the underlying TCP connection is alive, the peer might never respond to XMPP traffic that the entity sends, whether normal stanzas or specialized stream-checking traffic such as the application-level pings defined in <a class='info' href='#XEP-0199'>[XEP&#8209;0199]<span> (</span><span class='info'>Saint-Andre, P., &ldquo;XMPP Ping,&rdquo; June&nbsp;2009.</span><span>)</span></a> or the more comprehensive Stream Management protocol defined in <a class='info' href='#XEP-0198'>[XEP&#8209;0198]<span> (</span><span class='info'>Karneges, J., Hildebrand, J., Saint-Andre, P., Forno, F., Cridland, D., and M. Wild, &ldquo;Stream Management,&rdquo; February&nbsp;2011.</span><span>)</span></a>. In this case, it is appropriate for the entity to close a broken stream with a &lt;connection-timeout/&gt; stream error (<a class='info' href='#streams-error-conditions-connection-timeout'>Section&nbsp;4.9.3.4<span> (</span><span class='info'>connection-timeout</span><span>)</span></a>).
1658</p>
1659<a name="streams-silence-idle"></a><br /><hr />
1660<table summary="layout" cellpadding="0" cellspacing="2" class="TOCbug" align="right"><tr><td class="TOCbug"><a href="#toc">&nbsp;TOC&nbsp;</a></td></tr></table>
1661<a name="rfc.section.4.6.3"></a><h3>4.6.3.&nbsp;
1662Idle Peer</h3>
1663
1664<p>Even if the underlying TCP connection is alive and the
1665 stream is not broken, the peer might have sent no stanzas for
1666 a certain period of time. In this case, the peer itself MAY
1667 close the stream (as described under
1668 <a class='info' href='#streams-close'>Section&nbsp;4.4<span> (</span><span class='info'>Closing a Stream</span><span>)</span></a>) rather than leaving an unused
1669 stream open. If the idle peer does not close the stream, the
1670 other party MAY either close the stream using the handshake
1671 described under <a class='info' href='#streams-close'>Section&nbsp;4.4<span> (</span><span class='info'>Closing a Stream</span><span>)</span></a> or close the
1672 stream with a stream error (e.g., &lt;resource-constraint/&gt;
1673 (<a class='info' href='#streams-error-conditions-resource-constraint'>Section&nbsp;4.9.3.17<span> (</span><span class='info'>resource-constraint</span><span>)</span></a>) if
1674 the entity has reached a limit on the number of open TCP
1675 connections or &lt;policy-violation/&gt;
1676 (<a class='info' href='#streams-error-conditions-policy-violation'>Section&nbsp;4.9.3.14<span> (</span><span class='info'>policy-violation</span><span>)</span></a>)
1677 if the connection has exceeded a local timeout policy).
1678 However, consistent with the order of layers (specified under
1679 <a class='info' href='#security-layers'>Section&nbsp;13.3<span> (</span><span class='info'>Order of Layers</span><span>)</span></a>), the other party is advised
1680 to verify that the underlying TCP connection is alive and the
1681 stream is unbroken (as described above) before concluding that
1682 the peer is idle. Furthermore, it is preferable to be liberal
1683 in accepting idle peers, since experience has shown that doing
1684 so improves the reliability of communication over XMPP
1685 networks and that it is typically more efficient to maintain a
1686 stream between two servers than to aggressively time out such a stream.
1687</p>
1688<a name="streams-silence-check"></a><br /><hr />
1689<table summary="layout" cellpadding="0" cellspacing="2" class="TOCbug" align="right"><tr><td class="TOCbug"><a href="#toc">&nbsp;TOC&nbsp;</a></td></tr></table>
1690<a name="rfc.section.4.6.4"></a><h3>4.6.4.&nbsp;
1691Use of Checking Methods</h3>
1692
1693<p>Implementers are advised to support whichever
1694 stream-checking and connection-checking methods they deem
1695 appropriate, but to carefully weigh the network impact of such
1696 methods against the benefits of discovering broken streams and
1697 dead TCP connections in a timely manner. The length of time
1698 between the use of any particular check is very much a matter
1699 of local service policy and depends strongly on the network
1700 environment and usage scenarios of a given deployment and
1701 connection type. At the time of writing, it is RECOMMENDED that any such check be performed not more than once every 5 minutes and that, ideally, such checks will be initiated by clients rather than servers. Those who implement XMPP software and deploy XMPP services are encouraged to seek additional advice regarding appropriate timing of stream-checking and connection-checking methods, particularly when power-constrained devices are being used (e.g., in mobile environments).
1702</p>
1703<a name="streams-attr"></a><br /><hr />
1704<table summary="layout" cellpadding="0" cellspacing="2" class="TOCbug" align="right"><tr><td class="TOCbug"><a href="#toc">&nbsp;TOC&nbsp;</a></td></tr></table>
1705<a name="rfc.section.4.7"></a><h3>4.7.&nbsp;
1706Stream Attributes</h3>
1707
1708<p>The attributes of the root &lt;stream/&gt; element are defined in the following sections.
1709</p>
1710<p></p>
1711<blockquote class="text">
1712<p>Security Warning: Until and unless the confidentiality and integrity of the stream are protected via TLS as described under <a class='info' href='#tls'>Section&nbsp;5<span> (</span><span class='info'>STARTTLS Negotiation</span><span>)</span></a> or an equivalent security layer (such as the SASL GSSAPI mechanism), the attributes provided in a stream header could be tampered with by an attacker.
1713</p>
1714</blockquote>
1715
1716<p></p>
1717<blockquote class="text">
1718<p>Implementation Note: The attributes of the root &lt;stream/&gt; element are not prepended by a namespace prefix because, as explained in <a class='info' href='#XML-NAMES'>[XML&#8209;NAMES]<span> (</span><span class='info'>Thompson, H., Hollander, D., Layman, A., Bray, T., and R. Tobin, &ldquo;Namespaces in XML 1.0 (Third Edition),&rdquo; December&nbsp;2009.</span><span>)</span></a>, "[d]efault namespace declarations do not apply directly to attribute names; the interpretation of unprefixed attributes is determined by the element on which they appear."
1719</p>
1720</blockquote>
1721
1722<a name="streams-attr-from"></a><br /><hr />
1723<table summary="layout" cellpadding="0" cellspacing="2" class="TOCbug" align="right"><tr><td class="TOCbug"><a href="#toc">&nbsp;TOC&nbsp;</a></td></tr></table>
1724<a name="rfc.section.4.7.1"></a><h3>4.7.1.&nbsp;
1725from</h3>
1726
1727<p>The 'from' attribute specifies an XMPP identity of the entity sending the stream element.
1728</p>
1729<p>For initial stream headers in client-to-server communication, the 'from' attribute is the XMPP identity of the principal controlling the client, i.e., a JID of the form &lt;localpart@domainpart&gt;. The client might not know the XMPP identity, e.g., because the XMPP identity is assigned at a level other than the XMPP application layer (as in the Generic Security Service Application Program Interface <a class='info' href='#GSS-API'>[GSS&#8209;API]<span> (</span><span class='info'>Linn, J., &ldquo;Generic Security Service Application Program Interface Version 2, Update 1,&rdquo; January&nbsp;2000.</span><span>)</span></a>) or is derived by the server from information provided by the client (as in some deployments of end-user certificates with the SASL EXTERNAL mechanism). Furthermore, if the client considers the XMPP identity to be private information then it is advised not to include a 'from' attribute before the confidentiality and integrity of the stream are protected via TLS or an equivalent security layer. However, if the client knows the XMPP identity then it SHOULD include the 'from' attribute after the confidentiality and integrity of the stream are protected via TLS or an equivalent security layer.
1730</p><div style='display: table; width: 0; margin-left: 3em; margin-right: auto'><pre>
1731I: &lt;?xml version='1.0'?&gt;
1732 &lt;stream:stream
1733 from='juliet@im.example.com'
1734 to='im.example.com'
1735 version='1.0'
1736 xml:lang='en'
1737 xmlns='jabber:client'
1738 xmlns:stream='http://etherx.jabber.org/streams'&gt;
1739</pre></div>
1740<p>For initial stream headers in server-to-server communication, the 'from' attribute is one of the configured FQDNs of the server, i.e., a JID of the form &lt;domainpart&gt;. The initiating server might have more than one XMPP identity, e.g., in the case of a server that provides virtual hosting, so it will need to choose an identity that is associated with this output stream (e.g., based on the 'to' attribute of the stanza that triggered the stream negotiation attempt). Because a server is a "public entity" on the XMPP network, it MUST include the 'from' attribute after the confidentiality and integrity of the stream are protected via TLS or an equivalent security layer.
1741</p><div style='display: table; width: 0; margin-left: 3em; margin-right: auto'><pre>
1742I: &lt;?xml version='1.0'?&gt;
1743 &lt;stream:stream
1744 from='example.net'
1745 to='im.example.com'
1746 version='1.0'
1747 xml:lang='en'
1748 xmlns='jabber:server'
1749 xmlns:stream='http://etherx.jabber.org/streams'&gt;
1750</pre></div>
1751<p>For response stream headers in both client-to-server and server-to-server communication, the receiving entity MUST include the 'from' attribute and MUST set its value to one of the receiving entity's FQDNs (which MAY be an FQDN other than that specified in the 'to' attribute of the initial stream header, as described under <a class='info' href='#streams-error-rules-host'>Section&nbsp;4.9.1.3<span> (</span><span class='info'>Stream Errors When the Host Is Unspecified or Unknown</span><span>)</span></a> and <a class='info' href='#streams-error-conditions-host-unknown'>Section&nbsp;4.9.3.6<span> (</span><span class='info'>host-unknown</span><span>)</span></a>).
1752</p><div style='display: table; width: 0; margin-left: 3em; margin-right: auto'><pre>
1753R: &lt;?xml version='1.0'?&gt;
1754 &lt;stream:stream
1755 from='im.example.com'
1756 id='++TR84Sm6A3hnt3Q065SnAbbk3Y='
1757 to='juliet@im.example.com'
1758 version='1.0'
1759 xml:lang='en'
1760 xmlns='jabber:client'
1761 xmlns:stream='http://etherx.jabber.org/streams'&gt;
1762</pre></div>
1763<p>Whether or not the 'from' attribute is included, each entity MUST verify the identity of the other entity before exchanging XML stanzas with it, as described under <a class='info' href='#security-authentication'>Section&nbsp;13.5<span> (</span><span class='info'>Peer Entity Authentication</span><span>)</span></a>.
1764</p>
1765<p></p>
1766<blockquote class="text">
1767<p>Interoperability Note: It is possible that implementations based on <a class='info' href='#RFC3920'>[RFC3920]<span> (</span><span class='info'>Saint-Andre, P., Ed., &ldquo;Extensible Messaging and Presence Protocol (XMPP): Core,&rdquo; October&nbsp;2004.</span><span>)</span></a> will not include the 'from' address on any stream headers (even ones whose confidentiality and integrity are protected); an entity SHOULD be liberal in accepting such stream headers.
1768</p>
1769</blockquote>
1770
1771<a name="streams-attr-to"></a><br /><hr />
1772<table summary="layout" cellpadding="0" cellspacing="2" class="TOCbug" align="right"><tr><td class="TOCbug"><a href="#toc">&nbsp;TOC&nbsp;</a></td></tr></table>
1773<a name="rfc.section.4.7.2"></a><h3>4.7.2.&nbsp;
1774to</h3>
1775
1776<p>For initial stream headers in both client-to-server and server-to-server communication, the initiating entity MUST include the 'to' attribute and MUST set its value to a domainpart that the initiating entity knows or expects the receiving entity to service. (The same information can be provided in other ways, such as a Server Name Indication during TLS negotiation as described in <a class='info' href='#TLS-EXT'>[TLS&#8209;EXT]<span> (</span><span class='info'>Eastlake 3rd, D., &ldquo;Transport Layer Security (TLS) Extensions: Extension Definitions,&rdquo; January&nbsp;2011.</span><span>)</span></a>.)
1777</p><div style='display: table; width: 0; margin-left: 3em; margin-right: auto'><pre>
1778I: &lt;?xml version='1.0'?&gt;
1779 &lt;stream:stream
1780 from='juliet@im.example.com'
1781 to='im.example.com'
1782 version='1.0'
1783 xml:lang='en'
1784 xmlns='jabber:client'
1785 xmlns:stream='http://etherx.jabber.org/streams'&gt;
1786</pre></div>
1787<p>For response stream headers in client-to-server communication, if the client included a 'from' attribute in the initial stream header then the server MUST include a 'to' attribute in the response stream header and MUST set its value to the bare JID specified in the 'from' attribute of the initial stream header. If the client did not include a 'from' attribute in the initial stream header then the server MUST NOT include a 'to' attribute in the response stream header.
1788</p><div style='display: table; width: 0; margin-left: 3em; margin-right: auto'><pre>
1789R: &lt;?xml version='1.0'?&gt;
1790 &lt;stream:stream
1791 from='im.example.com'
1792 id='++TR84Sm6A3hnt3Q065SnAbbk3Y='
1793 to='juliet@im.example.com'
1794 version='1.0'
1795 xml:lang='en'
1796 xmlns='jabber:client'
1797 xmlns:stream='http://etherx.jabber.org/streams'&gt;
1798</pre></div>
1799<p>For response stream headers in server-to-server communication, the receiving entity MUST include a 'to' attribute in the response stream header and MUST set its value to the domainpart specified in the 'from' attribute of the initial stream header.
1800</p><div style='display: table; width: 0; margin-left: 3em; margin-right: auto'><pre>
1801R: &lt;?xml version='1.0'?&gt;
1802 &lt;stream:stream
1803 from='im.example.com'
1804 id='g4qSvGvBxJ+xeAd7QKezOQJFFlw='
1805 to='example.net'
1806 version='1.0'
1807 xml:lang='en'
1808 xmlns='jabber:server'
1809 xmlns:stream='http://etherx.jabber.org/streams'&gt;
1810</pre></div>
1811<p>Whether or not the 'to' attribute is included, each entity MUST verify the identity of the other entity before exchanging XML stanzas with it, as described under <a class='info' href='#security-authentication'>Section&nbsp;13.5<span> (</span><span class='info'>Peer Entity Authentication</span><span>)</span></a>.
1812</p>
1813<p></p>
1814<blockquote class="text">
1815<p>Interoperability Note: It is possible that implementations based on <a class='info' href='#RFC3920'>[RFC3920]<span> (</span><span class='info'>Saint-Andre, P., Ed., &ldquo;Extensible Messaging and Presence Protocol (XMPP): Core,&rdquo; October&nbsp;2004.</span><span>)</span></a> will not include the 'to' address on stream headers; an entity SHOULD be liberal in accepting such stream headers.
1816</p>
1817</blockquote>
1818
1819<a name="streams-attr-id"></a><br /><hr />
1820<table summary="layout" cellpadding="0" cellspacing="2" class="TOCbug" align="right"><tr><td class="TOCbug"><a href="#toc">&nbsp;TOC&nbsp;</a></td></tr></table>
1821<a name="rfc.section.4.7.3"></a><h3>4.7.3.&nbsp;
1822id</h3>
1823
1824<p>The 'id' attribute specifies a unique identifier for the stream, called a "stream ID". The stream ID MUST be generated by the receiving entity when it sends a response stream header and MUST BE unique within the receiving application (normally a server).
1825</p>
1826<p></p>
1827<blockquote class="text">
1828<p>Security Warning: The stream ID MUST be both unpredictable and non-repeating because it can be security-critical when reused by an authentication mechanisms, as is the case for Server Dialback <a class='info' href='#XEP-0220'>[XEP&#8209;0220]<span> (</span><span class='info'>Miller, J., Saint-Andre, P., and P. Hancke, &ldquo;Server Dialback,&rdquo; March&nbsp;2010.</span><span>)</span></a> and the "XMPP 0.9" authentication mechanism used before RFC 3920 defined the use of SASL in XMPP; for recommendations regarding randomness for security purposes, see <a class='info' href='#RANDOM'>[RANDOM]<span> (</span><span class='info'>Eastlake, D., Schiller, J., and S. Crocker, &ldquo;Randomness Requirements for Security,&rdquo; June&nbsp;2005.</span><span>)</span></a>.
1829</p>
1830</blockquote>
1831
1832<p>For initial stream headers, the initiating entity MUST NOT include the 'id' attribute; however, if the 'id' attribute is included, the receiving entity MUST ignore it.
1833</p>
1834<p>For response stream headers, the receiving entity MUST include the 'id' attribute.
1835</p><div style='display: table; width: 0; margin-left: 3em; margin-right: auto'><pre>
1836R: &lt;?xml version='1.0'?&gt;
1837 &lt;stream:stream
1838 from='im.example.com'
1839 id='++TR84Sm6A3hnt3Q065SnAbbk3Y='
1840 to='juliet@im.example.com'
1841 version='1.0'
1842 xml:lang='en'
1843 xmlns='jabber:client'
1844 xmlns:stream='http://etherx.jabber.org/streams'&gt;
1845</pre></div>
1846<p></p>
1847<blockquote class="text">
1848<p>Interoperability Note: In RFC 3920, the text regarding inclusion of the 'id' attribute was ambiguous, leading some implementations to leave the attribute off the response stream header.
1849</p>
1850</blockquote>
1851
1852<a name="streams-attr-xmllang"></a><br /><hr />
1853<table summary="layout" cellpadding="0" cellspacing="2" class="TOCbug" align="right"><tr><td class="TOCbug"><a href="#toc">&nbsp;TOC&nbsp;</a></td></tr></table>
1854<a name="rfc.section.4.7.4"></a><h3>4.7.4.&nbsp;
1855xml:lang</h3>
1856
1857<p>The 'xml:lang' attribute specifies an entity's preferred or default language for any human-readable XML character data to be sent over the stream (an XML stanza can also possess an 'xml:lang' attribute, as discussed under <a class='info' href='#stanzas-attributes-lang'>Section&nbsp;8.1.5<span> (</span><span class='info'>xml:lang</span><span>)</span></a>). The syntax of this attribute is defined in Section 2.12 of <a class='info' href='#XML'>[XML]<span> (</span><span class='info'>Maler, E., Yergeau, F., Sperberg-McQueen, C., Paoli, J., and T. Bray, &ldquo;Extensible Markup Language (XML) 1.0 (Fifth Edition),&rdquo; November&nbsp;2008.</span><span>)</span></a>; in particular, the value of the 'xml:lang' attribute MUST conform to the NMTOKEN datatype (as defined in Section 2.3 of <a class='info' href='#XML'>[XML]<span> (</span><span class='info'>Maler, E., Yergeau, F., Sperberg-McQueen, C., Paoli, J., and T. Bray, &ldquo;Extensible Markup Language (XML) 1.0 (Fifth Edition),&rdquo; November&nbsp;2008.</span><span>)</span></a>) and MUST conform to the language identifier format defined in <a class='info' href='#LANGTAGS'>[LANGTAGS]<span> (</span><span class='info'>Phillips, A. and M. Davis, &ldquo;Tags for Identifying Languages,&rdquo; September&nbsp;2009.</span><span>)</span></a>.
1858</p>
1859<p>For initial stream headers, the initiating entity SHOULD include the 'xml:lang' attribute.
1860</p><div style='display: table; width: 0; margin-left: 3em; margin-right: auto'><pre>
1861I: &lt;?xml version='1.0'?&gt;
1862 &lt;stream:stream
1863 from='juliet@im.example.com'
1864 to='im.example.com'
1865 version='1.0'
1866 xml:lang='en'
1867 xmlns='jabber:client'
1868 xmlns:stream='http://etherx.jabber.org/streams'&gt;
1869</pre></div>
1870<p>For response stream headers, the receiving entity MUST include the 'xml:lang' attribute. The following rules apply:
1871</p>
1872<p>
1873 </p>
1874<ul class="text">
1875<li>If the initiating entity included an 'xml:lang' attribute in its initial stream header and the receiving entity supports that language in the human-readable XML character data that it generates and sends to the initiating entity (e.g., in the &lt;text/&gt; element for stream and stanza errors), the value of the 'xml:lang' attribute MUST be the identifier for the initiating entity's preferred language (e.g., "de-CH").
1876</li>
1877<li>If the receiving entity supports a language that matches the initiating entity's preferred language according to the "lookup scheme" specified in Section 3.4 of <a class='info' href='#LANGMATCH'>[LANGMATCH]<span> (</span><span class='info'>Phillips, A. and M. Davis, &ldquo;Matching of Language Tags,&rdquo; September&nbsp;2006.</span><span>)</span></a> (e.g., "de" instead of "de-CH"), then the value of the 'xml:lang' attribute SHOULD be the identifier for the matching language.
1878</li>
1879<li>If the receiving entity does not support the initiating entity's preferred language or a matching language according to the lookup scheme (or if the initiating entity did not include the 'xml:lang' attribute in its initial stream header), then the value of the 'xml:lang' attribute MUST be the identifier for the default language of the receiving entity (e.g., "en").
1880</li>
1881</ul><p>
1882
1883</p><div style='display: table; width: 0; margin-left: 3em; margin-right: auto'><pre>
1884R: &lt;?xml version='1.0'?&gt;
1885 &lt;stream:stream
1886 from='im.example.com'
1887 id='++TR84Sm6A3hnt3Q065SnAbbk3Y='
1888 to='juliet@im.example.com'
1889 version='1.0'
1890 xml:lang='en'
1891 xmlns='jabber:client'
1892 xmlns:stream='http://etherx.jabber.org/streams'&gt;
1893</pre></div>
1894<p>If the initiating entity included the 'xml:lang' attribute in its initial stream header, the receiving entity SHOULD remember that value as the default xml:lang for all stanzas sent by the initiating entity over the current stream. As described under <a class='info' href='#stanzas-attributes-lang'>Section&nbsp;8.1.5<span> (</span><span class='info'>xml:lang</span><span>)</span></a>, the initiating entity MAY include the 'xml:lang' attribute in any XML stanzas it sends over the stream. If the initiating entity does not include the 'xml:lang' attribute in any such stanza, the receiving entity SHOULD add the 'xml:lang' attribute to the stanza when routing it to a remote server or delivering it to a connected client, where the value of the attribute MUST be the identifier for the language preferred by the initiating entity (even if the receiving entity does not support that language for human-readable XML character data it generates and sends to the initiating entity, such as in stream or stanza errors). If the initiating entity includes the 'xml:lang' attribute in any such stanza, the receiving entity MUST NOT modify or delete it when routing it to a remote server or delivering it to a connected client.
1895</p>
1896<a name="streams-attr-version"></a><br /><hr />
1897<table summary="layout" cellpadding="0" cellspacing="2" class="TOCbug" align="right"><tr><td class="TOCbug"><a href="#toc">&nbsp;TOC&nbsp;</a></td></tr></table>
1898<a name="rfc.section.4.7.5"></a><h3>4.7.5.&nbsp;
1899version</h3>
1900
1901<p>The inclusion of the version attribute set to a value of at least "1.0" signals support for the stream-related protocols defined in this specification, including <a class='info' href='#tls'>TLS negotiation<span> (</span><span class='info'>STARTTLS Negotiation</span><span>)</span></a>, <a class='info' href='#sasl'>SASL negotiation<span> (</span><span class='info'>SASL Negotiation</span><span>)</span></a>, <a class='info' href='#streams-negotiation-features'>stream features<span> (</span><span class='info'>Stream Features Format</span><span>)</span></a>, and <a class='info' href='#streams-error'>stream errors<span> (</span><span class='info'>Stream Errors</span><span>)</span></a>.
1902</p>
1903<p>The version of XMPP specified in this specification is "1.0"; in
1904particular, XMPP 1.0 encapsulates the stream-related protocols as well as the
1905basic semantics of the three defined XML stanza types (&lt;message/&gt;,
1906&lt;presence/&gt;, and &lt;iq/&gt; as described under Sections <a class='info' href='#stanzas-semantics-message'>8.2.1<span> (</span><span class='info'>Message Semantics</span><span>)</span></a>, <a class='info' href='#stanzas-semantics-presence'>8.2.2<span> (</span><span class='info'>Presence Semantics</span><span>)</span></a>, and <a class='info' href='#stanzas-semantics-iq'>8.2.3<span> (</span><span class='info'>IQ Semantics</span><span>)</span></a>, respectively).
1907</p>
1908<p>The numbering scheme for XMPP versions is "&lt;major&gt;.&lt;minor&gt;". The major and minor numbers MUST be treated as separate integers and each number MAY be incremented higher than a single digit. Thus, "XMPP 2.4" would be a lower version than "XMPP 2.13", which in turn would be lower than "XMPP 12.3". Leading zeros (e.g., "XMPP 6.01") MUST be ignored by recipients and MUST NOT be sent.
1909</p>
1910<p>The major version number will be incremented only if the stream and stanza formats or obligatory actions have changed so dramatically that an older version entity would not be able to interoperate with a newer version entity if it simply ignored the elements and attributes it did not understand and took the actions defined in the older specification.
1911</p>
1912<p>The minor version number will be incremented only if significant new capabilities have been added to the core protocol (e.g., a newly defined value of the 'type' attribute for message, presence, or IQ stanzas). The minor version number MUST be ignored by an entity with a smaller minor version number, but MAY be used for informational purposes by the entity with the larger minor version number (e.g., the entity with the larger minor version number would simply note that its correspondent would not be able to understand that value of the 'type' attribute and therefore would not send it).
1913</p>
1914<p>The following rules apply to the generation and handling of the 'version' attribute within stream headers:
1915</p>
1916<p>
1917 </p>
1918<ol class="text">
1919<li>The initiating entity MUST set the value of the 'version' attribute in the initial stream header to the highest version number it supports (e.g., if the highest version number it supports is that defined in this specification, it MUST set the value to "1.0").
1920</li>
1921<li>The receiving entity MUST set the value of the 'version' attribute in the response stream header to either the value supplied by the initiating entity or the highest version number supported by the receiving entity, whichever is lower. The receiving entity MUST perform a numeric comparison on the major and minor version numbers, not a string match on "&lt;major&gt;.&lt;minor&gt;".
1922</li>
1923<li>If the version number included in the response stream header is at least one major version lower than the version number included in the initial stream header and newer version entities cannot interoperate with older version entities as described, the initiating entity SHOULD close the stream with an &lt;unsupported-version/&gt; stream error (<a class='info' href='#streams-error-conditions-unsupported-version'>Section&nbsp;4.9.3.25<span> (</span><span class='info'>unsupported-version</span><span>)</span></a>).
1924</li>
1925<li>If either entity receives a stream header with no 'version' attribute, the entity MUST consider the version supported by the other entity to be "0.9" and SHOULD NOT include a 'version' attribute in the response stream header.
1926</li>
1927</ol><p>
1928
1929</p>
1930<a name="streams-attr-summary"></a><br /><hr />
1931<table summary="layout" cellpadding="0" cellspacing="2" class="TOCbug" align="right"><tr><td class="TOCbug"><a href="#toc">&nbsp;TOC&nbsp;</a></td></tr></table>
1932<a name="rfc.section.4.7.6"></a><h3>4.7.6.&nbsp;
1933Summary of Stream Attributes</h3>
1934
1935<p>The following table summarizes the attributes of the root &lt;stream/&gt; element.
1936</p><br /><hr class="insert" />
1937<a name="figure-4"></a>
1938<div style='display: table; width: 0; margin-left: 3em; margin-right: auto'><pre>
1939+----------+--------------------------+-------------------------+
1940| | initiating to receiving | receiving to initiating |
1941+----------+--------------------------+-------------------------+
1942| to | JID of receiver | JID of initiator |
1943| from | JID of initiator | JID of receiver |
1944| id | ignored | stream identifier |
1945| xml:lang | default language | default language |
1946| version | XMPP 1.0+ supported | XMPP 1.0+ supported |
1947+----------+--------------------------+-------------------------+
1948</pre></div><table border="0" cellpadding="0" cellspacing="2" align="center"><tr><td align="center"><font face="monaco, MS Sans Serif" size="1"><b>&nbsp;Figure&nbsp;4: Stream Attributes&nbsp;</b></font><br /></td></tr></table><hr class="insert" />
1949
1950<a name="streams-ns"></a><br /><hr />
1951<table summary="layout" cellpadding="0" cellspacing="2" class="TOCbug" align="right"><tr><td class="TOCbug"><a href="#toc">&nbsp;TOC&nbsp;</a></td></tr></table>
1952<a name="rfc.section.4.8"></a><h3>4.8.&nbsp;
1953XML Namespaces</h3>
1954
1955<p>Readers are referred to the specification of XML namespaces <a class='info' href='#XML-NAMES'>[XML&#8209;NAMES]<span> (</span><span class='info'>Thompson, H., Hollander, D., Layman, A., Bray, T., and R. Tobin, &ldquo;Namespaces in XML 1.0 (Third Edition),&rdquo; December&nbsp;2009.</span><span>)</span></a> for a full understanding of the concepts used in this section, especially the concept of a "default namespace" as provided in Section 3 and Section 6.2 of that specification.
1956</p>
1957<a name="streams-ns-stream"></a><br /><hr />
1958<table summary="layout" cellpadding="0" cellspacing="2" class="TOCbug" align="right"><tr><td class="TOCbug"><a href="#toc">&nbsp;TOC&nbsp;</a></td></tr></table>
1959<a name="rfc.section.4.8.1"></a><h3>4.8.1.&nbsp;
1960Stream Namespace</h3>
1961
1962<p>The root &lt;stream/&gt; element ("stream header") MUST be qualified by the namespace 'http://etherx.jabber.org/streams' (the "stream namespace"). If this rule is violated, the entity that receives the offending stream header MUST close the stream with a stream error, which SHOULD be &lt;invalid-namespace/&gt; (<a class='info' href='#streams-error-conditions-invalid-namespace'>Section&nbsp;4.9.3.10<span> (</span><span class='info'>invalid-namespace</span><span>)</span></a>), although some existing implementations send &lt;bad-format/&gt; (<a class='info' href='#streams-error-conditions-bad-format'>Section&nbsp;4.9.3.1<span> (</span><span class='info'>bad-format</span><span>)</span></a>) instead.
1963</p>
1964<a name="streams-ns-content"></a><br /><hr />
1965<table summary="layout" cellpadding="0" cellspacing="2" class="TOCbug" align="right"><tr><td class="TOCbug"><a href="#toc">&nbsp;TOC&nbsp;</a></td></tr></table>
1966<a name="rfc.section.4.8.2"></a><h3>4.8.2.&nbsp;
1967Content Namespace</h3>
1968
1969<p>An entity MAY declare a "content namespace" as the default namespace for data sent over the stream (i.e., data other than elements qualified by the stream namespace). If so, (1) the content namespace MUST be other than the stream namespace, and (2) the content namespace MUST be the same for the initial stream and the response stream so that both streams are qualified consistently. The content namespace applies to all first-level child elements sent over the stream unless explicitly qualified by another namespace (i.e., the content namespace is the default namespace).
1970</p>
1971<p>Alternatively (i.e., instead of declaring the content namespace as the default namespace), an entity MAY explicitly qualify the namespace for each first-level child element of the stream, using so-called "prefix-free canonicalization". These two styles are shown in the following examples.
1972</p>
1973<p>When a content namespace is declared as the default namespace, in rough outline a stream will look something like the following.
1974</p><div style='display: table; width: 0; margin-left: 3em; margin-right: auto'><pre>
1975&lt;stream:stream
1976 from='juliet@im.example.com'
1977 to='im.example.com'
1978 version='1.0'
1979 xml:lang='en'
1980 xmlns='jabber:client'
1981 xmlns:stream='http://etherx.jabber.org/streams'&gt;
1982 &lt;message&gt;
1983 &lt;body&gt;foo&lt;/body&gt;
1984 &lt;/message&gt;
1985&lt;/stream:stream&gt;
1986</pre></div>
1987<p>When a content namespace is not declared as the default namespace and so-called "prefix-free canonicalization" is used instead, in rough outline a stream will look something like the following.
1988</p><div style='display: table; width: 0; margin-left: 3em; margin-right: auto'><pre>
1989&lt;stream
1990 from='juliet@im.example.com'
1991 to='im.example.com'
1992 version='1.0'
1993 xml:lang='en'
1994 xmlns='http://etherx.jabber.org/streams'&gt;
1995 &lt;message xmlns='jabber:client'&gt;
1996 &lt;body&gt;foo&lt;/body&gt;
1997 &lt;/message&gt;
1998&lt;/stream&gt;
1999</pre></div>
2000<p>Traditionally, most XMPP implementations have used the content-namespace-as-default-namespace style rather than the prefix-free canonicalization style for stream headers; however, both styles are acceptable since they are semantically equivalent.
2001</p>
2002<a name="streams-ns-xmpp"></a><br /><hr />
2003<table summary="layout" cellpadding="0" cellspacing="2" class="TOCbug" align="right"><tr><td class="TOCbug"><a href="#toc">&nbsp;TOC&nbsp;</a></td></tr></table>
2004<a name="rfc.section.4.8.3"></a><h3>4.8.3.&nbsp;
2005XMPP Content Namespaces</h3>
2006
2007<p>XMPP as defined in this specification uses two content namespaces: 'jabber:client' and 'jabber:server'. These namespaces are nearly identical but are used in different contexts (client-to-server communication for 'jabber:client' and server-to-server communication for 'jabber:server'). The only difference between the two is that the 'to' and 'from' attributes are OPTIONAL on stanzas sent over XML streams qualified by the 'jabber:client' namespace, whereas they are REQUIRED on stanzas sent over XML streams qualified by the 'jabber:server' namespace. Support for these content namespaces implies support for the <a class='info' href='#stanzas-attributes'>common attributes<span> (</span><span class='info'>Common Attributes</span><span>)</span></a> and <a class='info' href='#stanzas-semantics'>basic semantics<span> (</span><span class='info'>Basic Semantics</span><span>)</span></a> of all three core stanza types (message, presence, and IQ).
2008</p>
2009<p>An implementation MAY support content namespaces other than 'jabber:client' or 'jabber:server'. However, because such namespaces would define applications other than XMPP, they are to be defined in separate specifications.
2010</p>
2011<p>An implementation MAY refuse to support any other content namespaces as default namespaces. If an entity receives a first-level child element qualified by a content namespace it does not support, it MUST close the stream with an &lt;invalid-namespace/&gt; stream error (<a class='info' href='#streams-error-conditions-invalid-namespace'>Section&nbsp;4.9.3.10<span> (</span><span class='info'>invalid-namespace</span><span>)</span></a>).
2012</p>
2013<p>Client implementations MUST support the 'jabber:client' content namespace as a default namespace. The 'jabber:server' content namespace is out of scope for an XMPP client, and a client MUST NOT send stanzas qualified by the 'jabber:server' namespace.
2014</p>
2015<p>Server implementations MUST support as default content namespaces both the 'jabber:client' namespace (when the stream is used for communication between a client and a server) and the 'jabber:server' namespace (when the stream is used for communication between two servers). When communicating with a connected client, a server MUST NOT send stanzas qualified by the 'jabber:server' namespace; when communicating with a peer server, a server MUST NOT send stanzas qualified by the 'jabber:client' namespace.
2016</p>
2017<p></p>
2018<blockquote class="text">
2019<p>Implementation Note: Because a client sends stanzas over a stream whose content namespace is 'jabber:client', if a server routes to a peer server a stanza it has received from a connected client then it needs to "re-scope" the stanza so that its content namespace is 'jabber:server'. Similarly, if a server delivers to a connected client a stanza it has received from a peer server then it needs to "re-scope" the stanza so that its content namespace is 'jabber:client'. This rule applies to XML stanzas as defined under <a class='info' href='#streams-fundamentals'>Section&nbsp;4.1<span> (</span><span class='info'>Stream Fundamentals</span><span>)</span></a> (i.e., a first-level &lt;message/&gt;, &lt;presence/&gt;, or &lt;iq/&gt; element qualified by the 'jabber:client' or 'jabber:server' namespace), and by namespace inheritance to all child elements of a stanza. However, the rule does not apply to elements qualified by namespaces other than 'jabber:client' and 'jabber:server' nor to any children of such elements (e.g., a &lt;message/&gt; element contained within an extension element (<a class='info' href='#stanzas-extended'>Section&nbsp;8.4<span> (</span><span class='info'>Extended Content</span><span>)</span></a>) for reporting purposes). Although it is not forbidden for an entity to generate stanzas in which an extension element contains a child element qualified by the 'jabber:client' or 'jabber:server' namespace, existing implementations handle such stanzas inconsistently; therefore, implementers are advised to weigh the likely lack of interoperability against the possible utility of such stanzas. Finally, servers are advised to apply stanza re-scoping to other stream connection methods and alternative XMPP connection methods, such as those specified in <a class='info' href='#XEP-0124'>[XEP&#8209;0124]<span> (</span><span class='info'>Paterson, I., Smith, D., and P. Saint-Andre, &ldquo;Bidirectional-streams Over Synchronous HTTP (BOSH),&rdquo; July&nbsp;2010.</span><span>)</span></a>, <a class='info' href='#XEP-0206'>[XEP&#8209;0206]<span> (</span><span class='info'>Paterson, I. and P. Saint-Andre, &ldquo;XMPP Over BOSH,&rdquo; July&nbsp;2010.</span><span>)</span></a>, <a class='info' href='#XEP-0114'>[XEP&#8209;0114]<span> (</span><span class='info'>Saint-Andre, P., &ldquo;Jabber Component Protocol,&rdquo; March&nbsp;2005.</span><span>)</span></a>, and <a class='info' href='#XEP-0225'>[XEP&#8209;0225]<span> (</span><span class='info'>Saint-Andre, P., &ldquo;Component Connections,&rdquo; October&nbsp;2008.</span><span>)</span></a>.
2020</p>
2021</blockquote>
2022
2023<a name="streams-ns-other"></a><br /><hr />
2024<table summary="layout" cellpadding="0" cellspacing="2" class="TOCbug" align="right"><tr><td class="TOCbug"><a href="#toc">&nbsp;TOC&nbsp;</a></td></tr></table>
2025<a name="rfc.section.4.8.4"></a><h3>4.8.4.&nbsp;
2026Other Namespaces</h3>
2027
2028<p>Either party to a stream MAY send data qualified by namespaces other than the content namespace and the stream namespace. For example, this is how data related to TLS negotiation and SASL negotiation are exchanged, as well as XMPP extensions such as Stream Management <a class='info' href='#XEP-0198'>[XEP&#8209;0198]<span> (</span><span class='info'>Karneges, J., Hildebrand, J., Saint-Andre, P., Forno, F., Cridland, D., and M. Wild, &ldquo;Stream Management,&rdquo; February&nbsp;2011.</span><span>)</span></a> and Server Dialback <a class='info' href='#XEP-0220'>[XEP&#8209;0220]<span> (</span><span class='info'>Miller, J., Saint-Andre, P., and P. Hancke, &ldquo;Server Dialback,&rdquo; March&nbsp;2010.</span><span>)</span></a>.
2029</p>
2030<p></p>
2031<blockquote class="text">
2032<p>Interoperability Note: For historical reasons, some server implementations expect a declaration of the 'jabber:server:dialback' namespace on server-to-server streams, as explained in <a class='info' href='#XEP-0220'>[XEP&#8209;0220]<span> (</span><span class='info'>Miller, J., Saint-Andre, P., and P. Hancke, &ldquo;Server Dialback,&rdquo; March&nbsp;2010.</span><span>)</span></a>.
2033</p>
2034</blockquote>
2035
2036<p>However, an XMPP server MUST NOT route or deliver data received over an input stream if that data is (a) qualified by another namespace and (b) addressed to an entity other than the server, unless the other party to the output stream over which the server would send the data has explicitly negotiated or advertised support for receiving arbitrary data from the server. This rule is included because XMPP is designed for the exchange of XML stanzas (not arbitrary XML data), and because allowing an entity to send arbitrary data to other entities could significantly increase the potential for exchanging malicious information. As an example of this rule, the server hosting the example.net domain would not route the following first-level XML element from &lt;romeo@example.net&gt; to &lt;juliet@example.com&gt;:
2037</p><div style='display: table; width: 0; margin-left: 3em; margin-right: auto'><pre>
2038 &lt;ns1:foo xmlns:ns1='http://example.org/ns1'
2039 from='romeo@example.net/resource1'
2040 to='juliet@example.com'&gt;
2041 &lt;ns1:bar/&gt;
2042 &lt;/ns1:foo&gt;
2043</pre></div>
2044<p>This rule also applies to first-level elements that look like stanzas but that are improperly namespaced and therefore really are not stanzas at all (see also <a class='info' href='#streams-ns-declarations'>Section&nbsp;4.8.5<span> (</span><span class='info'>Namespace Declarations and Prefixes</span><span>)</span></a>), for example:
2045</p><div style='display: table; width: 0; margin-left: 3em; margin-right: auto'><pre>
2046 &lt;ns2:message xmlns:ns2='http://example.org/ns2'
2047 from='romeo@example.net/resource1'
2048 to='juliet@example.com'&gt;
2049 &lt;body&gt;hi&lt;/body&gt;
2050 &lt;/ns2:message&gt;
2051</pre></div>
2052<p>Upon receiving arbitrary first-level XML elements over an input stream, a server MUST either ignore the data or close the stream with a stream error, which SHOULD be &lt;unsupported-stanza-type/&gt; (<a class='info' href='#streams-error-conditions-unsupported-stanza-type'>Section&nbsp;4.9.3.24<span> (</span><span class='info'>unsupported-stanza-type</span><span>)</span></a>).
2053</p>
2054<a name="streams-ns-declarations"></a><br /><hr />
2055<table summary="layout" cellpadding="0" cellspacing="2" class="TOCbug" align="right"><tr><td class="TOCbug"><a href="#toc">&nbsp;TOC&nbsp;</a></td></tr></table>
2056<a name="rfc.section.4.8.5"></a><h3>4.8.5.&nbsp;
2057Namespace Declarations and Prefixes</h3>
2058
2059<p>Because the content namespace is other than the stream namespace, if a content namespace is declared as the default namespace then the following statements are true:
2060</p>
2061<p>
2062 </p>
2063<ol class="text">
2064<li>The stream header needs to contain a namespace declaration for both the content namespace and the stream namespace.
2065</li>
2066<li>The stream namespace declaration needs to include a namespace prefix for the stream namespace.
2067</li>
2068</ol><p>
2069
2070</p>
2071<p></p>
2072<blockquote class="text">
2073<p>Interoperability Note: For historical reasons, an implementation MAY accept only the prefix 'stream' for the stream namespace (resulting in prefixed names such as &lt;stream:stream&gt; and &lt;stream:features&gt;); this specification retains that allowance from <a class='info' href='#RFC3920'>[RFC3920]<span> (</span><span class='info'>Saint-Andre, P., Ed., &ldquo;Extensible Messaging and Presence Protocol (XMPP): Core,&rdquo; October&nbsp;2004.</span><span>)</span></a> for the purpose of backward compatibility. Implementations are advised that using a prefix other than 'stream' for the stream namespace might result in interoperability problems. If an entity receives a stream header with a stream namespace prefix it does not accept, it MUST close the stream with a stream error, which SHOULD be &lt;bad-namespace-prefix/&gt; (<a class='info' href='#streams-error-conditions-bad-namespace-prefix'>Section&nbsp;4.9.3.2<span> (</span><span class='info'>bad-namespace-prefix</span><span>)</span></a>), although some existing implementations send &lt;bad-format/&gt; (<a class='info' href='#streams-error-conditions-bad-format'>Section&nbsp;4.9.3.1<span> (</span><span class='info'>bad-format</span><span>)</span></a>) instead.
2074</p>
2075</blockquote>
2076
2077<p>An implementation MUST NOT generate namespace prefixes for elements qualified by the content namespace (i.e., the default namespace for data sent over the stream) if the content namespace is 'jabber:client' or 'jabber:server'. For example, the following is illegal:
2078</p><div style='display: table; width: 0; margin-left: 3em; margin-right: auto'><pre>
2079&lt;stream:stream
2080 from='juliet@im.example.com'
2081 to='im.example.com'
2082 version='1.0'
2083 xml:lang='en'
2084 xmlns='jabber:client'
2085 xmlns:stream='http://etherx.jabber.org/streams'&gt;
2086
2087 &lt;foo:message xmlns:foo='jabber:client'&gt;
2088 &lt;foo:body&gt;foo&lt;/foo:body&gt;
2089 &lt;/foo:message&gt;
2090</pre></div>
2091<p>An XMPP entity SHOULD NOT accept data that violates this rule (in
2092particular, an XMPP server MUST NOT route or deliver such data to another
2093entity without first correcting the error); instead it SHOULD either ignore the data or close the stream with a stream error, which SHOULD be &lt;bad-namespace-prefix/&gt; (<a class='info' href='#streams-error-conditions-bad-namespace-prefix'>Section&nbsp;4.9.3.2<span> (</span><span class='info'>bad-namespace-prefix</span><span>)</span></a>).
2094</p>
2095<p>Namespaces declared in a stream header MUST apply only to that stream (e.g., the 'jabber:server:dialback' namespace used in Server Dialback <a class='info' href='#XEP-0220'>[XEP&#8209;0220]<span> (</span><span class='info'>Miller, J., Saint-Andre, P., and P. Hancke, &ldquo;Server Dialback,&rdquo; March&nbsp;2010.</span><span>)</span></a>). In particular, because XML stanzas intended for routing or delivery over streams with other entities will lose the namespace context declared in the header of the stream in which those stanzas originated, namespaces for extended content within such stanzas MUST NOT be declared in that stream header (see also <a class='info' href='#stanzas-extended'>Section&nbsp;8.4<span> (</span><span class='info'>Extended Content</span><span>)</span></a>). If either party to a stream declares such namespaces, the other party to the stream SHOULD close the stream with an &lt;invalid-namespace/&gt; stream error (<a class='info' href='#streams-error-conditions-invalid-namespace'>Section&nbsp;4.9.3.10<span> (</span><span class='info'>invalid-namespace</span><span>)</span></a>). In any case, an entity MUST ensure that such namespaces are properly declared (according to this section) when routing or delivering stanzas from an input stream to an output stream.
2096</p>
2097<a name="streams-error"></a><br /><hr />
2098<table summary="layout" cellpadding="0" cellspacing="2" class="TOCbug" align="right"><tr><td class="TOCbug"><a href="#toc">&nbsp;TOC&nbsp;</a></td></tr></table>
2099<a name="rfc.section.4.9"></a><h3>4.9.&nbsp;
2100Stream Errors</h3>
2101
2102<p>The root stream element MAY contain an &lt;error/&gt; child element that is qualified by the stream namespace. The error child SHALL be sent by a compliant entity if it perceives that a stream-level error has occurred.
2103</p>
2104<a name="streams-error-rules"></a><br /><hr />
2105<table summary="layout" cellpadding="0" cellspacing="2" class="TOCbug" align="right"><tr><td class="TOCbug"><a href="#toc">&nbsp;TOC&nbsp;</a></td></tr></table>
2106<a name="rfc.section.4.9.1"></a><h3>4.9.1.&nbsp;
2107Rules</h3>
2108
2109<p>The following rules apply to stream-level errors.
2110</p>
2111<a name="streams-error-rules-unrecoverable"></a><br /><hr />
2112<table summary="layout" cellpadding="0" cellspacing="2" class="TOCbug" align="right"><tr><td class="TOCbug"><a href="#toc">&nbsp;TOC&nbsp;</a></td></tr></table>
2113<a name="rfc.section.4.9.1.1"></a><h3>4.9.1.1.&nbsp;
2114Stream Errors Are Unrecoverable</h3>
2115
2116<p>Stream-level errors are unrecoverable. Therefore, if an error occurs at the level of the stream, the entity that detects the error MUST send an &lt;error/&gt; element with an appropriate child element specifying the error condition and then immediately close the stream as described under <a class='info' href='#streams-close'>Section&nbsp;4.4<span> (</span><span class='info'>Closing a Stream</span><span>)</span></a>.
2117</p><div style='display: table; width: 0; margin-left: 3em; margin-right: auto'><pre>
2118C: &lt;message&gt;&lt;body&gt;No closing tag!&lt;/message&gt;
2119
2120S: &lt;stream:error&gt;
2121 &lt;not-well-formed
2122 xmlns='urn:ietf:params:xml:ns:xmpp-streams'/&gt;
2123 &lt;/stream:error&gt;
2124 &lt;/stream:stream&gt;
2125</pre></div>
2126<p>The entity that receives the stream error then SHALL close the stream as explained under <a class='info' href='#streams-close'>Section&nbsp;4.4<span> (</span><span class='info'>Closing a Stream</span><span>)</span></a>.
2127</p><div style='display: table; width: 0; margin-left: 3em; margin-right: auto'><pre>
2128C: &lt;/stream:stream&gt;
2129</pre></div>
2130<a name="streams-error-rules-setup"></a><br /><hr />
2131<table summary="layout" cellpadding="0" cellspacing="2" class="TOCbug" align="right"><tr><td class="TOCbug"><a href="#toc">&nbsp;TOC&nbsp;</a></td></tr></table>
2132<a name="rfc.section.4.9.1.2"></a><h3>4.9.1.2.&nbsp;
2133Stream Errors Can Occur During Setup</h3>
2134
2135<p>If the error is triggered by the initial stream header, the receiving entity MUST still send the opening &lt;stream&gt; tag, include the &lt;error/&gt; element as a child of the stream element, and send the closing &lt;/stream&gt; tag (preferably in the same TCP packet).
2136</p><div style='display: table; width: 0; margin-left: 3em; margin-right: auto'><pre>
2137C: &lt;?xml version='1.0'?&gt;
2138 &lt;stream:stream
2139 from='juliet@im.example.com'
2140 to='im.example.com'
2141 version='1.0'
2142 xml:lang='en'
2143 xmlns='jabber:client'
2144 xmlns:stream='http://wrong.namespace.example.org/'&gt;
2145
2146S: &lt;?xml version='1.0'?&gt;
2147 &lt;stream:stream
2148 from='im.example.com'
2149 id='++TR84Sm6A3hnt3Q065SnAbbk3Y='
2150 to='juliet@im.example.com'
2151 version='1.0'
2152 xml:lang='en'
2153 xmlns='jabber:client'
2154 xmlns:stream='http://etherx.jabber.org/streams'&gt;
2155 &lt;stream:error&gt;
2156 &lt;invalid-namespace
2157 xmlns='urn:ietf:params:xml:ns:xmpp-streams'/&gt;
2158 &lt;/stream:error&gt;
2159 &lt;/stream:stream&gt;
2160</pre></div>
2161<a name="streams-error-rules-host"></a><br /><hr />
2162<table summary="layout" cellpadding="0" cellspacing="2" class="TOCbug" align="right"><tr><td class="TOCbug"><a href="#toc">&nbsp;TOC&nbsp;</a></td></tr></table>
2163<a name="rfc.section.4.9.1.3"></a><h3>4.9.1.3.&nbsp;
2164Stream Errors When the Host Is Unspecified or Unknown</h3>
2165
2166<p>If the initiating entity provides no 'to' attribute or provides an unknown host in the 'to' attribute and the error occurs during stream setup, the value of the 'from' attribute returned by the receiving entity in the stream header sent before closing the stream MUST be either an authoritative FQDN for the receiving entity or the empty string.
2167</p><div style='display: table; width: 0; margin-left: 3em; margin-right: auto'><pre>
2168C: &lt;?xml version='1.0'?&gt;
2169 &lt;stream:stream
2170 from='juliet@im.example.com'
2171 to='unknown.host.example.com'
2172 version='1.0'
2173 xml:lang='en'
2174 xmlns='jabber:client'
2175 xmlns:stream='http://etherx.jabber.org/streams'&gt;
2176
2177S: &lt;?xml version='1.0'?&gt;
2178 &lt;stream:stream
2179 from='im.example.com'
2180 id='++TR84Sm6A3hnt3Q065SnAbbk3Y='
2181 to='juliet@im.example.com'
2182 version='1.0'
2183 xml:lang='en'
2184 xmlns='jabber:client'
2185 xmlns:stream='http://etherx.jabber.org/streams'&gt;
2186 &lt;stream:error&gt;
2187 &lt;host-unknown
2188 xmlns='urn:ietf:params:xml:ns:xmpp-streams'/&gt;
2189 &lt;/stream:error&gt;
2190 &lt;/stream:stream&gt;
2191</pre></div>
2192<a name="streams-error-rules-where"></a><br /><hr />
2193<table summary="layout" cellpadding="0" cellspacing="2" class="TOCbug" align="right"><tr><td class="TOCbug"><a href="#toc">&nbsp;TOC&nbsp;</a></td></tr></table>
2194<a name="rfc.section.4.9.1.4"></a><h3>4.9.1.4.&nbsp;
2195Where Stream Errors Are Sent</h3>
2196
2197<p>When two TCP connections are used between the initiating entity and the receiving entity (one in each direction) rather than using a single bidirectional connection, the following rules apply:
2198</p>
2199<p>
2200 </p>
2201<ul class="text">
2202<li>Stream-level errors related to the initial stream are returned by the receiving entity on the response stream via the same TCP connection.
2203</li>
2204<li>Stanza errors triggered by outbound stanzas sent from the initiating entity over the initial stream via the same TCP connection are returned by the receiving entity on the response stream via the other ("return") TCP connection, since they are inbound stanzas from the perspective of the initiating entity.
2205</li>
2206</ul><p>
2207
2208</p>
2209<a name="streams-error-syntax"></a><br /><hr />
2210<table summary="layout" cellpadding="0" cellspacing="2" class="TOCbug" align="right"><tr><td class="TOCbug"><a href="#toc">&nbsp;TOC&nbsp;</a></td></tr></table>
2211<a name="rfc.section.4.9.2"></a><h3>4.9.2.&nbsp;
2212Syntax</h3>
2213
2214<p>The syntax for stream errors is as follows, where XML data shown within the square brackets '[' and ']' is OPTIONAL.
2215</p><div style='display: table; width: 0; margin-left: 3em; margin-right: auto'><pre>
2216&lt;stream:error&gt;
2217 &lt;defined-condition xmlns='urn:ietf:params:xml:ns:xmpp-streams'/&gt;
2218 [&lt;text xmlns='urn:ietf:params:xml:ns:xmpp-streams'
2219 xml:lang='langcode'&gt;
2220 OPTIONAL descriptive text
2221 &lt;/text&gt;]
2222 [OPTIONAL application-specific condition element]
2223&lt;/stream:error&gt;
2224</pre></div>
2225<p>The "defined-condition" MUST correspond to one of the stream error conditions defined under <a class='info' href='#streams-error-conditions'>Section&nbsp;4.9.3<span> (</span><span class='info'>Defined Stream Error Conditions</span><span>)</span></a>. However, because additional error conditions might be defined in the future, if an entity receives a stream error condition that it does not understand then it MUST treat the unknown condition as equivalent to &lt;undefined-condition/&gt; (<a class='info' href='#streams-error-conditions-undefined-condition'>Section&nbsp;4.9.3.21<span> (</span><span class='info'>undefined-condition</span><span>)</span></a>). If the designers of an XMPP protocol extension or the developers of an XMPP implementation need to communicate a stream error condition that is not defined in this specification, they can do so by defining an application-specific error condition element qualified by an application-specific namespace.
2226</p>
2227<p>The &lt;error/&gt; element:
2228</p>
2229<p></p>
2230<ul class="text">
2231<li>MUST contain a child element corresponding to one of the <a class='info' href='#streams-error-conditions'>defined stream error conditions<span> (</span><span class='info'>Defined Stream Error Conditions</span><span>)</span></a>; this element MUST be qualified by the 'urn:ietf:params:xml:ns:xmpp-streams' namespace.
2232</li>
2233<li>MAY contain a &lt;text/&gt; child element containing XML character data that describes the error in more detail; this element MUST be qualified by the 'urn:ietf:params:xml:ns:xmpp-streams' namespace and SHOULD possess an 'xml:lang' attribute specifying the natural language of the XML character data.
2234</li>
2235<li>MAY contain a child element for an application-specific error condition; this element MUST be qualified by an application-defined namespace, and its structure is defined by that namespace (see <a class='info' href='#streams-error-app'>Section&nbsp;4.9.4<span> (</span><span class='info'>Application-Specific Conditions</span><span>)</span></a>).
2236</li>
2237</ul>
2238
2239<p>The &lt;text/&gt; element is OPTIONAL. If included, it MUST be used only to provide descriptive or diagnostic information that supplements the meaning of a defined condition or application-specific condition. It MUST NOT be interpreted programmatically by an application. It MUST NOT be used as the error message presented to a human user, but MAY be shown in addition to the error message associated with the defined condition element (and, optionally, the application-specific condition element).
2240</p>
2241<a name="streams-error-conditions"></a><br /><hr />
2242<table summary="layout" cellpadding="0" cellspacing="2" class="TOCbug" align="right"><tr><td class="TOCbug"><a href="#toc">&nbsp;TOC&nbsp;</a></td></tr></table>
2243<a name="rfc.section.4.9.3"></a><h3>4.9.3.&nbsp;
2244Defined Stream Error Conditions</h3>
2245
2246<p>The following stream-level error conditions are defined.
2247</p>
2248<a name="streams-error-conditions-bad-format"></a><br /><hr />
2249<table summary="layout" cellpadding="0" cellspacing="2" class="TOCbug" align="right"><tr><td class="TOCbug"><a href="#toc">&nbsp;TOC&nbsp;</a></td></tr></table>
2250<a name="rfc.section.4.9.3.1"></a><h3>4.9.3.1.&nbsp;
2251bad-format</h3>
2252
2253<p>The entity has sent XML that cannot be processed.
2254</p>
2255<p>(In the following example, the client sends an XMPP message that is not well-formed XML, which alternatively might trigger a &lt;not-well-formed/&gt; stream error (<a class='info' href='#streams-error-conditions-not-well-formed'>Section&nbsp;4.9.3.13<span> (</span><span class='info'>not-well-formed</span><span>)</span></a>).)
2256</p><div style='display: table; width: 0; margin-left: 3em; margin-right: auto'><pre>
2257C: &lt;message&gt;
2258 &lt;body&gt;No closing tag!
2259 &lt;/message&gt;
2260
2261S: &lt;stream:error&gt;
2262 &lt;bad-format
2263 xmlns='urn:ietf:params:xml:ns:xmpp-streams'/&gt;
2264 &lt;/stream:error&gt;
2265 &lt;/stream:stream&gt;
2266</pre></div>
2267<p>This error can be used instead of the more specific XML-related errors, such as &lt;bad-namespace-prefix/&gt;, &lt;invalid-xml/&gt;, &lt;not-well-formed/&gt;, &lt;restricted-xml/&gt;, and &lt;unsupported-encoding/&gt;. However, the more specific errors are RECOMMENDED.
2268</p>
2269<a name="streams-error-conditions-bad-namespace-prefix"></a><br /><hr />
2270<table summary="layout" cellpadding="0" cellspacing="2" class="TOCbug" align="right"><tr><td class="TOCbug"><a href="#toc">&nbsp;TOC&nbsp;</a></td></tr></table>
2271<a name="rfc.section.4.9.3.2"></a><h3>4.9.3.2.&nbsp;
2272bad-namespace-prefix</h3>
2273
2274<p>The entity has sent a namespace prefix that is unsupported, or has sent no namespace prefix on an element that needs such a prefix (see <a class='info' href='#xml-ns'>Section&nbsp;11.2<span> (</span><span class='info'>XML Namespace Names and Prefixes</span><span>)</span></a>).
2275</p>
2276<p>(In the following example, the client specifies a namespace prefix of "foobar" for the XML stream namespace.)
2277</p><div style='display: table; width: 0; margin-left: 3em; margin-right: auto'><pre>
2278C: &lt;?xml version='1.0'?&gt;
2279 &lt;foobar:stream
2280 from='juliet@im.example.com'
2281 to='im.example.com'
2282 version='1.0'
2283 xmlns='jabber:client'
2284 xmlns:foobar='http://etherx.jabber.org/streams'&gt;
2285
2286S: &lt;?xml version='1.0'?&gt;
2287 &lt;stream:stream
2288 from='im.example.com'
2289 id='++TR84Sm6A3hnt3Q065SnAbbk3Y='
2290 to='juliet@im.example.com'
2291 version='1.0'
2292 xml:lang='en'
2293 xmlns='jabber:client'
2294 xmlns:stream='http://etherx.jabber.org/streams'&gt;
2295 &lt;stream:error&gt;
2296 &lt;bad-namespace-prefix
2297 xmlns='urn:ietf:params:xml:ns:xmpp-streams'/&gt;
2298 &lt;/stream:error&gt;
2299 &lt;/stream:stream&gt;
2300</pre></div>
2301<a name="streams-error-conditions-conflict"></a><br /><hr />
2302<table summary="layout" cellpadding="0" cellspacing="2" class="TOCbug" align="right"><tr><td class="TOCbug"><a href="#toc">&nbsp;TOC&nbsp;</a></td></tr></table>
2303<a name="rfc.section.4.9.3.3"></a><h3>4.9.3.3.&nbsp;
2304conflict</h3>
2305
2306<p>The server either (1) is closing the existing stream for this entity because a new stream has been initiated that conflicts with the existing stream, or (2) is refusing a new stream for this entity because allowing the new stream would conflict with an existing stream (e.g., because the server allows only a certain number of connections from the same IP address or allows only one server-to-server stream for a given domain pair as a way of helping to ensure in-order processing as described under <a class='info' href='#rules-order'>Section&nbsp;10.1<span> (</span><span class='info'>In-Order Processing</span><span>)</span></a>).
2307</p><div style='display: table; width: 0; margin-left: 3em; margin-right: auto'><pre>
2308C: &lt;?xml version='1.0'?&gt;
2309 &lt;stream:stream
2310 from='juliet@im.example.com'
2311 to='im.example.com'
2312 version='1.0'
2313 xmlns='jabber:client'
2314 xmlns:stream='http://etherx.jabber.org/streams'&gt;
2315
2316S: &lt;?xml version='1.0'?&gt;
2317 &lt;stream:stream
2318 from='im.example.com'
2319 id='++TR84Sm6A3hnt3Q065SnAbbk3Y='
2320 to='juliet@im.example.com'
2321 version='1.0'
2322 xml:lang='en'
2323 xmlns='jabber:client'
2324 xmlns:stream='http://etherx.jabber.org/streams'&gt;
2325 &lt;stream:error&gt;
2326 &lt;conflict
2327 xmlns='urn:ietf:params:xml:ns:xmpp-streams'/&gt;
2328 &lt;/stream:error&gt;
2329 &lt;/stream:stream&gt;
2330</pre></div>
2331<p>If a client receives a &lt;conflict/&gt; stream error (<a class='info' href='#streams-error-conditions-conflict'>Section&nbsp;4.9.3.3<span> (</span><span class='info'>conflict</span><span>)</span></a>), during the resource binding aspect of its reconnection attempt it MUST NOT blindly request the resourcepart it used during the former session but instead MUST choose a different resourcepart; details are provided under <a class='info' href='#bind'>Section&nbsp;7<span> (</span><span class='info'>Resource Binding</span><span>)</span></a>.
2332</p>
2333<a name="streams-error-conditions-connection-timeout"></a><br /><hr />
2334<table summary="layout" cellpadding="0" cellspacing="2" class="TOCbug" align="right"><tr><td class="TOCbug"><a href="#toc">&nbsp;TOC&nbsp;</a></td></tr></table>
2335<a name="rfc.section.4.9.3.4"></a><h3>4.9.3.4.&nbsp;
2336connection-timeout</h3>
2337
2338<p>One party is closing the stream because it has reason to believe that the other party has permanently lost the ability to communicate over the stream. The lack of ability to communicate can be discovered using various methods, such as whitespace keepalives as specified under <a class='info' href='#streams-close'>Section&nbsp;4.4<span> (</span><span class='info'>Closing a Stream</span><span>)</span></a>, XMPP-level pings as defined in <a class='info' href='#XEP-0199'>[XEP&#8209;0199]<span> (</span><span class='info'>Saint-Andre, P., &ldquo;XMPP Ping,&rdquo; June&nbsp;2009.</span><span>)</span></a>, and XMPP Stream Management as defined in <a class='info' href='#XEP-0198'>[XEP&#8209;0198]<span> (</span><span class='info'>Karneges, J., Hildebrand, J., Saint-Andre, P., Forno, F., Cridland, D., and M. Wild, &ldquo;Stream Management,&rdquo; February&nbsp;2011.</span><span>)</span></a>.
2339</p><div style='display: table; width: 0; margin-left: 3em; margin-right: auto'><pre>
2340P: &lt;stream:error&gt;
2341 &lt;connection-timeout
2342 xmlns='urn:ietf:params:xml:ns:xmpp-streams'/&gt;
2343 &lt;/stream:error&gt;
2344 &lt;/stream:stream&gt;
2345</pre></div>
2346<p></p>
2347<blockquote class="text">
2348<p>Interoperability Note: RFC 3920 specified that the &lt;connection-timeout/&gt; stream error (<a class='info' href='#streams-error-conditions-connection-timeout'>Section&nbsp;4.9.3.4<span> (</span><span class='info'>connection-timeout</span><span>)</span></a>) is to be used if the peer has not generated any traffic over the stream for some period of time. That behavior is no longer recommended; instead, the error SHOULD be used only if the connected client or peer server has not responded to data sent over the stream.
2349</p>
2350</blockquote>
2351
2352<a name="streams-error-conditions-host-gone"></a><br /><hr />
2353<table summary="layout" cellpadding="0" cellspacing="2" class="TOCbug" align="right"><tr><td class="TOCbug"><a href="#toc">&nbsp;TOC&nbsp;</a></td></tr></table>
2354<a name="rfc.section.4.9.3.5"></a><h3>4.9.3.5.&nbsp;
2355host-gone</h3>
2356
2357<p>The value of the 'to' attribute provided in the initial stream header corresponds to an FQDN that is no longer serviced by the receiving entity.
2358</p>
2359<p>(In the following example, the peer specifies a 'to' address of "foo.im.example.com" when connecting to the "im.example.com" server, but the server no longer hosts a service at that address.)
2360</p><div style='display: table; width: 0; margin-left: 3em; margin-right: auto'><pre>
2361P: &lt;?xml version='1.0'?&gt;
2362 &lt;stream:stream
2363 from='example.net'
2364 to='foo.im.example.com'
2365 version='1.0'
2366 xmlns='jabber:server'
2367 xmlns:stream='http://etherx.jabber.org/streams'&gt;
2368
2369S: &lt;?xml version='1.0'?&gt;
2370 &lt;stream:stream
2371 from='im.example.com'
2372 id='g4qSvGvBxJ+xeAd7QKezOQJFFlw='
2373 to='example.net'
2374 version='1.0'
2375 xml:lang='en'
2376 xmlns='jabber:server'
2377 xmlns:stream='http://etherx.jabber.org/streams'&gt;
2378 &lt;stream:error&gt;
2379 &lt;host-gone
2380 xmlns='urn:ietf:params:xml:ns:xmpp-streams'/&gt;
2381 &lt;/stream:error&gt;
2382 &lt;/stream:stream&gt;
2383</pre></div>
2384<a name="streams-error-conditions-host-unknown"></a><br /><hr />
2385<table summary="layout" cellpadding="0" cellspacing="2" class="TOCbug" align="right"><tr><td class="TOCbug"><a href="#toc">&nbsp;TOC&nbsp;</a></td></tr></table>
2386<a name="rfc.section.4.9.3.6"></a><h3>4.9.3.6.&nbsp;
2387host-unknown</h3>
2388
2389<p>The value of the 'to' attribute provided in the initial stream header does not correspond to an FQDN that is serviced by the receiving entity.
2390</p>
2391<p>(In the following example, the peer specifies a 'to' address of "example.org" when connecting to the "im.example.com" server, but the server knows nothing of that address.)
2392</p><div style='display: table; width: 0; margin-left: 3em; margin-right: auto'><pre>
2393P: &lt;?xml version='1.0'?&gt;
2394 &lt;stream:stream
2395 from='example.net'
2396 to='example.org'
2397 version='1.0'
2398 xmlns='jabber:server'
2399 xmlns:stream='http://etherx.jabber.org/streams'&gt;
2400
2401S: &lt;?xml version='1.0'?&gt;
2402 &lt;stream:stream
2403 from='im.example.com'
2404 id='g4qSvGvBxJ+xeAd7QKezOQJFFlw='
2405 to='example.net'
2406 version='1.0'
2407 xml:lang='en'
2408 xmlns='jabber:server'
2409 xmlns:stream='http://etherx.jabber.org/streams'&gt;
2410 &lt;stream:error&gt;
2411 &lt;host-unknown
2412 xmlns='urn:ietf:params:xml:ns:xmpp-streams'/&gt;
2413 &lt;/stream:error&gt;
2414 &lt;/stream:stream&gt;
2415</pre></div>
2416<a name="streams-error-conditions-improper-addressing"></a><br /><hr />
2417<table summary="layout" cellpadding="0" cellspacing="2" class="TOCbug" align="right"><tr><td class="TOCbug"><a href="#toc">&nbsp;TOC&nbsp;</a></td></tr></table>
2418<a name="rfc.section.4.9.3.7"></a><h3>4.9.3.7.&nbsp;
2419improper-addressing</h3>
2420
2421<p>A stanza sent between two servers lacks a 'to' or 'from' attribute, the 'from' or 'to' attribute has no value, or the value violates the rules for XMPP addresses <a class='info' href='#XMPP-ADDR'>[XMPP&#8209;ADDR]<span> (</span><span class='info'>Saint-Andre, P., &ldquo;Extensible Messaging and Presence Protocol (XMPP): Address Format,&rdquo; March&nbsp;2011.</span><span>)</span></a>.
2422</p>
2423<p>(In the following example, the peer sends a stanza without a 'to' address over a server-to-server stream.)
2424</p><div style='display: table; width: 0; margin-left: 3em; margin-right: auto'><pre>
2425P: &lt;message from='juliet@im.example.com'&gt;
2426 &lt;body&gt;Wherefore art thou?&lt;/body&gt;
2427 &lt;/message&gt;
2428
2429S: &lt;stream:error&gt;
2430 &lt;improper-addressing
2431 xmlns='urn:ietf:params:xml:ns:xmpp-streams'/&gt;
2432 &lt;/stream:error&gt;
2433 &lt;/stream:stream&gt;
2434</pre></div>
2435<a name="streams-error-conditions-internal-server-error"></a><br /><hr />
2436<table summary="layout" cellpadding="0" cellspacing="2" class="TOCbug" align="right"><tr><td class="TOCbug"><a href="#toc">&nbsp;TOC&nbsp;</a></td></tr></table>
2437<a name="rfc.section.4.9.3.8"></a><h3>4.9.3.8.&nbsp;
2438internal-server-error</h3>
2439
2440<p>The server has experienced a misconfiguration or other internal error that prevents it from servicing the stream.
2441</p><div style='display: table; width: 0; margin-left: 3em; margin-right: auto'><pre>
2442S: &lt;stream:error&gt;
2443 &lt;internal-server-error
2444 xmlns='urn:ietf:params:xml:ns:xmpp-streams'/&gt;
2445 &lt;/stream:error&gt;
2446 &lt;/stream:stream&gt;
2447</pre></div>
2448<a name="streams-error-conditions-invalid-from"></a><br /><hr />
2449<table summary="layout" cellpadding="0" cellspacing="2" class="TOCbug" align="right"><tr><td class="TOCbug"><a href="#toc">&nbsp;TOC&nbsp;</a></td></tr></table>
2450<a name="rfc.section.4.9.3.9"></a><h3>4.9.3.9.&nbsp;
2451invalid-from</h3>
2452
2453<p>The data provided in a 'from' attribute does not match an authorized JID or validated domain as negotiated (1) between two servers using SASL or Server Dialback, or (2) between a client and a server via SASL authentication and resource binding.
2454</p>
2455<p>(In the following example, a peer that has authenticated only as "example.net" attempts to send a stanza from an address at "example.org".)
2456</p><div style='display: table; width: 0; margin-left: 3em; margin-right: auto'><pre>
2457P: &lt;message from='romeo@example.org' to='juliet@im.example.com'&gt;
2458 &lt;body&gt;Neither, fair saint, if either thee dislike.&lt;/body&gt;
2459 &lt;/message&gt;
2460
2461S: &lt;stream:error&gt;
2462 &lt;invalid-from
2463 xmlns='urn:ietf:params:xml:ns:xmpp-streams'/&gt;
2464 &lt;/stream:error&gt;
2465 &lt;/stream:stream&gt;
2466</pre></div>
2467<a name="streams-error-conditions-invalid-namespace"></a><br /><hr />
2468<table summary="layout" cellpadding="0" cellspacing="2" class="TOCbug" align="right"><tr><td class="TOCbug"><a href="#toc">&nbsp;TOC&nbsp;</a></td></tr></table>
2469<a name="rfc.section.4.9.3.10"></a><h3>4.9.3.10.&nbsp;
2470invalid-namespace</h3>
2471
2472<p>The stream namespace name is something other than "http://etherx.jabber.org/streams" (see <a class='info' href='#xml-ns'>Section&nbsp;11.2<span> (</span><span class='info'>XML Namespace Names and Prefixes</span><span>)</span></a>) or the content namespace declared as the default namespace is not supported (e.g., something other than "jabber:client" or "jabber:server").
2473</p>
2474<p>(In the following example, the client specifies a namespace of 'http://wrong.namespace.example.org/' for the stream.)
2475</p><div style='display: table; width: 0; margin-left: 3em; margin-right: auto'><pre>
2476C: &lt;?xml version='1.0'?&gt;
2477 &lt;stream:stream
2478 from='juliet@im.example.com'
2479 to='im.example.com'
2480 version='1.0'
2481 xmlns='jabber:client'
2482 xmlns:stream='http://wrong.namespace.example.org/'&gt;
2483
2484S: &lt;?xml version='1.0'?&gt;
2485 &lt;stream:stream
2486 from='im.example.com'
2487 id='++TR84Sm6A3hnt3Q065SnAbbk3Y='
2488 to='juliet@im.example.com'
2489 version='1.0'
2490 xml:lang='en'
2491 xmlns='jabber:client'
2492 xmlns:stream='http://etherx.jabber.org/streams'&gt;
2493 &lt;stream:error&gt;
2494 &lt;invalid-namespace
2495 xmlns='urn:ietf:params:xml:ns:xmpp-streams'/&gt;
2496 &lt;/stream:error&gt;
2497 &lt;/stream:stream&gt;
2498</pre></div>
2499<a name="streams-error-conditions-invalid-xml"></a><br /><hr />
2500<table summary="layout" cellpadding="0" cellspacing="2" class="TOCbug" align="right"><tr><td class="TOCbug"><a href="#toc">&nbsp;TOC&nbsp;</a></td></tr></table>
2501<a name="rfc.section.4.9.3.11"></a><h3>4.9.3.11.&nbsp;
2502invalid-xml</h3>
2503
2504<p>The entity has sent invalid XML over the stream to a server that performs validation (see <a class='info' href='#xml-validation'>Section&nbsp;11.4<span> (</span><span class='info'>Validation</span><span>)</span></a>).
2505</p>
2506<p>(In the following example, the peer attempts to send an IQ stanza of type "subscribe", but the XML schema defines no such value for the 'type' attribute.)
2507</p><div style='display: table; width: 0; margin-left: 3em; margin-right: auto'><pre>
2508P: &lt;iq from='example.net'
2509 id='l3b1vs75'
2510 to='im.example.com'
2511 type='subscribe'&gt;
2512 &lt;ping xmlns='urn:xmpp:ping'/&gt;
2513 &lt;/iq&gt;
2514
2515S: &lt;stream:error&gt;
2516 &lt;invalid-xml
2517 xmlns='urn:ietf:params:xml:ns:xmpp-streams'/&gt;
2518 &lt;/stream:error&gt;
2519 &lt;/stream:stream&gt;
2520</pre></div>
2521<a name="streams-error-conditions-not-authorized"></a><br /><hr />
2522<table summary="layout" cellpadding="0" cellspacing="2" class="TOCbug" align="right"><tr><td class="TOCbug"><a href="#toc">&nbsp;TOC&nbsp;</a></td></tr></table>
2523<a name="rfc.section.4.9.3.12"></a><h3>4.9.3.12.&nbsp;
2524not-authorized</h3>
2525
2526<p>The entity has attempted to send XML stanzas or other outbound data before the stream has been authenticated, or otherwise is not authorized to perform an action related to stream negotiation; the receiving entity MUST NOT process the offending data before sending the stream error.
2527</p>
2528<p>(In the following example, the client attempts to send XML stanzas before authenticating with the server.)
2529</p><div style='display: table; width: 0; margin-left: 3em; margin-right: auto'><pre>
2530C: &lt;?xml version='1.0'?&gt;
2531 &lt;stream:stream
2532 from='juliet@im.example.com'
2533 to='im.example.com'
2534 version='1.0'
2535 xmlns='jabber:client'
2536 xmlns:stream='http://etherx.jabber.org/streams'&gt;
2537
2538S: &lt;?xml version='1.0'?&gt;
2539 &lt;stream:stream
2540 from='im.example.com'
2541 id='++TR84Sm6A3hnt3Q065SnAbbk3Y='
2542 to='juliet@im.example.com'
2543 version='1.0'
2544 xml:lang='en'
2545 xmlns='jabber:client'
2546 xmlns:stream='http://etherx.jabber.org/streams'&gt;
2547
2548C: &lt;message to='romeo@example.net'&gt;
2549 &lt;body&gt;Wherefore art thou?&lt;/body&gt;
2550 &lt;/message&gt;
2551
2552S: &lt;stream:error&gt;
2553 &lt;not-authorized
2554 xmlns='urn:ietf:params:xml:ns:xmpp-streams'/&gt;
2555 &lt;/stream:error&gt;
2556 &lt;/stream:stream&gt;
2557</pre></div>
2558<a name="streams-error-conditions-not-well-formed"></a><br /><hr />
2559<table summary="layout" cellpadding="0" cellspacing="2" class="TOCbug" align="right"><tr><td class="TOCbug"><a href="#toc">&nbsp;TOC&nbsp;</a></td></tr></table>
2560<a name="rfc.section.4.9.3.13"></a><h3>4.9.3.13.&nbsp;
2561not-well-formed</h3>
2562
2563<p>The initiating entity has sent XML that violates the well-formedness rules of <a class='info' href='#XML'>[XML]<span> (</span><span class='info'>Maler, E., Yergeau, F., Sperberg-McQueen, C., Paoli, J., and T. Bray, &ldquo;Extensible Markup Language (XML) 1.0 (Fifth Edition),&rdquo; November&nbsp;2008.</span><span>)</span></a> or <a class='info' href='#XML-NAMES'>[XML&#8209;NAMES]<span> (</span><span class='info'>Thompson, H., Hollander, D., Layman, A., Bray, T., and R. Tobin, &ldquo;Namespaces in XML 1.0 (Third Edition),&rdquo; December&nbsp;2009.</span><span>)</span></a>.
2564</p>
2565<p>(In the following example, the client sends an XMPP message that is not namespace-well-formed.)
2566</p><div style='display: table; width: 0; margin-left: 3em; margin-right: auto'><pre>
2567C: &lt;message&gt;
2568 &lt;foo:body&gt;What is this foo?&lt;/foo:body&gt;
2569 &lt;/message&gt;
2570
2571S: &lt;stream:error&gt;
2572 &lt;not-well-formed
2573 xmlns='urn:ietf:params:xml:ns:xmpp-streams'/&gt;
2574 &lt;/stream:error&gt;
2575 &lt;/stream:stream&gt;
2576</pre></div>
2577<p></p>
2578<blockquote class="text">
2579<p>Interoperability Note: In RFC 3920, the name of this error condition was "xml-not-well-formed" instead of "not-well-formed". The name was changed because the element name &lt;xml-not-well-formed/&gt; violates the constraint from Section 3 of <a class='info' href='#XML'>[XML]<span> (</span><span class='info'>Maler, E., Yergeau, F., Sperberg-McQueen, C., Paoli, J., and T. Bray, &ldquo;Extensible Markup Language (XML) 1.0 (Fifth Edition),&rdquo; November&nbsp;2008.</span><span>)</span></a> that "names beginning with a match to (('X'|'x')('M'|'m')('L'|'l')) are reserved for standardization in this or future versions of this specification".
2580</p>
2581</blockquote>
2582
2583<a name="streams-error-conditions-policy-violation"></a><br /><hr />
2584<table summary="layout" cellpadding="0" cellspacing="2" class="TOCbug" align="right"><tr><td class="TOCbug"><a href="#toc">&nbsp;TOC&nbsp;</a></td></tr></table>
2585<a name="rfc.section.4.9.3.14"></a><h3>4.9.3.14.&nbsp;
2586policy-violation</h3>
2587
2588<p>The entity has violated some local service policy (e.g., a stanza exceeds a configured size limit); the server MAY choose to specify the policy in the &lt;text/&gt; element or in an application-specific condition element.
2589</p>
2590<p>(In the following example, the client sends an XMPP message that is too large according to the server's local service policy.)
2591</p><div style='display: table; width: 0; margin-left: 3em; margin-right: auto'><pre>
2592C: &lt;message to='juliet@im.example.com' id='foo'&gt;
2593 &lt;body&gt;[ ... the-emacs-manual ... ]&lt;/body&gt;
2594 &lt;/message&gt;
2595
2596S: &lt;stream:error&gt;
2597 &lt;policy-violation
2598 xmlns='urn:ietf:params:xml:ns:xmpp-streams'/&gt;
2599 &lt;stanza-too-big xmlns='urn:xmpp:errors'/&gt;
2600 &lt;/stream:error&gt;
2601
2602S: &lt;/stream:stream&gt;
2603</pre></div>
2604<a name="streams-error-conditions-remote-connection-failed"></a><br /><hr />
2605<table summary="layout" cellpadding="0" cellspacing="2" class="TOCbug" align="right"><tr><td class="TOCbug"><a href="#toc">&nbsp;TOC&nbsp;</a></td></tr></table>
2606<a name="rfc.section.4.9.3.15"></a><h3>4.9.3.15.&nbsp;
2607remote-connection-failed</h3>
2608
2609<p>The server is unable to properly connect to a remote entity that is needed for authentication or authorization (e.g., in certain scenarios related to Server Dialback <a class='info' href='#XEP-0220'>[XEP&#8209;0220]<span> (</span><span class='info'>Miller, J., Saint-Andre, P., and P. Hancke, &ldquo;Server Dialback,&rdquo; March&nbsp;2010.</span><span>)</span></a>); this condition is not to be used when the cause of the error is within the administrative domain of the XMPP service provider, in which case the &lt;internal-server-error/&gt; condition is more appropriate.
2610</p><div style='display: table; width: 0; margin-left: 3em; margin-right: auto'><pre>
2611C: &lt;?xml version='1.0'?&gt;
2612 &lt;stream:stream
2613 from='juliet@im.example.com'
2614 to='im.example.com'
2615 version='1.0'
2616 xmlns='jabber:client'
2617 xmlns:stream='http://etherx.jabber.org/streams'&gt;
2618
2619S: &lt;?xml version='1.0'?&gt;
2620 &lt;stream:stream
2621 from='im.example.com'
2622 id='++TR84Sm6A3hnt3Q065SnAbbk3Y='
2623 to='juliet@im.example.com'
2624 version='1.0'
2625 xml:lang='en'
2626 xmlns='jabber:client'
2627 xmlns:stream='http://etherx.jabber.org/streams'&gt;
2628 &lt;stream:error&gt;
2629 &lt;remote-connection-failed
2630 xmlns='urn:ietf:params:xml:ns:xmpp-streams'/&gt;
2631 &lt;/stream:error&gt;
2632 &lt;/stream:stream&gt;
2633</pre></div>
2634<a name="streams-error-conditions-reset"></a><br /><hr />
2635<table summary="layout" cellpadding="0" cellspacing="2" class="TOCbug" align="right"><tr><td class="TOCbug"><a href="#toc">&nbsp;TOC&nbsp;</a></td></tr></table>
2636<a name="rfc.section.4.9.3.16"></a><h3>4.9.3.16.&nbsp;
2637reset</h3>
2638
2639<p>The server is closing the stream because it has new (typically security-critical) features to offer, because the keys or certificates used to establish a secure context for the stream have expired or have been revoked during the life of the stream (<a class='info' href='#security-certificates-validation-streams'>Section&nbsp;13.7.2.3<span> (</span><span class='info'>Checking of Certificates in Long-Lived Streams</span><span>)</span></a>), because the TLS sequence number has wrapped (<a class='info' href='#tls-rules-renegotiation'>Section&nbsp;5.3.5<span> (</span><span class='info'>TLS Renegotiation</span><span>)</span></a>), etc. The reset applies to the stream and to any security context established for that stream (e.g., via TLS and SASL), which means that encryption and authentication need to be negotiated again for the new stream (e.g., TLS session resumption cannot be used).
2640</p><div style='display: table; width: 0; margin-left: 3em; margin-right: auto'><pre>
2641S: &lt;stream:error&gt;
2642 &lt;reset
2643 xmlns='urn:ietf:params:xml:ns:xmpp-streams'/&gt;
2644 &lt;/stream:error&gt;
2645 &lt;/stream:stream&gt;
2646</pre></div>
2647<a name="streams-error-conditions-resource-constraint"></a><br /><hr />
2648<table summary="layout" cellpadding="0" cellspacing="2" class="TOCbug" align="right"><tr><td class="TOCbug"><a href="#toc">&nbsp;TOC&nbsp;</a></td></tr></table>
2649<a name="rfc.section.4.9.3.17"></a><h3>4.9.3.17.&nbsp;
2650resource-constraint</h3>
2651
2652<p>The server lacks the system resources necessary to service the stream.
2653</p><div style='display: table; width: 0; margin-left: 3em; margin-right: auto'><pre>
2654C: &lt;?xml version='1.0'?&gt;
2655 &lt;stream:stream
2656 from='juliet@im.example.com'
2657 to='im.example.com'
2658 version='1.0'
2659 xmlns='jabber:client'
2660 xmlns:stream='http://etherx.jabber.org/streams'&gt;
2661
2662S: &lt;?xml version='1.0'?&gt;
2663 &lt;stream:stream
2664 from='im.example.com'
2665 id='++TR84Sm6A3hnt3Q065SnAbbk3Y='
2666 to='juliet@im.example.com'
2667 version='1.0'
2668 xml:lang='en'
2669 xmlns='jabber:client'
2670 xmlns:stream='http://etherx.jabber.org/streams'&gt;
2671 &lt;stream:error&gt;
2672 &lt;resource-constraint
2673 xmlns='urn:ietf:params:xml:ns:xmpp-streams'/&gt;
2674 &lt;/stream:error&gt;
2675 &lt;/stream:stream&gt;
2676</pre></div>
2677<a name="streams-error-conditions-restricted-xml"></a><br /><hr />
2678<table summary="layout" cellpadding="0" cellspacing="2" class="TOCbug" align="right"><tr><td class="TOCbug"><a href="#toc">&nbsp;TOC&nbsp;</a></td></tr></table>
2679<a name="rfc.section.4.9.3.18"></a><h3>4.9.3.18.&nbsp;
2680restricted-xml</h3>
2681
2682<p>The entity has attempted to send restricted XML features such as a comment, processing instruction, DTD subset, or XML entity reference (see <a class='info' href='#xml-restrictions'>Section&nbsp;11.1<span> (</span><span class='info'>XML Restrictions</span><span>)</span></a>).
2683</p>
2684<p>(In the following example, the client sends an XMPP message containing an XML comment.)
2685</p><div style='display: table; width: 0; margin-left: 3em; margin-right: auto'><pre>
2686C: &lt;message to='juliet@im.example.com'&gt;
2687 &lt;!--&lt;subject/&gt;--&gt;
2688 &lt;body&gt;This message has no subject.&lt;/body&gt;
2689 &lt;/message&gt;
2690
2691S: &lt;stream:error&gt;
2692 &lt;restricted-xml
2693 xmlns='urn:ietf:params:xml:ns:xmpp-streams'/&gt;
2694 &lt;/stream:error&gt;
2695 &lt;/stream:stream&gt;
2696</pre></div>
2697<a name="streams-error-conditions-see-other-host"></a><br /><hr />
2698<table summary="layout" cellpadding="0" cellspacing="2" class="TOCbug" align="right"><tr><td class="TOCbug"><a href="#toc">&nbsp;TOC&nbsp;</a></td></tr></table>
2699<a name="rfc.section.4.9.3.19"></a><h3>4.9.3.19.&nbsp;
2700see-other-host</h3>
2701
2702<p>The server will not provide service to the initiating entity but is redirecting traffic to another host under the administrative control of the same service provider. The XML character data of the &lt;see-other-host/&gt; element returned by the server MUST specify the alternate FQDN or IP address at which to connect, which MUST be a valid domainpart or a domainpart plus port number (separated by the ':' character in the form "domainpart:port"). If the domainpart is the same as the source domain, derived domain, or resolved IPv4 or IPv6 address to which the initiating entity originally connected (differing only by the port number), then the initiating entity SHOULD simply attempt to reconnect at that address. (The format of an IPv6 address MUST follow <a class='info' href='#IPv6-ADDR'>[IPv6&#8209;ADDR]<span> (</span><span class='info'>Kawamura, S. and M. Kawashima, &ldquo;A Recommendation for IPv6 Address Text Representation,&rdquo; August&nbsp;2010.</span><span>)</span></a>, which includes the enclosing the IPv6 address in square brackets '[' and ']' as originally defined by <a class='info' href='#URI'>[URI]<span> (</span><span class='info'>Berners-Lee, T., Fielding, R., and L. Masinter, &ldquo;Uniform Resource Identifier (URI): Generic Syntax,&rdquo; January&nbsp;2005.</span><span>)</span></a>.) Otherwise, the initiating entity MUST resolve the FQDN specified in the &lt;see-other-host/&gt; element as described under <a class='info' href='#tcp-resolution'>Section&nbsp;3.2<span> (</span><span class='info'>Resolution of Fully Qualified Domain Names</span><span>)</span></a>.
2703</p><div style='display: table; width: 0; margin-left: 3em; margin-right: auto'><pre>
2704C: &lt;?xml version='1.0'?&gt;
2705 &lt;stream:stream
2706 from='juliet@im.example.com'
2707 to='im.example.com'
2708 version='1.0'
2709 xmlns='jabber:client'
2710 xmlns:stream='http://etherx.jabber.org/streams'&gt;
2711
2712S: &lt;?xml version='1.0'?&gt;
2713 &lt;stream:stream
2714 from='im.example.com'
2715 id='++TR84Sm6A3hnt3Q065SnAbbk3Y='
2716 to='juliet@im.example.com'
2717 version='1.0'
2718 xml:lang='en'
2719 xmlns='jabber:client'
2720 xmlns:stream='http://etherx.jabber.org/streams'&gt;
2721 &lt;stream:error&gt;
2722 &lt;see-other-host
2723 xmlns='urn:ietf:params:xml:ns:xmpp-streams'&gt;
2724 [2001:41D0:1:A49b::1]:9222
2725 &lt;/see-other-host&gt;
2726 &lt;/stream:error&gt;
2727 &lt;/stream:stream&gt;
2728</pre></div>
2729<p>When negotiating a stream with the host to which it has been redirected, the initiating entity MUST apply the same policies it would have applied to the original connection attempt (e.g., a policy requiring TLS), MUST specify the same 'to' address on the initial stream header, and MUST verify the identity of the new host using the same reference identifier(s) it would have used for the original connection attempt (in accordance with <a class='info' href='#TLS-CERTS'>[TLS&#8209;CERTS]<span> (</span><span class='info'>Saint-Andre, P. and J. Hodges, &ldquo;Representation and Verification of Domain-Based Application Service Identity within Internet Public Key Infrastructure Using X.509 (PKIX) Certificates in the Context of Transport Layer Security (TLS),&rdquo; March&nbsp;2011.</span><span>)</span></a>). Even if the receiving entity returns a &lt;see-other-host/&gt; error before the confidentiality and integrity of the stream have been established (thus introducing the possibility of a denial-of-service attack), the fact that the initiating entity needs to verify the identity of the XMPP service based on the same reference identifiers implies that the initiating entity will not connect to a malicious entity. To reduce the possibility of a denial-of-service attack, (a) the receiving entity SHOULD NOT close the stream with a &lt;see-other-host/&gt; stream error until after the confidentiality and integrity of the stream have been protected via TLS or an equivalent security layer (such as the SASL GSSAPI mechanism), and (b) the receiving entity MAY have a policy of following redirects only if it has authenticated the receiving entity. In addition, the initiating entity SHOULD abort the connection attempt after a certain number of successive redirects (e.g., at least 2 but no more than 5).
2730</p>
2731<a name="streams-error-conditions-system-shutdown"></a><br /><hr />
2732<table summary="layout" cellpadding="0" cellspacing="2" class="TOCbug" align="right"><tr><td class="TOCbug"><a href="#toc">&nbsp;TOC&nbsp;</a></td></tr></table>
2733<a name="rfc.section.4.9.3.20"></a><h3>4.9.3.20.&nbsp;
2734system-shutdown</h3>
2735
2736<p>The server is being shut down and all active streams are being closed.
2737</p><div style='display: table; width: 0; margin-left: 3em; margin-right: auto'><pre>
2738S: &lt;stream:error&gt;
2739 &lt;system-shutdown
2740 xmlns='urn:ietf:params:xml:ns:xmpp-streams'/&gt;
2741 &lt;/stream:error&gt;
2742 &lt;/stream:stream&gt;
2743</pre></div>
2744<a name="streams-error-conditions-undefined-condition"></a><br /><hr />
2745<table summary="layout" cellpadding="0" cellspacing="2" class="TOCbug" align="right"><tr><td class="TOCbug"><a href="#toc">&nbsp;TOC&nbsp;</a></td></tr></table>
2746<a name="rfc.section.4.9.3.21"></a><h3>4.9.3.21.&nbsp;
2747undefined-condition</h3>
2748
2749<p>The error condition is not one of those defined by the other conditions in this list; this error condition SHOULD NOT be used except in conjunction with an application-specific condition.
2750</p><div style='display: table; width: 0; margin-left: 3em; margin-right: auto'><pre>
2751S: &lt;stream:error&gt;
2752 &lt;undefined-condition
2753 xmlns='urn:ietf:params:xml:ns:xmpp-streams'/&gt;
2754 &lt;app-error xmlns='http://example.org/ns'/&gt;
2755 &lt;/stream:error&gt;
2756 &lt;/stream:stream&gt;
2757</pre></div>
2758<a name="streams-error-conditions-unsupported-encoding"></a><br /><hr />
2759<table summary="layout" cellpadding="0" cellspacing="2" class="TOCbug" align="right"><tr><td class="TOCbug"><a href="#toc">&nbsp;TOC&nbsp;</a></td></tr></table>
2760<a name="rfc.section.4.9.3.22"></a><h3>4.9.3.22.&nbsp;
2761unsupported-encoding</h3>
2762
2763<p>The initiating entity has encoded the stream in an encoding that is not supported by the server (see <a class='info' href='#xml-encoding'>Section&nbsp;11.6<span> (</span><span class='info'>Character Encoding</span><span>)</span></a>) or has otherwise improperly encoded the stream (e.g., by violating the rules of the <a class='info' href='#UTF-8'>[UTF&#8209;8]<span> (</span><span class='info'>Yergeau, F., &ldquo;UTF-8, a transformation format of ISO 10646,&rdquo; November&nbsp;2003.</span><span>)</span></a> encoding).
2764</p>
2765<p>(In the following example, the client attempts to encode data using UTF-16 instead of UTF-8.)
2766</p><div style='display: table; width: 0; margin-left: 3em; margin-right: auto'><pre>
2767C: &lt;?xml version='1.0' encoding='UTF-16'?&gt;
2768 &lt;stream:stream
2769 from='juliet@im.example.com'
2770 to='im.example.com'
2771 version='1.0'
2772 xmlns='jabber:client'
2773 xmlns:stream='http://etherx.jabber.org/streams'&gt;
2774
2775S: &lt;?xml version='1.0'?&gt;
2776 &lt;stream:stream
2777 from='im.example.com'
2778 id='++TR84Sm6A3hnt3Q065SnAbbk3Y='
2779 to='juliet@im.example.com'
2780 version='1.0'
2781 xml:lang='en'
2782 xmlns='jabber:client'
2783 xmlns:stream='http://etherx.jabber.org/streams'&gt;
2784 &lt;stream:error&gt;
2785 &lt;unsupported-encoding
2786 xmlns='urn:ietf:params:xml:ns:xmpp-streams'/&gt;
2787 &lt;/stream:error&gt;
2788 &lt;/stream:stream&gt;
2789</pre></div>
2790<a name="streams-error-conditions-unsupported-feature"></a><br /><hr />
2791<table summary="layout" cellpadding="0" cellspacing="2" class="TOCbug" align="right"><tr><td class="TOCbug"><a href="#toc">&nbsp;TOC&nbsp;</a></td></tr></table>
2792<a name="rfc.section.4.9.3.23"></a><h3>4.9.3.23.&nbsp;
2793unsupported-feature</h3>
2794
2795<p>The receiving entity has advertised a mandatory-to-negotiate stream feature that the initiating entity does not support, and has offered no other mandatory-to-negotiate feature alongside the unsupported feature.
2796</p>
2797<p>(In the following example, the receiving entity requires negotiation of an example feature, but the initiating entity does not support the feature.)
2798</p><div style='display: table; width: 0; margin-left: 3em; margin-right: auto'><pre>
2799R: &lt;stream:features&gt;
2800 &lt;example xmlns='urn:xmpp:example'&gt;
2801 &lt;required/&gt;
2802 &lt;/example&gt;
2803 &lt;/stream:features&gt;
2804
2805I: &lt;stream:error&gt;
2806 &lt;unsupported-feature
2807 xmlns='urn:ietf:params:xml:ns:xmpp-streams'/&gt;
2808 &lt;/stream:error&gt;
2809 &lt;/stream:stream&gt;
2810</pre></div>
2811<a name="streams-error-conditions-unsupported-stanza-type"></a><br /><hr />
2812<table summary="layout" cellpadding="0" cellspacing="2" class="TOCbug" align="right"><tr><td class="TOCbug"><a href="#toc">&nbsp;TOC&nbsp;</a></td></tr></table>
2813<a name="rfc.section.4.9.3.24"></a><h3>4.9.3.24.&nbsp;
2814unsupported-stanza-type</h3>
2815
2816<p>The initiating entity has sent a first-level child of the stream that is not supported by the server, either because the receiving entity does not understand the namespace or because the receiving entity does not understand the element name for the applicable namespace (which might be the content namespace declared as the default namespace).
2817</p>
2818<p>(In the following example, the client attempts to send a first-level child element of &lt;pubsub/&gt; qualified by the 'jabber:client' namespace, but the schema for that namespace defines no such element.)
2819</p><div style='display: table; width: 0; margin-left: 3em; margin-right: auto'><pre>
2820C: &lt;pubsub xmlns='jabber:client'&gt;
2821 &lt;publish node='princely_musings'&gt;
2822 &lt;item id='ae890ac52d0df67ed7cfdf51b644e901'&gt;
2823 &lt;entry xmlns='http://www.w3.org/2005/Atom'&gt;
2824 &lt;title&gt;Soliloquy&lt;/title&gt;
2825 &lt;summary&gt;
2826To be, or not to be: that is the question:
2827Whether 'tis nobler in the mind to suffer
2828The slings and arrows of outrageous fortune,
2829Or to take arms against a sea of troubles,
2830And by opposing end them?
2831 &lt;/summary&gt;
2832 &lt;link rel='alternate' type='text/html'
2833 href='http://denmark.example/2003/12/13/atom03'/&gt;
2834 &lt;id&gt;tag:denmark.example,2003:entry-32397&lt;/id&gt;
2835 &lt;published&gt;2003-12-13T18:30:02Z&lt;/published&gt;
2836 &lt;updated&gt;2003-12-13T18:30:02Z&lt;/updated&gt;
2837 &lt;/entry&gt;
2838 &lt;/item&gt;
2839 &lt;/publish&gt;
2840 &lt;/pubsub&gt;
2841
2842S: &lt;stream:error&gt;
2843 &lt;unsupported-stanza-type
2844 xmlns='urn:ietf:params:xml:ns:xmpp-streams'/&gt;
2845 &lt;/stream:error&gt;
2846 &lt;/stream:stream&gt;
2847</pre></div>
2848<a name="streams-error-conditions-unsupported-version"></a><br /><hr />
2849<table summary="layout" cellpadding="0" cellspacing="2" class="TOCbug" align="right"><tr><td class="TOCbug"><a href="#toc">&nbsp;TOC&nbsp;</a></td></tr></table>
2850<a name="rfc.section.4.9.3.25"></a><h3>4.9.3.25.&nbsp;
2851unsupported-version</h3>
2852
2853<p>The 'version' attribute provided by the initiating entity in the stream header specifies a version of XMPP that is not supported by the server.
2854</p><div style='display: table; width: 0; margin-left: 3em; margin-right: auto'><pre>
2855C: &lt;?xml version='1.0'?&gt;
2856 &lt;stream:stream
2857 from='juliet@im.example.com'
2858 to='im.example.com'
2859 version='11.0'
2860 xmlns='jabber:client'
2861 xmlns:stream='http://etherx.jabber.org/streams'&gt;
2862
2863S: &lt;?xml version='1.0'?&gt;
2864 &lt;stream:stream
2865 from='im.example.com'
2866 id='++TR84Sm6A3hnt3Q065SnAbbk3Y='
2867 to='juliet@im.example.com'
2868 version='1.0'
2869 xml:lang='en'
2870 xmlns='jabber:client'
2871 xmlns:stream='http://etherx.jabber.org/streams'&gt;
2872 &lt;stream:error&gt;
2873 &lt;unsupported-version
2874 xmlns='urn:ietf:params:xml:ns:xmpp-streams'/&gt;
2875 &lt;/stream:error&gt;
2876 &lt;/stream:stream&gt;
2877</pre></div>
2878<a name="streams-error-app"></a><br /><hr />
2879<table summary="layout" cellpadding="0" cellspacing="2" class="TOCbug" align="right"><tr><td class="TOCbug"><a href="#toc">&nbsp;TOC&nbsp;</a></td></tr></table>
2880<a name="rfc.section.4.9.4"></a><h3>4.9.4.&nbsp;
2881Application-Specific Conditions</h3>
2882
2883<p>As noted, an application MAY provide application-specific
2884 stream error information by including a properly namespaced child in the error element. The application-specific element SHOULD supplement or further qualify a defined element. Thus, the &lt;error/&gt; element will contain two or three child elements.
2885</p><div style='display: table; width: 0; margin-left: 3em; margin-right: auto'><pre>
2886C: &lt;message&gt;
2887 &lt;body&gt;
2888 My keyboard layout is:
2889
2890 QWERTYUIOP{}|
2891 ASDFGHJKL:"
2892 ZXCVBNM&lt;&gt;?
2893 &lt;/body&gt;
2894 &lt;/message&gt;
2895
2896S: &lt;stream:error&gt;
2897 &lt;not-well-formed
2898 xmlns='urn:ietf:params:xml:ns:xmpp-streams'/&gt;
2899 &lt;text xml:lang='en' xmlns='urn:ietf:params:xml:ns:xmpp-streams'&gt;
2900 Some special application diagnostic information!
2901 &lt;/text&gt;
2902 &lt;escape-your-data xmlns='http://example.org/ns'/&gt;
2903 &lt;/stream:error&gt;
2904 &lt;/stream:stream&gt;
2905</pre></div>
2906<a name="streams-example"></a><br /><hr />
2907<table summary="layout" cellpadding="0" cellspacing="2" class="TOCbug" align="right"><tr><td class="TOCbug"><a href="#toc">&nbsp;TOC&nbsp;</a></td></tr></table>
2908<a name="rfc.section.4.10"></a><h3>4.10.&nbsp;
2909Simplified Stream Examples</h3>
2910
2911<p>This section contains two highly simplified examples of a stream-based connection between a client and a server; these examples are included for the purpose of illustrating the concepts introduced thus far, but the reader needs to be aware that these examples elide many details (see <a class='info' href='#examples'>Section&nbsp;9<span> (</span><span class='info'>Detailed Examples</span><span>)</span></a> for more complete examples).
2912</p>
2913<p>A basic connection:
2914</p><div style='display: table; width: 0; margin-left: 3em; margin-right: auto'><pre>
2915C: &lt;?xml version='1.0'?&gt;
2916 &lt;stream:stream
2917 from='juliet@im.example.com'
2918 to='im.example.com'
2919 version='1.0'
2920 xml:lang='en'
2921 xmlns='jabber:client'
2922 xmlns:stream='http://etherx.jabber.org/streams'&gt;
2923
2924S: &lt;?xml version='1.0'?&gt;
2925 &lt;stream:stream
2926 from='im.example.com'
2927 id='++TR84Sm6A3hnt3Q065SnAbbk3Y='
2928 to='juliet@im.example.com'
2929 version='1.0'
2930 xml:lang='en'
2931 xmlns='jabber:client'
2932 xmlns:stream='http://etherx.jabber.org/streams'&gt;
2933
2934[ ... stream negotiation ... ]
2935
2936C: &lt;message from='juliet@im.example.com/balcony'
2937 to='romeo@example.net'
2938 xml:lang='en'&gt;
2939 &lt;body&gt;Art thou not Romeo, and a Montague?&lt;/body&gt;
2940 &lt;/message&gt;
2941
2942S: &lt;message from='romeo@example.net/orchard'
2943 to='juliet@im.example.com/balcony'
2944 xml:lang='en'&gt;
2945 &lt;body&gt;Neither, fair saint, if either thee dislike.&lt;/body&gt;
2946 &lt;/message&gt;
2947
2948C: &lt;/stream:stream&gt;
2949
2950S: &lt;/stream:stream&gt;
2951</pre></div>
2952<p>A connection gone bad:
2953</p><div style='display: table; width: 0; margin-left: 3em; margin-right: auto'><pre>
2954C: &lt;?xml version='1.0'?&gt;
2955 &lt;stream:stream
2956 from='juliet@im.example.com'
2957 to='im.example.com'
2958 version='1.0'
2959 xml:lang='en'
2960 xmlns='jabber:client'
2961 xmlns:stream='http://etherx.jabber.org/streams'&gt;
2962
2963S: &lt;?xml version='1.0'?&gt;
2964 &lt;stream:stream
2965 from='im.example.com'
2966 id='++TR84Sm6A3hnt3Q065SnAbbk3Y='
2967 to='juliet@im.example.com'
2968 version='1.0'
2969 xml:lang='en'
2970 xmlns='jabber:client'
2971 xmlns:stream='http://etherx.jabber.org/streams'&gt;
2972
2973[ ... stream negotiation ... ]
2974
2975C: &lt;message from='juliet@im.example.com/balcony'
2976 to='romeo@example.net'
2977 xml:lang='en'&gt;
2978 &lt;body&gt;No closing tag!
2979 &lt;/message&gt;
2980
2981S: &lt;stream:error&gt;
2982 &lt;not-well-formed
2983 xmlns='urn:ietf:params:xml:ns:xmpp-streams'/&gt;
2984 &lt;/stream:error&gt;
2985 &lt;/stream:stream&gt;
2986
2987</pre></div>
2988<p>More detailed examples are provided under <a class='info' href='#examples'>Section&nbsp;9<span> (</span><span class='info'>Detailed Examples</span><span>)</span></a>.
2989</p>
2990<a name="tls"></a><br /><hr />
2991<table summary="layout" cellpadding="0" cellspacing="2" class="TOCbug" align="right"><tr><td class="TOCbug"><a href="#toc">&nbsp;TOC&nbsp;</a></td></tr></table>
2992<a name="rfc.section.5"></a><h3>5.&nbsp;
2993STARTTLS Negotiation</h3>
2994
2995<a name="tls-fundamentals"></a><br /><hr />
2996<table summary="layout" cellpadding="0" cellspacing="2" class="TOCbug" align="right"><tr><td class="TOCbug"><a href="#toc">&nbsp;TOC&nbsp;</a></td></tr></table>
2997<a name="rfc.section.5.1"></a><h3>5.1.&nbsp;
2998Fundamentals</h3>
2999
3000<p>XMPP includes a method for securing the stream from tampering and eavesdropping. This channel encryption method makes use of the Transport Layer Security <a class='info' href='#TLS'>[TLS]<span> (</span><span class='info'>Dierks, T. and E. Rescorla, &ldquo;The Transport Layer Security (TLS) Protocol Version 1.2,&rdquo; August&nbsp;2008.</span><span>)</span></a> protocol, specifically a "STARTTLS" extension that is modeled after similar extensions for the <a class='info' href='#IMAP'>[IMAP]<span> (</span><span class='info'>Crispin, M., &ldquo;INTERNET MESSAGE ACCESS PROTOCOL - VERSION 4rev1,&rdquo; March&nbsp;2003.</span><span>)</span></a>, <a class='info' href='#POP3'>[POP3]<span> (</span><span class='info'>Myers, J. and M. Rose, &ldquo;Post Office Protocol - Version 3,&rdquo; May&nbsp;1996.</span><span>)</span></a>, and <a class='info' href='#ACAP'>[ACAP]<span> (</span><span class='info'>Newman, C. and J. Myers, &ldquo;ACAP -- Application Configuration Access Protocol,&rdquo; November&nbsp;1997.</span><span>)</span></a> protocols as described in <a class='info' href='#USINGTLS'>[USINGTLS]<span> (</span><span class='info'>Newman, C., &ldquo;Using TLS with IMAP, POP3 and ACAP,&rdquo; June&nbsp;1999.</span><span>)</span></a>. The XML namespace name for the STARTTLS extension is 'urn:ietf:params:xml:ns:xmpp-tls'.
3001</p>
3002<a name="tls-support"></a><br /><hr />
3003<table summary="layout" cellpadding="0" cellspacing="2" class="TOCbug" align="right"><tr><td class="TOCbug"><a href="#toc">&nbsp;TOC&nbsp;</a></td></tr></table>
3004<a name="rfc.section.5.2"></a><h3>5.2.&nbsp;
3005Support</h3>
3006
3007<p>Support for STARTTLS is REQUIRED in XMPP client and server implementations. An administrator of a given deployment MAY specify that TLS is mandatory-to-negotiate for client-to-server communication, server-to-server communication, or both. An initiating entity SHOULD use TLS to secure its stream with the receiving entity before proceeding with SASL authentication.
3008</p>
3009<a name="tls-rules"></a><br /><hr />
3010<table summary="layout" cellpadding="0" cellspacing="2" class="TOCbug" align="right"><tr><td class="TOCbug"><a href="#toc">&nbsp;TOC&nbsp;</a></td></tr></table>
3011<a name="rfc.section.5.3"></a><h3>5.3.&nbsp;
3012Stream Negotiation Rules</h3>
3013
3014<a name="tls-rules-mtn"></a><br /><hr />
3015<table summary="layout" cellpadding="0" cellspacing="2" class="TOCbug" align="right"><tr><td class="TOCbug"><a href="#toc">&nbsp;TOC&nbsp;</a></td></tr></table>
3016<a name="rfc.section.5.3.1"></a><h3>5.3.1.&nbsp;
3017Mandatory-to-Negotiate</h3>
3018
3019<p>If the receiving entity advertises only the STARTTLS feature or if the receiving entity includes the &lt;required/&gt; child element as explained under <a class='info' href='#tls-process-stream'>Section&nbsp;5.4.1<span> (</span><span class='info'>Exchange of Stream Headers and Stream Features</span><span>)</span></a>, the parties MUST consider TLS as mandatory-to-negotiate. If TLS is mandatory-to-negotiate, the receiving entity SHOULD NOT advertise support for any stream feature except STARTTLS during the initial stage of the stream negotiation process, because further stream features might depend on prior negotiation of TLS given the order of layers in XMPP (e.g., the particular SASL mechanisms offered by the receiving entity will likely depend on whether TLS has been negotiated).
3020</p>
3021<a name="tls-rules-restart"></a><br /><hr />
3022<table summary="layout" cellpadding="0" cellspacing="2" class="TOCbug" align="right"><tr><td class="TOCbug"><a href="#toc">&nbsp;TOC&nbsp;</a></td></tr></table>
3023<a name="rfc.section.5.3.2"></a><h3>5.3.2.&nbsp;
3024Restart</h3>
3025
3026<p>After TLS negotiation, the parties MUST restart the stream.
3027</p>
3028<a name="tls-rules-data"></a><br /><hr />
3029<table summary="layout" cellpadding="0" cellspacing="2" class="TOCbug" align="right"><tr><td class="TOCbug"><a href="#toc">&nbsp;TOC&nbsp;</a></td></tr></table>
3030<a name="rfc.section.5.3.3"></a><h3>5.3.3.&nbsp;
3031Data Formatting</h3>
3032
3033<p>During STARTTLS negotiation, the entities MUST NOT send any whitespace as separators between XML elements (i.e., from the last character of the first-level &lt;starttls/&gt; element qualified by the 'urn:ietf:params:xml:ns:xmpp-tls' namespace as sent by the initiating entity, until the last character of the first-level &lt;proceed/&gt; element qualified by the 'urn:ietf:params:xml:ns:xmpp-tls' namespace as sent by the receiving entity). This prohibition helps to ensure proper security layer byte precision. Any such whitespace shown in the STARTTLS examples provided in this document is included only for the sake of readability.
3034</p>
3035<a name="tls-rules-order"></a><br /><hr />
3036<table summary="layout" cellpadding="0" cellspacing="2" class="TOCbug" align="right"><tr><td class="TOCbug"><a href="#toc">&nbsp;TOC&nbsp;</a></td></tr></table>
3037<a name="rfc.section.5.3.4"></a><h3>5.3.4.&nbsp;
3038Order of TLS and SASL Negotiations</h3>
3039
3040<p>If the initiating entity chooses to use TLS, STARTTLS negotiation MUST be completed before proceeding to <a class='info' href='#sasl'>SASL negotiation<span> (</span><span class='info'>SASL Negotiation</span><span>)</span></a>; this order of negotiation is necessary to help safeguard authentication information sent during SASL negotiation, as well as to make it possible to base the use of the SASL EXTERNAL mechanism on a certificate (or other credentials) provided during prior TLS negotiation.
3041</p>
3042<a name="tls-rules-renegotiation"></a><br /><hr />
3043<table summary="layout" cellpadding="0" cellspacing="2" class="TOCbug" align="right"><tr><td class="TOCbug"><a href="#toc">&nbsp;TOC&nbsp;</a></td></tr></table>
3044<a name="rfc.section.5.3.5"></a><h3>5.3.5.&nbsp;
3045TLS Renegotiation</h3>
3046
3047<p>The TLS protocol allows either party in a TLS-protected channel to initiate a new handshake that establishes new cryptographic parameters (see <a class='info' href='#TLS-NEG'>[TLS&#8209;NEG]<span> (</span><span class='info'>Rescorla, E., Ray, M., Dispensa, S., and N. Oskov, &ldquo;Transport Layer Security (TLS) Renegotiation Indication Extension,&rdquo; February&nbsp;2010.</span><span>)</span></a>). The cases most commonly mentioned are:
3048</p>
3049<p>
3050 </p>
3051<ol class="text">
3052<li>Refreshing encryption keys.
3053</li>
3054<li>Wrapping the TLS sequence number as explained in Section 6.1 of <a class='info' href='#TLS'>[TLS]<span> (</span><span class='info'>Dierks, T. and E. Rescorla, &ldquo;The Transport Layer Security (TLS) Protocol Version 1.2,&rdquo; August&nbsp;2008.</span><span>)</span></a>.
3055</li>
3056<li>Protecting client credentials by completing server authentication first and then completing client authentication over the protected channel.
3057</li>
3058</ol><p>
3059
3060</p>
3061<p>Because it is relatively inexpensive to establish streams in XMPP, for the first two cases it is preferable to use an XMPP stream reset (as described under <a class='info' href='#streams-error-conditions-reset'>Section&nbsp;4.9.3.16<span> (</span><span class='info'>reset</span><span>)</span></a>) instead of performing TLS renegotiation.
3062</p>
3063<p>The third case has improved security characteristics when the TLS client (which might be an XMPP server) presents credentials to the TLS server. If communicating such credentials to an unauthenticated TLS server might leak private information, it can be appropriate to complete TLS negotiation for the purpose of authenticating the TLS server to the TLS client and then attempt TLS renegotiation for the purpose of authenticating the TLS client to the TLS server. However, this case is extremely rare because the credentials presented by an XMPP server or XMPP client acting as a TLS client are almost always public (i.e., a PKIX certificate), and therefore providing those credentials before authenticating the XMPP server acting as a TLS server would not in general leak private information.
3064</p>
3065<p>As a result, implementers are encouraged to carefully weigh the costs and benefits of TLS renegotiation before supporting it in their software, and XMPP entities that act as TLS clients are discouraged from attempting TLS renegotiation unless the certificate (or other credential information) sent during TLS negotiation is known to be private.
3066</p>
3067<p>Support for TLS renegotiation is strictly OPTIONAL. However, implementations that support TLS renegotiation MUST implement and use the TLS Renegotiation Extension <a class='info' href='#TLS-NEG'>[TLS&#8209;NEG]<span> (</span><span class='info'>Rescorla, E., Ray, M., Dispensa, S., and N. Oskov, &ldquo;Transport Layer Security (TLS) Renegotiation Indication Extension,&rdquo; February&nbsp;2010.</span><span>)</span></a>.
3068</p>
3069<p>If an entity that does not support TLS renegotiation detects a renegotiation attempt, then it MUST immediately close the underlying TCP connection without returning a stream error (since the violation has occurred at the TLS layer, not the XMPP layer, as described under <a class='info' href='#security-layers'>Section&nbsp;13.3<span> (</span><span class='info'>Order of Layers</span><span>)</span></a>).
3070</p>
3071<p>If an entity that supports TLS renegotiation detects a TLS renegotiation attempt that does not use the TLS Renegotiation Extension <a class='info' href='#TLS-NEG'>[TLS&#8209;NEG]<span> (</span><span class='info'>Rescorla, E., Ray, M., Dispensa, S., and N. Oskov, &ldquo;Transport Layer Security (TLS) Renegotiation Indication Extension,&rdquo; February&nbsp;2010.</span><span>)</span></a>, then it MUST immediately close the underlying TCP connection without returning a stream error (since the violation has occurred at the TLS layer, not the XMPP layer as described under <a class='info' href='#security-layers'>Section&nbsp;13.3<span> (</span><span class='info'>Order of Layers</span><span>)</span></a>).
3072</p>
3073<a name="tls-rules-extensions"></a><br /><hr />
3074<table summary="layout" cellpadding="0" cellspacing="2" class="TOCbug" align="right"><tr><td class="TOCbug"><a href="#toc">&nbsp;TOC&nbsp;</a></td></tr></table>
3075<a name="rfc.section.5.3.6"></a><h3>5.3.6.&nbsp;
3076TLS Extensions</h3>
3077
3078<p>Either party to a stream MAY include any TLS extension during the TLS negotiation itself. This is a matter for the TLS layer, not the XMPP layer.
3079</p>
3080<a name="tls-process"></a><br /><hr />
3081<table summary="layout" cellpadding="0" cellspacing="2" class="TOCbug" align="right"><tr><td class="TOCbug"><a href="#toc">&nbsp;TOC&nbsp;</a></td></tr></table>
3082<a name="rfc.section.5.4"></a><h3>5.4.&nbsp;
3083Process</h3>
3084
3085<a name="tls-process-stream"></a><br /><hr />
3086<table summary="layout" cellpadding="0" cellspacing="2" class="TOCbug" align="right"><tr><td class="TOCbug"><a href="#toc">&nbsp;TOC&nbsp;</a></td></tr></table>
3087<a name="rfc.section.5.4.1"></a><h3>5.4.1.&nbsp;
3088Exchange of Stream Headers and Stream Features</h3>
3089
3090<p>The initiating entity resolves the FQDN of the receiving entity as specified under <a class='info' href='#tcp'>Section&nbsp;3<span> (</span><span class='info'>TCP Binding</span><span>)</span></a>, opens a TCP connection to the advertised port at the resolved IP address, and sends an initial stream header to the receiving entity.
3091</p><div style='display: table; width: 0; margin-left: 3em; margin-right: auto'><pre>
3092I: &lt;stream:stream
3093 from='juliet@im.example.com'
3094 to='im.example.com'
3095 version='1.0'
3096 xml:lang='en'
3097 xmlns='jabber:client'
3098 xmlns:stream='http://etherx.jabber.org/streams'&gt;
3099</pre></div>
3100<p>The receiving entity MUST send a response stream header to the initiating entity over the TCP connection opened by the initiating entity.
3101</p><div style='display: table; width: 0; margin-left: 3em; margin-right: auto'><pre>
3102R: &lt;stream:stream
3103 from='im.example.com'
3104 id='t7AMCin9zjMNwQKDnplntZPIDEI='
3105 to='juliet@im.example.com'
3106 version='1.0'
3107 xml:lang='en'
3108 xmlns='jabber:client'
3109 xmlns:stream='http://etherx.jabber.org/streams'&gt;
3110</pre></div>
3111<p>The receiving entity then MUST send stream features to the initiating entity. If the receiving entity supports TLS, the stream features MUST include an advertisement for support of STARTTLS negotiation, i.e., a &lt;starttls/&gt; element qualified by the 'urn:ietf:params:xml:ns:xmpp-tls' namespace.
3112</p>
3113<p>If the receiving entity considers STARTTLS negotiation to be mandatory-to-negotiate, the &lt;starttls/&gt; element MUST contain an empty &lt;required/&gt; child element.
3114</p><div style='display: table; width: 0; margin-left: 3em; margin-right: auto'><pre>
3115R: &lt;stream:features&gt;
3116 &lt;starttls xmlns='urn:ietf:params:xml:ns:xmpp-tls'&gt;
3117 &lt;required/&gt;
3118 &lt;/starttls&gt;
3119 &lt;/stream:features&gt;
3120</pre></div>
3121<a name="tls-process-initiate"></a><br /><hr />
3122<table summary="layout" cellpadding="0" cellspacing="2" class="TOCbug" align="right"><tr><td class="TOCbug"><a href="#toc">&nbsp;TOC&nbsp;</a></td></tr></table>
3123<a name="rfc.section.5.4.2"></a><h3>5.4.2.&nbsp;
3124Initiation of STARTTLS Negotiation</h3>
3125
3126<a name="tls-process-initiate-command"></a><br /><hr />
3127<table summary="layout" cellpadding="0" cellspacing="2" class="TOCbug" align="right"><tr><td class="TOCbug"><a href="#toc">&nbsp;TOC&nbsp;</a></td></tr></table>
3128<a name="rfc.section.5.4.2.1"></a><h3>5.4.2.1.&nbsp;
3129STARTTLS Command</h3>
3130
3131<p>In order to begin the STARTTLS negotiation, the initiating entity issues the STARTTLS command (i.e., a &lt;starttls/&gt; element qualified by the 'urn:ietf:params:xml:ns:xmpp-tls' namespace) to instruct the receiving entity that it wishes to begin a STARTTLS negotiation to secure the stream.
3132</p><div style='display: table; width: 0; margin-left: 3em; margin-right: auto'><pre>
3133I: &lt;starttls xmlns='urn:ietf:params:xml:ns:xmpp-tls'/&gt;
3134</pre></div>
3135<p>The receiving entity MUST reply with either a &lt;proceed/&gt; element (proceed case) or a &lt;failure/&gt; element (failure case) qualified by the 'urn:ietf:params:xml:ns:xmpp-tls' namespace.
3136</p>
3137<a name="tls-process-initiate-failure"></a><br /><hr />
3138<table summary="layout" cellpadding="0" cellspacing="2" class="TOCbug" align="right"><tr><td class="TOCbug"><a href="#toc">&nbsp;TOC&nbsp;</a></td></tr></table>
3139<a name="rfc.section.5.4.2.2"></a><h3>5.4.2.2.&nbsp;
3140Failure Case</h3>
3141
3142<p>If the failure case occurs, the receiving entity MUST return a &lt;failure/&gt; element qualified by the 'urn:ietf:params:xml:ns:xmpp-tls' namespace, close the XML stream, and terminate the underlying TCP connection.
3143</p><div style='display: table; width: 0; margin-left: 3em; margin-right: auto'><pre>
3144R: &lt;failure xmlns='urn:ietf:params:xml:ns:xmpp-tls'/&gt;
3145
3146R: &lt;/stream:stream&gt;
3147</pre></div>
3148<p>Causes for the failure case include but are not limited to:
3149</p>
3150<p>
3151 </p>
3152<ol class="text">
3153<li>The initiating entity has sent a malformed STARTTLS command.
3154</li>
3155<li>The receiving entity did not offer the STARTTLS feature in its stream features.
3156</li>
3157<li>The receiving entity cannot complete STARTTLS negotiation because of an internal error.
3158</li>
3159</ol><p>
3160
3161</p>
3162<p></p>
3163<blockquote class="text">
3164<p>Informational Note: STARTTLS failure is not triggered by TLS errors such as bad_certificate or handshake_failure, which are generated and handled during the TLS negotiation itself as described in <a class='info' href='#TLS'>[TLS]<span> (</span><span class='info'>Dierks, T. and E. Rescorla, &ldquo;The Transport Layer Security (TLS) Protocol Version 1.2,&rdquo; August&nbsp;2008.</span><span>)</span></a>.
3165</p>
3166</blockquote>
3167
3168<p>If the failure case occurs, the initiating entity MAY attempt to reconnect as explained under <a class='info' href='#tcp-reconnect'>Section&nbsp;3.3<span> (</span><span class='info'>Reconnection</span><span>)</span></a>.
3169</p>
3170<a name="tls-process-initiate-proceed"></a><br /><hr />
3171<table summary="layout" cellpadding="0" cellspacing="2" class="TOCbug" align="right"><tr><td class="TOCbug"><a href="#toc">&nbsp;TOC&nbsp;</a></td></tr></table>
3172<a name="rfc.section.5.4.2.3"></a><h3>5.4.2.3.&nbsp;
3173Proceed Case</h3>
3174
3175<p>If the proceed case occurs, the receiving entity MUST return a &lt;proceed/&gt; element qualified by the 'urn:ietf:params:xml:ns:xmpp-tls' namespace.
3176</p><div style='display: table; width: 0; margin-left: 3em; margin-right: auto'><pre>
3177R: &lt;proceed xmlns='urn:ietf:params:xml:ns:xmpp-tls'/&gt;
3178</pre></div>
3179<p>The receiving entity MUST consider the TLS negotiation to have begun immediately after sending the closing '&gt;' character of the &lt;proceed/&gt; element to the initiating entity. The initiating entity MUST consider the TLS negotiation to have begun immediately after receiving the closing '&gt;' character of the &lt;proceed/&gt; element from the receiving entity.
3180</p>
3181<p>The entities now proceed to TLS negotiation as explained in the next section.
3182</p>
3183<a name="tls-process-neg"></a><br /><hr />
3184<table summary="layout" cellpadding="0" cellspacing="2" class="TOCbug" align="right"><tr><td class="TOCbug"><a href="#toc">&nbsp;TOC&nbsp;</a></td></tr></table>
3185<a name="rfc.section.5.4.3"></a><h3>5.4.3.&nbsp;
3186TLS Negotiation</h3>
3187
3188<a name="tls-process-neg-rules"></a><br /><hr />
3189<table summary="layout" cellpadding="0" cellspacing="2" class="TOCbug" align="right"><tr><td class="TOCbug"><a href="#toc">&nbsp;TOC&nbsp;</a></td></tr></table>
3190<a name="rfc.section.5.4.3.1"></a><h3>5.4.3.1.&nbsp;
3191Rules</h3>
3192
3193<p>In order to complete TLS negotiation over the TCP connection, the entities MUST follow the process defined in <a class='info' href='#TLS'>[TLS]<span> (</span><span class='info'>Dierks, T. and E. Rescorla, &ldquo;The Transport Layer Security (TLS) Protocol Version 1.2,&rdquo; August&nbsp;2008.</span><span>)</span></a>.
3194</p>
3195<p>The following rules apply:
3196</p>
3197<p>
3198 </p>
3199<ol class="text">
3200<li>The entities MUST NOT send any further XML data until the TLS negotiation is complete.
3201</li>
3202<li>When using any of the mandatory-to-implement (MTI) ciphersuites specified under <a class='info' href='#security-mti'>Section&nbsp;13.8<span> (</span><span class='info'>Mandatory-to-Implement TLS and SASL Technologies</span><span>)</span></a>, the receiving entity MUST present a certificate.
3203</li>
3204<li>So that mutual certificate authentication will be possible, the receiving entity SHOULD send a certificate request to the initiating entity, and the initiating entity SHOULD send a certificate to the receiving entity (but for privacy reasons might opt not to send a certificate until after the receiving entity has authenticated to the initiating entity).
3205</li>
3206<li>The receiving entity SHOULD choose which certificate to present based on the domainpart contained in the 'to' attribute of the initial stream header (in essence, this domainpart is functionally equivalent to the Server Name Indication defined for TLS in <a class='info' href='#TLS-EXT'>[TLS&#8209;EXT]<span> (</span><span class='info'>Eastlake 3rd, D., &ldquo;Transport Layer Security (TLS) Extensions: Extension Definitions,&rdquo; January&nbsp;2011.</span><span>)</span></a>).
3207</li>
3208<li>To determine if the TLS negotiation will succeed, the initiating entity MUST attempt to validate the receiving entity's certificate in accordance with the certificate validation procedures specified under <a class='info' href='#security-certificates-validation'>Section&nbsp;13.7.2<span> (</span><span class='info'>Certificate Validation</span><span>)</span></a>.
3209</li>
3210<li>If the initiating entity presents a certificate, the receiving entity too MUST attempt to validate the initiating entity's certificate in accordance with the certificate validation procedures specified under <a class='info' href='#security-certificates-validation'>Section&nbsp;13.7.2<span> (</span><span class='info'>Certificate Validation</span><span>)</span></a>.
3211</li>
3212<li>Following successful TLS negotiation, all further data transmitted by either party MUST be protected with the negotiated algorithms, keys, and secrets (i.e., encrypted, integrity-protected, or both depending on the ciphersuite used).
3213</li>
3214</ol><p>
3215
3216</p>
3217<p></p>
3218<blockquote class="text">
3219<p>Security Warning: See <a class='info' href='#security-mti'>Section&nbsp;13.8<span> (</span><span class='info'>Mandatory-to-Implement TLS and SASL Technologies</span><span>)</span></a> regarding ciphersuites that MUST be supported for TLS; naturally, other ciphersuites MAY be supported as well.
3220</p>
3221</blockquote>
3222
3223<a name="tls-process-neg-failure"></a><br /><hr />
3224<table summary="layout" cellpadding="0" cellspacing="2" class="TOCbug" align="right"><tr><td class="TOCbug"><a href="#toc">&nbsp;TOC&nbsp;</a></td></tr></table>
3225<a name="rfc.section.5.4.3.2"></a><h3>5.4.3.2.&nbsp;
3226TLS Failure</h3>
3227
3228<p>If the TLS negotiation results in failure, the receiving entity MUST terminate the TCP connection.
3229</p>
3230<p>The receiving entity MUST NOT send a closing &lt;/stream&gt; tag before terminating the TCP connection (since the failure has occurred at the TLS layer, not the XMPP layer as described under <a class='info' href='#security-layers'>Section&nbsp;13.3<span> (</span><span class='info'>Order of Layers</span><span>)</span></a>).
3231</p>
3232<p>The initiating entity MAY attempt to reconnect as explained under <a class='info' href='#tcp-reconnect'>Section&nbsp;3.3<span> (</span><span class='info'>Reconnection</span><span>)</span></a>, with or without attempting TLS negotiation (in accordance with local service policy, user-configured preferences, etc.).
3233</p>
3234<a name="tls-process-neg-success"></a><br /><hr />
3235<table summary="layout" cellpadding="0" cellspacing="2" class="TOCbug" align="right"><tr><td class="TOCbug"><a href="#toc">&nbsp;TOC&nbsp;</a></td></tr></table>
3236<a name="rfc.section.5.4.3.3"></a><h3>5.4.3.3.&nbsp;
3237TLS Success</h3>
3238
3239<p>If the TLS negotiation is successful, then the entities MUST proceed as follows.
3240</p>
3241<p>
3242 </p>
3243<ol class="text">
3244<li>The initiating entity MUST discard any information transmitted in layers above TCP that it obtained from the receiving entity in an insecure manner before TLS took effect (e.g., the receiving entity's 'from' address or the stream ID and stream features received from the receiving entity).
3245</li>
3246<li>The receiving entity MUST discard any information transmitted in layers above TCP that it obtained from the initiating entity in an insecure manner before TLS took effect (e.g., the initiating entity's 'from' address).
3247</li>
3248<li>The initiating entity MUST send a new initial stream header to the receiving entity over the encrypted connection (as specified under <a class='info' href='#streams-negotiation-restart'>Section&nbsp;4.3.3<span> (</span><span class='info'>Restarts</span><span>)</span></a>, the initiating entity MUST NOT send a closing &lt;/stream&gt; tag before sending the new initial stream header, since the receiving entity and initiating entity MUST consider the original stream to be replaced upon success of the TLS negotiation).
3249 <div style='display: table; width: 0; margin-left: 3em; margin-right: auto'><pre>
3250I: &lt;stream:stream
3251 from='juliet@im.example.com'
3252 to='im.example.com'
3253 version='1.0'
3254 xml:lang='en'
3255 xmlns='jabber:client'
3256 xmlns:stream='http://etherx.jabber.org/streams'&gt;
3257</pre></div>
3258
3259</li>
3260<li>The receiving entity MUST respond with a new response stream header over the encrypted connection (for which it MUST generate a new stream ID instead of reusing the old stream ID).
3261 <div style='display: table; width: 0; margin-left: 3em; margin-right: auto'><pre>
3262R: &lt;stream:stream
3263 from='im.example.com'
3264 id='vgKi/bkYME8OAj4rlXMkpucAqe4='
3265 to='juliet@im.example.com'
3266 version='1.0'
3267 xml:lang='en'
3268 xmlns='jabber:client'
3269 xmlns:stream='http://etherx.jabber.org/streams'&gt;
3270</pre></div>
3271
3272</li>
3273<li>The receiving entity also MUST send stream features to the initiating entity, which MUST NOT include the STARTTLS feature but which SHOULD include the SASL stream feature as described under <a class='info' href='#sasl'>Section&nbsp;6<span> (</span><span class='info'>SASL Negotiation</span><span>)</span></a> (see especially <a class='info' href='#sasl-process-stream'>Section&nbsp;6.4.1<span> (</span><span class='info'>Exchange of Stream Headers and Stream Features</span><span>)</span></a> regarding the few reasons why the SASL stream feature would not be offered here).
3274 <div style='display: table; width: 0; margin-left: 3em; margin-right: auto'><pre>
3275R: &lt;stream:features&gt;
3276 &lt;mechanisms xmlns='urn:ietf:params:xml:ns:xmpp-sasl'&gt;
3277 &lt;mechanism&gt;EXTERNAL&lt;/mechanism&gt;
3278 &lt;mechanism&gt;SCRAM-SHA-1-PLUS&lt;/mechanism&gt;
3279 &lt;mechanism&gt;SCRAM-SHA-1&lt;/mechanism&gt;
3280 &lt;mechanism&gt;PLAIN&lt;/mechanism&gt;
3281 &lt;/mechanisms&gt;
3282 &lt;/stream:features&gt;
3283</pre></div>
3284
3285</li>
3286</ol><p>
3287
3288</p>
3289<a name="sasl"></a><br /><hr />
3290<table summary="layout" cellpadding="0" cellspacing="2" class="TOCbug" align="right"><tr><td class="TOCbug"><a href="#toc">&nbsp;TOC&nbsp;</a></td></tr></table>
3291<a name="rfc.section.6"></a><h3>6.&nbsp;
3292SASL Negotiation</h3>
3293
3294<a name="sasl-fundamentals"></a><br /><hr />
3295<table summary="layout" cellpadding="0" cellspacing="2" class="TOCbug" align="right"><tr><td class="TOCbug"><a href="#toc">&nbsp;TOC&nbsp;</a></td></tr></table>
3296<a name="rfc.section.6.1"></a><h3>6.1.&nbsp;
3297Fundamentals</h3>
3298
3299<p>XMPP includes a method for authenticating a stream by means of an XMPP-specific profile of the Simple Authentication and Security Layer protocol (see <a class='info' href='#SASL'>[SASL]<span> (</span><span class='info'>Melnikov, A. and K. Zeilenga, &ldquo;Simple Authentication and Security Layer (SASL),&rdquo; June&nbsp;2006.</span><span>)</span></a>). SASL provides a generalized method for adding authentication support to connection-based protocols, and XMPP uses an XML namespace profile of SASL that conforms to the profiling requirements of <a class='info' href='#SASL'>[SASL]<span> (</span><span class='info'>Melnikov, A. and K. Zeilenga, &ldquo;Simple Authentication and Security Layer (SASL),&rdquo; June&nbsp;2006.</span><span>)</span></a>. The XML namespace name for the SASL extension is 'urn:ietf:params:xml:ns:xmpp-sasl'.
3300</p>
3301<a name="sasl-support"></a><br /><hr />
3302<table summary="layout" cellpadding="0" cellspacing="2" class="TOCbug" align="right"><tr><td class="TOCbug"><a href="#toc">&nbsp;TOC&nbsp;</a></td></tr></table>
3303<a name="rfc.section.6.2"></a><h3>6.2.&nbsp;
3304Support</h3>
3305
3306<p>Support for SASL negotiation is REQUIRED in XMPP client and server implementations.
3307</p>
3308<a name="sasl-rules"></a><br /><hr />
3309<table summary="layout" cellpadding="0" cellspacing="2" class="TOCbug" align="right"><tr><td class="TOCbug"><a href="#toc">&nbsp;TOC&nbsp;</a></td></tr></table>
3310<a name="rfc.section.6.3"></a><h3>6.3.&nbsp;
3311Stream Negotiation Rules</h3>
3312
3313<a name="sasl-rules-mtn"></a><br /><hr />
3314<table summary="layout" cellpadding="0" cellspacing="2" class="TOCbug" align="right"><tr><td class="TOCbug"><a href="#toc">&nbsp;TOC&nbsp;</a></td></tr></table>
3315<a name="rfc.section.6.3.1"></a><h3>6.3.1.&nbsp;
3316Mandatory-to-Negotiate</h3>
3317
3318<p>The parties to a stream MUST consider SASL as mandatory-to-negotiate.
3319</p>
3320<a name="sasl-rules-restart"></a><br /><hr />
3321<table summary="layout" cellpadding="0" cellspacing="2" class="TOCbug" align="right"><tr><td class="TOCbug"><a href="#toc">&nbsp;TOC&nbsp;</a></td></tr></table>
3322<a name="rfc.section.6.3.2"></a><h3>6.3.2.&nbsp;
3323Restart</h3>
3324
3325<p>After SASL negotiation, the parties MUST restart the stream.
3326</p>
3327<a name="sasl-rules-preferences"></a><br /><hr />
3328<table summary="layout" cellpadding="0" cellspacing="2" class="TOCbug" align="right"><tr><td class="TOCbug"><a href="#toc">&nbsp;TOC&nbsp;</a></td></tr></table>
3329<a name="rfc.section.6.3.3"></a><h3>6.3.3.&nbsp;
3330Mechanism Preferences</h3>
3331
3332<p>Any entity that will act as a SASL client or a SASL server MUST
3333maintain an ordered list of its preferred SASL mechanisms according to the
3334client or server, where the list is ordered according to local policy or user
3335configuration (which SHOULD be in order of perceived strength to enable the
3336strongest authentication possible). The initiating entity MUST maintain its
3337own preference order independent of the preference order of the receiving
3338entity. A client MUST try SASL mechanisms in its preference order. For example, if the server offers the ordered list "PLAIN SCRAM-SHA-1 GSSAPI" or "SCRAM-SHA-1 GSSAPI PLAIN" but the client's ordered list is "GSSAPI SCRAM-SHA-1", the client MUST try GSSAPI first and then SCRAM-SHA-1 but MUST NOT try PLAIN (since PLAIN is not on its list).
3339</p>
3340<a name="sasl-rules-offers"></a><br /><hr />
3341<table summary="layout" cellpadding="0" cellspacing="2" class="TOCbug" align="right"><tr><td class="TOCbug"><a href="#toc">&nbsp;TOC&nbsp;</a></td></tr></table>
3342<a name="rfc.section.6.3.4"></a><h3>6.3.4.&nbsp;
3343Mechanism Offers</h3>
3344
3345<p>If the receiving entity considers <a class='info' href='#tls'>TLS negotiation<span> (</span><span class='info'>STARTTLS Negotiation</span><span>)</span></a> to be mandatory-to-negotiate before it will accept authentication with a particular SASL mechanism, it MUST NOT advertise that mechanism in its list of available SASL mechanisms before TLS negotiation has been completed.
3346</p>
3347<p>The receiving entity SHOULD offer the SASL EXTERNAL mechanism if both of the following conditions hold:
3348</p>
3349<p>
3350 </p>
3351<ol class="text">
3352<li>During TLS negotiation the initiating entity presented a certificate that is acceptable to the receiving entity for purposes of strong identity verification in accordance with local service policies (e.g., because said certificate is unexpired, is unrevoked, and is anchored to a root trusted by the receiving entity).
3353</li>
3354<li>The receiving entity expects that the initiating entity will be able to authenticate and authorize as the identity provided in the certificate; in the case of a server-to-server stream, the receiving entity might have such an expectation because a DNS domain name presented in the initiating entity's certificate matches the domain referenced in the 'from' attribute of the initial stream header, where the matching rules of <a class='info' href='#TLS-CERTS'>[TLS&#8209;CERTS]<span> (</span><span class='info'>Saint-Andre, P. and J. Hodges, &ldquo;Representation and Verification of Domain-Based Application Service Identity within Internet Public Key Infrastructure Using X.509 (PKIX) Certificates in the Context of Transport Layer Security (TLS),&rdquo; March&nbsp;2011.</span><span>)</span></a> apply; in the case of a client-to-server stream, the receiving entity might have such an expectation because the bare JID presented in the initiating entity's certificate matches a user account that is registered with the server or because other information contained in the initiating entity's certificate matches that of an entity that has permission to use the server for access to an XMPP network.
3355</li>
3356</ol><p>
3357
3358</p>
3359<p>However, the receiving entity MAY offer the SASL EXTERNAL mechanism under other circumstances, as well.
3360</p>
3361<p>When the receiving entity offers the SASL EXTERNAL mechanism, the receiving entity SHOULD list the EXTERNAL mechanism first among its offered SASL mechanisms and the initiating entity SHOULD attempt SASL negotiation using the EXTERNAL mechanism first (this preference will tend to increase the likelihood that the parties can negotiate mutual certificate authentication).
3362</p>
3363<p><a class='info' href='#security-mti'>Section&nbsp;13.8<span> (</span><span class='info'>Mandatory-to-Implement TLS and SASL Technologies</span><span>)</span></a> specifies SASL mechanisms that MUST be supported; naturally, other SASL mechanisms MAY be supported as well.
3364</p>
3365<p></p>
3366<blockquote class="text">
3367<p>Informational Note: Best practices for the use of SASL in the context of XMPP are described in <a class='info' href='#XEP-0175'>[XEP&#8209;0175]<span> (</span><span class='info'>Saint-Andre, P., &ldquo;Best Practices for Use of SASL ANONYMOUS,&rdquo; September&nbsp;2009.</span><span>)</span></a> for the ANONYMOUS mechanism and in <a class='info' href='#XEP-0178'>[XEP&#8209;0178]<span> (</span><span class='info'>Saint-Andre, P. and P. Millard, &ldquo;Best Practices for Use of SASL EXTERNAL with Certificates,&rdquo; February&nbsp;2007.</span><span>)</span></a> for the EXTERNAL mechanism.
3368</p>
3369</blockquote>
3370
3371<a name="sasl-rules-data"></a><br /><hr />
3372<table summary="layout" cellpadding="0" cellspacing="2" class="TOCbug" align="right"><tr><td class="TOCbug"><a href="#toc">&nbsp;TOC&nbsp;</a></td></tr></table>
3373<a name="rfc.section.6.3.5"></a><h3>6.3.5.&nbsp;
3374Data Formatting</h3>
3375
3376<p>The following data formatting rules apply to the SASL negotiation:
3377</p>
3378<p>
3379 </p>
3380<ol class="text">
3381<li>During SASL negotiation, the entities MUST NOT send any whitespace as separators between XML elements (i.e., from the last character of the first-level &lt;auth/&gt; element qualified by the 'urn:ietf:params:xml:ns:xmpp-sasl' namespace as sent by the initiating entity, until the last character of the first-level &lt;success/&gt; element qualified by the 'urn:ietf:params:xml:ns:xmpp-sasl' namespace as sent by the receiving entity). This prohibition helps to ensure proper security layer byte precision. Any such whitespace shown in the SASL examples provided in this document is included only for the sake of readability.
3382</li>
3383<li>Any XML character data contained within the XML elements MUST be encoded using base 64, where the encoding adheres to the definition in Section 4 of <a class='info' href='#BASE64'>[BASE64]<span> (</span><span class='info'>Josefsson, S., &ldquo;The Base16, Base32, and Base64 Data Encodings,&rdquo; October&nbsp;2006.</span><span>)</span></a> and where the padding bits are set to zero.
3384</li>
3385<li>As formally specified in the XML schema for the 'urn:ietf:params:xml:ns:xmpp-sasl' namespace under <a class='info' href='#schemas-sasl'>Appendix&nbsp;A.4<span> (</span><span class='info'>SASL Namespace</span><span>)</span></a>, the receiving entity MAY include one or more application-specific child elements inside the &lt;mechanisms/&gt; element to provide information that might be needed by the initiating entity in order to complete successful SASL negotiation using one or more of the offered mechanisms; however, the syntax and semantics of all such elements are out of scope for this specification (see <a class='info' href='#XEP-0233'>[XEP&#8209;0233]<span> (</span><span class='info'>Miller, M., Saint-Andre, P., and J. Hildebrand, &ldquo;Domain-Based Service Names in XMPP SASL Negotiation,&rdquo; June&nbsp;2010.</span><span>)</span></a> for one example).
3386</li>
3387</ol><p>
3388
3389</p>
3390<a name="sasl-rules-layers"></a><br /><hr />
3391<table summary="layout" cellpadding="0" cellspacing="2" class="TOCbug" align="right"><tr><td class="TOCbug"><a href="#toc">&nbsp;TOC&nbsp;</a></td></tr></table>
3392<a name="rfc.section.6.3.6"></a><h3>6.3.6.&nbsp;
3393Security Layers</h3>
3394
3395<p>Upon successful SASL negotiation that involves negotiation
3396 of a security layer, both the initiating entity and the
3397 receiving entity MUST discard any application-layer state (i.e, state from the XMPP layer, excluding state from the TLS negotiation or SASL negotiation).
3398</p>
3399<a name="sasl-rules-username"></a><br /><hr />
3400<table summary="layout" cellpadding="0" cellspacing="2" class="TOCbug" align="right"><tr><td class="TOCbug"><a href="#toc">&nbsp;TOC&nbsp;</a></td></tr></table>
3401<a name="rfc.section.6.3.7"></a><h3>6.3.7.&nbsp;
3402Simple User Name</h3>
3403
3404<p>Some SASL mechanisms (e.g., CRAM-MD5, DIGEST-MD5, and SCRAM) specify that the authentication identity used in the context of such mechanisms is a "simple user name" (see Section 2 of <a class='info' href='#SASL'>[SASL]<span> (</span><span class='info'>Melnikov, A. and K. Zeilenga, &ldquo;Simple Authentication and Security Layer (SASL),&rdquo; June&nbsp;2006.</span><span>)</span></a> as well as <a class='info' href='#SASLPREP'>[SASLPREP]<span> (</span><span class='info'>Zeilenga, K., &ldquo;SASLprep: Stringprep Profile for User Names and Passwords,&rdquo; February&nbsp;2005.</span><span>)</span></a>). The exact form of the simple user name in any particular mechanism or deployment thereof is a local matter, and a simple user name does not necessarily map to an application identifier such as a JID or JID component (e.g., a localpart). However, in the absence of local information provided by the server, an XMPP client SHOULD assume that the authentication identity for such a SASL mechanism is a simple user name equal to the localpart of the user's JID.
3405</p>
3406<a name="sasl-rules-authzid"></a><br /><hr />
3407<table summary="layout" cellpadding="0" cellspacing="2" class="TOCbug" align="right"><tr><td class="TOCbug"><a href="#toc">&nbsp;TOC&nbsp;</a></td></tr></table>
3408<a name="rfc.section.6.3.8"></a><h3>6.3.8.&nbsp;
3409Authorization Identity</h3>
3410
3411<p>An authorization identity is an OPTIONAL identity included by the initiating entity to specify an identity to act as (see Section 2 of <a class='info' href='#SASL'>[SASL]<span> (</span><span class='info'>Melnikov, A. and K. Zeilenga, &ldquo;Simple Authentication and Security Layer (SASL),&rdquo; June&nbsp;2006.</span><span>)</span></a>). In client-to-server streams, it would most likely be used by an administrator to perform some management task on behalf of another user, whereas in server-to-server streams it would most likely be used to specify a particular add-on service at an XMPP service (e.g., a multi-user chat server at conference.example.com that is hosted by the example.com XMPP service). If the initiating entity wishes to act on behalf of another entity and the selected SASL mechanism supports transmission of an authorization identity, the initiating entity MUST provide an authorization identity during SASL negotiation. If the initiating entity does not wish to act on behalf of another entity, it MUST NOT provide an authorization identity.
3412</p>
3413<p>In the case of client-to-server communication, the value of an authorization identity MUST be a bare JID (&lt;localpart@domainpart&gt;) rather than a full JID (&lt;localpart@domainpart/resourcepart&gt;).
3414</p>
3415<p>In the case of server-to-server communication, the value of an authorization identity MUST be a domainpart only (&lt;domainpart&gt;).
3416</p>
3417<p>If the initiating entity provides an authorization identity during SASL negotiation, the receiving entity is responsible for verifying that the initiating entity is in fact allowed to assume the specified authorization identity; if not, the receiving entity MUST return an &lt;invalid-authzid/&gt; SASL error as described under <a class='info' href='#sasl-errors-invalid-authzid'>Section&nbsp;6.5.6<span> (</span><span class='info'>invalid-authzid</span><span>)</span></a>.
3418</p>
3419<a name="sasl-rules-realms"></a><br /><hr />
3420<table summary="layout" cellpadding="0" cellspacing="2" class="TOCbug" align="right"><tr><td class="TOCbug"><a href="#toc">&nbsp;TOC&nbsp;</a></td></tr></table>
3421<a name="rfc.section.6.3.9"></a><h3>6.3.9.&nbsp;
3422Realms</h3>
3423
3424<p>The receiving entity MAY include a realm when negotiating certain SASL mechanisms (e.g., both the GSSAPI and DIGEST-MD5 mechanisms allow the authentication exchange to include a realm, though in different ways, whereas the EXTERNAL, SCRAM, and PLAIN mechanisms do not). If the receiving entity does not communicate a realm, the initiating entity MUST NOT assume that any realm exists. The realm MUST be used only for the purpose of authentication; in particular, an initiating entity MUST NOT attempt to derive an XMPP domainpart from the realm information provided by the receiving entity.
3425</p>
3426<a name="sasl-rules-roundtrips"></a><br /><hr />
3427<table summary="layout" cellpadding="0" cellspacing="2" class="TOCbug" align="right"><tr><td class="TOCbug"><a href="#toc">&nbsp;TOC&nbsp;</a></td></tr></table>
3428<a name="rfc.section.6.3.10"></a><h3>6.3.10.&nbsp;
3429Round Trips</h3>
3430
3431<p><a class='info' href='#SASL'>[SASL]<span> (</span><span class='info'>Melnikov, A. and K. Zeilenga, &ldquo;Simple Authentication and Security Layer (SASL),&rdquo; June&nbsp;2006.</span><span>)</span></a> specifies that a using protocol such as XMPP can define two methods by which the protocol can save round trips where allowed for the SASL mechanism:
3432</p>
3433<p>
3434 </p>
3435<ol class="text">
3436<li>When the SASL client (the XMPP "initiating entity") requests an authentication exchange, it can include "initial response" data with its request if appropriate for the SASL mechanism in use. In XMPP, this is done by including the initial response as the XML character data of the &lt;auth/&gt; element.
3437</li>
3438<li>At the end of the authentication exchange, the SASL server (the XMPP "receiving entity") can include "additional data with success" if appropriate for the SASL mechanism in use. In XMPP, this is done by including the additional data as the XML character data of the &lt;success/&gt; element.
3439</li>
3440</ol><p>
3441
3442</p>
3443<p>For the sake of protocol efficiency, it is REQUIRED for clients and servers to support these methods and RECOMMENDED to use them; however, clients and servers MUST support the less efficient modes as well.
3444</p>
3445<a name="sasl-process"></a><br /><hr />
3446<table summary="layout" cellpadding="0" cellspacing="2" class="TOCbug" align="right"><tr><td class="TOCbug"><a href="#toc">&nbsp;TOC&nbsp;</a></td></tr></table>
3447<a name="rfc.section.6.4"></a><h3>6.4.&nbsp;
3448Process</h3>
3449
3450<p>The process for SASL negotiation is as follows.
3451</p>
3452<a name="sasl-process-stream"></a><br /><hr />
3453<table summary="layout" cellpadding="0" cellspacing="2" class="TOCbug" align="right"><tr><td class="TOCbug"><a href="#toc">&nbsp;TOC&nbsp;</a></td></tr></table>
3454<a name="rfc.section.6.4.1"></a><h3>6.4.1.&nbsp;
3455Exchange of Stream Headers and Stream Features</h3>
3456
3457<p>If SASL negotiation follows successful <a class='info' href='#tls'>STARTTLS negotiation<span> (</span><span class='info'>STARTTLS Negotiation</span><span>)</span></a>, then the SASL negotiation occurs over the protected stream that has already been negotiated. If not, the initiating entity resolves the FQDN of the receiving entity as specified under <a class='info' href='#tcp'>Section&nbsp;3<span> (</span><span class='info'>TCP Binding</span><span>)</span></a>, opens a TCP connection to the advertised port at the resolved IP address, and sends an initial stream header to the receiving entity. In either case, the receiving entity will receive an initial stream from the initiating entity.
3458</p><div style='display: table; width: 0; margin-left: 3em; margin-right: auto'><pre>
3459I: &lt;stream:stream
3460 from='juliet@im.example.com'
3461 to='im.example.com'
3462 version='1.0'
3463 xml:lang='en'
3464 xmlns='jabber:client'
3465 xmlns:stream='http://etherx.jabber.org/streams'&gt;
3466</pre></div>
3467<p>When the receiving entity processes an initial stream header from the initiating entity, it MUST send a response stream header to the initiating entity (for which it MUST generate a unique stream ID. If TLS negotiation has already succeeded, then this stream ID MUST be different from the stream ID sent before TLS negotiation succeeded).
3468</p><div style='display: table; width: 0; margin-left: 3em; margin-right: auto'><pre>
3469R: &lt;stream:stream
3470 from='im.example.com'
3471 id='vgKi/bkYME8OAj4rlXMkpucAqe4='
3472 to='juliet@im.example.com'
3473 version='1.0'
3474 xml:lang='en'
3475 xmlns='jabber:client'
3476 xmlns:stream='http://etherx.jabber.org/streams'&gt;
3477</pre></div>
3478<p>The receiving entity also MUST send stream features to the initiating entity. The stream features SHOULD include an advertisement for support of SASL negotiation, i.e., a &lt;mechanisms/&gt; element qualified by the 'urn:ietf:params:xml:ns:xmpp-sasl' namespace. Typically there are only three cases in which support for SASL negotiation would not be advertised here:
3479</p>
3480<p>
3481 </p>
3482<ul class="text">
3483<li>TLS negotiation needs to happen before SASL can be offered (i.e., TLS is required and the receiving entity is responding to the very first initial stream header it has received for this connection attempt).
3484</li>
3485<li>SASL negotiation is impossible for a server-to-server connection (i.e., the initiating server has not provided a certificate that would enable strong authentication and therefore the receiving server is falling back to weak identity verification using the Server Dialback protocol <a class='info' href='#XEP-0220'>[XEP&#8209;0220]<span> (</span><span class='info'>Miller, J., Saint-Andre, P., and P. Hancke, &ldquo;Server Dialback,&rdquo; March&nbsp;2010.</span><span>)</span></a>).
3486</li>
3487<li>SASL has already been negotiated (i.e., the receiving entity is responding to an initial stream header sent as a stream restart after successful SASL negotiation).
3488</li>
3489</ul><p>
3490
3491</p>
3492<p>The &lt;mechanisms/&gt; element MUST contain one &lt;mechanism/&gt; child element for each authentication mechanism the receiving entity offers to the initiating entity. As noted, the order of &lt;mechanism/&gt; elements in the XML indicates the preference order of the SASL mechanisms according to the receiving entity (which is not necessarily the preference order according to the initiating entity).
3493</p><div style='display: table; width: 0; margin-left: 3em; margin-right: auto'><pre>
3494R: &lt;stream:features&gt;
3495 &lt;mechanisms xmlns='urn:ietf:params:xml:ns:xmpp-sasl'&gt;
3496 &lt;mechanism&gt;EXTERNAL&lt;/mechanism&gt;
3497 &lt;mechanism&gt;SCRAM-SHA-1-PLUS&lt;/mechanism&gt;
3498 &lt;mechanism&gt;SCRAM-SHA-1&lt;/mechanism&gt;
3499 &lt;mechanism&gt;PLAIN&lt;/mechanism&gt;
3500 &lt;/mechanisms&gt;
3501 &lt;/stream:features&gt;
3502</pre></div>
3503<a name="sasl-process-neg-initiate"></a><br /><hr />
3504<table summary="layout" cellpadding="0" cellspacing="2" class="TOCbug" align="right"><tr><td class="TOCbug"><a href="#toc">&nbsp;TOC&nbsp;</a></td></tr></table>
3505<a name="rfc.section.6.4.2"></a><h3>6.4.2.&nbsp;
3506Initiation</h3>
3507
3508<p>In order to begin the SASL negotiation, the initiating entity sends an &lt;auth/&gt; element qualified by the 'urn:ietf:params:xml:ns:xmpp-sasl' namespace and includes an appropriate value for the 'mechanism' attribute, thus starting the handshake for that particular authentication mechanism. This element MAY contain XML character data (in SASL terminology, the "initial response") if the mechanism supports or requires it. If the initiating entity needs to send a zero-length initial response, it MUST transmit the response as a single equals sign character ("="), which indicates that the response is present but contains no data.
3509</p><div style='display: table; width: 0; margin-left: 3em; margin-right: auto'><pre>
3510I: &lt;auth xmlns='urn:ietf:params:xml:ns:xmpp-sasl'
3511 mechanism='PLAIN'&gt;AGp1bGlldAByMG0zMG15cjBtMzA=&lt;/auth&gt;
3512</pre></div>
3513<p>If the initiating entity subsequently sends another &lt;auth/&gt; element and the ongoing authentication handshake has not yet completed, the receiving entity MUST discard the ongoing handshake and MUST process a new handshake for the subsequently requested SASL mechanism.
3514</p>
3515<a name="sasl-process-neg-challengeresponse"></a><br /><hr />
3516<table summary="layout" cellpadding="0" cellspacing="2" class="TOCbug" align="right"><tr><td class="TOCbug"><a href="#toc">&nbsp;TOC&nbsp;</a></td></tr></table>
3517<a name="rfc.section.6.4.3"></a><h3>6.4.3.&nbsp;
3518Challenge-Response Sequence</h3>
3519
3520<p>If necessary, the receiving entity challenges the initiating entity by sending a &lt;challenge/&gt; element qualified by the 'urn:ietf:params:xml:ns:xmpp-sasl' namespace; this element MAY contain XML character data (which MUST be generated in accordance with the definition of the SASL mechanism chosen by the initiating entity).
3521</p>
3522<p>The initiating entity responds to the challenge by sending a &lt;response/&gt; element qualified by the 'urn:ietf:params:xml:ns:xmpp-sasl' namespace; this element MAY contain XML character data (which MUST be generated in accordance with the definition of the SASL mechanism chosen by the initiating entity).
3523</p>
3524<p>If necessary, the receiving entity sends more challenges and the initiating entity sends more responses.
3525</p>
3526<p>This series of challenge/response pairs continues until one of three things happens:
3527</p>
3528<p>
3529 </p>
3530<ul class="text">
3531<li>The initiating entity aborts the handshake for this authentication mechanism.
3532</li>
3533<li>The receiving entity reports failure of the handshake.
3534</li>
3535<li>The receiving entity reports success of the handshake.
3536</li>
3537</ul><p>
3538
3539</p>
3540<p>These scenarios are described in the following sections.
3541</p>
3542<a name="sasl-process-neg-abort"></a><br /><hr />
3543<table summary="layout" cellpadding="0" cellspacing="2" class="TOCbug" align="right"><tr><td class="TOCbug"><a href="#toc">&nbsp;TOC&nbsp;</a></td></tr></table>
3544<a name="rfc.section.6.4.4"></a><h3>6.4.4.&nbsp;
3545Abort</h3>
3546
3547<p>The initiating entity aborts the handshake for this authentication mechanism by sending an &lt;abort/&gt; element qualified by the 'urn:ietf:params:xml:ns:xmpp-sasl' namespace.
3548</p><div style='display: table; width: 0; margin-left: 3em; margin-right: auto'><pre>
3549I: &lt;abort xmlns='urn:ietf:params:xml:ns:xmpp-sasl'/&gt;
3550</pre></div>
3551<p>Upon receiving an &lt;abort/&gt; element, the receiving entity MUST return a &lt;failure/&gt; element qualified by the 'urn:ietf:params:xml:ns:xmpp-sasl' namespace and containing an &lt;aborted/&gt; child element.
3552</p><div style='display: table; width: 0; margin-left: 3em; margin-right: auto'><pre>
3553R: &lt;failure xmlns='urn:ietf:params:xml:ns:xmpp-sasl'&gt;
3554 &lt;aborted/&gt;
3555 &lt;/failure&gt;
3556</pre></div>
3557<a name="sasl-process-neg-failure"></a><br /><hr />
3558<table summary="layout" cellpadding="0" cellspacing="2" class="TOCbug" align="right"><tr><td class="TOCbug"><a href="#toc">&nbsp;TOC&nbsp;</a></td></tr></table>
3559<a name="rfc.section.6.4.5"></a><h3>6.4.5.&nbsp;
3560SASL Failure</h3>
3561
3562<p>The receiving entity reports failure of the handshake for this authentication mechanism by sending a &lt;failure/&gt; element qualified by the 'urn:ietf:params:xml:ns:xmpp-sasl' namespace (the particular cause of failure MUST be communicated in an appropriate child element of the &lt;failure/&gt; element as defined under <a class='info' href='#sasl-errors'>Section&nbsp;6.5<span> (</span><span class='info'>SASL Errors</span><span>)</span></a>).
3563</p><div style='display: table; width: 0; margin-left: 3em; margin-right: auto'><pre>
3564R: &lt;failure xmlns='urn:ietf:params:xml:ns:xmpp-sasl'&gt;
3565 &lt;not-authorized/&gt;
3566 &lt;/failure&gt;
3567</pre></div>
3568<p>Where appropriate for the chosen SASL mechanism, the
3569 receiving entity SHOULD allow a configurable but reasonable
3570 number of retries (at least 2 and no more than 5); this
3571 enables the initiating entity (e.g., an end-user client) to
3572 tolerate incorrectly provided credentials (e.g., a mistyped password) without being forced to reconnect (which it would if the receiving entity immediately returned a SASL failure and closed the stream).
3573</p>
3574<p>If the initiating entity attempts a reasonable number of retries with the same SASL mechanism and all attempts fail, it MAY fall back to the next mechanism in its ordered list by sending a new &lt;auth/&gt; request to the receiving entity, thus starting a new handshake for that authentication mechanism. If all handshakes fail and there are no remaining mechanisms in the initiating entity's list of supported and acceptable mechanisms, the initiating entity SHOULD simply close the stream as described under <a class='info' href='#streams-close'>Section&nbsp;4.4<span> (</span><span class='info'>Closing a Stream</span><span>)</span></a> (instead of waiting for the stream to time out).
3575</p>
3576<p>If the initiating entity exceeds the number of retries, the receiving entity MUST close the stream with a stream error, which SHOULD be &lt;policy-violation/&gt; (<a class='info' href='#streams-error-conditions-policy-violation'>Section&nbsp;4.9.3.14<span> (</span><span class='info'>policy-violation</span><span>)</span></a>), although some existing implementations send &lt;not-authorized/&gt; (<a class='info' href='#streams-error-conditions-not-authorized'>Section&nbsp;4.9.3.12<span> (</span><span class='info'>not-authorized</span><span>)</span></a>) instead.
3577</p>
3578<p></p>
3579<blockquote class="text">
3580<p>Implementation Note: For server-to-server streams, if the receiving entity cannot offer the SASL EXTERNAL mechanism or any other SASL mechanism based on the security context established during TLS negotiation, the receiving entity MAY attempt to complete weak identity verification using the Server Dialback protocol <a class='info' href='#XEP-0220'>[XEP&#8209;0220]<span> (</span><span class='info'>Miller, J., Saint-Andre, P., and P. Hancke, &ldquo;Server Dialback,&rdquo; March&nbsp;2010.</span><span>)</span></a>; however, if according to local service policies weak identity verification is insufficient then the receiving entity SHOULD instead close the stream with a &lt;policy-violation/&gt; stream error (<a class='info' href='#streams-error-conditions-policy-violation'>Section&nbsp;4.9.3.14<span> (</span><span class='info'>policy-violation</span><span>)</span></a>) instead of waiting for the stream to time out.
3581</p>
3582</blockquote>
3583
3584<a name="sasl-process-neg-success"></a><br /><hr />
3585<table summary="layout" cellpadding="0" cellspacing="2" class="TOCbug" align="right"><tr><td class="TOCbug"><a href="#toc">&nbsp;TOC&nbsp;</a></td></tr></table>
3586<a name="rfc.section.6.4.6"></a><h3>6.4.6.&nbsp;
3587SASL Success</h3>
3588
3589<p>Before considering the SASL handshake to be a success, if the initiating entity provided a 'from' attribute on an initial stream header whose confidentiality and integrity were protected via TLS or an equivalent security layer (such as the SASL GSSAPI mechanism) then the receiving entity SHOULD correlate the authentication identity resulting from the SASL negotiation with that 'from' address; if the two identities do not match then the receiving entity SHOULD terminate the connection attempt (however, the receiving entity might have legitimate reasons not to terminate the connection attempt, for example, because it has overridden a connecting client's address to correct the JID format or assign a JID based on information presented in an end-user certificate).
3590</p>
3591<p>The receiving entity reports success of the handshake by sending a &lt;success/&gt; element qualified by the 'urn:ietf:params:xml:ns:xmpp-sasl' namespace; this element MAY contain XML character data (in SASL terminology, "additional data with success") if the chosen SASL mechanism supports or requires it. If the receiving entity needs to send additional data of zero length, it MUST transmit the data as a single equals sign character ("=").
3592</p><div style='display: table; width: 0; margin-left: 3em; margin-right: auto'><pre>
3593R: &lt;success xmlns='urn:ietf:params:xml:ns:xmpp-sasl'/&gt;
3594</pre></div>
3595<p></p>
3596<blockquote class="text">
3597<p>Informational Note: For client-to-server streams, the authorization identity communicated during SASL negotiation is used to determine the canonical address for the initiating client according to the receiving server, as described under <a class='info' href='#streams-negotiation-address'>Section&nbsp;4.3.6<span> (</span><span class='info'>Determination of Addresses</span><span>)</span></a>.
3598</p>
3599</blockquote>
3600
3601<p>Upon receiving the &lt;success/&gt; element, the initiating entity MUST initiate a new stream over the existing TCP connection by sending a new initial stream header to the receiving entity (as specified under <a class='info' href='#streams-negotiation-restart'>Section&nbsp;4.3.3<span> (</span><span class='info'>Restarts</span><span>)</span></a>, the initiating entity MUST NOT send a closing &lt;/stream&gt; tag before sending the new initial stream header, since the receiving entity and initiating entity MUST consider the original stream to be replaced upon success of the SASL negotiation).
3602</p><div style='display: table; width: 0; margin-left: 3em; margin-right: auto'><pre>
3603I: &lt;stream:stream
3604 from='juliet@im.example.com'
3605 to='im.example.com'
3606 version='1.0'
3607 xml:lang='en'
3608 xmlns='jabber:client'
3609 xmlns:stream='http://etherx.jabber.org/streams'&gt;
3610</pre></div>
3611<p>Upon receiving the new initial stream header from the initiating entity, the receiving entity MUST respond by sending a new response stream header to the initiating entity (for which it MUST generate a new stream ID instead of reusing the old stream ID).
3612</p><div style='display: table; width: 0; margin-left: 3em; margin-right: auto'><pre>
3613R: &lt;stream:stream
3614 from='im.example.com'
3615 id='gPybzaOzBmaADgxKXu9UClbprp0='
3616 to='juliet@im.example.com'
3617 version='1.0'
3618 xml:lang='en'
3619 xmlns='jabber:client'
3620 xmlns:stream='http://etherx.jabber.org/streams'&gt;
3621</pre></div>
3622<p>The receiving entity MUST also send stream features, containing any further available features or containing no features (via an empty &lt;features/&gt; element).
3623</p><div style='display: table; width: 0; margin-left: 3em; margin-right: auto'><pre>
3624R: &lt;stream:features&gt;
3625 &lt;bind xmlns='urn:ietf:params:xml:ns:xmpp-bind'/&gt;
3626 &lt;/stream:features&gt;
3627</pre></div>
3628<a name="sasl-errors"></a><br /><hr />
3629<table summary="layout" cellpadding="0" cellspacing="2" class="TOCbug" align="right"><tr><td class="TOCbug"><a href="#toc">&nbsp;TOC&nbsp;</a></td></tr></table>
3630<a name="rfc.section.6.5"></a><h3>6.5.&nbsp;
3631SASL Errors</h3>
3632
3633<p>The syntax of SASL errors is as follows, where the XML data shown within the square brackets '[' and ']' is OPTIONAL.
3634</p><div style='display: table; width: 0; margin-left: 3em; margin-right: auto'><pre>
3635&lt;failure xmlns='urn:ietf:params:xml:ns:xmpp-sasl'&gt;
3636 &lt;defined-condition/&gt;
3637 [&lt;text xml:lang='langcode'&gt;
3638 OPTIONAL descriptive text
3639 &lt;/text&gt;]
3640&lt;/failure&gt;
3641</pre></div>
3642<p>The "defined-condition" MUST be one of the SASL-related error conditions defined in the following sections. However, because additional error conditions might be defined in the future, if an entity receives a SASL error condition that it does not understand then it MUST treat the unknown condition as a generic authentication failure, i.e., as equivalent to &lt;not-authorized/&gt; (<a class='info' href='#sasl-errors-not-authorized'>Section&nbsp;6.5.10<span> (</span><span class='info'>not-authorized</span><span>)</span></a>).
3643</p>
3644<p>Inclusion of the &lt;text/&gt; element is OPTIONAL, and can be used to provide application-specific information about the error condition, which information MAY be displayed to a human but only as a supplement to the defined condition.
3645</p>
3646<p>Because XMPP itself defines an application profile of SASL and there is no expectation that more specialized XMPP applications will be built on top of SASL, the SASL error format does not provide extensibility for application-specific error conditions as is done for XML streams (<a class='info' href='#streams-error-app'>Section&nbsp;4.9.4<span> (</span><span class='info'>Application-Specific Conditions</span><span>)</span></a>) and XML stanzas (<a class='info' href='#stanzas-error-app'>Section&nbsp;8.3.4<span> (</span><span class='info'>Application-Specific Conditions</span><span>)</span></a>).
3647</p>
3648<a name="sasl-errors-aborted"></a><br /><hr />
3649<table summary="layout" cellpadding="0" cellspacing="2" class="TOCbug" align="right"><tr><td class="TOCbug"><a href="#toc">&nbsp;TOC&nbsp;</a></td></tr></table>
3650<a name="rfc.section.6.5.1"></a><h3>6.5.1.&nbsp;
3651aborted</h3>
3652
3653<p>The receiving entity acknowledges that the authentication handshake has been aborted by the initiating entity; sent in reply to the &lt;abort/&gt; element.
3654</p><div style='display: table; width: 0; margin-left: 3em; margin-right: auto'><pre>
3655I: &lt;abort xmlns='urn:ietf:params:xml:ns:xmpp-sasl'/&gt;
3656
3657R: &lt;failure xmlns='urn:ietf:params:xml:ns:xmpp-sasl'&gt;
3658 &lt;aborted/&gt;
3659 &lt;/failure&gt;
3660</pre></div>
3661<a name="sasl-errors-account-disabled"></a><br /><hr />
3662<table summary="layout" cellpadding="0" cellspacing="2" class="TOCbug" align="right"><tr><td class="TOCbug"><a href="#toc">&nbsp;TOC&nbsp;</a></td></tr></table>
3663<a name="rfc.section.6.5.2"></a><h3>6.5.2.&nbsp;
3664account-disabled</h3>
3665
3666<p>The account of the initiating entity has been temporarily disabled; sent in reply to an &lt;auth/&gt; element (with or without initial response data) or a &lt;response/&gt; element.
3667</p><div style='display: table; width: 0; margin-left: 3em; margin-right: auto'><pre>
3668I: &lt;auth xmlns='urn:ietf:params:xml:ns:xmpp-sasl'
3669 mechanism='PLAIN'&gt;AGp1bGlldAByMG0zMG15cjBtMzA=&lt;/auth&gt;
3670
3671R: &lt;failure xmlns='urn:ietf:params:xml:ns:xmpp-sasl'&gt;
3672 &lt;account-disabled/&gt;
3673 &lt;text xml:lang='en'&gt;Call 212-555-1212 for assistance.&lt;/text&gt;
3674 &lt;/failure&gt;
3675</pre></div>
3676<a name="sasl-errors-credentials-expired"></a><br /><hr />
3677<table summary="layout" cellpadding="0" cellspacing="2" class="TOCbug" align="right"><tr><td class="TOCbug"><a href="#toc">&nbsp;TOC&nbsp;</a></td></tr></table>
3678<a name="rfc.section.6.5.3"></a><h3>6.5.3.&nbsp;
3679credentials-expired</h3>
3680
3681<p>The authentication failed because the initiating entity provided credentials that have expired; sent in reply to a &lt;response/&gt; element or an &lt;auth/&gt; element with initial response data.
3682</p><div style='display: table; width: 0; margin-left: 3em; margin-right: auto'><pre>
3683I: &lt;response xmlns='urn:ietf:params:xml:ns:xmpp-sasl'&gt;
3684 [ ... ]
3685 &lt;/response&gt;
3686
3687R: &lt;failure xmlns='urn:ietf:params:xml:ns:xmpp-sasl'&gt;
3688 &lt;credentials-expired/&gt;
3689 &lt;/failure&gt;
3690</pre></div>
3691<a name="sasl-errors-encryption-required"></a><br /><hr />
3692<table summary="layout" cellpadding="0" cellspacing="2" class="TOCbug" align="right"><tr><td class="TOCbug"><a href="#toc">&nbsp;TOC&nbsp;</a></td></tr></table>
3693<a name="rfc.section.6.5.4"></a><h3>6.5.4.&nbsp;
3694encryption-required</h3>
3695
3696<p>The mechanism requested by the initiating entity cannot be used unless the confidentiality and integrity of the underlying stream are protected (typically via TLS); sent in reply to an &lt;auth/&gt; element (with or without initial response data).
3697</p><div style='display: table; width: 0; margin-left: 3em; margin-right: auto'><pre>
3698I: &lt;auth xmlns='urn:ietf:params:xml:ns:xmpp-sasl'
3699 mechanism='PLAIN'&gt;AGp1bGlldAByMG0zMG15cjBtMzA=&lt;/auth&gt;
3700
3701R: &lt;failure xmlns='urn:ietf:params:xml:ns:xmpp-sasl'&gt;
3702 &lt;encryption-required/&gt;
3703 &lt;/failure&gt;
3704</pre></div>
3705<a name="sasl-errors-incorrect-encoding"></a><br /><hr />
3706<table summary="layout" cellpadding="0" cellspacing="2" class="TOCbug" align="right"><tr><td class="TOCbug"><a href="#toc">&nbsp;TOC&nbsp;</a></td></tr></table>
3707<a name="rfc.section.6.5.5"></a><h3>6.5.5.&nbsp;
3708incorrect-encoding</h3>
3709
3710<p>The data provided by the initiating entity could not be processed because the base 64 encoding is incorrect (e.g., because the encoding does not adhere to the definition in Section 4 of <a class='info' href='#BASE64'>[BASE64]<span> (</span><span class='info'>Josefsson, S., &ldquo;The Base16, Base32, and Base64 Data Encodings,&rdquo; October&nbsp;2006.</span><span>)</span></a>); sent in reply to a &lt;response/&gt; element or an &lt;auth/&gt; element with initial response data.
3711</p><div style='display: table; width: 0; margin-left: 3em; margin-right: auto'><pre>
3712I: &lt;auth xmlns='urn:ietf:params:xml:ns:xmpp-sasl'
3713 mechanism='DIGEST-MD5'&gt;[ ... ]&lt;/auth&gt;
3714
3715R: &lt;failure xmlns='urn:ietf:params:xml:ns:xmpp-sasl'&gt;
3716 &lt;incorrect-encoding/&gt;
3717 &lt;/failure&gt;
3718</pre></div>
3719<a name="sasl-errors-invalid-authzid"></a><br /><hr />
3720<table summary="layout" cellpadding="0" cellspacing="2" class="TOCbug" align="right"><tr><td class="TOCbug"><a href="#toc">&nbsp;TOC&nbsp;</a></td></tr></table>
3721<a name="rfc.section.6.5.6"></a><h3>6.5.6.&nbsp;
3722invalid-authzid</h3>
3723
3724<p>The authzid provided by the initiating entity is invalid, either because it is incorrectly formatted or because the initiating entity does not have permissions to authorize that ID; sent in reply to a &lt;response/&gt; element or an &lt;auth/&gt; element with initial response data.
3725</p><div style='display: table; width: 0; margin-left: 3em; margin-right: auto'><pre>
3726I: &lt;response xmlns='urn:ietf:params:xml:ns:xmpp-sasl'&gt;
3727 [ ... ]
3728 &lt;/response&gt;
3729
3730R: &lt;failure xmlns='urn:ietf:params:xml:ns:xmpp-sasl'&gt;
3731 &lt;invalid-authzid/&gt;
3732 &lt;/failure&gt;
3733</pre></div>
3734<a name="sasl-errors-invalid-mechanism"></a><br /><hr />
3735<table summary="layout" cellpadding="0" cellspacing="2" class="TOCbug" align="right"><tr><td class="TOCbug"><a href="#toc">&nbsp;TOC&nbsp;</a></td></tr></table>
3736<a name="rfc.section.6.5.7"></a><h3>6.5.7.&nbsp;
3737invalid-mechanism</h3>
3738
3739<p>The initiating entity did not specify a mechanism, or requested a mechanism that is not supported by the receiving entity; sent in reply to an &lt;auth/&gt; element.
3740</p><div style='display: table; width: 0; margin-left: 3em; margin-right: auto'><pre>
3741I: &lt;auth xmlns='urn:ietf:params:xml:ns:xmpp-sasl'
3742 mechanism='CRAM-MD5'/&gt;
3743
3744R: &lt;failure xmlns='urn:ietf:params:xml:ns:xmpp-sasl'&gt;
3745 &lt;invalid-mechanism/&gt;
3746 &lt;/failure&gt;
3747</pre></div>
3748<a name="sasl-errors-malformed-request"></a><br /><hr />
3749<table summary="layout" cellpadding="0" cellspacing="2" class="TOCbug" align="right"><tr><td class="TOCbug"><a href="#toc">&nbsp;TOC&nbsp;</a></td></tr></table>
3750<a name="rfc.section.6.5.8"></a><h3>6.5.8.&nbsp;
3751malformed-request</h3>
3752
3753<p>The request is malformed (e.g., the &lt;auth/&gt; element includes initial response data but the mechanism does not allow that, or the data sent violates the syntax for the specified SASL mechanism); sent in reply to an &lt;abort/&gt;, &lt;auth/&gt;, &lt;challenge/&gt;, or &lt;response/&gt; element.
3754</p>
3755<p>(In the following example, the XML character data of the &lt;auth/&gt; element contains more than 255 UTF-8-encoded Unicode characters and therefore violates the "token" production for the SASL ANONYMOUS mechanism as specified in <a class='info' href='#ANONYMOUS'>[ANONYMOUS]<span> (</span><span class='info'>Zeilenga, K., &ldquo;Anonymous Simple Authentication and Security Layer (SASL) Mechanism,&rdquo; June&nbsp;2006.</span><span>)</span></a>.)
3756</p><div style='display: table; width: 0; margin-left: 3em; margin-right: auto'><pre>
3757I: &lt;auth xmlns='urn:ietf:params:xml:ns:xmpp-sasl'
3758 mechanism='ANONYMOUS'&gt;[ ... some-long-token ... ]&lt;/auth&gt;
3759
3760R: &lt;failure xmlns='urn:ietf:params:xml:ns:xmpp-sasl'&gt;
3761 &lt;malformed-request/&gt;
3762 &lt;/failure&gt;
3763</pre></div>
3764<a name="sasl-errors-mechanism-too-weak"></a><br /><hr />
3765<table summary="layout" cellpadding="0" cellspacing="2" class="TOCbug" align="right"><tr><td class="TOCbug"><a href="#toc">&nbsp;TOC&nbsp;</a></td></tr></table>
3766<a name="rfc.section.6.5.9"></a><h3>6.5.9.&nbsp;
3767mechanism-too-weak</h3>
3768
3769<p>The mechanism requested by the initiating entity is weaker than server policy permits for that initiating entity; sent in reply to an &lt;auth/&gt; element (with or without initial response data).
3770</p><div style='display: table; width: 0; margin-left: 3em; margin-right: auto'><pre>
3771I: &lt;auth xmlns='urn:ietf:params:xml:ns:xmpp-sasl'
3772 mechanism='PLAIN'&gt;AGp1bGlldAByMG0zMG15cjBtMzA=&lt;/auth&gt;
3773
3774R: &lt;failure xmlns='urn:ietf:params:xml:ns:xmpp-sasl'&gt;
3775 &lt;mechanism-too-weak/&gt;
3776 &lt;/failure&gt;
3777</pre></div>
3778<a name="sasl-errors-not-authorized"></a><br /><hr />
3779<table summary="layout" cellpadding="0" cellspacing="2" class="TOCbug" align="right"><tr><td class="TOCbug"><a href="#toc">&nbsp;TOC&nbsp;</a></td></tr></table>
3780<a name="rfc.section.6.5.10"></a><h3>6.5.10.&nbsp;
3781not-authorized</h3>
3782
3783<p>The authentication failed because the initiating entity did not provide proper credentials, or because some generic authentication failure has occurred but the receiving entity does not wish to disclose specific information about the cause of the failure; sent in reply to a &lt;response/&gt; element or an &lt;auth/&gt; element with initial response data.
3784</p><div style='display: table; width: 0; margin-left: 3em; margin-right: auto'><pre>
3785I: &lt;response xmlns='urn:ietf:params:xml:ns:xmpp-sasl'&gt;
3786 [ ... ]
3787 &lt;/response&gt;
3788
3789R: &lt;failure xmlns='urn:ietf:params:xml:ns:xmpp-sasl'&gt;
3790 &lt;not-authorized/&gt;
3791 &lt;/failure&gt;
3792</pre></div>
3793<p></p>
3794<blockquote class="text">
3795<p>Security Warning: This error condition includes but is not limited to the case of incorrect credentials or a nonexistent username. In order to discourage directory harvest attacks, no differentiation is made between incorrect credentials and a nonexistent username.
3796</p>
3797</blockquote>
3798
3799<a name="sasl-errors-temporary-auth-failure"></a><br /><hr />
3800<table summary="layout" cellpadding="0" cellspacing="2" class="TOCbug" align="right"><tr><td class="TOCbug"><a href="#toc">&nbsp;TOC&nbsp;</a></td></tr></table>
3801<a name="rfc.section.6.5.11"></a><h3>6.5.11.&nbsp;
3802temporary-auth-failure</h3>
3803
3804<p>The authentication failed because of a temporary error condition within the receiving entity, and it is advisable for the initiating entity to try again later; sent in reply to an &lt;auth/&gt; element or a &lt;response/&gt; element.
3805</p><div style='display: table; width: 0; margin-left: 3em; margin-right: auto'><pre>
3806I: &lt;response xmlns='urn:ietf:params:xml:ns:xmpp-sasl'&gt;
3807 [ ... ]
3808 &lt;/response&gt;
3809
3810R: &lt;failure xmlns='urn:ietf:params:xml:ns:xmpp-sasl'&gt;
3811 &lt;temporary-auth-failure/&gt;
3812 &lt;/failure&gt;
3813</pre></div>
3814<a name="sasl-def"></a><br /><hr />
3815<table summary="layout" cellpadding="0" cellspacing="2" class="TOCbug" align="right"><tr><td class="TOCbug"><a href="#toc">&nbsp;TOC&nbsp;</a></td></tr></table>
3816<a name="rfc.section.6.6"></a><h3>6.6.&nbsp;
3817SASL Definition</h3>
3818
3819<p>The profiling requirements of <a class='info' href='#SASL'>[SASL]<span> (</span><span class='info'>Melnikov, A. and K. Zeilenga, &ldquo;Simple Authentication and Security Layer (SASL),&rdquo; June&nbsp;2006.</span><span>)</span></a> require that the
3820following information be supplied by the definition of a using protocol.
3821</p>
3822<p></p>
3823<blockquote class="text"><dl>
3824<dt>service name:</dt>
3825<dd>"xmpp"
3826</dd>
3827<dt>initiation sequence:</dt>
3828<dd>After the initiating entity provides
3829an opening XML stream header and the receiving entity replies in kind, the
3830receiving entity provides a list of acceptable authentication methods. The
3831initiating entity chooses one method from the list and sends it to the
3832receiving entity as the value of the 'mechanism' attribute possessed by an
3833&lt;auth/&gt; element, optionally including an initial response to avoid a
3834round trip.
3835</dd>
3836<dt>exchange sequence:</dt>
3837<dd>Challenges and responses are carried
3838through the exchange of &lt;challenge/&gt; elements from receiving entity to
3839initiating entity and &lt;response/&gt; elements from initiating entity to
3840receiving entity. The receiving entity reports failure by sending a
3841&lt;failure/&gt; element and success by sending a &lt;success/&gt; element; the
3842initiating entity aborts the exchange by sending an &lt;abort/&gt; element.
3843Upon successful negotiation, both sides consider the original XML stream to be
3844closed and new stream headers are sent by both entities.
3845</dd>
3846<dt>security layer negotiation:</dt>
3847<dd>The security layer takes
3848effect immediately after sending the closing '&gt;' character of the
3849&lt;success/&gt; element for the receiving entity, and immediately after
3850receiving the closing '&gt;' character of the &lt;success/&gt; element for the
3851initiating entity. The order of layers is first <a class='info' href='#TCP'>[TCP]<span> (</span><span class='info'>Postel, J., &ldquo;Transmission Control Protocol,&rdquo; September&nbsp;1981.</span><span>)</span></a>, then
3852<a class='info' href='#TLS'>[TLS]<span> (</span><span class='info'>Dierks, T. and E. Rescorla, &ldquo;The Transport Layer Security (TLS) Protocol Version 1.2,&rdquo; August&nbsp;2008.</span><span>)</span></a>, then <a class='info' href='#SASL'>[SASL]<span> (</span><span class='info'>Melnikov, A. and K. Zeilenga, &ldquo;Simple Authentication and Security Layer (SASL),&rdquo; June&nbsp;2006.</span><span>)</span></a>, then XMPP.
3853</dd>
3854<dt>use of the authorization identity:</dt>
3855<dd>The authorization
3856identity can be used in XMPP to denote the non-default
3857&lt;localpart@domainpart&gt; of a client; an empty string is equivalent to an
3858absent authorization identity.
3859</dd>
3860</dl></blockquote>
3861
3862<a name="bind"></a><br /><hr />
3863<table summary="layout" cellpadding="0" cellspacing="2" class="TOCbug" align="right"><tr><td class="TOCbug"><a href="#toc">&nbsp;TOC&nbsp;</a></td></tr></table>
3864<a name="rfc.section.7"></a><h3>7.&nbsp;
3865Resource Binding</h3>
3866
3867<a name="bind-fundamentals"></a><br /><hr />
3868<table summary="layout" cellpadding="0" cellspacing="2" class="TOCbug" align="right"><tr><td class="TOCbug"><a href="#toc">&nbsp;TOC&nbsp;</a></td></tr></table>
3869<a name="rfc.section.7.1"></a><h3>7.1.&nbsp;
3870Fundamentals</h3>
3871
3872<p>After a client authenticates with a server, it MUST bind a specific resource to the stream so that the server can properly address the client. That is, there MUST be an XMPP resource associated with the bare JID (&lt;localpart@domainpart&gt;) of the client, so that the address for use over that stream is a full JID of the form &lt;localpart@domainpart/resource&gt; (including the resourcepart). This ensures that the server can deliver XML stanzas to and receive XML stanzas from the client in relation to entities other than the server itself or the client's account, as explained under <a class='info' href='#rules'>Section&nbsp;10<span> (</span><span class='info'>Server Rules for Processing XML Stanzas</span><span>)</span></a>.
3873</p>
3874<p></p>
3875<blockquote class="text">
3876<p>Informational Note: The client could exchange stanzas with the server itself or the client's account before binding a resource since the full JID is needed only for addressing outside the context of the stream negotiated between the client and the server, but this is not commonly done.
3877</p>
3878</blockquote>
3879
3880<p>After a client has bound a resource to the stream, it is referred to as a "connected resource". A server SHOULD allow an entity to maintain multiple connected resources simultaneously, where each connected resource is associated with a distinct XML stream and is differentiated from the other connected resources by a distinct resourcepart.
3881</p>
3882<p></p>
3883<blockquote class="text">
3884<p>Security Warning: A server SHOULD enable the administrator of an XMPP service to limit the number of connected resources in order to prevent certain denial-of-service attacks as described under <a class='info' href='#security-dos'>Section&nbsp;13.12<span> (</span><span class='info'>Denial of Service</span><span>)</span></a>.
3885</p>
3886</blockquote>
3887
3888<p>If, before completing the resource binding step, the client attempts to send an XML stanza to an entity other than the server itself or the client's account, the server MUST NOT process the stanza and MUST close the stream with a &lt;not-authorized/&gt; stream error (<a class='info' href='#streams-error-conditions-not-authorized'>Section&nbsp;4.9.3.12<span> (</span><span class='info'>not-authorized</span><span>)</span></a>).
3889</p>
3890<p>The XML namespace name for the resource binding extension is 'urn:ietf:params:xml:ns:xmpp-bind'.
3891</p>
3892<a name="bind-support"></a><br /><hr />
3893<table summary="layout" cellpadding="0" cellspacing="2" class="TOCbug" align="right"><tr><td class="TOCbug"><a href="#toc">&nbsp;TOC&nbsp;</a></td></tr></table>
3894<a name="rfc.section.7.2"></a><h3>7.2.&nbsp;
3895Support</h3>
3896
3897<p>Support for resource binding is REQUIRED in XMPP client and server implementations.
3898</p>
3899<a name="bind-rules"></a><br /><hr />
3900<table summary="layout" cellpadding="0" cellspacing="2" class="TOCbug" align="right"><tr><td class="TOCbug"><a href="#toc">&nbsp;TOC&nbsp;</a></td></tr></table>
3901<a name="rfc.section.7.3"></a><h3>7.3.&nbsp;
3902Stream Negotiation Rules</h3>
3903
3904<a name="bind-rules-mtn"></a><br /><hr />
3905<table summary="layout" cellpadding="0" cellspacing="2" class="TOCbug" align="right"><tr><td class="TOCbug"><a href="#toc">&nbsp;TOC&nbsp;</a></td></tr></table>
3906<a name="rfc.section.7.3.1"></a><h3>7.3.1.&nbsp;
3907Mandatory-to-Negotiate</h3>
3908
3909<p>The parties to a stream MUST consider resource binding as mandatory-to-negotiate.
3910</p>
3911<a name="bind-rules-restart"></a><br /><hr />
3912<table summary="layout" cellpadding="0" cellspacing="2" class="TOCbug" align="right"><tr><td class="TOCbug"><a href="#toc">&nbsp;TOC&nbsp;</a></td></tr></table>
3913<a name="rfc.section.7.3.2"></a><h3>7.3.2.&nbsp;
3914Restart</h3>
3915
3916<p>After resource binding, the parties MUST NOT restart the stream.
3917</p>
3918<a name="bind-feature"></a><br /><hr />
3919<table summary="layout" cellpadding="0" cellspacing="2" class="TOCbug" align="right"><tr><td class="TOCbug"><a href="#toc">&nbsp;TOC&nbsp;</a></td></tr></table>
3920<a name="rfc.section.7.4"></a><h3>7.4.&nbsp;
3921Advertising Support</h3>
3922
3923<p>Upon sending a new response stream header to the client after successful SASL negotiation, the server MUST include a &lt;bind/&gt; element qualified by the 'urn:ietf:params:xml:ns:xmpp-bind' namespace in the stream features it presents to the client.
3924</p>
3925<p>The server MUST NOT include the resource binding stream feature until after the client has authenticated, typically by means of successful SASL negotiation.
3926</p><div style='display: table; width: 0; margin-left: 3em; margin-right: auto'><pre>
3927S: &lt;stream:stream
3928 from='im.example.com'
3929 id='gPybzaOzBmaADgxKXu9UClbprp0='
3930 to='juliet@im.example.com'
3931 version='1.0'
3932 xml:lang='en'
3933 xmlns='jabber:client'
3934 xmlns:stream='http://etherx.jabber.org/streams'&gt;
3935
3936S: &lt;stream:features&gt;
3937 &lt;bind xmlns='urn:ietf:params:xml:ns:xmpp-bind'/&gt;
3938 &lt;/stream:features&gt;
3939</pre></div>
3940<p>Upon being informed that resource binding is mandatory-to-negotiate, the client MUST bind a resource to the stream as described in the following sections.
3941</p>
3942<a name="bind-generation"></a><br /><hr />
3943<table summary="layout" cellpadding="0" cellspacing="2" class="TOCbug" align="right"><tr><td class="TOCbug"><a href="#toc">&nbsp;TOC&nbsp;</a></td></tr></table>
3944<a name="rfc.section.7.5"></a><h3>7.5.&nbsp;
3945Generation of Resource Identifiers</h3>
3946
3947<p>A resourcepart MUST at a minimum be unique among the connected resources for that &lt;localpart@domainpart&gt;. Enforcement of this policy is the responsibility of the server.
3948</p>
3949<p></p>
3950<blockquote class="text">
3951<p>Security Warning: A resourcepart can be security-critical. For example, if a malicious entity can guess a client's resourcepart then it might be able to determine if the client (and therefore the controlling principal) is online or offline, thus resulting in a presence leak as described under <a class='info' href='#security-leaks-presence'>Section&nbsp;13.10.2<span> (</span><span class='info'>Presence Information</span><span>)</span></a>. To prevent that possibility, a client can either (1) generate a random resourcepart on its own or (2) ask the server to generate a resourcepart on its behalf. One method for ensuring that the resourcepart is random is to generate a Universally Unique Identifier (UUID) as specified in <a class='info' href='#UUID'>[UUID]<span> (</span><span class='info'>Leach, P., Mealling, M., and R. Salz, &ldquo;A Universally Unique IDentifier (UUID) URN Namespace,&rdquo; July&nbsp;2005.</span><span>)</span></a>.
3952</p>
3953</blockquote>
3954
3955<a name="bind-servergen"></a><br /><hr />
3956<table summary="layout" cellpadding="0" cellspacing="2" class="TOCbug" align="right"><tr><td class="TOCbug"><a href="#toc">&nbsp;TOC&nbsp;</a></td></tr></table>
3957<a name="rfc.section.7.6"></a><h3>7.6.&nbsp;
3958Server-Generated Resource Identifier</h3>
3959
3960<p>A server MUST be able to generate an XMPP resourcepart on behalf of a client. The resourcepart generated by the server MUST be random (see <a class='info' href='#RANDOM'>[RANDOM]<span> (</span><span class='info'>Eastlake, D., Schiller, J., and S. Crocker, &ldquo;Randomness Requirements for Security,&rdquo; June&nbsp;2005.</span><span>)</span></a>).
3961</p>
3962<a name="bind-servergen-success"></a><br /><hr />
3963<table summary="layout" cellpadding="0" cellspacing="2" class="TOCbug" align="right"><tr><td class="TOCbug"><a href="#toc">&nbsp;TOC&nbsp;</a></td></tr></table>
3964<a name="rfc.section.7.6.1"></a><h3>7.6.1.&nbsp;
3965Success Case</h3>
3966
3967<p>A client requests a server-generated resourcepart by sending an IQ stanza of type "set" (see <a class='info' href='#stanzas-semantics-iq'>Section&nbsp;8.2.3<span> (</span><span class='info'>IQ Semantics</span><span>)</span></a>) containing an empty &lt;bind/&gt; element qualified by the 'urn:ietf:params:xml:ns:xmpp-bind' namespace.
3968</p><div style='display: table; width: 0; margin-left: 3em; margin-right: auto'><pre>
3969C: &lt;iq id='tn281v37' type='set'&gt;
3970 &lt;bind xmlns='urn:ietf:params:xml:ns:xmpp-bind'/&gt;
3971 &lt;/iq&gt;
3972</pre></div>
3973<p>Once the server has generated an XMPP resourcepart for the client, it MUST return an IQ stanza of type "result" to the client, which MUST include a &lt;jid/&gt; child element that specifies the full JID for the connected resource as determined by the server.
3974</p><div style='display: table; width: 0; margin-left: 3em; margin-right: auto'><pre>
3975S: &lt;iq id='tn281v37' type='result'&gt;
3976 &lt;bind xmlns='urn:ietf:params:xml:ns:xmpp-bind'&gt;
3977 &lt;jid&gt;
3978 juliet@im.example.com/4db06f06-1ea4-11dc-aca3-000bcd821bfb
3979 &lt;/jid&gt;
3980 &lt;/bind&gt;
3981 &lt;/iq&gt;
3982</pre></div>
3983<a name="bind-servergen-error"></a><br /><hr />
3984<table summary="layout" cellpadding="0" cellspacing="2" class="TOCbug" align="right"><tr><td class="TOCbug"><a href="#toc">&nbsp;TOC&nbsp;</a></td></tr></table>
3985<a name="rfc.section.7.6.2"></a><h3>7.6.2.&nbsp;
3986Error Cases</h3>
3987
3988<p>When a client asks the server to generate a resourcepart during resource binding, the following stanza error conditions are defined:
3989</p>
3990<p>
3991 </p>
3992<ul class="text">
3993<li>The account has reached a limit on the number of simultaneous connected resources allowed.
3994</li>
3995<li>The client is otherwise not allowed to bind a resource to the stream.
3996</li>
3997</ul><p>
3998
3999</p>
4000<p>Naturally, it is possible that error conditions not specified here might occur, as described under <a class='info' href='#stanzas-error'>Section&nbsp;8.3<span> (</span><span class='info'>Stanza Errors</span><span>)</span></a>.
4001</p>
4002<a name="bind-servergen-error-resourceconstraint"></a><br /><hr />
4003<table summary="layout" cellpadding="0" cellspacing="2" class="TOCbug" align="right"><tr><td class="TOCbug"><a href="#toc">&nbsp;TOC&nbsp;</a></td></tr></table>
4004<a name="rfc.section.7.6.2.1"></a><h3>7.6.2.1.&nbsp;
4005Resource Constraint</h3>
4006
4007<p>If the account has reached a limit on the number of simultaneous connected resources allowed, the server MUST return a &lt;resource-constraint/&gt; stanza error (<a class='info' href='#stanzas-error-conditions-resource-constraint'>Section&nbsp;8.3.3.18<span> (</span><span class='info'>resource-constraint</span><span>)</span></a>).
4008</p><div style='display: table; width: 0; margin-left: 3em; margin-right: auto'><pre>
4009S: &lt;iq id='tn281v37' type='error'&gt;
4010 &lt;error type='wait'&gt;
4011 &lt;resource-constraint
4012 xmlns='urn:ietf:params:xml:ns:xmpp-stanzas'/&gt;
4013 &lt;/error&gt;
4014 &lt;/iq&gt;
4015</pre></div>
4016<a name="bind-servergen-error-notallowed"></a><br /><hr />
4017<table summary="layout" cellpadding="0" cellspacing="2" class="TOCbug" align="right"><tr><td class="TOCbug"><a href="#toc">&nbsp;TOC&nbsp;</a></td></tr></table>
4018<a name="rfc.section.7.6.2.2"></a><h3>7.6.2.2.&nbsp;
4019Not Allowed</h3>
4020
4021<p>If the client is otherwise not allowed to bind a resource to the stream, the server MUST return a &lt;not-allowed/&gt; stanza error (<a class='info' href='#stanzas-error-conditions-not-allowed'>Section&nbsp;8.3.3.10<span> (</span><span class='info'>not-allowed</span><span>)</span></a>).
4022</p><div style='display: table; width: 0; margin-left: 3em; margin-right: auto'><pre>
4023S: &lt;iq id='tn281v37' type='error'&gt;
4024 &lt;error type='cancel'&gt;
4025 &lt;not-allowed
4026 xmlns='urn:ietf:params:xml:ns:xmpp-stanzas'/&gt;
4027 &lt;/error&gt;
4028 &lt;/iq&gt;
4029</pre></div>
4030<a name="bind-clientsubmit"></a><br /><hr />
4031<table summary="layout" cellpadding="0" cellspacing="2" class="TOCbug" align="right"><tr><td class="TOCbug"><a href="#toc">&nbsp;TOC&nbsp;</a></td></tr></table>
4032<a name="rfc.section.7.7"></a><h3>7.7.&nbsp;
4033Client-Submitted Resource Identifier</h3>
4034
4035<p>Instead of asking the server to generate a resourcepart on its behalf, a client MAY attempt to submit a resourcepart that it has generated or that the controlling user has provided.
4036</p>
4037<a name="bind-clientsubmit-success"></a><br /><hr />
4038<table summary="layout" cellpadding="0" cellspacing="2" class="TOCbug" align="right"><tr><td class="TOCbug"><a href="#toc">&nbsp;TOC&nbsp;</a></td></tr></table>
4039<a name="rfc.section.7.7.1"></a><h3>7.7.1.&nbsp;
4040Success Case</h3>
4041
4042<p>A client asks its server to accept a client-submitted resourcepart by sending an IQ stanza of type "set" containing a &lt;bind/&gt; element with a child &lt;resource/&gt; element containing non-zero-length XML character data.
4043</p><div style='display: table; width: 0; margin-left: 3em; margin-right: auto'><pre>
4044C: &lt;iq id='wy2xa82b4' type='set'&gt;
4045 &lt;bind xmlns='urn:ietf:params:xml:ns:xmpp-bind'&gt;
4046 &lt;resource&gt;balcony&lt;/resource&gt;
4047 &lt;/bind&gt;
4048 &lt;/iq&gt;
4049</pre></div>
4050<p>The server SHOULD accept the client-submitted resourcepart. It does so by returning an IQ stanza of type "result" to the client, including a &lt;jid/&gt; child element that specifies the full JID for the connected resource and contains without modification the client-submitted text.
4051</p><div style='display: table; width: 0; margin-left: 3em; margin-right: auto'><pre>
4052S: &lt;iq id='wy2xa82b4' type='result'&gt;
4053 &lt;bind xmlns='urn:ietf:params:xml:ns:xmpp-bind'&gt;
4054 &lt;jid&gt;juliet@im.example.com/balcony&lt;/jid&gt;
4055 &lt;/bind&gt;
4056 &lt;/iq&gt;
4057</pre></div>
4058<p>Alternatively, in accordance with local service policies the server MAY refuse the client-submitted resourcepart and override it with a resourcepart that the server generates.
4059</p><div style='display: table; width: 0; margin-left: 3em; margin-right: auto'><pre>
4060S: &lt;iq id='wy2xa82b4' type='result'&gt;
4061 &lt;bind xmlns='urn:ietf:params:xml:ns:xmpp-bind'&gt;
4062 &lt;jid&gt;
4063 juliet@im.example.com/balcony 4db06f06-1ea4-11dc-aca3-000bcd821bfb
4064 &lt;/jid&gt;
4065 &lt;/bind&gt;
4066 &lt;/iq&gt;
4067</pre></div>
4068<a name="bind-clientsubmit-error"></a><br /><hr />
4069<table summary="layout" cellpadding="0" cellspacing="2" class="TOCbug" align="right"><tr><td class="TOCbug"><a href="#toc">&nbsp;TOC&nbsp;</a></td></tr></table>
4070<a name="rfc.section.7.7.2"></a><h3>7.7.2.&nbsp;
4071Error Cases</h3>
4072
4073<p>When a client attempts to submit its own XMPP resourcepart during resource binding, the following stanza error conditions are defined in addition to those described under <a class='info' href='#bind-servergen-error'>Section&nbsp;7.6.2<span> (</span><span class='info'>Error Cases</span><span>)</span></a>:
4074</p>
4075<p>
4076 </p>
4077<ul class="text">
4078<li>The provided resourcepart cannot be processed by the server.
4079</li>
4080<li>The provided resourcepart is already in use.
4081</li>
4082</ul><p>
4083
4084</p>
4085<p>Naturally, it is possible that error conditions not specified here might occur, as described under <a class='info' href='#stanzas-error'>Section&nbsp;8.3<span> (</span><span class='info'>Stanza Errors</span><span>)</span></a>.
4086</p>
4087<a name="bind-clientsubmit-error-badrequest"></a><br /><hr />
4088<table summary="layout" cellpadding="0" cellspacing="2" class="TOCbug" align="right"><tr><td class="TOCbug"><a href="#toc">&nbsp;TOC&nbsp;</a></td></tr></table>
4089<a name="rfc.section.7.7.2.1"></a><h3>7.7.2.1.&nbsp;
4090Bad Request</h3>
4091
4092<p>If the provided resourcepart cannot be processed by the server (e.g., because it is of zero length or because it otherwise violates the rules for resourceparts specified in <a class='info' href='#XMPP-ADDR'>[XMPP&#8209;ADDR]<span> (</span><span class='info'>Saint-Andre, P., &ldquo;Extensible Messaging and Presence Protocol (XMPP): Address Format,&rdquo; March&nbsp;2011.</span><span>)</span></a>), the server can return a &lt;bad-request/&gt; stanza error (<a class='info' href='#stanzas-error-conditions-bad-request'>Section&nbsp;8.3.3.1<span> (</span><span class='info'>bad-request</span><span>)</span></a>) but SHOULD instead process the resourcepart so that it is in conformance.
4093</p><div style='display: table; width: 0; margin-left: 3em; margin-right: auto'><pre>
4094S: &lt;iq id='wy2xa82b4' type='error'&gt;
4095 &lt;error type='modify'&gt;
4096 &lt;bad-request xmlns='urn:ietf:params:xml:ns:xmpp-stanzas'/&gt;
4097 &lt;/error&gt;
4098 &lt;/iq&gt;
4099</pre></div>
4100<a name="bind-clientsubmit-error-conflict"></a><br /><hr />
4101<table summary="layout" cellpadding="0" cellspacing="2" class="TOCbug" align="right"><tr><td class="TOCbug"><a href="#toc">&nbsp;TOC&nbsp;</a></td></tr></table>
4102<a name="rfc.section.7.7.2.2"></a><h3>7.7.2.2.&nbsp;
4103Conflict</h3>
4104
4105<p>If there is a currently connected client whose session
4106 has the resourcepart being requested by the newly connecting client, the server MUST do one of the following (which of these the server does is a matter for implementation or local service policy, although suggestions are provided below).
4107</p>
4108<p>
4109 </p>
4110<ol class="text">
4111<li>Override the resourcepart provided by the newly connecting client with a server-generated resourcepart.
4112
4113 This behavior is encouraged, because it simplifies the resource binding process for client implementations.
4114</li>
4115<li>Disallow the resource binding attempt of the newly
4116 connecting client and maintain the session of the
4117 currently connected client.
4118
4119 This behavior is neither encouraged nor discouraged, despite the fact that it was implicitly encouraged in RFC 3920; however, note that handling of the &lt;conflict/&gt; error is unevenly supported among existing client implementations, which often treat it as an authentication error and have been observed to discard cached credentials when receiving it.
4120</li>
4121<li>Terminate the session of the currently connected
4122 client and allow the resource binding attempt of the
4123 newly connecting client.
4124
4125 Although this was the traditional behavior of early XMPP
4126 server implementations, it is now discouraged because it
4127 can lead to a never-ending cycle of two clients
4128 effectively disconnecting each other; however, note that
4129 this behavior can be appropriate in some deployment
4130 scenarios or if the server knows that the currently connected client has a dead connection or broken stream as described under <a class='info' href='#streams-silence'>Section&nbsp;4.6<span> (</span><span class='info'>Handling of Silent Peers</span><span>)</span></a>.
4131</li>
4132</ol><p>
4133
4134</p>
4135<p>If the server follows behavior #1, it returns an
4136 &lt;iq/&gt; stanza of type "result" to the newly connecting client, where the &lt;jid/&gt; child of the &lt;bind/&gt; element contains XML character data that indicates the full JID of the client, including the resourcepart that was generated by the server.
4137</p><div style='display: table; width: 0; margin-left: 3em; margin-right: auto'><pre>
4138S: &lt;iq id='wy2xa82b4' type='result'&gt;
4139 &lt;bind xmlns='urn:ietf:params:xml:ns:xmpp-bind'&gt;
4140 &lt;jid&gt;
4141 juliet@im.example.com/balcony 4db06f06-1ea4-11dc-aca3-000bcd821bfb
4142 &lt;/jid&gt;
4143 &lt;/bind&gt;
4144 &lt;/iq&gt;
4145</pre></div>
4146<p>If the server follows behavior #2, it sends a &lt;conflict/&gt; stanza error (<a class='info' href='#stanzas-error-conditions-conflict'>Section&nbsp;8.3.3.2<span> (</span><span class='info'>conflict</span><span>)</span></a>) in response to the resource binding attempt of the newly connecting client but maintains the XML stream so that the newly connecting client has an opportunity to negotiate a non-conflicting resourcepart (i.e., the newly connecting client needs to choose a different resourcepart before making another attempt to bind a resource).
4147</p><div style='display: table; width: 0; margin-left: 3em; margin-right: auto'><pre>
4148S: &lt;iq id='wy2xa82b4' type='error'&gt;
4149 &lt;error type='modify'&gt;
4150 &lt;conflict xmlns='urn:ietf:params:xml:ns:xmpp-stanzas'/&gt;
4151 &lt;/error&gt;
4152 &lt;/iq&gt;
4153</pre></div>
4154<p>If the server follows behavior #3, it returns a &lt;conflict/&gt; stream error (<a class='info' href='#streams-error-conditions-conflict'>Section&nbsp;4.9.3.3<span> (</span><span class='info'>conflict</span><span>)</span></a>) to the currently connected client (as described under <a class='info' href='#streams-error-conditions-conflict'>Section&nbsp;4.9.3.3<span> (</span><span class='info'>conflict</span><span>)</span></a>) and returns an IQ stanza of type "result" (indicating success) in response to the resource binding attempt of the newly connecting client.
4155</p><div style='display: table; width: 0; margin-left: 3em; margin-right: auto'><pre>
4156S: &lt;iq id='wy2xa82b4' type='result'&gt;
4157 &lt;bind xmlns='urn:ietf:params:xml:ns:xmpp-bind'&gt;
4158 &lt;jid&gt;
4159 juliet@im.example.com/balcony
4160 &lt;/jid&gt;
4161 &lt;/bind&gt;
4162 &lt;/iq&gt;
4163</pre></div>
4164<a name="bind-clientsubmit-retries"></a><br /><hr />
4165<table summary="layout" cellpadding="0" cellspacing="2" class="TOCbug" align="right"><tr><td class="TOCbug"><a href="#toc">&nbsp;TOC&nbsp;</a></td></tr></table>
4166<a name="rfc.section.7.7.3"></a><h3>7.7.3.&nbsp;
4167Retries</h3>
4168
4169<p>If an error occurs when a client submits a resourcepart, the server SHOULD allow a configurable but reasonable number of retries (at least 5 and no more than 10); this enables the client to tolerate incorrectly provided resourceparts (e.g., bad data formats or duplicate text strings) without being forced to reconnect.
4170</p>
4171<p>After the client has reached the retry limit, the server MUST close the stream with a &lt;policy-violation/&gt; stream error (<a class='info' href='#streams-error-conditions-policy-violation'>Section&nbsp;4.9.3.14<span> (</span><span class='info'>policy-violation</span><span>)</span></a>).
4172</p>
4173<a name="stanzas"></a><br /><hr />
4174<table summary="layout" cellpadding="0" cellspacing="2" class="TOCbug" align="right"><tr><td class="TOCbug"><a href="#toc">&nbsp;TOC&nbsp;</a></td></tr></table>
4175<a name="rfc.section.8"></a><h3>8.&nbsp;
4176XML Stanzas</h3>
4177
4178<p>After a client and a server (or two servers) have completed stream negotiation, either party can send XML stanzas. Three kinds of XML stanza are defined for the 'jabber:client' and 'jabber:server' namespaces: &lt;message/&gt;, &lt;presence/&gt;, and &lt;iq/&gt;. In addition, there are five common attributes for these stanza types. These common attributes, as well as the basic semantics of the three stanza types, are defined in this specification; more detailed information regarding the syntax of XML stanzas for instant messaging and presence applications is provided in <a class='info' href='#XMPP-IM'>[XMPP&#8209;IM]<span> (</span><span class='info'>Saint-Andre, P., &ldquo;Extensible Messaging and Presence Protocol (XMPP): Instant Messaging and Presence,&rdquo; March&nbsp;2011.</span><span>)</span></a>, and for other applications in the relevant XMPP extension specifications.
4179</p>
4180<p>Support for the XML stanza syntax and semantics defined in this specification is REQUIRED in XMPP client and server implementations.
4181</p>
4182<p></p>
4183<blockquote class="text">
4184<p>Security Warning: A server MUST NOT process a partial stanza and MUST NOT attach meaning to the transmission timing of any part of a stanza (before receipt of the closing tag).
4185</p>
4186</blockquote>
4187
4188<a name="stanzas-attributes"></a><br /><hr />
4189<table summary="layout" cellpadding="0" cellspacing="2" class="TOCbug" align="right"><tr><td class="TOCbug"><a href="#toc">&nbsp;TOC&nbsp;</a></td></tr></table>
4190<a name="rfc.section.8.1"></a><h3>8.1.&nbsp;
4191Common Attributes</h3>
4192
4193<p>The following five attributes are common to message, presence, and IQ stanzas.
4194</p>
4195<a name="stanzas-attributes-to"></a><br /><hr />
4196<table summary="layout" cellpadding="0" cellspacing="2" class="TOCbug" align="right"><tr><td class="TOCbug"><a href="#toc">&nbsp;TOC&nbsp;</a></td></tr></table>
4197<a name="rfc.section.8.1.1"></a><h3>8.1.1.&nbsp;
4198to</h3>
4199
4200<p>The 'to' attribute specifies the JID of the intended recipient for the stanza.
4201</p><div style='display: table; width: 0; margin-left: 3em; margin-right: auto'><pre>
4202&lt;message to='romeo@example.net'&gt;
4203 &lt;body&gt;Art thou not Romeo, and a Montague?&lt;/body&gt;
4204&lt;/message&gt;
4205</pre></div>
4206<p>For information about server processing of inbound and outbound XML stanzas based on the 'to' address, refer to <a class='info' href='#rules'>Section&nbsp;10<span> (</span><span class='info'>Server Rules for Processing XML Stanzas</span><span>)</span></a>.
4207</p>
4208<a name="stanzas-attributes-to-c2s"></a><br /><hr />
4209<table summary="layout" cellpadding="0" cellspacing="2" class="TOCbug" align="right"><tr><td class="TOCbug"><a href="#toc">&nbsp;TOC&nbsp;</a></td></tr></table>
4210<a name="rfc.section.8.1.1.1"></a><h3>8.1.1.1.&nbsp;
4211Client-to-Server Streams</h3>
4212
4213<p>The following rules apply to inclusion of the 'to' attribute in stanzas sent from a connected client to its server over an XML stream qualified by the 'jabber:client' namespace.
4214</p>
4215<p>
4216 </p>
4217<ol class="text">
4218<li>A stanza with a specific intended recipient (e.g., a conversation partner, a remote service, the server itself, even another resource associated with the user's bare JID) MUST possess a 'to' attribute whose value is an XMPP address.
4219</li>
4220<li>A stanza sent from a client to a server for direct processing by the server (e.g., roster processing as described in <a class='info' href='#XMPP-IM'>[XMPP&#8209;IM]<span> (</span><span class='info'>Saint-Andre, P., &ldquo;Extensible Messaging and Presence Protocol (XMPP): Instant Messaging and Presence,&rdquo; March&nbsp;2011.</span><span>)</span></a> or presence sent to the server for broadcasting to other entities) MUST NOT possess a 'to' attribute.
4221</li>
4222</ol><p>
4223
4224</p>
4225<p>The following rules apply to inclusion of the 'to' attribute in stanzas sent from a server to a connected client over an XML stream qualified by the 'jabber:client' namespace.
4226</p>
4227<p>
4228 </p>
4229<ol class="text">
4230<li>If the server has received the stanza from another connected client or from a peer server, the server MUST NOT modify the 'to' address before delivering the stanza to the client.
4231</li>
4232<li>If the server has itself generated the stanza (e.g., a response to an IQ stanza of type "get" or "set", even if the stanza did not include a 'to' address), the stanza MAY include a 'to' address, which MUST be the full JID of the client; however, if the stanza does not include a 'to' address then the client MUST treat it as if the 'to' address were included with a value of the client's full JID.
4233</li>
4234</ol><p>
4235
4236</p>
4237<p></p>
4238<blockquote class="text">
4239<p>Implementation Note: It is the server's responsibility to deliver only stanzas that are addressed to the client's full JID or the user's bare JID; thus, there is no need for the client to check the 'to' address of incoming stanzas. However, if the client does check the 'to' address then it is suggested to check at most the bare JID portion (not the full JID), since the 'to' address might be the user's bare JID, the client's current full JID, or even a full JID with a different resourcepart (e.g., in the case of so-called "offline messages" as described in <a class='info' href='#XEP-0160'>[XEP&#8209;0160]<span> (</span><span class='info'>Saint-Andre, P., &ldquo;Best Practices for Handling Offline Messages,&rdquo; January&nbsp;2006.</span><span>)</span></a>).
4240</p>
4241</blockquote>
4242
4243<a name="stanzas-attributes-to-s2s"></a><br /><hr />
4244<table summary="layout" cellpadding="0" cellspacing="2" class="TOCbug" align="right"><tr><td class="TOCbug"><a href="#toc">&nbsp;TOC&nbsp;</a></td></tr></table>
4245<a name="rfc.section.8.1.1.2"></a><h3>8.1.1.2.&nbsp;
4246Server-to-Server Streams</h3>
4247
4248<p>The following rules apply to inclusion of the 'to' attribute in the context of XML streams qualified by the 'jabber:server' namespace (i.e., server-to-server streams).
4249</p>
4250<p>
4251 </p>
4252<ol class="text">
4253<li>A stanza MUST possess a 'to' attribute whose value is an XMPP address; if a server receives a stanza that does not meet this restriction, it MUST close the stream with an &lt;improper-addressing/&gt; stream error (<a class='info' href='#streams-error-conditions-improper-addressing'>Section&nbsp;4.9.3.7<span> (</span><span class='info'>improper-addressing</span><span>)</span></a>).
4254</li>
4255<li>The domainpart of the JID contained in the stanza's 'to' attribute MUST match the FQDN of the receiving server (or any validated domain thereof) as communicated via SASL negotiation (see <a class='info' href='#sasl'>Section&nbsp;6<span> (</span><span class='info'>SASL Negotiation</span><span>)</span></a>), Server Dialback (see <a class='info' href='#XEP-0220'>[XEP&#8209;0220]<span> (</span><span class='info'>Miller, J., Saint-Andre, P., and P. Hancke, &ldquo;Server Dialback,&rdquo; March&nbsp;2010.</span><span>)</span></a>), or similar means; if a server receives a stanza that does not meet this restriction, it MUST close the stream with a &lt;host-unknown/&gt; stream error (<a class='info' href='#streams-error-conditions-host-unknown'>Section&nbsp;4.9.3.6<span> (</span><span class='info'>host-unknown</span><span>)</span></a>) or a &lt;host-gone/&gt; stream error (<a class='info' href='#streams-error-conditions-host-gone'>Section&nbsp;4.9.3.5<span> (</span><span class='info'>host-gone</span><span>)</span></a>).
4256</li>
4257</ol><p>
4258
4259</p>
4260<a name="stanzas-attributes-from"></a><br /><hr />
4261<table summary="layout" cellpadding="0" cellspacing="2" class="TOCbug" align="right"><tr><td class="TOCbug"><a href="#toc">&nbsp;TOC&nbsp;</a></td></tr></table>
4262<a name="rfc.section.8.1.2"></a><h3>8.1.2.&nbsp;
4263from</h3>
4264
4265<p>The 'from' attribute specifies the JID of the sender.
4266</p><div style='display: table; width: 0; margin-left: 3em; margin-right: auto'><pre>
4267&lt;message from='juliet@im.example.com/balcony'
4268 to='romeo@example.net'&gt;
4269 &lt;body&gt;Art thou not Romeo, and a Montague?&lt;/body&gt;
4270&lt;/message&gt;
4271</pre></div>
4272<a name="stanzas-attributes-from-c2s"></a><br /><hr />
4273<table summary="layout" cellpadding="0" cellspacing="2" class="TOCbug" align="right"><tr><td class="TOCbug"><a href="#toc">&nbsp;TOC&nbsp;</a></td></tr></table>
4274<a name="rfc.section.8.1.2.1"></a><h3>8.1.2.1.&nbsp;
4275Client-to-Server Streams</h3>
4276
4277<p>The following rules apply to the 'from' attribute in the context of XML streams qualified by the 'jabber:client' namespace (i.e., client-to-server streams).
4278</p>
4279<p>
4280 </p>
4281<ol class="text">
4282<li>When a server receives an XML stanza from a connected client, the server MUST add a 'from' attribute to the stanza or override the 'from' attribute specified by the client, where the value of the 'from' attribute MUST be the full JID (&lt;localpart@domainpart/resource&gt;) determined by the server for the connected resource that generated the stanza (see <a class='info' href='#streams-negotiation-address'>Section&nbsp;4.3.6<span> (</span><span class='info'>Determination of Addresses</span><span>)</span></a>), or the bare JID (&lt;localpart@domainpart&gt;) in the case of subscription-related presence stanzas (see <a class='info' href='#XMPP-IM'>[XMPP&#8209;IM]<span> (</span><span class='info'>Saint-Andre, P., &ldquo;Extensible Messaging and Presence Protocol (XMPP): Instant Messaging and Presence,&rdquo; March&nbsp;2011.</span><span>)</span></a>).
4283</li>
4284<li>When the server generates a stanza on its own behalf for delivery to the client from the server itself, the stanza MUST include a 'from' attribute whose value is the bare JID (i.e., &lt;domainpart&gt;) of the server as agreed upon during stream negotiation (e.g., based on the 'to' attribute of the initial stream header).
4285</li>
4286<li>When the server generates a stanza from the server for delivery to the client on behalf of the account of the connected client (e.g., in the context of data storage services provided by the server on behalf of the client), the stanza MUST either (a) not include a 'from' attribute or (b) include a 'from' attribute whose value is the account's bare JID (&lt;localpart@domainpart&gt;).
4287</li>
4288<li>A server MUST NOT send to the client a stanza without a 'from' attribute if the stanza was not generated by the server on its own behalf (e.g., if it was generated by another client or a peer server and the server is merely delivering it to the client on behalf of some other entity); therefore, when a client receives a stanza that does not include a 'from' attribute, it MUST assume that the stanza is from the user's account on the server.
4289</li>
4290</ol><p>
4291
4292</p>
4293<a name="stanzas-attributes-from-s2s"></a><br /><hr />
4294<table summary="layout" cellpadding="0" cellspacing="2" class="TOCbug" align="right"><tr><td class="TOCbug"><a href="#toc">&nbsp;TOC&nbsp;</a></td></tr></table>
4295<a name="rfc.section.8.1.2.2"></a><h3>8.1.2.2.&nbsp;
4296Server-to-Server Streams</h3>
4297
4298<p>The following rules apply to the 'from' attribute in the context of XML streams qualified by the 'jabber:server' namespace (i.e., server-to-server streams).
4299</p>
4300<p>
4301 </p>
4302<ol class="text">
4303<li>A stanza MUST possess a 'from' attribute whose value is an XMPP address; if a server receives a stanza that does not meet this restriction, it MUST close the stream with an &lt;improper-addressing/&gt; stream error (<a class='info' href='#streams-error-conditions-improper-addressing'>Section&nbsp;4.9.3.7<span> (</span><span class='info'>improper-addressing</span><span>)</span></a>).
4304</li>
4305<li>The domainpart of the JID contained in the stanza's 'from' attribute MUST match the FQDN of the sending server (or any validated domain thereof) as communicated via SASL negotiation (see <a class='info' href='#sasl'>Section&nbsp;6<span> (</span><span class='info'>SASL Negotiation</span><span>)</span></a>), Server Dialback (see <a class='info' href='#XEP-0220'>[XEP&#8209;0220]<span> (</span><span class='info'>Miller, J., Saint-Andre, P., and P. Hancke, &ldquo;Server Dialback,&rdquo; March&nbsp;2010.</span><span>)</span></a>), or similar means; if a server receives a stanza that does not meet this restriction, it MUST close the stream with an &lt;invalid-from/&gt; stream error (<a class='info' href='#streams-error-conditions-invalid-from'>Section&nbsp;4.9.3.9<span> (</span><span class='info'>invalid-from</span><span>)</span></a>).
4306</li>
4307</ol><p>
4308
4309</p>
4310<p>Enforcement of these rules helps to prevent certain denial-of-service attacks as described under <a class='info' href='#security-dos'>Section&nbsp;13.12<span> (</span><span class='info'>Denial of Service</span><span>)</span></a>.
4311</p>
4312<a name="stanzas-attributes-id"></a><br /><hr />
4313<table summary="layout" cellpadding="0" cellspacing="2" class="TOCbug" align="right"><tr><td class="TOCbug"><a href="#toc">&nbsp;TOC&nbsp;</a></td></tr></table>
4314<a name="rfc.section.8.1.3"></a><h3>8.1.3.&nbsp;
4315id</h3>
4316
4317<p>The 'id' attribute is used by the originating entity to track any response or error stanza that it might receive in relation to the generated stanza from another entity (such as an intermediate server or the intended recipient).
4318</p>
4319<p>It is up to the originating entity whether the value of the 'id' attribute is unique only within its current stream or unique globally.
4320</p>
4321<p>For &lt;message/&gt; and &lt;presence/&gt; stanzas, it is RECOMMENDED for the originating entity to include an 'id' attribute; for &lt;iq/&gt; stanzas, it is REQUIRED.
4322</p>
4323<p>If the generated stanza includes an 'id' attribute then it is REQUIRED for the response or error stanza to also include an 'id' attribute, where the value of the 'id' attribute MUST match that of the generated stanza.
4324</p>
4325<p>The semantics of IQ stanzas impose additional restrictions as described under <a class='info' href='#stanzas-semantics-iq'>Section&nbsp;8.2.3<span> (</span><span class='info'>IQ Semantics</span><span>)</span></a>.
4326</p>
4327<a name="stanzas-attributes-type"></a><br /><hr />
4328<table summary="layout" cellpadding="0" cellspacing="2" class="TOCbug" align="right"><tr><td class="TOCbug"><a href="#toc">&nbsp;TOC&nbsp;</a></td></tr></table>
4329<a name="rfc.section.8.1.4"></a><h3>8.1.4.&nbsp;
4330type</h3>
4331
4332<p>The 'type' attribute specifies the purpose or context of the message, presence, or IQ stanza. The particular allowable values for the 'type' attribute vary depending on whether the stanza is a message, presence, or IQ stanza. The defined values for message and presence stanzas are specific to instant messaging and presence applications and therefore are defined in <a class='info' href='#XMPP-IM'>[XMPP&#8209;IM]<span> (</span><span class='info'>Saint-Andre, P., &ldquo;Extensible Messaging and Presence Protocol (XMPP): Instant Messaging and Presence,&rdquo; March&nbsp;2011.</span><span>)</span></a>, whereas the values for IQ stanzas specify the part of the semantics for all structured request-response exchanges (no matter what the payload) and therefore are specified under <a class='info' href='#stanzas-semantics-iq'>Section&nbsp;8.2.3<span> (</span><span class='info'>IQ Semantics</span><span>)</span></a>. The only 'type' value common to all three kinds of stanzas is "error" as described under <a class='info' href='#stanzas-error'>Section&nbsp;8.3<span> (</span><span class='info'>Stanza Errors</span><span>)</span></a>.
4333</p>
4334<a name="stanzas-attributes-lang"></a><br /><hr />
4335<table summary="layout" cellpadding="0" cellspacing="2" class="TOCbug" align="right"><tr><td class="TOCbug"><a href="#toc">&nbsp;TOC&nbsp;</a></td></tr></table>
4336<a name="rfc.section.8.1.5"></a><h3>8.1.5.&nbsp;
4337xml:lang</h3>
4338
4339<p>A stanza SHOULD possess an 'xml:lang' attribute (as defined in Section 2.12 of <a class='info' href='#XML'>[XML]<span> (</span><span class='info'>Maler, E., Yergeau, F., Sperberg-McQueen, C., Paoli, J., and T. Bray, &ldquo;Extensible Markup Language (XML) 1.0 (Fifth Edition),&rdquo; November&nbsp;2008.</span><span>)</span></a>) if the stanza contains XML character data that is intended to be presented to a human user (as explained in <a class='info' href='#CHARSETS'>[CHARSETS]<span> (</span><span class='info'>Alvestrand, H., &ldquo;IETF Policy on Character Sets and Languages,&rdquo; January&nbsp;1998.</span><span>)</span></a>, "internationalization is for humans"). The value of the 'xml:lang' attribute specifies the default language of any such human-readable XML character data.
4340</p><div style='display: table; width: 0; margin-left: 3em; margin-right: auto'><pre>
4341&lt;presence from='romeo@example.net/orchard' xml:lang='en'&gt;
4342 &lt;show&gt;dnd&lt;/show&gt;
4343 &lt;status&gt;Wooing Juliet&lt;/status&gt;
4344&lt;/presence&gt;
4345</pre></div>
4346<p>The value of the 'xml:lang' attribute MAY be overridden by the 'xml:lang' attribute of a specific child element.
4347</p><div style='display: table; width: 0; margin-left: 3em; margin-right: auto'><pre>
4348&lt;presence from='romeo@example.net/orchard' xml:lang='en'&gt;
4349 &lt;show&gt;dnd&lt;/show&gt;
4350 &lt;status&gt;Wooing Juliet&lt;/status&gt;
4351 &lt;status xml:lang='cs'&gt;Dvo&amp;#x0159;&amp;#x00ED;m se Julii&lt;/status&gt;
4352&lt;/presence&gt;
4353</pre></div>
4354<p>If an outbound stanza generated by a client does not possess an 'xml:lang' attribute, the client's server SHOULD add an 'xml:lang' attribute whose value is that specified for the client's output stream as defined under <a class='info' href='#streams-attr-xmllang'>Section&nbsp;4.7.4<span> (</span><span class='info'>xml:lang</span><span>)</span></a>.
4355</p><div style='display: table; width: 0; margin-left: 3em; margin-right: auto'><pre>
4356C: &lt;presence from='romeo@example.net/orchard'&gt;
4357 &lt;show&gt;dnd&lt;/show&gt;
4358 &lt;status&gt;Wooing Juliet&lt;/status&gt;
4359 &lt;/presence&gt;
4360
4361S: &lt;presence from='romeo@example.net/orchard'
4362 to='juliet@im.example.com'
4363 xml:lang='en'&gt;
4364 &lt;show&gt;dnd&lt;/show&gt;
4365 &lt;status&gt;Wooing Juliet&lt;/status&gt;
4366 &lt;/presence&gt;
4367</pre></div>
4368<p>If an inbound stanza received by a client or server does not possess an 'xml:lang' attribute, an implementation MUST assume that the default language is that specified for the entity's input stream as defined under <a class='info' href='#streams-attr-xmllang'>Section&nbsp;4.7.4<span> (</span><span class='info'>xml:lang</span><span>)</span></a>.
4369</p>
4370<p>The value of the 'xml:lang' attribute MUST conform to the NMTOKEN datatype (as defined in Section 2.3 of <a class='info' href='#XML'>[XML]<span> (</span><span class='info'>Maler, E., Yergeau, F., Sperberg-McQueen, C., Paoli, J., and T. Bray, &ldquo;Extensible Markup Language (XML) 1.0 (Fifth Edition),&rdquo; November&nbsp;2008.</span><span>)</span></a>) and MUST conform to the format defined in <a class='info' href='#LANGTAGS'>[LANGTAGS]<span> (</span><span class='info'>Phillips, A. and M. Davis, &ldquo;Tags for Identifying Languages,&rdquo; September&nbsp;2009.</span><span>)</span></a>.
4371</p>
4372<p>A server MUST NOT modify or delete 'xml:lang' attributes on stanzas it receives from other entities.
4373</p>
4374<a name="stanzas-semantics"></a><br /><hr />
4375<table summary="layout" cellpadding="0" cellspacing="2" class="TOCbug" align="right"><tr><td class="TOCbug"><a href="#toc">&nbsp;TOC&nbsp;</a></td></tr></table>
4376<a name="rfc.section.8.2"></a><h3>8.2.&nbsp;
4377Basic Semantics</h3>
4378
4379<a name="stanzas-semantics-message"></a><br /><hr />
4380<table summary="layout" cellpadding="0" cellspacing="2" class="TOCbug" align="right"><tr><td class="TOCbug"><a href="#toc">&nbsp;TOC&nbsp;</a></td></tr></table>
4381<a name="rfc.section.8.2.1"></a><h3>8.2.1.&nbsp;
4382Message Semantics</h3>
4383
4384<p>The &lt;message/&gt; stanza is a "push" mechanism whereby one entity pushes information to another entity, similar to the communications that occur in a system such as email. All message stanzas will possess a 'to' attribute that specifies the intended recipient of the message (see <a class='info' href='#stanzas-attributes-to'>Section&nbsp;8.1.1<span> (</span><span class='info'>to</span><span>)</span></a> and <a class='info' href='#rules-noto'>Section&nbsp;10.3<span> (</span><span class='info'>No 'to' Address</span><span>)</span></a>), unless the message is being sent to the bare JID of a connected client's account. Upon receiving a message stanza with a 'to' address, a server SHOULD attempt to route or deliver it to the intended recipient (see <a class='info' href='#rules'>Section&nbsp;10<span> (</span><span class='info'>Server Rules for Processing XML Stanzas</span><span>)</span></a> for general routing and delivery rules related to XML stanzas).
4385</p>
4386<a name="stanzas-semantics-presence"></a><br /><hr />
4387<table summary="layout" cellpadding="0" cellspacing="2" class="TOCbug" align="right"><tr><td class="TOCbug"><a href="#toc">&nbsp;TOC&nbsp;</a></td></tr></table>
4388<a name="rfc.section.8.2.2"></a><h3>8.2.2.&nbsp;
4389Presence Semantics</h3>
4390
4391<p>The &lt;presence/&gt; stanza is a specialized "broadcast" or "publish-subscribe" mechanism, whereby multiple entities receive information (in this case, network availability information) about an entity to which they have subscribed. In general, a publishing client SHOULD send a presence stanza with no 'to' attribute, in which case the server to which the client is connected will broadcast that stanza to all subscribed entities. However, a publishing client MAY also send a presence stanza with a 'to' attribute, in which case the server will route or deliver that stanza to the intended recipient. Although the &lt;presence/&gt; stanza is most often used by XMPP clients, it can also be used by servers, add-on services, and any other kind of XMPP entity. See <a class='info' href='#rules'>Section&nbsp;10<span> (</span><span class='info'>Server Rules for Processing XML Stanzas</span><span>)</span></a> for general routing and delivery rules related to XML stanzas, and <a class='info' href='#XMPP-IM'>[XMPP&#8209;IM]<span> (</span><span class='info'>Saint-Andre, P., &ldquo;Extensible Messaging and Presence Protocol (XMPP): Instant Messaging and Presence,&rdquo; March&nbsp;2011.</span><span>)</span></a> for rules specific to presence applications.
4392</p>
4393<a name="stanzas-semantics-iq"></a><br /><hr />
4394<table summary="layout" cellpadding="0" cellspacing="2" class="TOCbug" align="right"><tr><td class="TOCbug"><a href="#toc">&nbsp;TOC&nbsp;</a></td></tr></table>
4395<a name="rfc.section.8.2.3"></a><h3>8.2.3.&nbsp;
4396IQ Semantics</h3>
4397
4398<p>Info/Query, or IQ, is a "request-response" mechanism, similar in some ways to the Hypertext Transfer Protocol <a class='info' href='#HTTP'>[HTTP]<span> (</span><span class='info'>Fielding, R., Gettys, J., Mogul, J., Frystyk, H., Masinter, L., Leach, P., and T. Berners-Lee, &ldquo;Hypertext Transfer Protocol -- HTTP/1.1,&rdquo; June&nbsp;1999.</span><span>)</span></a>. The semantics of IQ enable an entity to make a request of, and receive a response from, another entity. The data content of the request and response is defined by the schema or other structural definition associated with the XML namespace that qualifies the direct child element of the IQ element (see <a class='info' href='#stanzas-extended'>Section&nbsp;8.4<span> (</span><span class='info'>Extended Content</span><span>)</span></a>), and the interaction is tracked by the requesting entity through use of the 'id' attribute. Thus, IQ interactions follow a common pattern of structured data exchange such as get/result or set/result (although an error can be returned in reply to a request if appropriate):
4399</p><br /><hr class="insert" />
4400<a name="figure-5"></a>
4401<div style='display: table; width: 0; margin-left: 3em; margin-right: auto'><pre>
4402Requesting Responding
4403 Entity Entity
4404---------- ----------
4405 | |
4406 | &lt;iq id='1' type='get'&gt; |
4407 | [ ... payload ... ] |
4408 | &lt;/iq&gt; |
4409 | -------------------------&gt; |
4410 | |
4411 | &lt;iq id='1' type='result'&gt; |
4412 | [ ... payload ... ] |
4413 | &lt;/iq&gt; |
4414 | &lt;------------------------- |
4415 | |
4416 | &lt;iq id='2' type='set'&gt; |
4417 | [ ... payload ... ] |
4418 | &lt;/iq&gt; |
4419 | -------------------------&gt; |
4420 | |
4421 | &lt;iq id='2' type='error'&gt; |
4422 | [ ... condition ... ] |
4423 | &lt;/iq&gt; |
4424 | &lt;------------------------- |
4425 | |
4426</pre></div><table border="0" cellpadding="0" cellspacing="2" align="center"><tr><td align="center"><font face="monaco, MS Sans Serif" size="1"><b>&nbsp;Figure&nbsp;5: Semantics of IQ Stanzas&nbsp;</b></font><br /></td></tr></table><hr class="insert" />
4427
4428<p>To enforce these semantics, the following rules apply:
4429</p>
4430<p></p>
4431<ol class="text">
4432<li>The 'id' attribute is REQUIRED for IQ stanzas.
4433</li>
4434<li>The 'type' attribute is REQUIRED for IQ stanzas. The value MUST be one of the following; if not, the recipient or an intermediate router MUST return a &lt;bad-request/&gt; stanza error (<a class='info' href='#stanzas-error-conditions-bad-request'>Section&nbsp;8.3.3.1<span> (</span><span class='info'>bad-request</span><span>)</span></a>).
4435
4436
4437<ul class="text">
4438<li>get -- The stanza requests information, inquires about what data is needed in order to complete further operations, etc.
4439</li>
4440<li>set -- The stanza provides data that is needed for an operation to be completed, sets new values, replaces existing values, etc.
4441</li>
4442<li>result -- The stanza is a response to a successful get or set request.
4443</li>
4444<li>error -- The stanza reports an error that has occurred regarding processing or delivery of a get or set request (see <a class='info' href='#stanzas-error'>Section&nbsp;8.3<span> (</span><span class='info'>Stanza Errors</span><span>)</span></a>).
4445</li>
4446</ul>
4447
4448</li>
4449<li>An entity that receives an IQ request of type "get" or "set" MUST reply with an IQ response of type "result" or "error". The response MUST preserve the 'id' attribute of the request (or be empty if the generated stanza did not include an 'id' attribute).
4450</li>
4451<li>An entity that receives a stanza of type "result" or "error" MUST NOT respond to the stanza by sending a further IQ response of type "result" or "error"; however, the requesting entity MAY send another request (e.g., an IQ of type "set" to provide obligatory information discovered through a get/result pair).
4452</li>
4453<li>An IQ stanza of type "get" or "set" MUST contain exactly one child element, which specifies the semantics of the particular request.
4454</li>
4455<li>An IQ stanza of type "result" MUST include zero or one child elements.
4456</li>
4457<li>An IQ stanza of type "error" MAY include the child element contained in the associated "get" or "set" and MUST include an &lt;error/&gt; child; for details, see <a class='info' href='#stanzas-error'>Section&nbsp;8.3<span> (</span><span class='info'>Stanza Errors</span><span>)</span></a>.
4458</li>
4459</ol>
4460
4461<a name="stanzas-error"></a><br /><hr />
4462<table summary="layout" cellpadding="0" cellspacing="2" class="TOCbug" align="right"><tr><td class="TOCbug"><a href="#toc">&nbsp;TOC&nbsp;</a></td></tr></table>
4463<a name="rfc.section.8.3"></a><h3>8.3.&nbsp;
4464Stanza Errors</h3>
4465
4466<p>Stanza-related errors are handled in a manner similar to <a class='info' href='#streams-error'>stream errors<span> (</span><span class='info'>Stream Errors</span><span>)</span></a>. Unlike stream errors, stanza errors are recoverable; therefore, they do not result in termination of the XML stream and underlying TCP connection. Instead, the entity that discovers the error condition returns an error stanza, which is a stanza that:
4467</p>
4468<p>
4469 </p>
4470<ul class="text">
4471<li>is of the same kind (message, presence, or IQ) as the generated stanza that triggered the error
4472</li>
4473<li>has a 'type' attribute set to a value of "error"
4474</li>
4475<li>typically swaps the 'from' and 'to' addresses of the generated stanza
4476</li>
4477<li>mirrors the 'id' attribute (if any) of the generated stanza that triggered the error
4478</li>
4479<li>contains an &lt;error/&gt; child element that specifies the error condition and therefore provides a hint regarding actions that the sender might be able to take in an effort to remedy the error (however, it is not always possible to remedy the error)
4480</li>
4481</ul><p>
4482
4483</p>
4484<a name="stanzas-error-rules"></a><br /><hr />
4485<table summary="layout" cellpadding="0" cellspacing="2" class="TOCbug" align="right"><tr><td class="TOCbug"><a href="#toc">&nbsp;TOC&nbsp;</a></td></tr></table>
4486<a name="rfc.section.8.3.1"></a><h3>8.3.1.&nbsp;
4487Rules</h3>
4488
4489<p>The following rules apply to stanza errors:
4490</p>
4491<p></p>
4492<ol class="text">
4493<li>The receiving or processing entity that detects an error condition in relation to a stanza SHOULD return an error stanza (and MUST do so for IQ stanzas).
4494</li>
4495<li>The error stanza SHOULD simply swap the 'from' and 'to' addresses from the generated stanza, unless doing so would (1) result in an information leak (see under <a class='info' href='#security-leaks'>Section&nbsp;13.10<span> (</span><span class='info'>Information Leaks</span><span>)</span></a>) or other breach of security, or (2) force the sender of the error stanza to include a malformed JID in the 'from' or 'to' address of the error stanza.
4496</li>
4497<li>If the generated stanza was &lt;message/&gt; or &lt;presence/&gt; and included an 'id' attribute then it is REQUIRED for the error stanza to also include an 'id' attribute. If the generated stanza was &lt;iq/&gt; then the error stanza MUST include an 'id' attribute. In all cases, the value of the 'id' attribute MUST match that of the generated stanza (or be empty if the generated stanza did not include an 'id' attribute).
4498</li>
4499<li>An error stanza MUST contain an &lt;error/&gt; child element.
4500</li>
4501<li>The entity that returns an error stanza MAY pass along its JID to the sender of the generated stanza (e.g., for diagnostic or tracking purposes) through the addition of a 'by' attribute to the &lt;error/&gt; child element.
4502</li>
4503<li>The entity that returns an error stanza MAY include the original XML sent so that the sender can inspect and, if necessary, correct the XML before attempting to resend (however, this is a courtesy only and the originating entity MUST NOT depend on receiving the original payload). Naturally, the entity MUST NOT include the original data if it not well-formed XML, violates the XML restrictions of XMPP (see under <a class='info' href='#xml-restrictions'>Section&nbsp;11.1<span> (</span><span class='info'>XML Restrictions</span><span>)</span></a>), or is otherwise harmful (e.g., exceeds a size limit).
4504</li>
4505<li>An &lt;error/&gt; child MUST NOT be included if the 'type' attribute has a value other than "error" (or if there is no 'type' attribute).
4506</li>
4507<li>An entity that receives an error stanza MUST NOT respond to the stanza with a further error stanza; this helps to prevent looping.
4508</li>
4509</ol>
4510
4511<a name="stanzas-error-syntax"></a><br /><hr />
4512<table summary="layout" cellpadding="0" cellspacing="2" class="TOCbug" align="right"><tr><td class="TOCbug"><a href="#toc">&nbsp;TOC&nbsp;</a></td></tr></table>
4513<a name="rfc.section.8.3.2"></a><h3>8.3.2.&nbsp;
4514Syntax</h3>
4515
4516<p>The syntax for stanza-related errors is as follows, where XML data shown within the square brackets '[' and ']' is OPTIONAL, 'intended-recipient' is the JID of the entity to which the original stanza was addressed, 'sender' is the JID of the originating entity, and 'error-generator' is the entity that detects the fact that an error has occurred and thus returns an error stanza.
4517</p><div style='display: table; width: 0; margin-left: 3em; margin-right: auto'><pre>
4518&lt;stanza-kind from='intended-recipient' to='sender' type='error'&gt;
4519 [OPTIONAL to include sender XML here]
4520 &lt;error [by='error-generator']
4521 type='error-type'&gt;
4522 &lt;defined-condition xmlns='urn:ietf:params:xml:ns:xmpp-stanzas'/&gt;
4523 [&lt;text xmlns='urn:ietf:params:xml:ns:xmpp-stanzas'
4524 xml:lang='langcode'&gt;
4525 OPTIONAL descriptive text
4526 &lt;/text&gt;]
4527 [OPTIONAL application-specific condition element]
4528 &lt;/error&gt;
4529&lt;/stanza-kind&gt;
4530</pre></div>
4531<p>The "stanza-kind" MUST be one of message, presence, or iq.
4532</p>
4533<p>The "error-type" MUST be one of the following:
4534</p>
4535<p>
4536 </p>
4537<ul class="text">
4538<li>auth -- retry after providing credentials
4539</li>
4540<li>cancel -- do not retry (the error cannot be remedied)
4541</li>
4542<li>continue -- proceed (the condition was only a warning)
4543</li>
4544<li>modify -- retry after changing the data sent
4545</li>
4546<li>wait -- retry after waiting (the error is temporary)
4547</li>
4548</ul><p>
4549
4550</p>
4551<p>The "defined-condition" MUST correspond to one of the stanza error conditions defined under <a class='info' href='#stanzas-error-conditions'>Section&nbsp;8.3.3<span> (</span><span class='info'>Defined Conditions</span><span>)</span></a>. However, because additional error conditions might be defined in the future, if an entity receives a stanza error condition that it does not understand then it MUST treat the unknown condition as equivalent to &lt;undefined-condition/&gt; (<a class='info' href='#stanzas-error-conditions-undefined-condition'>Section&nbsp;8.3.3.21<span> (</span><span class='info'>undefined-condition</span><span>)</span></a>). If the designers of an XMPP protocol extension or the developers of an XMPP implementation need to communicate a stanza error condition that is not defined in this specification, they can do so by defining an application-specific error condition element qualified by an application-specific namespace.
4552</p>
4553<p>The &lt;error/&gt; element:
4554</p>
4555<p></p>
4556<ul class="text">
4557<li>MUST contain a defined condition element.
4558</li>
4559<li>MAY contain a &lt;text/&gt; child element containing XML character data that describes the error in more detail; this element MUST be qualified by the 'urn:ietf:params:xml:ns:xmpp-stanzas' namespace and SHOULD possess an 'xml:lang' attribute specifying the natural language of the XML character data.
4560</li>
4561<li>MAY contain a child element for an application-specific error condition; this element MUST be qualified by an application-specific namespace that defines the syntax and semantics of the element.
4562</li>
4563</ul>
4564
4565<p>The &lt;text/&gt; element is OPTIONAL. If included, it is to be used only to provide descriptive or diagnostic information that supplements the meaning of a defined condition or application-specific condition. It MUST NOT be interpreted programmatically by an application. It SHOULD NOT be used as the error message presented to a human user, but MAY be shown in addition to the error message associated with the defined condition element (and, optionally, the application-specific condition element).
4566</p>
4567<p></p>
4568<blockquote class="text">
4569<p>Interoperability Note: The syntax defined in <a class='info' href='#RFC3920'>[RFC3920]<span> (</span><span class='info'>Saint-Andre, P., Ed., &ldquo;Extensible Messaging and Presence Protocol (XMPP): Core,&rdquo; October&nbsp;2004.</span><span>)</span></a> included a legacy 'code' attribute, whose semantics have been replaced by the defined condition elements; information about mapping defined condition elements to values of the legacy 'code' attribute can be found in <a class='info' href='#XEP-0086'>[XEP&#8209;0086]<span> (</span><span class='info'>Norris, R. and P. Saint-Andre, &ldquo;Error Condition Mappings,&rdquo; February&nbsp;2004.</span><span>)</span></a>.
4570</p>
4571</blockquote>
4572
4573<a name="stanzas-error-conditions"></a><br /><hr />
4574<table summary="layout" cellpadding="0" cellspacing="2" class="TOCbug" align="right"><tr><td class="TOCbug"><a href="#toc">&nbsp;TOC&nbsp;</a></td></tr></table>
4575<a name="rfc.section.8.3.3"></a><h3>8.3.3.&nbsp;
4576Defined Conditions</h3>
4577
4578<p>The following conditions are defined for use in stanza errors.
4579</p>
4580<p>The error-type value that is RECOMMENDED for each defined condition is the usual expected type; however, in some circumstances a different type might be more appropriate.
4581</p>
4582<a name="stanzas-error-conditions-bad-request"></a><br /><hr />
4583<table summary="layout" cellpadding="0" cellspacing="2" class="TOCbug" align="right"><tr><td class="TOCbug"><a href="#toc">&nbsp;TOC&nbsp;</a></td></tr></table>
4584<a name="rfc.section.8.3.3.1"></a><h3>8.3.3.1.&nbsp;
4585bad-request</h3>
4586
4587<p>The sender has sent a stanza containing XML that does not conform to the appropriate schema or that cannot be processed (e.g., an IQ stanza that includes an unrecognized value of the 'type' attribute, or an element that is qualified by a recognized namespace but that violates the defined syntax for the element); the associated error type SHOULD be "modify".
4588</p><div style='display: table; width: 0; margin-left: 3em; margin-right: auto'><pre>
4589C: &lt;iq from='juliet@im.example.com/balcony'
4590 id='zj3v142b'
4591 to='im.example.com'
4592 type='subscribe'&gt;
4593 &lt;ping xmlns='urn:xmpp:ping'/&gt;
4594 &lt;/iq&gt;
4595
4596S: &lt;iq from='im.example.com'
4597 id='zj3v142b'
4598 to='juliet@im.example.com/balcony'
4599 type='error'&gt;
4600 &lt;error type='modify'&gt;
4601 &lt;bad-request xmlns='urn:ietf:params:xml:ns:xmpp-stanzas'/&gt;
4602 &lt;/error&gt;
4603 &lt;/iq&gt;
4604</pre></div>
4605<a name="stanzas-error-conditions-conflict"></a><br /><hr />
4606<table summary="layout" cellpadding="0" cellspacing="2" class="TOCbug" align="right"><tr><td class="TOCbug"><a href="#toc">&nbsp;TOC&nbsp;</a></td></tr></table>
4607<a name="rfc.section.8.3.3.2"></a><h3>8.3.3.2.&nbsp;
4608conflict</h3>
4609
4610<p>Access cannot be granted because an existing resource exists with the same name or address; the associated error type SHOULD be "cancel".
4611</p><div style='display: table; width: 0; margin-left: 3em; margin-right: auto'><pre>
4612C: &lt;iq id='wy2xa82b4' type='set'&gt;
4613 &lt;bind xmlns='urn:ietf:params:xml:ns:xmpp-bind'&gt;
4614 &lt;resource&gt;balcony&lt;/resource&gt;
4615 &lt;/bind&gt;
4616 &lt;/iq&gt;
4617
4618S: &lt;iq id='wy2xa82b4' type='error'&gt;
4619 &lt;error type='cancel'&gt;
4620 &lt;conflict xmlns='urn:ietf:params:xml:ns:xmpp-stanzas'/&gt;
4621 &lt;/error&gt;
4622 &lt;/iq&gt;
4623</pre></div>
4624<a name="stanzas-error-conditions-feature-not-implemented"></a><br /><hr />
4625<table summary="layout" cellpadding="0" cellspacing="2" class="TOCbug" align="right"><tr><td class="TOCbug"><a href="#toc">&nbsp;TOC&nbsp;</a></td></tr></table>
4626<a name="rfc.section.8.3.3.3"></a><h3>8.3.3.3.&nbsp;
4627feature-not-implemented</h3>
4628
4629<p>The feature represented in the XML stanza is not implemented by the intended recipient or an intermediate server and therefore the stanza cannot be processed (e.g., the entity understands the namespace but does not recognize the element name); the associated error type SHOULD be "cancel" or "modify".
4630</p><div style='display: table; width: 0; margin-left: 3em; margin-right: auto'><pre>
4631C: &lt;iq from='juliet@im.example.com/balcony'
4632 id='9u2bax16'
4633 to='pubsub.example.com'
4634 type='get'&gt;
4635 &lt;pubsub xmlns='http://jabber.org/protocol/pubsub'&gt;
4636 &lt;subscriptions/&gt;
4637 &lt;/pubsub&gt;
4638 &lt;/iq&gt;
4639
4640E: &lt;iq from='pubsub.example.com'
4641 id='9u2bax16'
4642 to='juliet@im.example.com/balcony'
4643 type='error'&gt;
4644 &lt;error type='cancel'&gt;
4645 &lt;feature-not-implemented
4646 xmlns='urn:ietf:params:xml:ns:xmpp-stanzas'/&gt;
4647 &lt;unsupported
4648 xmlns='http://jabber.org/protocol/pubsub#errors'
4649 feature='retrieve-subscriptions'/&gt;
4650 &lt;/error&gt;
4651 &lt;/iq&gt;
4652</pre></div>
4653<a name="stanzas-error-conditions-forbidden"></a><br /><hr />
4654<table summary="layout" cellpadding="0" cellspacing="2" class="TOCbug" align="right"><tr><td class="TOCbug"><a href="#toc">&nbsp;TOC&nbsp;</a></td></tr></table>
4655<a name="rfc.section.8.3.3.4"></a><h3>8.3.3.4.&nbsp;
4656forbidden</h3>
4657
4658<p>The requesting entity does not possess the necessary permissions to perform an action that only certain authorized roles or individuals are allowed to complete (i.e., it typically relates to authorization rather than authentication); the associated error type SHOULD be "auth".
4659</p><div style='display: table; width: 0; margin-left: 3em; margin-right: auto'><pre>
4660C: &lt;presence
4661 from='juliet@im.example.com/balcony'
4662 id='y2bs71v4'
4663 to='characters@muc.example.com/JulieC'&gt;
4664 &lt;x xmlns='http://jabber.org/protocol/muc'/&gt;
4665 &lt;/presence&gt;
4666
4667E: &lt;presence
4668 from='characters@muc.example.com/JulieC'
4669 id='y2bs71v4'
4670 to='juliet@im.example.com/balcony'
4671 type='error'&gt;
4672 &lt;error type='auth'&gt;
4673 &lt;forbidden xmlns='urn:ietf:params:xml:ns:xmpp-stanzas'/&gt;
4674 &lt;/error&gt;
4675 &lt;/presence&gt;
4676</pre></div>
4677<a name="stanzas-error-conditions-gone"></a><br /><hr />
4678<table summary="layout" cellpadding="0" cellspacing="2" class="TOCbug" align="right"><tr><td class="TOCbug"><a href="#toc">&nbsp;TOC&nbsp;</a></td></tr></table>
4679<a name="rfc.section.8.3.3.5"></a><h3>8.3.3.5.&nbsp;
4680gone</h3>
4681
4682<p>The recipient or server can no longer be contacted at this address, typically on a permanent basis (as opposed to the &lt;redirect/&gt; error condition, which is used for temporary addressing failures); the associated error type SHOULD be "cancel" and the error stanza SHOULD include a new address (if available) as the XML character data of the &lt;gone/&gt; element (which MUST be a Uniform Resource Identifier <a class='info' href='#URI'>[URI]<span> (</span><span class='info'>Berners-Lee, T., Fielding, R., and L. Masinter, &ldquo;Uniform Resource Identifier (URI): Generic Syntax,&rdquo; January&nbsp;2005.</span><span>)</span></a> or Internationalized Resource Identifier <a class='info' href='#IRI'>[IRI]<span> (</span><span class='info'>Duerst, M. and M. Suignard, &ldquo;Internationalized Resource Identifiers (IRIs),&rdquo; January&nbsp;2005.</span><span>)</span></a> at which the entity can be contacted, typically an XMPP IRI as specified in <a class='info' href='#XMPP-URI'>[XMPP&#8209;URI]<span> (</span><span class='info'>Saint-Andre, P., &ldquo;Internationalized Resource Identifiers (IRIs) and Uniform Resource Identifiers (URIs) for the Extensible Messaging and Presence Protocol (XMPP),&rdquo; February&nbsp;2008.</span><span>)</span></a>).
4683</p><div style='display: table; width: 0; margin-left: 3em; margin-right: auto'><pre>
4684C: &lt;message
4685 from='juliet@im.example.com/churchyard'
4686 id='sj2b371v'
4687 to='romeo@example.net'
4688 type='chat'&gt;
4689 &lt;body&gt;Thy lips are warm.&lt;/body&gt;
4690 &lt;/message&gt;
4691
4692S: &lt;message
4693 from='romeo@example.net'
4694 id='sj2b371v'
4695 to='juliet@im.example.com/churchyard'
4696 type='error'&gt;
4697 &lt;error by='example.net'
4698 type='cancel'&gt;
4699 &lt;gone xmlns='urn:ietf:params:xml:ns:xmpp-stanzas'&gt;
4700 xmpp:romeo@afterlife.example.net
4701 &lt;/gone&gt;
4702 &lt;/error&gt;
4703 &lt;/message&gt;
4704</pre></div>
4705<a name="stanzas-error-conditions-internal-server-error"></a><br /><hr />
4706<table summary="layout" cellpadding="0" cellspacing="2" class="TOCbug" align="right"><tr><td class="TOCbug"><a href="#toc">&nbsp;TOC&nbsp;</a></td></tr></table>
4707<a name="rfc.section.8.3.3.6"></a><h3>8.3.3.6.&nbsp;
4708internal-server-error</h3>
4709
4710<p>The server has experienced a misconfiguration or other
4711 internal error that prevents it from processing the stanza;
4712 the associated error type SHOULD be "cancel".
4713</p><div style='display: table; width: 0; margin-left: 3em; margin-right: auto'><pre>
4714C: &lt;presence
4715 from='juliet@im.example.com/balcony'
4716 id='y2bs71v4'
4717 to='characters@muc.example.com/JulieC'&gt;
4718 &lt;x xmlns='http://jabber.org/protocol/muc'/&gt;
4719 &lt;/presence&gt;
4720
4721E: &lt;presence
4722 from='characters@muc.example.com/JulieC'
4723 id='y2bs71v4'
4724 to='juliet@im.example.com/balcony'
4725 type='error'&gt;
4726 &lt;error type='cancel'&gt;
4727 &lt;internal-server-error
4728 xmlns='urn:ietf:params:xml:ns:xmpp-stanzas'/&gt;
4729 &lt;/error&gt;
4730 &lt;/presence&gt;
4731</pre></div>
4732<a name="stanzas-error-conditions-item-not-found"></a><br /><hr />
4733<table summary="layout" cellpadding="0" cellspacing="2" class="TOCbug" align="right"><tr><td class="TOCbug"><a href="#toc">&nbsp;TOC&nbsp;</a></td></tr></table>
4734<a name="rfc.section.8.3.3.7"></a><h3>8.3.3.7.&nbsp;
4735item-not-found</h3>
4736
4737<p>The addressed JID or item requested cannot be found; the associated error type SHOULD be "cancel".
4738</p><div style='display: table; width: 0; margin-left: 3em; margin-right: auto'><pre>
4739C: &lt;presence from='userfoo@example.com/bar'
4740 id='pwb2n78i'
4741 to='nosuchroom@conference.example.org/foo'/&gt;
4742
4743S: &lt;presence from='nosuchroom@conference.example.org/foo'
4744 id='pwb2n78i'
4745 to='userfoo@example.com/bar'
4746 type='error'&gt;
4747 &lt;error type='cancel'&gt;
4748 &lt;item-not-found xmlns='urn:ietf:params:xml:ns:xmpp-stanzas'/&gt;
4749 &lt;/error&gt;
4750 &lt;/presence&gt;
4751</pre></div>
4752<p></p>
4753<blockquote class="text">
4754<p>Security Warning: An application MUST NOT return this error if doing so would provide information about the intended recipient's network availability to an entity that is not authorized to know such information (for a more detailed discussion of presence authorization, refer to the discussion of presence subscriptions in <a class='info' href='#XMPP-IM'>[XMPP&#8209;IM]<span> (</span><span class='info'>Saint-Andre, P., &ldquo;Extensible Messaging and Presence Protocol (XMPP): Instant Messaging and Presence,&rdquo; March&nbsp;2011.</span><span>)</span></a>); instead it MUST return a &lt;service-unavailable/&gt; stanza error (<a class='info' href='#stanzas-error-conditions-service-unavailable'>Section&nbsp;8.3.3.19<span> (</span><span class='info'>service-unavailable</span><span>)</span></a>).
4755</p>
4756</blockquote>
4757
4758<a name="stanzas-error-conditions-jid-malformed"></a><br /><hr />
4759<table summary="layout" cellpadding="0" cellspacing="2" class="TOCbug" align="right"><tr><td class="TOCbug"><a href="#toc">&nbsp;TOC&nbsp;</a></td></tr></table>
4760<a name="rfc.section.8.3.3.8"></a><h3>8.3.3.8.&nbsp;
4761jid-malformed</h3>
4762
4763<p>The sending entity has provided (e.g., during resource binding) or communicated (e.g., in the 'to' address of a stanza) an XMPP address or aspect thereof that violates the rules defined in <a class='info' href='#XMPP-ADDR'>[XMPP&#8209;ADDR]<span> (</span><span class='info'>Saint-Andre, P., &ldquo;Extensible Messaging and Presence Protocol (XMPP): Address Format,&rdquo; March&nbsp;2011.</span><span>)</span></a>; the associated error type SHOULD be "modify".
4764</p><div style='display: table; width: 0; margin-left: 3em; margin-right: auto'><pre>
4765C: &lt;presence
4766 from='juliet@im.example.com/balcony'
4767 id='y2bs71v4'
4768 to='ch@r@cters@muc.example.com/JulieC'&gt;
4769 &lt;x xmlns='http://jabber.org/protocol/muc'/&gt;
4770 &lt;/presence&gt;
4771
4772E: &lt;presence
4773 from='ch@r@cters@muc.example.com/JulieC'
4774 id='y2bs71v4'
4775 to='juliet@im.example.com/balcony'
4776 type='error'&gt;
4777 &lt;error by='muc.example.com'
4778 type='modify'&gt;
4779 &lt;jid-malformed
4780 xmlns='urn:ietf:params:xml:ns:xmpp-stanzas'/&gt;
4781 &lt;/error&gt;
4782 &lt;/presence&gt;
4783</pre></div>
4784<p></p>
4785<blockquote class="text">
4786<p>Implementation Note: Enforcement of the format for XMPP localparts is primarily the responsibility of the service at which the associated account or entity is located (e.g., the example.com service is responsible for returning &lt;jid-malformed/&gt; errors related to all JIDs of the form &lt;localpart@example.com&gt;), whereas enforcement of the format for XMPP domainparts is primarily the responsibility of the service that seeks to route a stanza to the service identified by that domainpart (e.g., the example.org service is responsible for returning &lt;jid-malformed/&gt; errors related to stanzas that users of that service have to tried send to JIDs of the form &lt;localpart@example.com&gt;). However, any entity that detects a malformed JID MAY return this error.
4787</p>
4788</blockquote>
4789
4790<a name="stanzas-error-conditions-not-acceptable"></a><br /><hr />
4791<table summary="layout" cellpadding="0" cellspacing="2" class="TOCbug" align="right"><tr><td class="TOCbug"><a href="#toc">&nbsp;TOC&nbsp;</a></td></tr></table>
4792<a name="rfc.section.8.3.3.9"></a><h3>8.3.3.9.&nbsp;
4793not-acceptable</h3>
4794
4795<p>The recipient or server understands the request but cannot process it because the request does not meet criteria defined by the recipient or server (e.g., a request to subscribe to information that does not simultaneously include configuration parameters needed by the recipient); the associated error type SHOULD be "modify".
4796</p><div style='display: table; width: 0; margin-left: 3em; margin-right: auto'><pre>
4797C: &lt;message to='juliet@im.example.com' id='yt2vs71m'&gt;
4798 &lt;body&gt;[ ... the-emacs-manual ... ]&lt;/body&gt;
4799 &lt;/message&gt;
4800
4801S: &lt;message from='juliet@im.example.com' id='yt2vs71m'&gt;
4802 &lt;error type='modify'&gt;
4803 &lt;not-acceptable
4804 xmlns='urn:ietf:params:xml:ns:xmpp-stanzas'/&gt;
4805 &lt;/error&gt;
4806 &lt;/message&gt;
4807</pre></div>
4808<a name="stanzas-error-conditions-not-allowed"></a><br /><hr />
4809<table summary="layout" cellpadding="0" cellspacing="2" class="TOCbug" align="right"><tr><td class="TOCbug"><a href="#toc">&nbsp;TOC&nbsp;</a></td></tr></table>
4810<a name="rfc.section.8.3.3.10"></a><h3>8.3.3.10.&nbsp;
4811not-allowed</h3>
4812
4813<p>The recipient or server does not allow any entity to perform the action (e.g., sending to entities at a blacklisted domain); the associated error type SHOULD be "cancel".
4814</p><div style='display: table; width: 0; margin-left: 3em; margin-right: auto'><pre>
4815C: &lt;presence
4816 from='juliet@im.example.com/balcony'
4817 id='y2bs71v4'
4818 to='characters@muc.example.com/JulieC'&gt;
4819 &lt;x xmlns='http://jabber.org/protocol/muc'/&gt;
4820 &lt;/presence&gt;
4821
4822E: &lt;presence
4823 from='characters@muc.example.com/JulieC'
4824 id='y2bs71v4'
4825 to='juliet@im.example.com/balcony'
4826 type='error'&gt;
4827 &lt;error type='cancel'&gt;
4828 &lt;not-allowed xmlns='urn:ietf:params:xml:ns:xmpp-stanzas'/&gt;
4829 &lt;/error&gt;
4830 &lt;/presence&gt;
4831</pre></div>
4832<a name="stanzas-error-conditions-not-authorized"></a><br /><hr />
4833<table summary="layout" cellpadding="0" cellspacing="2" class="TOCbug" align="right"><tr><td class="TOCbug"><a href="#toc">&nbsp;TOC&nbsp;</a></td></tr></table>
4834<a name="rfc.section.8.3.3.11"></a><h3>8.3.3.11.&nbsp;
4835not-authorized</h3>
4836
4837<p>The sender needs to provide credentials before being allowed to perform the action, or has provided improper credentials (the name "not-authorized", which was borrowed from the "401 Unauthorized" error of <a class='info' href='#HTTP'>[HTTP]<span> (</span><span class='info'>Fielding, R., Gettys, J., Mogul, J., Frystyk, H., Masinter, L., Leach, P., and T. Berners-Lee, &ldquo;Hypertext Transfer Protocol -- HTTP/1.1,&rdquo; June&nbsp;1999.</span><span>)</span></a>, might lead the reader to think that this condition relates to authorization, but instead it is typically used in relation to authentication); the associated error type SHOULD be "auth".
4838</p><div style='display: table; width: 0; margin-left: 3em; margin-right: auto'><pre>
4839C: &lt;presence
4840 from='juliet@im.example.com/balcony'
4841 id='y2bs71v4'
4842 to='characters@muc.example.com/JulieC'&gt;
4843 &lt;x xmlns='http://jabber.org/protocol/muc'/&gt;
4844 &lt;/presence&gt;
4845
4846E: &lt;presence
4847 from='characters@muc.example.com/JulieC'
4848 id='y2bs71v4'
4849 to='juliet@im.example.com/balcony'&gt;
4850 &lt;error type='auth'&gt;
4851 &lt;not-authorized xmlns='urn:ietf:params:xml:ns:xmpp-stanzas'/&gt;
4852 &lt;/error&gt;
4853 &lt;/presence&gt;
4854</pre></div>
4855<a name="stanzas-error-conditions-policy-violation"></a><br /><hr />
4856<table summary="layout" cellpadding="0" cellspacing="2" class="TOCbug" align="right"><tr><td class="TOCbug"><a href="#toc">&nbsp;TOC&nbsp;</a></td></tr></table>
4857<a name="rfc.section.8.3.3.12"></a><h3>8.3.3.12.&nbsp;
4858policy-violation</h3>
4859
4860<p>The entity has violated some local service policy (e.g., a message contains words that are prohibited by the service) and the server MAY choose to specify the policy in the &lt;text/&gt; element or in an application-specific condition element; the associated error type SHOULD be "modify" or "wait" depending on the policy being violated.
4861</p>
4862<p>(In the following example, the client sends an XMPP message containing words that are forbidden according to the server's local service policy.)
4863</p><div style='display: table; width: 0; margin-left: 3em; margin-right: auto'><pre>
4864C: &lt;message from='romeo@example.net/foo'
4865 to='bill@im.example.com'
4866 id='vq71f4nb'&gt;
4867 &lt;body&gt;%#&amp;@^!!!&lt;/body&gt;
4868 &lt;/message&gt;
4869
4870S: &lt;message from='bill@im.example.com'
4871 id='vq71f4nb'
4872 to='romeo@example.net/foo'&gt;
4873 &lt;error by='example.net' type='modify'&gt;
4874 &lt;policy-violation
4875 xmlns='urn:ietf:params:xml:ns:xmpp-stanzas'/&gt;
4876 &lt;/error&gt;
4877 &lt;/message&gt;
4878</pre></div>
4879<a name="stanzas-error-conditions-recipient-unavailable"></a><br /><hr />
4880<table summary="layout" cellpadding="0" cellspacing="2" class="TOCbug" align="right"><tr><td class="TOCbug"><a href="#toc">&nbsp;TOC&nbsp;</a></td></tr></table>
4881<a name="rfc.section.8.3.3.13"></a><h3>8.3.3.13.&nbsp;
4882recipient-unavailable</h3>
4883
4884<p>The intended recipient is temporarily unavailable, undergoing maintenance, etc.; the associated error type SHOULD be "wait".
4885</p><div style='display: table; width: 0; margin-left: 3em; margin-right: auto'><pre>
4886C: &lt;presence
4887 from='juliet@im.example.com/balcony'
4888 id='y2bs71v4'
4889 to='characters@muc.example.com/JulieC'&gt;
4890 &lt;x xmlns='http://jabber.org/protocol/muc'/&gt;
4891 &lt;/presence&gt;
4892
4893E: &lt;presence
4894 from='characters@muc.example.com/JulieC'
4895 id='y2bs71v4'
4896 to='juliet@im.example.com/balcony'&gt;
4897 &lt;error type='wait'&gt;
4898 &lt;recipient-unavailable
4899 xmlns='urn:ietf:params:xml:ns:xmpp-stanzas'/&gt;
4900 &lt;/error&gt;
4901 &lt;/presence&gt;
4902</pre></div>
4903<p></p>
4904<blockquote class="text">
4905<p>Security Warning: An application MUST NOT return this error if doing so would provide information about the intended recipient's network availability to an entity that is not authorized to know such information (for a more detailed discussion of presence authorization, refer to the discussion of presence subscriptions in <a class='info' href='#XMPP-IM'>[XMPP&#8209;IM]<span> (</span><span class='info'>Saint-Andre, P., &ldquo;Extensible Messaging and Presence Protocol (XMPP): Instant Messaging and Presence,&rdquo; March&nbsp;2011.</span><span>)</span></a>); instead it MUST return a &lt;service-unavailable/&gt; stanza error (<a class='info' href='#stanzas-error-conditions-service-unavailable'>Section&nbsp;8.3.3.19<span> (</span><span class='info'>service-unavailable</span><span>)</span></a>).
4906</p>
4907</blockquote>
4908
4909<a name="stanzas-error-conditions-redirect"></a><br /><hr />
4910<table summary="layout" cellpadding="0" cellspacing="2" class="TOCbug" align="right"><tr><td class="TOCbug"><a href="#toc">&nbsp;TOC&nbsp;</a></td></tr></table>
4911<a name="rfc.section.8.3.3.14"></a><h3>8.3.3.14.&nbsp;
4912redirect</h3>
4913
4914<p>The recipient or server is redirecting requests for this information to another entity, typically in a temporary fashion (as opposed to the &lt;gone/&gt; error condition, which is used for permanent addressing failures); the associated error type SHOULD be "modify" and the error stanza SHOULD contain the alternate address in the XML character data of the &lt;redirect/&gt; element (which MUST be a URI or IRI with which the sender can communicate, typically an XMPP IRI as specified in <a class='info' href='#XMPP-URI'>[XMPP&#8209;URI]<span> (</span><span class='info'>Saint-Andre, P., &ldquo;Internationalized Resource Identifiers (IRIs) and Uniform Resource Identifiers (URIs) for the Extensible Messaging and Presence Protocol (XMPP),&rdquo; February&nbsp;2008.</span><span>)</span></a>).
4915</p><div style='display: table; width: 0; margin-left: 3em; margin-right: auto'><pre>
4916C: &lt;presence
4917 from='juliet@im.example.com/balcony'
4918 id='y2bs71v4'
4919 to='characters@muc.example.com/JulieC'&gt;
4920 &lt;x xmlns='http://jabber.org/protocol/muc'/&gt;
4921 &lt;/presence&gt;
4922
4923E: &lt;presence
4924 from='characters@muc.example.com/JulieC'
4925 id='y2bs71v4'
4926 to='juliet@im.example.com/balcony'
4927 type='error'&gt;
4928 &lt;error type='modify'&gt;
4929 &lt;redirect xmlns='urn:ietf:params:xml:ns:xmpp-stanzas'&gt;
4930 xmpp:characters@conference.example.org
4931 &lt;/redirect&gt;
4932 &lt;/error&gt;
4933 &lt;/presence&gt;
4934</pre></div>
4935<p></p>
4936<blockquote class="text">
4937<p>Security Warning: An application receiving a stanza-level redirect SHOULD warn a human user of the redirection attempt and request approval before proceeding to communicate with the entity whose address is contained in the XML character data of the &lt;redirect/&gt; element, because that entity might have a different identity or might enforce different security policies. The end-to-end authentication or signing of XMPP stanzas could help to mitigate this risk, since it would enable the sender to determine if the entity to which it has been redirected has the same identity as the entity it originally attempted to contact. An application MAY have a policy of following redirects only if it has authenticated the receiving entity. In addition, an application SHOULD abort the communication attempt after a certain number of successive redirects (e.g., at least 2 but no more than 5).
4938</p>
4939</blockquote>
4940
4941<a name="stanzas-error-conditions-registration-required"></a><br /><hr />
4942<table summary="layout" cellpadding="0" cellspacing="2" class="TOCbug" align="right"><tr><td class="TOCbug"><a href="#toc">&nbsp;TOC&nbsp;</a></td></tr></table>
4943<a name="rfc.section.8.3.3.15"></a><h3>8.3.3.15.&nbsp;
4944registration-required</h3>
4945
4946<p>The requesting entity is not authorized to access the requested service because prior registration is necessary (examples of prior registration include members-only rooms in XMPP multi-user chat <a class='info' href='#XEP-0045'>[XEP&#8209;0045]<span> (</span><span class='info'>Saint-Andre, P., &ldquo;Multi-User Chat,&rdquo; July&nbsp;2007.</span><span>)</span></a> and gateways to non-XMPP instant messaging services, which traditionally required registration in order to use the gateway <a class='info' href='#XEP-0100'>[XEP&#8209;0100]<span> (</span><span class='info'>Saint-Andre, P. and D. Smith, &ldquo;Gateway Interaction,&rdquo; October&nbsp;2005.</span><span>)</span></a>); the associated error type SHOULD be "auth".
4947</p><div style='display: table; width: 0; margin-left: 3em; margin-right: auto'><pre>
4948C: &lt;presence
4949 from='juliet@im.example.com/balcony'
4950 id='y2bs71v4'
4951 to='characters@muc.example.com/JulieC'&gt;
4952 &lt;x xmlns='http://jabber.org/protocol/muc'/&gt;
4953 &lt;/presence&gt;
4954
4955E: &lt;presence
4956 from='characters@muc.example.com/JulieC'
4957 id='y2bs71v4'
4958 to='juliet@im.example.com/balcony'&gt;
4959 &lt;error type='auth'&gt;
4960 &lt;registration-required
4961 xmlns='urn:ietf:params:xml:ns:xmpp-stanzas'/&gt;
4962 &lt;/error&gt;
4963 &lt;/presence&gt;
4964</pre></div>
4965<a name="stanzas-error-conditions-remote-server-not-found"></a><br /><hr />
4966<table summary="layout" cellpadding="0" cellspacing="2" class="TOCbug" align="right"><tr><td class="TOCbug"><a href="#toc">&nbsp;TOC&nbsp;</a></td></tr></table>
4967<a name="rfc.section.8.3.3.16"></a><h3>8.3.3.16.&nbsp;
4968remote-server-not-found</h3>
4969
4970<p>A remote server or service specified as part or all of the JID of the intended recipient does not exist or cannot be resolved (e.g., there is no _xmpp-server._tcp DNS SRV record, the A or AAAA fallback resolution fails, or A/AAAA lookups succeed but there is no response on the IANA-registered port 5269); the associated error type SHOULD be "cancel".
4971</p><div style='display: table; width: 0; margin-left: 3em; margin-right: auto'><pre>
4972C: &lt;message
4973 from='romeo@example.net/home'
4974 id='ud7n1f4h'
4975 to='bar@example.org'
4976 type='chat'&gt;
4977 &lt;body&gt;yt?&lt;/body&gt;
4978 &lt;/message&gt;
4979
4980E: &lt;message
4981 from='bar@example.org'
4982 id='ud7n1f4h'
4983 to='romeo@example.net/home'
4984 type='error'&gt;
4985 &lt;error type='cancel'&gt;
4986 &lt;remote-server-not-found
4987 xmlns='urn:ietf:params:xml:ns:xmpp-stanzas'/&gt;
4988 &lt;/error&gt;
4989 &lt;/message&gt;
4990</pre></div>
4991<a name="stanzas-error-conditions-remote-server-timeout"></a><br /><hr />
4992<table summary="layout" cellpadding="0" cellspacing="2" class="TOCbug" align="right"><tr><td class="TOCbug"><a href="#toc">&nbsp;TOC&nbsp;</a></td></tr></table>
4993<a name="rfc.section.8.3.3.17"></a><h3>8.3.3.17.&nbsp;
4994remote-server-timeout</h3>
4995
4996<p>A remote server or service specified as part or all of the JID of the intended recipient (or needed to fulfill a request) was resolved but communications could not be established within a reasonable amount of time (e.g., an XML stream cannot be established at the resolved IP address and port, or an XML stream can be established but stream negotiation fails because of problems with TLS, SASL, Server Dialback, etc.); the associated error type SHOULD be "wait" (unless the error is of a more permanent nature, e.g., the remote server is found but it cannot be authenticated or it violates security policies).
4997</p><div style='display: table; width: 0; margin-left: 3em; margin-right: auto'><pre>
4998C: &lt;message
4999 from='romeo@example.net/home'
5000 id='ud7n1f4h'
5001 to='bar@example.org'
5002 type='chat'&gt;
5003 &lt;body&gt;yt?&lt;/body&gt;
5004 &lt;/message&gt;
5005
5006E: &lt;message
5007 from='bar@example.org'
5008 id='ud7n1f4h'
5009 to='romeo@example.net/home'
5010 type='error'&gt;
5011 &lt;error type='wait'&gt;
5012 &lt;remote-server-timeout
5013 xmlns='urn:ietf:params:xml:ns:xmpp-stanzas'/&gt;
5014 &lt;/error&gt;
5015 &lt;/message&gt;
5016</pre></div>
5017<a name="stanzas-error-conditions-resource-constraint"></a><br /><hr />
5018<table summary="layout" cellpadding="0" cellspacing="2" class="TOCbug" align="right"><tr><td class="TOCbug"><a href="#toc">&nbsp;TOC&nbsp;</a></td></tr></table>
5019<a name="rfc.section.8.3.3.18"></a><h3>8.3.3.18.&nbsp;
5020resource-constraint</h3>
5021
5022<p>The server or recipient is busy or lacks the system resources necessary to service the request; the associated error type SHOULD be "wait".
5023</p><div style='display: table; width: 0; margin-left: 3em; margin-right: auto'><pre>
5024C: &lt;iq from='romeo@example.net/foo'
5025 id='kj4vz31m'
5026 to='pubsub.example.com'
5027 type='get'&gt;
5028 &lt;pubsub xmlns='http://jabber.org/protocol/pubsub'&gt;
5029 &lt;items node='my_musings'/&gt;
5030 &lt;/pubsub&gt;
5031 &lt;/iq&gt;
5032
5033E: &lt;iq from='pubsub.example.com'
5034 id='kj4vz31m'
5035 to='romeo@example.net/foo'
5036 type='error'&gt;
5037 &lt;error type='wait'&gt;
5038 &lt;resource-constraint
5039 xmlns='urn:ietf:params:xml:ns:xmpp-stanzas'/&gt;
5040 &lt;/error&gt;
5041 &lt;/iq&gt;
5042</pre></div>
5043<a name="stanzas-error-conditions-service-unavailable"></a><br /><hr />
5044<table summary="layout" cellpadding="0" cellspacing="2" class="TOCbug" align="right"><tr><td class="TOCbug"><a href="#toc">&nbsp;TOC&nbsp;</a></td></tr></table>
5045<a name="rfc.section.8.3.3.19"></a><h3>8.3.3.19.&nbsp;
5046service-unavailable</h3>
5047
5048<p>The server or recipient does not currently provide the requested service; the associated error type SHOULD be "cancel".
5049</p><div style='display: table; width: 0; margin-left: 3em; margin-right: auto'><pre>
5050C: &lt;message from='romeo@example.net/foo'
5051 to='juliet@im.example.com'&gt;
5052 &lt;body&gt;Hello?&lt;/body&gt;
5053 &lt;/message&gt;
5054
5055S: &lt;message from='juliet@im.example.com/foo'
5056 to='romeo@example.net'&gt;
5057 &lt;error type='cancel'&gt;
5058 &lt;service-unavailable
5059 xmlns='urn:ietf:params:xml:ns:xmpp-stanzas'/&gt;
5060 &lt;/error&gt;
5061 &lt;/message&gt;
5062</pre></div>
5063<p></p>
5064<blockquote class="text">
5065<p>Security Warning: An application MUST return a &lt;service-unavailable/&gt; stanza error (<a class='info' href='#stanzas-error-conditions-service-unavailable'>Section&nbsp;8.3.3.19<span> (</span><span class='info'>service-unavailable</span><span>)</span></a>) instead of &lt;item-not-found/&gt; (<a class='info' href='#stanzas-error-conditions-item-not-found'>Section&nbsp;8.3.3.7<span> (</span><span class='info'>item-not-found</span><span>)</span></a>) or &lt;recipient-unavailable/&gt; (<a class='info' href='#stanzas-error-conditions-recipient-unavailable'>Section&nbsp;8.3.3.13<span> (</span><span class='info'>recipient-unavailable</span><span>)</span></a>) if sending one of the latter errors would provide information about the intended recipient's network availability to an entity that is not authorized to know such information (for a more detailed discussion of presence authorization, refer to <a class='info' href='#XMPP-IM'>[XMPP&#8209;IM]<span> (</span><span class='info'>Saint-Andre, P., &ldquo;Extensible Messaging and Presence Protocol (XMPP): Instant Messaging and Presence,&rdquo; March&nbsp;2011.</span><span>)</span></a>).
5066</p>
5067</blockquote>
5068
5069<a name="stanzas-error-conditions-subscription-required"></a><br /><hr />
5070<table summary="layout" cellpadding="0" cellspacing="2" class="TOCbug" align="right"><tr><td class="TOCbug"><a href="#toc">&nbsp;TOC&nbsp;</a></td></tr></table>
5071<a name="rfc.section.8.3.3.20"></a><h3>8.3.3.20.&nbsp;
5072subscription-required</h3>
5073
5074<p>The requesting entity is not authorized to access the requested service because a prior subscription is necessary (examples of prior subscription include authorization to receive presence information as defined in <a class='info' href='#XMPP-IM'>[XMPP&#8209;IM]<span> (</span><span class='info'>Saint-Andre, P., &ldquo;Extensible Messaging and Presence Protocol (XMPP): Instant Messaging and Presence,&rdquo; March&nbsp;2011.</span><span>)</span></a> and opt-in data feeds for XMPP publish-subscribe as defined in <a class='info' href='#XEP-0060'>[XEP&#8209;0060]<span> (</span><span class='info'>Millard, P., Saint-Andre, P., and R. Meijer, &ldquo;Publish-Subscribe,&rdquo; July&nbsp;2010.</span><span>)</span></a>); the associated error type SHOULD be "auth".
5075</p><div style='display: table; width: 0; margin-left: 3em; margin-right: auto'><pre>
5076C: &lt;message
5077 from='romeo@example.net/orchard'
5078 id='pa73b4n7'
5079 to='playwright@shakespeare.example.com'
5080 type='chat'&gt;
5081 &lt;subject&gt;ACT II, SCENE II&lt;/subject&gt;
5082 &lt;body&gt;help, I forgot my lines!&lt;/body&gt;
5083 &lt;/message&gt;
5084
5085E: &lt;message
5086 from='playwright@shakespeare.example.com'
5087 id='pa73b4n7'
5088 to='romeo@example.net/orchard'
5089 type='error'&gt;
5090 &lt;error type='auth'&gt;
5091 &lt;subscription-required
5092 xmlns='urn:ietf:params:xml:ns:xmpp-stanzas'/&gt;
5093 &lt;/error&gt;
5094 &lt;/message&gt;
5095</pre></div>
5096<a name="stanzas-error-conditions-undefined-condition"></a><br /><hr />
5097<table summary="layout" cellpadding="0" cellspacing="2" class="TOCbug" align="right"><tr><td class="TOCbug"><a href="#toc">&nbsp;TOC&nbsp;</a></td></tr></table>
5098<a name="rfc.section.8.3.3.21"></a><h3>8.3.3.21.&nbsp;
5099undefined-condition</h3>
5100
5101<p>The error condition is not one of those defined by the
5102 other conditions in this list; any error type can be
5103 associated with this condition, and it SHOULD NOT be used except in conjunction with an application-specific condition.
5104</p><div style='display: table; width: 0; margin-left: 3em; margin-right: auto'><pre>
5105C: &lt;message
5106 from='northumberland@shakespeare.example'
5107 id='richard2-4.1.247'
5108 to='kingrichard@royalty.england.example'&gt;
5109 &lt;body&gt;My lord, dispatch; read o'er these articles.&lt;/body&gt;
5110 &lt;amp xmlns='http://jabber.org/protocol/amp'&gt;
5111 &lt;rule action='notify'
5112 condition='deliver'
5113 value='stored'/&gt;
5114 &lt;/amp&gt;
5115 &lt;/message&gt;
5116
5117S: &lt;message from='example.org'
5118 id='amp1'
5119 to='northumberland@example.net/field'
5120 type='error'&gt;
5121 &lt;amp xmlns='http://jabber.org/protocol/amp'
5122 from='kingrichard@example.org'
5123 status='error'
5124 to='northumberland@example.net/field'&gt;
5125 &lt;rule action='error'
5126 condition='deliver'
5127 value='stored'/&gt;
5128 &lt;/amp&gt;
5129 &lt;error type='modify'&gt;
5130 &lt;undefined-condition
5131 xmlns='urn:ietf:params:xml:ns:xmpp-stanzas'/&gt;
5132 &lt;failed-rules xmlns='http://jabber.org/protocol/amp#errors'&gt;
5133 &lt;rule action='error'
5134 condition='deliver'
5135 value='stored'/&gt;
5136 &lt;/failed-rules&gt;
5137 &lt;/error&gt;
5138 &lt;/message&gt;
5139</pre></div>
5140<a name="stanzas-error-conditions-unexpected-request"></a><br /><hr />
5141<table summary="layout" cellpadding="0" cellspacing="2" class="TOCbug" align="right"><tr><td class="TOCbug"><a href="#toc">&nbsp;TOC&nbsp;</a></td></tr></table>
5142<a name="rfc.section.8.3.3.22"></a><h3>8.3.3.22.&nbsp;
5143unexpected-request</h3>
5144
5145<p>The recipient or server understood the request but was not expecting it at this time (e.g., the request was out of order); the associated error type SHOULD be "wait" or "modify".
5146</p><div style='display: table; width: 0; margin-left: 3em; margin-right: auto'><pre>
5147C: &lt;iq from='romeo@example.net/foo'
5148 id='o6hsv25z'
5149 to='pubsub.example.com'
5150 type='set'&gt;
5151 &lt;pubsub xmlns='http://jabber.org/protocol/pubsub'&gt;
5152 &lt;unsubscribe
5153 node='my_musings'
5154 jid='romeo@example.net'/&gt;
5155 &lt;/pubsub&gt;
5156 &lt;/iq&gt;
5157
5158E: &lt;iq from='pubsub.example.com'
5159 id='o6hsv25z'
5160 to='romeo@example.net/foo'
5161 type='error'&gt;
5162 &lt;error type='modify'&gt;
5163 &lt;unexpected-request
5164 xmlns='urn:ietf:params:xml:ns:xmpp-stanzas'/&gt;
5165 &lt;not-subscribed
5166 xmlns='http://jabber.org/protocol/pubsub#errors'/&gt;
5167 &lt;/error&gt;
5168 &lt;/iq&gt;
5169</pre></div>
5170<a name="stanzas-error-app"></a><br /><hr />
5171<table summary="layout" cellpadding="0" cellspacing="2" class="TOCbug" align="right"><tr><td class="TOCbug"><a href="#toc">&nbsp;TOC&nbsp;</a></td></tr></table>
5172<a name="rfc.section.8.3.4"></a><h3>8.3.4.&nbsp;
5173Application-Specific Conditions</h3>
5174
5175<p>As noted, an application MAY provide application-specific stanza error information by including a properly namespaced child within the error element. Typically, the application-specific element supplements or further qualifies a defined element. Thus, the &lt;error/&gt; element will contain two or three child elements.
5176</p><div style='display: table; width: 0; margin-left: 3em; margin-right: auto'><pre>
5177&lt;iq id='ixc3v1b9' type='error'&gt;
5178 &lt;error type='modify'&gt;
5179 &lt;bad-request xmlns='urn:ietf:params:xml:ns:xmpp-stanzas'/&gt;
5180 &lt;too-many-parameters xmlns='http://example.org/ns'/&gt;
5181 &lt;/error&gt;
5182&lt;/iq&gt;
5183</pre></div><div style='display: table; width: 0; margin-left: 3em; margin-right: auto'><pre>
5184&lt;message type='error' id='7h3baci9'&gt;
5185 &lt;error type='modify'&gt;
5186 &lt;undefined-condition
5187 xmlns='urn:ietf:params:xml:ns:xmpp-stanzas'/&gt;
5188 &lt;text xml:lang='en'
5189 xmlns='urn:ietf:params:xml:ns:xmpp-stanzas'&gt;
5190 [ ... application-specific information ... ]
5191 &lt;/text&gt;
5192 &lt;too-many-parameters xmlns='http://example.org/ns'/&gt;
5193 &lt;/error&gt;
5194&lt;/message&gt;
5195</pre></div>
5196<p>An entity that receives an application-specific error condition it does not understand MUST ignore that condition but appropriately process the rest of the error stanza.
5197</p>
5198<a name="stanzas-extended"></a><br /><hr />
5199<table summary="layout" cellpadding="0" cellspacing="2" class="TOCbug" align="right"><tr><td class="TOCbug"><a href="#toc">&nbsp;TOC&nbsp;</a></td></tr></table>
5200<a name="rfc.section.8.4"></a><h3>8.4.&nbsp;
5201Extended Content</h3>
5202
5203<p>Although the message, presence, and IQ stanzas provide basic semantics for messaging, availability, and request-response interactions, XMPP uses XML namespaces (see <a class='info' href='#XML-NAMES'>[XML&#8209;NAMES]<span> (</span><span class='info'>Thompson, H., Hollander, D., Layman, A., Bray, T., and R. Tobin, &ldquo;Namespaces in XML 1.0 (Third Edition),&rdquo; December&nbsp;2009.</span><span>)</span></a>) to extend the basic stanza syntax for the purpose of providing additional functionality.
5204</p>
5205<p>A message or presence stanza MAY contain one or more optional child elements specifying content that extends the meaning of the message (e.g., an XHTML-formatted version of the message body as described in <a class='info' href='#XEP-0071'>[XEP&#8209;0071]<span> (</span><span class='info'>Saint-Andre, P., &ldquo;XHTML-IM,&rdquo; September&nbsp;2008.</span><span>)</span></a>), and an IQ stanza of type "get" or "set" MUST contain one such child element. Such a child element MAY have any name and MUST possess a namespace declaration (other than "jabber:client", "jabber:server", or "http://etherx.jabber.org/streams") that defines the data contained within the child element. Such a child element is called an "extension element". An extension element can be included either at the direct child level of the stanza or in any mix of levels.
5206</p>
5207<p>Similarly, "extension attributes" are allowed. That is: a stanza itself (i.e., an &lt;iq/&gt;, &lt;message/&gt;, or &lt;presence/&gt; element qualified by the "jabber:client" or "jabber:server" content namespace) or any child element of such a stanza (whether an extension element or a child element qualified by the content namespace) MAY also include one or more attributes qualified by XML namespaces other than the content namespace or the reserved "http://www.w3.org/XML/1998/namespace" namespace (including the so-called "empty namespace" if the attribute is not prefixed as described under <a class='info' href='#XML-NAMES'>[XML&#8209;NAMES]<span> (</span><span class='info'>Thompson, H., Hollander, D., Layman, A., Bray, T., and R. Tobin, &ldquo;Namespaces in XML 1.0 (Third Edition),&rdquo; December&nbsp;2009.</span><span>)</span></a>).
5208</p>
5209<p></p>
5210<blockquote class="text">
5211<p>Interoperability Note: For the sake of backward compatibility and maximum interoperability, an entity that generates a stanza SHOULD NOT include such attributes in the stanza itself or in child elements of the stanza that are qualified by the content namespaces "jabber:client" or "jabber:server" (e.g., the &lt;body/&gt; child of the &lt;message/&gt; stanza).
5212</p>
5213</blockquote>
5214
5215<p>An extension element or extension attribute is said to be "extended content" and the qualifying namespace for such an element or attribute is said to be an "extended namespace".
5216</p>
5217<p></p>
5218<blockquote class="text">
5219<p>Informational Note: Although extended namespaces for XMPP are commonly defined by the XMPP Standards Foundation (XSF) and by the IETF, no specification or IETF standards action is necessary to define extended namespaces, and any individual or organization is free to define XMPP extensions.
5220</p>
5221</blockquote>
5222
5223<p>To illustrate these concepts, several examples follow.
5224</p>
5225<p>The following stanza contains one direct child element whose extended namespace is 'jabber:iq:roster':
5226</p><div style='display: table; width: 0; margin-left: 3em; margin-right: auto'><pre>
5227&lt;iq from='juliet@capulet.com/balcony'
5228 id='h83vxa4c'
5229 type='get'&gt;
5230 &lt;query xmlns='jabber:iq:roster'/&gt;
5231&lt;/iq&gt;
5232</pre></div>
5233<p>The following stanza contains two direct child elements with two different extended namespaces.
5234</p><div style='display: table; width: 0; margin-left: 3em; margin-right: auto'><pre>
5235&lt;presence from='juliet@capulet.com/balcony'&gt;
5236 &lt;c xmlns='http://jabber.org/protocol/caps'
5237 hash='sha-1'
5238 node='http://code.google.com/p/exodus'
5239 ver='QgayPKawpkPSDYmwT/WM94uAlu0='/&gt;
5240 &lt;x xmlns='vcard-temp:x:update'&gt;
5241 &lt;photo&gt;sha1-hash-of-image&lt;/photo&gt;
5242 &lt;/x&gt;
5243&lt;/presence&gt;
5244</pre></div>
5245<p>The following stanza contains two child elements, one of which is qualified by the "jabber:client" or "jabber:server" content namespace and one of which is qualified by an extended namespace; the extension element in turn contains a child element that is qualified by a different extended namespace.
5246</p><div style='display: table; width: 0; margin-left: 3em; margin-right: auto'><pre>
5247&lt;message to='juliet@capulet.com'&gt;
5248 &lt;body&gt;Hello?&lt;/body&gt;
5249 &lt;html xmlns='http://jabber.org/protocol/xhtml-im'&gt;
5250 &lt;body xmlns='http://www.w3.org/1999/xhtml'&gt;
5251 &lt;p style='font-weight:bold'&gt;Hello?&lt;/p&gt;
5252 &lt;/body&gt;
5253 &lt;/html&gt;
5254&lt;/message&gt;
5255</pre></div>
5256<p>It is conventional in the XMPP community for implementations to not generate namespace prefixes for elements that are qualified by extended namespaces (in the XML community, this convention is sometimes called "prefix-free canonicalization"). However, if an implementation generates such namespace prefixes then it MUST include the namespace declaration in the stanza itself or a child element of the stanza, not in the stream header (see <a class='info' href='#streams-ns-other'>Section&nbsp;4.8.4<span> (</span><span class='info'>Other Namespaces</span><span>)</span></a>).
5257</p>
5258<p>Routing entities (typically servers) SHOULD try to maintain prefixes when serializing XML stanzas for processing, but receiving entities MUST NOT depend on the prefix strings to have any particular value (the allowance for the 'stream' prefix, described under <a class='info' href='#streams-ns-declarations'>Section&nbsp;4.8.5<span> (</span><span class='info'>Namespace Declarations and Prefixes</span><span>)</span></a>, is an exception to this rule, albeit for streams rather than stanzas).
5259</p>
5260<p>Support for any given extended namespace is OPTIONAL on the part of any implementation. If an entity does not understand such a namespace, the entity's expected behavior depends on whether the entity is (1) the recipient or (2) a server that is routing or delivering the stanza to the recipient.
5261</p>
5262<p>If a recipient receives a stanza that contains an element or attribute it does not understand, it MUST NOT attempt to process that XML data and instead MUST proceed as follows.
5263</p>
5264<p>
5265 </p>
5266<ul class="text">
5267<li>If an intended recipient receives a message stanza whose only child element is qualified by a namespace it does not understand, then depending on the XMPP application it MUST either ignore the entire stanza or return a stanza error, which SHOULD be &lt;service-unavailable/&gt; (<a class='info' href='#stanzas-error-conditions-service-unavailable'>Section&nbsp;8.3.3.19<span> (</span><span class='info'>service-unavailable</span><span>)</span></a>).
5268</li>
5269<li>If an intended recipient receives a presence stanza whose only child element is qualified by a namespace it does not understand, then it MUST ignore the child element by treating the presence stanza as if it contained no child element.
5270</li>
5271<li>If an intended recipient receives a message or presence stanza that contains XML data qualified by a namespace it does not understand, then it MUST ignore the portion of the stanza qualified by the unknown namespace.
5272</li>
5273<li>If an intended recipient receives an IQ stanza of type "get" or "set" containing a child element qualified by a namespace it does not understand, then the entity MUST return an IQ stanza of type "error" with an error condition of &lt;service-unavailable/&gt;.
5274</li>
5275</ul><p>
5276
5277</p>
5278<p>If a server handles a stanza that is intended for delivery to another entity and that contains a child element it does not understand, it MUST route the stanza unmodified to a remote server or deliver the stanza unmodified to a connected client associated with a local account.
5279</p>
5280<a name="examples"></a><br /><hr />
5281<table summary="layout" cellpadding="0" cellspacing="2" class="TOCbug" align="right"><tr><td class="TOCbug"><a href="#toc">&nbsp;TOC&nbsp;</a></td></tr></table>
5282<a name="rfc.section.9"></a><h3>9.&nbsp;
5283Detailed Examples</h3>
5284
5285<p>The detailed examples in this section further illustrate the protocols defined in this specification.
5286</p>
5287<a name="examples-c2s"></a><br /><hr />
5288<table summary="layout" cellpadding="0" cellspacing="2" class="TOCbug" align="right"><tr><td class="TOCbug"><a href="#toc">&nbsp;TOC&nbsp;</a></td></tr></table>
5289<a name="rfc.section.9.1"></a><h3>9.1.&nbsp;
5290Client-to-Server Examples</h3>
5291
5292<p>The following examples show the XMPP data flow for a client
5293negotiating an XML stream with a server, exchanging XML stanzas, and closing
5294the negotiated stream. The server is "im.example.com", the server requires use
5295of TLS, the client authenticates via the SASL SCRAM-SHA-1 mechanism as
5296&lt;juliet@im.example.com&gt; with a password of
5297 "r0m30myr0m30", and the client binds a client-submitted resource to the stream. It is assumed that before sending the initial stream header, the client has already resolved an SRV record of _xmpp&#8209;client._tcp.im.example.com and has opened a TCP connection to the advertised port at the resolved IP address.
5298</p>
5299<a name="examples-c2s-tls"></a><br /><hr />
5300<table summary="layout" cellpadding="0" cellspacing="2" class="TOCbug" align="right"><tr><td class="TOCbug"><a href="#toc">&nbsp;TOC&nbsp;</a></td></tr></table>
5301<a name="rfc.section.9.1.1"></a><h3>9.1.1.&nbsp;
5302TLS</h3>
5303
5304<p>Step 1: Client initiates stream to server:
5305</p><div style='display: table; width: 0; margin-left: 3em; margin-right: auto'><pre>
5306C: &lt;stream:stream
5307 from='juliet@im.example.com'
5308 to='im.example.com'
5309 version='1.0'
5310 xml:lang='en'
5311 xmlns='jabber:client'
5312 xmlns:stream='http://etherx.jabber.org/streams'&gt;
5313</pre></div>
5314<p>Step 2: Server responds by sending a response stream header to client:
5315</p><div style='display: table; width: 0; margin-left: 3em; margin-right: auto'><pre>
5316S: &lt;stream:stream
5317 from='im.example.com'
5318 id='t7AMCin9zjMNwQKDnplntZPIDEI='
5319 to='juliet@im.example.com'
5320 version='1.0'
5321 xml:lang='en'
5322 xmlns='jabber:client'
5323 xmlns:stream='http://etherx.jabber.org/streams'&gt;
5324</pre></div>
5325<p>Step 3: Server sends stream features to client (only the STARTTLS extension at this point, which is mandatory-to-negotiate):
5326</p><div style='display: table; width: 0; margin-left: 3em; margin-right: auto'><pre>
5327S: &lt;stream:features&gt;
5328 &lt;starttls xmlns='urn:ietf:params:xml:ns:xmpp-tls'&gt;
5329 &lt;required/&gt;
5330 &lt;/starttls&gt;
5331 &lt;/stream:features&gt;
5332</pre></div>
5333<p>Step 4: Client sends STARTTLS command to server:
5334</p><div style='display: table; width: 0; margin-left: 3em; margin-right: auto'><pre>
5335C: &lt;starttls xmlns='urn:ietf:params:xml:ns:xmpp-tls'/&gt;
5336</pre></div>
5337<p>Step 5: Server informs client that it is allowed to proceed:
5338</p><div style='display: table; width: 0; margin-left: 3em; margin-right: auto'><pre>
5339S: &lt;proceed xmlns='urn:ietf:params:xml:ns:xmpp-tls'/&gt;
5340</pre></div>
5341<p>Step 5 (alt): Server informs client that STARTTLS negotiation has failed, closes the XML stream, and terminates the TCP connection (thus, the stream negotiation process ends unsuccessfully and the parties do not move on to the next step):
5342</p><div style='display: table; width: 0; margin-left: 3em; margin-right: auto'><pre>
5343S: &lt;failure xmlns='urn:ietf:params:xml:ns:xmpp-tls'/&gt;
5344 &lt;/stream:stream&gt;
5345</pre></div>
5346<p>Step 6: Client and server attempt to complete TLS negotiation over the existing TCP connection (see <a class='info' href='#TLS'>[TLS]<span> (</span><span class='info'>Dierks, T. and E. Rescorla, &ldquo;The Transport Layer Security (TLS) Protocol Version 1.2,&rdquo; August&nbsp;2008.</span><span>)</span></a> for details).
5347</p>
5348<p>Step 7: If TLS negotiation is successful, client initiates a new stream to server over the TLS-protected TCP connection:
5349</p><div style='display: table; width: 0; margin-left: 3em; margin-right: auto'><pre>
5350C: &lt;stream:stream
5351 from='juliet@im.example.com'
5352 to='im.example.com'
5353 version='1.0'
5354 xml:lang='en'
5355 xmlns='jabber:client'
5356 xmlns:stream='http://etherx.jabber.org/streams'&gt;
5357</pre></div>
5358<p>Step 7 (alt): If TLS negotiation is unsuccessful, server closes TCP connection (thus, the stream negotiation process ends unsuccessfully and the parties do not move on to the next step):
5359</p>
5360<a name="examples-c2s-sasl"></a><br /><hr />
5361<table summary="layout" cellpadding="0" cellspacing="2" class="TOCbug" align="right"><tr><td class="TOCbug"><a href="#toc">&nbsp;TOC&nbsp;</a></td></tr></table>
5362<a name="rfc.section.9.1.2"></a><h3>9.1.2.&nbsp;
5363SASL</h3>
5364
5365<p>Step 8: Server responds by sending a stream header to client along with any available stream features:
5366</p><div style='display: table; width: 0; margin-left: 3em; margin-right: auto'><pre>
5367S: &lt;stream:stream
5368 from='im.example.com'
5369 id='vgKi/bkYME8OAj4rlXMkpucAqe4='
5370 to='juliet@im.example.com'
5371 version='1.0'
5372 xml:lang='en'
5373 xmlns='jabber:client'
5374 xmlns:stream='http://etherx.jabber.org/streams'&gt;
5375
5376S: &lt;stream:features&gt;
5377 &lt;mechanisms xmlns='urn:ietf:params:xml:ns:xmpp-sasl'&gt;
5378 &lt;mechanism&gt;SCRAM-SHA-1-PLUS&lt;/mechanism&gt;
5379 &lt;mechanism&gt;SCRAM-SHA-1&lt;/mechanism&gt;
5380 &lt;mechanism&gt;PLAIN&lt;/mechanism&gt;
5381 &lt;/mechanisms&gt;
5382 &lt;/stream:features&gt;
5383</pre></div>
5384<p>Step 9: Client selects an authentication mechanism
5385 (in this case, SCRAM-SHA-1), including initial response data:
5386</p><div style='display: table; width: 0; margin-left: 3em; margin-right: auto'><pre>
5387C: &lt;auth xmlns="urn:ietf:params:xml:ns:xmpp-sasl"
5388 mechanism="SCRAM-SHA-1"&gt;
5389 biwsbj1qdWxpZXQscj1vTXNUQUF3QUFBQU1BQUFBTlAwVEFBQUFBQUJQVTBBQQ==
5390 &lt;/auth&gt;
5391</pre></div>
5392<p>The decoded base 64 data is "n,,n=juliet,r=oMsTAAwAAAAMAAAANP0TAAAAAABPU0AA".
5393</p>
5394<p>Step 10: Server sends a challenge:
5395</p><div style='display: table; width: 0; margin-left: 3em; margin-right: auto'><pre>
5396S: &lt;challenge xmlns="urn:ietf:params:xml:ns:xmpp-sasl"&gt;
5397 cj1vTXNUQUF3QUFBQU1BQUFBTlAwVEFBQUFBQUJQVTBBQWUxMjQ2OTViLTY5Y
5398 TktNGRlNi05YzMwLWI1MWIzODA4YzU5ZSxzPU5qaGtZVE0wTURndE5HWTBaaT
5399 AwTmpkbUxUa3hNbVV0TkRsbU5UTm1ORE5rTURNeixpPTQwOTY=
5400 &lt;/challenge&gt;
5401</pre></div>
5402<p>The decoded base 64 data is "r=oMsTAAwAAAAMAAAANP0TAAAAAABPU0AAe124695b-69a9-4de6-9c30-b51b3808c59e,s=NjhkYTM0MDgtNGY0Zi00NjdmLTkxMmUtNDlmNTNmNDNkMDMz,i=4096" (line breaks not included in actual data).
5403</p>
5404<p>Step 11: Client sends a response:
5405</p><div style='display: table; width: 0; margin-left: 3em; margin-right: auto'><pre>
5406C: &lt;response xmlns="urn:ietf:params:xml:ns:xmpp-sasl"&gt;
5407 Yz1iaXdzLHI9b01zVEFBd0FBQUFNQUFBQU5QMFRBQUFBQUFCUFUwQUFlMTI0N
5408 jk1Yi02OWE5LTRkZTYtOWMzMC1iNTFiMzgwOGM1OWUscD1VQTU3dE0vU3ZwQV
5409 RCa0gyRlhzMFdEWHZKWXc9
5410 &lt;/response&gt;
5411</pre></div>
5412<p>
5413 The decoded base 64 data is "c=biws,r=oMsTAAwAAAAMAAAANP0TAAAAAABPU0
5414 AAe124695b-69a9-4de6-9c30-b51b3808c59e,p=UA57tM/
5415 SvpATBkH2FXs0WDXvJYw=" (line breaks not included in actual data).
5416
5417</p>
5418<p>Step 12: Server informs client of success, including additional data with success:
5419</p><div style='display: table; width: 0; margin-left: 3em; margin-right: auto'><pre>
5420S: &lt;success xmlns='urn:ietf:params:xml:ns:xmpp-sasl'&gt;
5421 dj1wTk5ERlZFUXh1WHhDb1NFaVc4R0VaKzFSU289
5422 &lt;/success&gt;
5423</pre></div>
5424<p>The decoded base 64 data is "v=pNNDFVEQxuXxCoSEiW8GEZ+1RSo=".
5425</p>
5426<p>Step 12 (alt): Server returns a SASL error to client (thus, the stream negotiation process ends unsuccessfully and the parties do not move on to the next step):
5427</p><div style='display: table; width: 0; margin-left: 3em; margin-right: auto'><pre>
5428S: &lt;failure xmlns='urn:ietf:params:xml:ns:xmpp-sasl'&gt;
5429 &lt;not-authorized/&gt;
5430 &lt;/failure&gt;
5431 &lt;/stream&gt;
5432</pre></div>
5433<p>Step 13: Client initiates a new stream to server:
5434</p><div style='display: table; width: 0; margin-left: 3em; margin-right: auto'><pre>
5435C: &lt;stream:stream
5436 from='juliet@im.example.com'
5437 to='im.example.com'
5438 version='1.0'
5439 xml:lang='en'
5440 xmlns='jabber:client'
5441 xmlns:stream='http://etherx.jabber.org/streams'&gt;
5442</pre></div>
5443<a name="examples-c2s-bind"></a><br /><hr />
5444<table summary="layout" cellpadding="0" cellspacing="2" class="TOCbug" align="right"><tr><td class="TOCbug"><a href="#toc">&nbsp;TOC&nbsp;</a></td></tr></table>
5445<a name="rfc.section.9.1.3"></a><h3>9.1.3.&nbsp;
5446Resource Binding</h3>
5447
5448<p>Step 14: Server responds by sending a stream header to client along with supported features (in this case, resource binding):
5449</p><div style='display: table; width: 0; margin-left: 3em; margin-right: auto'><pre>
5450S: &lt;stream:stream
5451 from='im.example.com'
5452 id='gPybzaOzBmaADgxKXu9UClbprp0='
5453 to='juliet@im.example.com'
5454 version='1.0'
5455 xml:lang='en'
5456 xmlns='jabber:client'
5457 xmlns:stream='http://etherx.jabber.org/streams'&gt;
5458
5459S: &lt;stream:features&gt;
5460 &lt;bind xmlns='urn:ietf:params:xml:ns:xmpp-bind'/&gt;
5461 &lt;/stream:features&gt;
5462</pre></div>
5463<p>Upon being informed that resource binding is mandatory-to-negotiate, the client needs to bind a resource to the stream; here we assume that the client submits a human-readable text string.
5464</p>
5465<p>Step 15: Client binds a resource:
5466</p><div style='display: table; width: 0; margin-left: 3em; margin-right: auto'><pre>
5467C: &lt;iq id='yhc13a95' type='set'&gt;
5468 &lt;bind xmlns='urn:ietf:params:xml:ns:xmpp-bind'&gt;
5469 &lt;resource&gt;balcony&lt;/resource&gt;
5470 &lt;/bind&gt;
5471 &lt;/iq&gt;
5472</pre></div>
5473<p>Step 16: Server accepts submitted resourcepart and informs client of successful resource binding:
5474</p><div style='display: table; width: 0; margin-left: 3em; margin-right: auto'><pre>
5475S: &lt;iq id='yhc13a95' type='result'&gt;
5476 &lt;bind xmlns='urn:ietf:params:xml:ns:xmpp-bind'&gt;
5477 &lt;jid&gt;
5478 juliet@im.example.com/balcony
5479 &lt;/jid&gt;
5480 &lt;/bind&gt;
5481 &lt;/iq&gt;
5482</pre></div>
5483<p>Step 16 (alt): Server returns error to client (thus, the stream negotiation process ends unsuccessfully and the parties do not move on to the next step):
5484</p><div style='display: table; width: 0; margin-left: 3em; margin-right: auto'><pre>
5485S: &lt;iq id='yhc13a95' type='error'&gt;
5486 &lt;error type='cancel'&gt;
5487 &lt;conflict xmlns='urn:ietf:params:xml:ns:xmpp-stanzas'/&gt;
5488 &lt;/error&gt;
5489 &lt;/iq&gt;
5490</pre></div>
5491<a name="examples-c2s-stanzas"></a><br /><hr />
5492<table summary="layout" cellpadding="0" cellspacing="2" class="TOCbug" align="right"><tr><td class="TOCbug"><a href="#toc">&nbsp;TOC&nbsp;</a></td></tr></table>
5493<a name="rfc.section.9.1.4"></a><h3>9.1.4.&nbsp;
5494Stanza Exchange</h3>
5495
5496<p>Now the client is allowed to send XML stanzas over the negotiated stream.
5497</p><div style='display: table; width: 0; margin-left: 3em; margin-right: auto'><pre>
5498C: &lt;message from='juliet@im.example.com/balcony'
5499 id='ju2ba41c'
5500 to='romeo@example.net'
5501 type='chat'
5502 xml:lang='en'&gt;
5503 &lt;body&gt;Art thou not Romeo, and a Montague?&lt;/body&gt;
5504 &lt;/message&gt;
5505</pre></div>
5506<p>If necessary, sender's server negotiates XML streams with intended recipient's server (see <a class='info' href='#examples-s2s'>Section&nbsp;9.2<span> (</span><span class='info'>Server-to-Server Examples</span><span>)</span></a>).
5507</p>
5508<p>The intended recipient replies, and the message is delivered to the client.
5509</p><div style='display: table; width: 0; margin-left: 3em; margin-right: auto'><pre>
5510E: &lt;message from='romeo@example.net/orchard'
5511 id='ju2ba41c'
5512 to='juliet@im.example.com/balcony'
5513 type='chat'
5514 xml:lang='en'&gt;
5515 &lt;body&gt;Neither, fair saint, if either thee dislike.&lt;/body&gt;
5516 &lt;/message&gt;
5517</pre></div>
5518<p>The client can subsequently send and receive an unbounded number of subsequent XML stanzas over the stream.
5519</p>
5520<a name="examples-c2s-close"></a><br /><hr />
5521<table summary="layout" cellpadding="0" cellspacing="2" class="TOCbug" align="right"><tr><td class="TOCbug"><a href="#toc">&nbsp;TOC&nbsp;</a></td></tr></table>
5522<a name="rfc.section.9.1.5"></a><h3>9.1.5.&nbsp;
5523Close</h3>
5524
5525<p>Desiring to send no further messages, the client closes its stream to the server but waits for incoming data from the server.
5526</p><div style='display: table; width: 0; margin-left: 3em; margin-right: auto'><pre>
5527C: &lt;/stream:stream&gt;
5528</pre></div>
5529<p>Consistent with <a class='info' href='#streams-close'>Section&nbsp;4.4<span> (</span><span class='info'>Closing a Stream</span><span>)</span></a>, the server might send additional data to the client and then closes its stream to the client.
5530</p><div style='display: table; width: 0; margin-left: 3em; margin-right: auto'><pre>
5531S: &lt;/stream:stream&gt;
5532</pre></div>
5533<p>The client now sends a TLS close_notify alert, receives a responding close_notify alert from the server, and then terminates the underlying TCP connection.
5534</p>
5535<a name="examples-s2s"></a><br /><hr />
5536<table summary="layout" cellpadding="0" cellspacing="2" class="TOCbug" align="right"><tr><td class="TOCbug"><a href="#toc">&nbsp;TOC&nbsp;</a></td></tr></table>
5537<a name="rfc.section.9.2"></a><h3>9.2.&nbsp;
5538Server-to-Server Examples</h3>
5539
5540<p>The following examples show the data flow for a server negotiating an XML stream with a peer server, exchanging XML stanzas, and closing the negotiated stream. The initiating server ("Server1") is im.example.com; the receiving server ("Server2") is example.net and it requires use of TLS; im.example.com presents a certificate and authenticates via the SASL EXTERNAL mechanism. It is assumed that before sending the initial stream header, Server1 has already resolved an SRV record of _xmpp-server._tcp.example.net and has opened a TCP connection to the advertised port at the resolved IP address. Note how Server1 declares the content namespace "jabber:server" as the default namespace and uses prefixes for stream-related elements, whereas Server2 uses prefix-free canonicalization.
5541</p>
5542<a name="examples-s2s-tls"></a><br /><hr />
5543<table summary="layout" cellpadding="0" cellspacing="2" class="TOCbug" align="right"><tr><td class="TOCbug"><a href="#toc">&nbsp;TOC&nbsp;</a></td></tr></table>
5544<a name="rfc.section.9.2.1"></a><h3>9.2.1.&nbsp;
5545TLS</h3>
5546
5547<p>Step 1: Server1 initiates stream to Server2:
5548</p><div style='display: table; width: 0; margin-left: 3em; margin-right: auto'><pre>
5549S1: &lt;stream:stream
5550 from='im.example.com'
5551 to='example.net'
5552 version='1.0'
5553 xmlns='jabber:server'
5554 xmlns:stream='http://etherx.jabber.org/streams'&gt;
5555</pre></div>
5556<p>Step 2: Server2 responds by sending a response stream header to Server1:
5557</p><div style='display: table; width: 0; margin-left: 3em; margin-right: auto'><pre>
5558S2: &lt;stream
5559 from='example.net'
5560 id='hTiXkW+ih9k2SqdGkk/AZi0OJ/Q='
5561 to='im.example.com'
5562 version='1.0'
5563 xmlns='http://etherx.jabber.org/streams'&gt;
5564</pre></div>
5565<p>Step 3: Server2 sends stream features to Server1 (only the STARTTLS extension at this point, which is mandatory-to-negotiate):
5566</p><div style='display: table; width: 0; margin-left: 3em; margin-right: auto'><pre>
5567S2: &lt;features xmlns='http://etherx.jabber.org/streams'&gt;
5568 &lt;starttls xmlns='urn:ietf:params:xml:ns:xmpp-tls'&gt;
5569 &lt;required/&gt;
5570 &lt;/starttls&gt;
5571 &lt;/features&gt;
5572</pre></div>
5573<p>Step 4: Server1 sends the STARTTLS command to Server2:
5574</p><div style='display: table; width: 0; margin-left: 3em; margin-right: auto'><pre>
5575S1: &lt;starttls xmlns='urn:ietf:params:xml:ns:xmpp-tls'/&gt;
5576</pre></div>
5577<p>Step 5: Server2 informs Server1 that it is allowed to proceed:
5578</p><div style='display: table; width: 0; margin-left: 3em; margin-right: auto'><pre>
5579S2: &lt;proceed xmlns='urn:ietf:params:xml:ns:xmpp-tls'/&gt;
5580</pre></div>
5581<p>Step 5 (alt): Server2 informs Server1 that STARTTLS negotiation has failed, closes the stream, and terminates the TCP connection (thus, the stream negotiation process ends unsuccessfully and the parties do not move on to the next step):
5582</p><div style='display: table; width: 0; margin-left: 3em; margin-right: auto'><pre>
5583S2: &lt;failure xmlns='urn:ietf:params:xml:ns:xmpp-tls'/&gt;
5584 &lt;/stream&gt;
5585</pre></div>
5586<p>Step 6: Server1 and Server2 attempt to complete TLS negotiation via TCP (see <a class='info' href='#TLS'>[TLS]<span> (</span><span class='info'>Dierks, T. and E. Rescorla, &ldquo;The Transport Layer Security (TLS) Protocol Version 1.2,&rdquo; August&nbsp;2008.</span><span>)</span></a> for details).
5587</p>
5588<p>Step 7: If TLS negotiation is successful, Server1 initiates a new stream to Server2 over the TLS-protected TCP connection:
5589</p><div style='display: table; width: 0; margin-left: 3em; margin-right: auto'><pre>
5590S1: &lt;stream:stream
5591 from='im.example.com'
5592 to='example.net'
5593 version='1.0'
5594 xmlns='jabber:server'
5595 xmlns:stream='http://etherx.jabber.org/streams'&gt;
5596</pre></div>
5597<p>Step 7 (alt): If TLS negotiation is unsuccessful, Server2
5598 closes the TCP connection (thus, the stream negotiation process ends unsuccessfully and the parties do not move on to the next step).
5599</p>
5600<a name="examples-s2s-sasl"></a><br /><hr />
5601<table summary="layout" cellpadding="0" cellspacing="2" class="TOCbug" align="right"><tr><td class="TOCbug"><a href="#toc">&nbsp;TOC&nbsp;</a></td></tr></table>
5602<a name="rfc.section.9.2.2"></a><h3>9.2.2.&nbsp;
5603SASL</h3>
5604
5605<p>Step 8: Server2 sends a response stream header to Server1 along with available stream features (including a preference for the SASL EXTERNAL mechanism):
5606</p><div style='display: table; width: 0; margin-left: 3em; margin-right: auto'><pre>
5607S2: &lt;stream
5608 from='example.net'
5609 id='RChdjlgj/TIBcbT9Keu31zDihH4='
5610 to='im.example.com'
5611 version='1.0'
5612 xmlns='http://etherx.jabber.org/streams'&gt;
5613
5614S2: &lt;features xmlns='http://etherx.jabber.org/streams'&gt;
5615 &lt;mechanisms xmlns='urn:ietf:params:xml:ns:xmpp-sasl'&gt;
5616 &lt;mechanism&gt;EXTERNAL&lt;/mechanism&gt;
5617 &lt;/mechanisms&gt;
5618 &lt;/features&gt;
5619</pre></div>
5620<p>Step 9: Server1 selects the EXTERNAL mechanism (including an empty response of "="):
5621</p><div style='display: table; width: 0; margin-left: 3em; margin-right: auto'><pre>
5622S1: &lt;auth xmlns='urn:ietf:params:xml:ns:xmpp-sasl'
5623 mechanism='EXTERNAL'&gt;=&lt;/auth&gt;
5624</pre></div>
5625<p>Step 10: Server2 returns success:
5626</p><div style='display: table; width: 0; margin-left: 3em; margin-right: auto'><pre>
5627S2: &lt;success xmlns='urn:ietf:params:xml:ns:xmpp-sasl'/&gt;
5628</pre></div>
5629<p>Step 10 (alt): Server2 informs Server1 of failed authentication (thus, the stream negotiation process ends unsuccessfully and the parties do not move on to the next step):
5630</p><div style='display: table; width: 0; margin-left: 3em; margin-right: auto'><pre>
5631S2: &lt;failure xmlns='urn:ietf:params:xml:ns:xmpp-sasl'&gt;
5632 &lt;not-authorized/&gt;
5633 &lt;/failure&gt;
5634 &lt;/stream&gt;
5635</pre></div>
5636<p>Step 11: Server1 initiates a new stream to Server2:
5637</p><div style='display: table; width: 0; margin-left: 3em; margin-right: auto'><pre>
5638S1: &lt;stream:stream
5639 from='im.example.com'
5640 to='example.net'
5641 version='1.0'
5642 xmlns='jabber:server'
5643 xmlns:stream='http://etherx.jabber.org/streams'&gt;
5644</pre></div>
5645<p>Step 12: Server2 responds by sending a stream header to Server1 along with any additional features (or, in this case, an empty features element):
5646</p><div style='display: table; width: 0; margin-left: 3em; margin-right: auto'><pre>
5647S2: &lt;stream
5648 from='example.net'
5649 id='MbbV2FeojySpUIP6J91qaa+TWHM='
5650 to='im.example.com'
5651 version='1.0'
5652 xmlns='http://etherx.jabber.org/streams'&gt;
5653
5654S2: &lt;features xmlns='http://etherx.jabber.org/streams'/&gt;
5655</pre></div>
5656<a name="examples-s2s-stanzas"></a><br /><hr />
5657<table summary="layout" cellpadding="0" cellspacing="2" class="TOCbug" align="right"><tr><td class="TOCbug"><a href="#toc">&nbsp;TOC&nbsp;</a></td></tr></table>
5658<a name="rfc.section.9.2.3"></a><h3>9.2.3.&nbsp;
5659Stanza Exchange</h3>
5660
5661<p>Now Server1 is allowed to send XML stanzas to Server2 over the negotiated stream from im.example.com to example.net; here we assume that the transferred stanzas are those shown earlier for client-to-server communication, albeit over a server-to-server stream qualified by the 'jabber:server' namespace.
5662</p>
5663<p>Server1 sends XML stanza to Server2:
5664</p><div style='display: table; width: 0; margin-left: 3em; margin-right: auto'><pre>
5665S1: &lt;message from='juliet@im.example.com/balcony'
5666 id='ju2ba41c'
5667 to='romeo@example.net'
5668 type='chat'
5669 xml:lang='en'&gt;
5670 &lt;body&gt;Art thou not Romeo, and a Montague?&lt;/body&gt;
5671 &lt;/message&gt;
5672</pre></div>
5673<a name="examples-s2s-close"></a><br /><hr />
5674<table summary="layout" cellpadding="0" cellspacing="2" class="TOCbug" align="right"><tr><td class="TOCbug"><a href="#toc">&nbsp;TOC&nbsp;</a></td></tr></table>
5675<a name="rfc.section.9.2.4"></a><h3>9.2.4.&nbsp;
5676Close</h3>
5677
5678<p>Desiring to send no further messages, Server1 closes its stream to Server2 but waits for incoming data from Server2. (In practice, the stream would most likely remain open for some time, since Server1 and Server2 do not immediately know if the stream will be needed for further communication.)
5679</p><div style='display: table; width: 0; margin-left: 3em; margin-right: auto'><pre>
5680S1: &lt;/stream:stream&gt;
5681</pre></div>
5682<p>Consistent with the recommended stream closing handshake, Server2 closes the stream as well:
5683</p><div style='display: table; width: 0; margin-left: 3em; margin-right: auto'><pre>
5684S2: &lt;/stream&gt;
5685</pre></div>
5686<p>Server1 now sends a TLS close_notify alert, receives a responding close_notify alert from Server2, and then terminates the underlying TCP connection.
5687</p>
5688<a name="rules"></a><br /><hr />
5689<table summary="layout" cellpadding="0" cellspacing="2" class="TOCbug" align="right"><tr><td class="TOCbug"><a href="#toc">&nbsp;TOC&nbsp;</a></td></tr></table>
5690<a name="rfc.section.10"></a><h3>10.&nbsp;
5691Server Rules for Processing XML Stanzas</h3>
5692
5693<p>Each server implementation will contain its own logic for processing stanzas it receives. Such logic determines whether the server needs to route a given stanza to another domain, deliver it to a local entity (typically a connected client associated with a local account), or handle it directly within the server itself. This section provides general rules for processing XML stanzas. However, particular XMPP applications MAY specify delivery rules that modify or supplement the following rules (e.g., a set of delivery rules for instant messaging and presence applications is defined in <a class='info' href='#XMPP-IM'>[XMPP&#8209;IM]<span> (</span><span class='info'>Saint-Andre, P., &ldquo;Extensible Messaging and Presence Protocol (XMPP): Instant Messaging and Presence,&rdquo; March&nbsp;2011.</span><span>)</span></a>).
5694</p>
5695<a name="rules-order"></a><br /><hr />
5696<table summary="layout" cellpadding="0" cellspacing="2" class="TOCbug" align="right"><tr><td class="TOCbug"><a href="#toc">&nbsp;TOC&nbsp;</a></td></tr></table>
5697<a name="rfc.section.10.1"></a><h3>10.1.&nbsp;
5698In-Order Processing</h3>
5699
5700<p>An XMPP server MUST ensure in-order processing of the stanzas and other XML elements it receives over a given input stream from a connected client or remote server.
5701</p>
5702<p>In-order processing applies (a) to any XML elements used to negotiate and manage XML streams, and (b) to all uses of XML stanzas, including but not limited to the following:
5703</p>
5704<p>
5705 </p>
5706<ol class="text">
5707<li>Stanzas sent by a client to its server or to its own bare JID for direct processing by the server (e.g., in-order processing of a roster get and initial presence as described in <a class='info' href='#XMPP-IM'>[XMPP&#8209;IM]<span> (</span><span class='info'>Saint-Andre, P., &ldquo;Extensible Messaging and Presence Protocol (XMPP): Instant Messaging and Presence,&rdquo; March&nbsp;2011.</span><span>)</span></a>).
5708</li>
5709<li>Stanzas sent by a connected client and intended for delivery to another entity associated with the server (e.g., stanzas addressed from &lt;juliet@im.example.com&gt; to &lt;nurse@im.example.com&gt;). The server MUST ensure that it delivers stanzas addressed to the intended recipient in the order it receives them over the input stream from the sending client, treating stanzas addressed to the bare JID and the full JID of the intended recipient as equivalent for delivery purposes.
5710</li>
5711<li>Stanzas sent by a connected client and intended for delivery to an entity located at a remote domain (e.g., stanzas addressed from &lt;juliet@im.example.com&gt; to &lt;romeo@example.net&gt;). The routing server MUST ensure that it routes stanzas addressed to the intended recipient in the order it receives them over the input stream from the sending client, treating stanzas addressed to the bare JID and the full JID of the intended recipient as equivalent for routing purposes. To help ensure in-order processing, the routing server MUST route such stanzas over a single output stream to the remote domain, rather than sending some stanzas over one server-to-server stream and other stanzas over another server-to-server stream.
5712</li>
5713<li>Stanzas routed from one server to another server for delivery to an entity associated with the remote domain (e.g., stanzas addressed from &lt;juliet@im.example.com&gt; to &lt;romeo@example.net&gt; and routed by &lt;im.example.com&gt; over a server-to-server stream to &lt;example.net&gt;). The delivering server MUST ensure that it delivers stanzas to the intended recipient in the order it receives them over the input stream from the routing server, treating stanzas addressed to the bare JID and the full JID of the intended recipient as equivalent for delivery purposes.
5714</li>
5715<li>Stanzas sent by one server to another server for direct processing by the server that is hosting the remote domain (e.g., stanzas addressed from &lt;im.example.com&gt; to &lt;example.net&gt;).
5716</li>
5717</ol><p>
5718
5719</p>
5720<p>If the server's processing of a particular request could have an effect on its processing of subsequent data it might receive over that input stream (e.g., enforcement of communication policies), it MUST suspend processing of subsequent data until it has processed the request.
5721</p>
5722<p>In-order processing applies only to a single input stream. Therefore, a server is not responsible for ensuring the coherence of data it receives across multiple input streams associated with the same local account (e.g., stanzas received over two different input streams from &lt;juliet@im.example.com/balcony&gt; and &lt;juliet@im.example.com/chamber&gt;) or the same remote domain (e.g., two different input streams negotiated by a remote domain; however, a server MAY close the stream with a &lt;conflict/&gt; stream error (<a class='info' href='#streams-error-conditions-conflict'>Section&nbsp;4.9.3.3<span> (</span><span class='info'>conflict</span><span>)</span></a>) if a remote server attempts to negotiate more than one stream, as described under <a class='info' href='#streams-error-conditions-conflict'>Section&nbsp;4.9.3.3<span> (</span><span class='info'>conflict</span><span>)</span></a>).
5723</p>
5724<a name="rules-gen"></a><br /><hr />
5725<table summary="layout" cellpadding="0" cellspacing="2" class="TOCbug" align="right"><tr><td class="TOCbug"><a href="#toc">&nbsp;TOC&nbsp;</a></td></tr></table>
5726<a name="rfc.section.10.2"></a><h3>10.2.&nbsp;
5727General Considerations</h3>
5728
5729<p>At high level, there are three primary considerations at play in server processing of XML stanzas, which sometimes are at odds but need to be managed in a consistent way:
5730</p>
5731<p>
5732 </p>
5733<ol class="text">
5734<li>It is good to deliver a stanza to the intended recipient if possible.
5735</li>
5736<li>If a stanza cannot be delivered, it is helpful to inform the sender.
5737</li>
5738<li>It is bad to facilitate directory harvesting attacks (<a class='info' href='#security-harvesting'>Section&nbsp;13.11<span> (</span><span class='info'>Directory Harvesting</span><span>)</span></a>) and presence leaks (<a class='info' href='#security-leaks-presence'>Section&nbsp;13.10.2<span> (</span><span class='info'>Presence Information</span><span>)</span></a>).
5739</li>
5740</ol><p>
5741
5742</p>
5743<p>With regard to possible delivery-related attacks, the following points need to be kept in mind:
5744</p>
5745<p>
5746 </p>
5747<ol class="text">
5748<li>From the perspective of an attacker, there is little if any effective difference between the server's (i) delivering the stanza or storing it offline for later delivery (see <a class='info' href='#XMPP-IM'>[XMPP&#8209;IM]<span> (</span><span class='info'>Saint-Andre, P., &ldquo;Extensible Messaging and Presence Protocol (XMPP): Instant Messaging and Presence,&rdquo; March&nbsp;2011.</span><span>)</span></a>) and (ii) silently ignoring it (because an error is not returned immediately in any of those cases); therefore, in scenarios where a server delivers a stanza or places the stanza into offline storage for later delivery, it needs to silently ignore the stanza if that account does not exist.
5749</li>
5750<li>How a server processes stanzas sent to the bare JID &lt;localpart@domainpart&gt; has implications for directory harvesting, because an attacker could determine whether an account exists if the server responds differently depending on whether there is an account for a given bare JID.
5751</li>
5752<li>How a server processes stanzas sent to a full JID has implications for presence leaks, because an attacker could send requests to multiple full JIDs and receive different replies depending on whether the user has a device currently online at that full JID. The use of randomized resourceparts (whether generated by the client or the server as described under <a class='info' href='#bind'>Section&nbsp;7<span> (</span><span class='info'>Resource Binding</span><span>)</span></a>) significantly helps to mitigate this attack, so it is of somewhat lesser concern than the directory harvesting attack.
5753</li>
5754</ol><p>
5755
5756</p>
5757<p>Naturally, presence is not leaked if the entity to which a user's server returns an error already knows the user's presence or is authorized to do so (e.g., by means of a presence subscription or directed presence), and a server does not enable a directory harvesting attack if it returns an error to an entity that already knows if a user exists (e.g., because the entity is in the user's contact list); these matters are discussed more fully in <a class='info' href='#XMPP-IM'>[XMPP&#8209;IM]<span> (</span><span class='info'>Saint-Andre, P., &ldquo;Extensible Messaging and Presence Protocol (XMPP): Instant Messaging and Presence,&rdquo; March&nbsp;2011.</span><span>)</span></a>.
5758</p>
5759<a name="rules-noto"></a><br /><hr />
5760<table summary="layout" cellpadding="0" cellspacing="2" class="TOCbug" align="right"><tr><td class="TOCbug"><a href="#toc">&nbsp;TOC&nbsp;</a></td></tr></table>
5761<a name="rfc.section.10.3"></a><h3>10.3.&nbsp;
5762No 'to' Address</h3>
5763
5764<p>If the stanza possesses no 'to' attribute, the server MUST handle it directly on behalf of the entity that sent it, where the meaning of "handle it directly" depends on whether the stanza is message, presence, or IQ. Because all stanzas received from other servers MUST possess a 'to' attribute, this rule applies only to stanzas received from a local entity (typically a client) that is connected to the server.
5765</p>
5766<a name="rules-noto-message"></a><br /><hr />
5767<table summary="layout" cellpadding="0" cellspacing="2" class="TOCbug" align="right"><tr><td class="TOCbug"><a href="#toc">&nbsp;TOC&nbsp;</a></td></tr></table>
5768<a name="rfc.section.10.3.1"></a><h3>10.3.1.&nbsp;
5769Message</h3>
5770
5771<p>If the server receives a message stanza with no 'to' attribute, it MUST treat the message as if the 'to' address were the bare JID &lt;localpart@domainpart&gt; of the sending entity.
5772</p>
5773<a name="rules-noto-presence"></a><br /><hr />
5774<table summary="layout" cellpadding="0" cellspacing="2" class="TOCbug" align="right"><tr><td class="TOCbug"><a href="#toc">&nbsp;TOC&nbsp;</a></td></tr></table>
5775<a name="rfc.section.10.3.2"></a><h3>10.3.2.&nbsp;
5776Presence</h3>
5777
5778<p>If the server receives a presence stanza with no 'to' attribute, it MUST broadcast it to the entities that are subscribed to the sending entity's presence, if applicable (<a class='info' href='#XMPP-IM'>[XMPP&#8209;IM]<span> (</span><span class='info'>Saint-Andre, P., &ldquo;Extensible Messaging and Presence Protocol (XMPP): Instant Messaging and Presence,&rdquo; March&nbsp;2011.</span><span>)</span></a> defines the semantics of such broadcasting for presence applications).
5779</p>
5780<a name="rules-noto-IQ"></a><br /><hr />
5781<table summary="layout" cellpadding="0" cellspacing="2" class="TOCbug" align="right"><tr><td class="TOCbug"><a href="#toc">&nbsp;TOC&nbsp;</a></td></tr></table>
5782<a name="rfc.section.10.3.3"></a><h3>10.3.3.&nbsp;
5783IQ</h3>
5784
5785<p>If the server receives an IQ stanza with no 'to' attribute, it MUST process the stanza on behalf of the account from which received the stanza, as follows:
5786</p>
5787<p>
5788 </p>
5789<ol class="text">
5790<li>If the IQ stanza is of type "get" or "set" and the server understands the namespace that qualifies the payload, the server MUST handle the stanza on behalf of the sending entity or return an appropriate error to the sending entity. Although the meaning of "handle" is determined by the semantics of the qualifying namespace, in general the server will respond to the IQ stanza of type "get" or "set" by returning an appropriate IQ stanza of type "result" or "error", responding as if the server were the bare JID of the sending entity. As an example, if the sending entity sends an IQ stanza of type "get" where the payload is qualified by the 'jabber:iq:roster' namespace (as described in <a class='info' href='#XMPP-IM'>[XMPP&#8209;IM]<span> (</span><span class='info'>Saint-Andre, P., &ldquo;Extensible Messaging and Presence Protocol (XMPP): Instant Messaging and Presence,&rdquo; March&nbsp;2011.</span><span>)</span></a>), then the server will return the roster associated with the sending entity's bare JID to the particular resource of the sending entity that requested the roster.
5791</li>
5792<li>If the IQ stanza is of type "get" or "set" and the server does not understand the namespace that qualifies the payload, the server MUST return an error to the sending entity, which MUST be &lt;service-unavailable/&gt;.
5793</li>
5794<li>If the IQ stanza is of type "error" or "result", the server MUST handle the error or result in accordance with the payload of the associated IQ stanza or type "get" or "set" (if there is no such associated stanza, the server MUST ignore the error or result stanza).
5795</li>
5796</ol><p>
5797
5798</p>
5799<a name="rules-remote"></a><br /><hr />
5800<table summary="layout" cellpadding="0" cellspacing="2" class="TOCbug" align="right"><tr><td class="TOCbug"><a href="#toc">&nbsp;TOC&nbsp;</a></td></tr></table>
5801<a name="rfc.section.10.4"></a><h3>10.4.&nbsp;
5802Remote Domain</h3>
5803
5804<p>If the domainpart of the JID contained in the 'to' attribute does not match one of the configured FQDNs of the server, the server SHOULD attempt to route the stanza to the remote domain (subject to local service provisioning and security policies regarding inter-domain communication, since such communication is OPTIONAL for any given deployment). As described in the following sections, there are two possible cases.
5805</p>
5806<p></p>
5807<blockquote class="text">
5808<p>Security Warning: These rules apply only client-to-server streams. As described under <a class='info' href='#stanzas-attributes-to-s2s'>Section&nbsp;8.1.1.2<span> (</span><span class='info'>Server-to-Server Streams</span><span>)</span></a>, a server MUST NOT accept a stanza over a server-to-server stream if the domainpart of the JID in the 'to' attribute does not match an FQDN serviced by the receiving server.
5809</p>
5810</blockquote>
5811
5812<a name="rules-remote-existing"></a><br /><hr />
5813<table summary="layout" cellpadding="0" cellspacing="2" class="TOCbug" align="right"><tr><td class="TOCbug"><a href="#toc">&nbsp;TOC&nbsp;</a></td></tr></table>
5814<a name="rfc.section.10.4.1"></a><h3>10.4.1.&nbsp;
5815Existing Stream</h3>
5816
5817<p>If a server-to-server stream already exists between the two domains, the sender's server SHOULD attempt to route the stanza to the authoritative server for the remote domain over the existing stream.
5818</p>
5819<a name="rules-remote-nostream"></a><br /><hr />
5820<table summary="layout" cellpadding="0" cellspacing="2" class="TOCbug" align="right"><tr><td class="TOCbug"><a href="#toc">&nbsp;TOC&nbsp;</a></td></tr></table>
5821<a name="rfc.section.10.4.2"></a><h3>10.4.2.&nbsp;
5822No Existing Stream</h3>
5823
5824<p>If there exists no server-to-server stream between the two domains, the sender's server will proceed as follows:
5825</p>
5826<p>
5827 </p>
5828<ol class="text">
5829<li>Resolve the FQDN of the remote domain (as described under <a class='info' href='#security-reuse-dns'>Section&nbsp;13.9.2<span> (</span><span class='info'>Use of DNS</span><span>)</span></a>).
5830</li>
5831<li>Negotiate a server-to-server stream between the two domains (as defined under <a class='info' href='#tls'>Section&nbsp;5<span> (</span><span class='info'>STARTTLS Negotiation</span><span>)</span></a> and <a class='info' href='#sasl'>Section&nbsp;6<span> (</span><span class='info'>SASL Negotiation</span><span>)</span></a>).
5832</li>
5833<li>Route the stanza to the authoritative server for the remote domain over the newly established stream.
5834</li>
5835</ol><p>
5836
5837</p>
5838<a name="rules-remote-error"></a><br /><hr />
5839<table summary="layout" cellpadding="0" cellspacing="2" class="TOCbug" align="right"><tr><td class="TOCbug"><a href="#toc">&nbsp;TOC&nbsp;</a></td></tr></table>
5840<a name="rfc.section.10.4.3"></a><h3>10.4.3.&nbsp;
5841Error Handling</h3>
5842
5843<p>If routing of a stanza to the intended recipient's server is unsuccessful, the sender's server MUST return an error to the sender. If resolution of the remote domain is unsuccessful, the stanza error MUST be &lt;remote-server-not-found/&gt; (<a class='info' href='#stanzas-error-conditions-remote-server-not-found'>Section&nbsp;8.3.3.16<span> (</span><span class='info'>remote-server-not-found</span><span>)</span></a>). If resolution succeeds but streams cannot be negotiated, the stanza error MUST be &lt;remote-server-timeout/&gt; (<a class='info' href='#stanzas-error-conditions-remote-server-timeout'>Section&nbsp;8.3.3.17<span> (</span><span class='info'>remote-server-timeout</span><span>)</span></a>).
5844</p>
5845<p>If stream negotiation with the intended recipient's server is successful but the remote server cannot deliver the stanza to the recipient, the remote server MUST return an appropriate error to the sender by way of the sender's server.
5846</p>
5847<a name="rules-local"></a><br /><hr />
5848<table summary="layout" cellpadding="0" cellspacing="2" class="TOCbug" align="right"><tr><td class="TOCbug"><a href="#toc">&nbsp;TOC&nbsp;</a></td></tr></table>
5849<a name="rfc.section.10.5"></a><h3>10.5.&nbsp;
5850Local Domain</h3>
5851
5852<p>If the domainpart of the JID contained in the 'to' attribute matches one of the configured FQDNs of the server, the server MUST first determine if the FQDN is serviced by the server itself or by a specialized local service. If the latter, the server MUST route the stanza to that service. If the former, the server MUST proceed as follows. However, the server MUST NOT route or "forward" the stanza to another domain, because it is the server's responsibility to process all stanzas for which the domainpart of the 'to' address matches one of the configured FQDNs of the server (among other things, this helps to prevent looping).
5853</p>
5854<a name="rules-local-domain"></a><br /><hr />
5855<table summary="layout" cellpadding="0" cellspacing="2" class="TOCbug" align="right"><tr><td class="TOCbug"><a href="#toc">&nbsp;TOC&nbsp;</a></td></tr></table>
5856<a name="rfc.section.10.5.1"></a><h3>10.5.1.&nbsp;
5857domainpart</h3>
5858
5859<p>If the JID contained in the 'to' attribute is of the form &lt;domainpart&gt;, then the server MUST either (a) handle the stanza as appropriate for the stanza kind or (b) return an error stanza to the sender.
5860</p>
5861<a name="rules-local-domainresource"></a><br /><hr />
5862<table summary="layout" cellpadding="0" cellspacing="2" class="TOCbug" align="right"><tr><td class="TOCbug"><a href="#toc">&nbsp;TOC&nbsp;</a></td></tr></table>
5863<a name="rfc.section.10.5.2"></a><h3>10.5.2.&nbsp;
5864domainpart/resourcepart</h3>
5865
5866<p>If the JID contained in the 'to' attribute is of the form &lt;domainpart/resourcepart&gt;, then the server MUST either (a) handle the stanza as appropriate for the stanza kind or (b) return an error stanza to the sender.
5867</p>
5868<a name="rules-local-barejid"></a><br /><hr />
5869<table summary="layout" cellpadding="0" cellspacing="2" class="TOCbug" align="right"><tr><td class="TOCbug"><a href="#toc">&nbsp;TOC&nbsp;</a></td></tr></table>
5870<a name="rfc.section.10.5.3"></a><h3>10.5.3.&nbsp;
5871localpart@domainpart</h3>
5872
5873<p>An address of this type is normally associated with an account on the server. The following rules provide some general guidelines; more detailed rules in the context of instant messaging and presence applications are provided in <a class='info' href='#XMPP-IM'>[XMPP&#8209;IM]<span> (</span><span class='info'>Saint-Andre, P., &ldquo;Extensible Messaging and Presence Protocol (XMPP): Instant Messaging and Presence,&rdquo; March&nbsp;2011.</span><span>)</span></a>.
5874</p>
5875<a name="rules-local-barejid-nosuchuser"></a><br /><hr />
5876<table summary="layout" cellpadding="0" cellspacing="2" class="TOCbug" align="right"><tr><td class="TOCbug"><a href="#toc">&nbsp;TOC&nbsp;</a></td></tr></table>
5877<a name="rfc.section.10.5.3.1"></a><h3>10.5.3.1.&nbsp;
5878No Such User</h3>
5879
5880<p>If there is no local account associated with the &lt;localpart@domainpart&gt;, how the stanza is processed depends on the stanza type.
5881</p>
5882<p>
5883 </p>
5884<ul class="text">
5885<li>For a message stanza, the server MUST either (a) silently ignore the stanza or (b) return a &lt;service-unavailable/&gt; stanza error (<a class='info' href='#stanzas-error-conditions-service-unavailable'>Section&nbsp;8.3.3.19<span> (</span><span class='info'>service-unavailable</span><span>)</span></a>) to the sender.
5886</li>
5887<li>For a presence stanza, the server SHOULD ignore the stanza (or behave as described in <a class='info' href='#XMPP-IM'>[XMPP&#8209;IM]<span> (</span><span class='info'>Saint-Andre, P., &ldquo;Extensible Messaging and Presence Protocol (XMPP): Instant Messaging and Presence,&rdquo; March&nbsp;2011.</span><span>)</span></a>).
5888</li>
5889<li>For an IQ stanza, the server MUST return a &lt;service-unavailable/&gt; stanza error (<a class='info' href='#stanzas-error-conditions-service-unavailable'>Section&nbsp;8.3.3.19<span> (</span><span class='info'>service-unavailable</span><span>)</span></a>) to the sender.
5890</li>
5891</ul><p>
5892
5893</p>
5894<a name="rules-local-barejid-userexists"></a><br /><hr />
5895<table summary="layout" cellpadding="0" cellspacing="2" class="TOCbug" align="right"><tr><td class="TOCbug"><a href="#toc">&nbsp;TOC&nbsp;</a></td></tr></table>
5896<a name="rfc.section.10.5.3.2"></a><h3>10.5.3.2.&nbsp;
5897User Exists</h3>
5898
5899<p>If the JID contained in the 'to' attribute is of the form &lt;localpart@domainpart&gt;, how the stanza is processed depends on the stanza type.
5900</p>
5901<p>
5902 </p>
5903<ul class="text">
5904<li>For a message stanza, if there exists at least one connected resource for the account then the server SHOULD deliver it to at least one of the connected resources. If there exists no connected resource then the server MUST either (a) store the message offline for delivery when the account next has a connected resource or (b) return a &lt;service-unavailable/&gt; stanza error (<a class='info' href='#stanzas-error-conditions-service-unavailable'>Section&nbsp;8.3.3.19<span> (</span><span class='info'>service-unavailable</span><span>)</span></a>).
5905</li>
5906<li>For a presence stanza, if there exists at least one connected resource that has sent initial presence (i.e., has a "presence session" as defined in <a class='info' href='#XMPP-IM'>[XMPP&#8209;IM]<span> (</span><span class='info'>Saint-Andre, P., &ldquo;Extensible Messaging and Presence Protocol (XMPP): Instant Messaging and Presence,&rdquo; March&nbsp;2011.</span><span>)</span></a>) then the server SHOULD deliver it to such resources. If there exists no connected resource then the server SHOULD ignore the stanza (or behave as described in <a class='info' href='#XMPP-IM'>[XMPP&#8209;IM]<span> (</span><span class='info'>Saint-Andre, P., &ldquo;Extensible Messaging and Presence Protocol (XMPP): Instant Messaging and Presence,&rdquo; March&nbsp;2011.</span><span>)</span></a>).
5907</li>
5908<li>For an IQ stanza, the server MUST handle it directly on behalf of the intended recipient.
5909</li>
5910</ul><p>
5911
5912</p>
5913<a name="rules-local-fulljid"></a><br /><hr />
5914<table summary="layout" cellpadding="0" cellspacing="2" class="TOCbug" align="right"><tr><td class="TOCbug"><a href="#toc">&nbsp;TOC&nbsp;</a></td></tr></table>
5915<a name="rfc.section.10.5.4"></a><h3>10.5.4.&nbsp;
5916localpart@domainpart/resourcepart</h3>
5917
5918<p>If the JID contained in the 'to' attribute is of the form &lt;localpart@domainpart/resourcepart&gt; and the user exists but there is no connected resource that exactly matches the full JID, the stanza SHOULD be processed as if the JID were of the form &lt;localpart@domainpart&gt; as described under <a class='info' href='#rules-local-barejid-userexists'>Section&nbsp;10.5.3.2<span> (</span><span class='info'>User Exists</span><span>)</span></a>.
5919</p>
5920<p>If the JID contained in the 'to' attribute is of the form &lt;localpart@domainpart/resourcepart&gt;, the user exists, and there is a connected resource that exactly matches the full JID, the server MUST deliver the stanza to that connected resource.
5921</p>
5922<a name="xml"></a><br /><hr />
5923<table summary="layout" cellpadding="0" cellspacing="2" class="TOCbug" align="right"><tr><td class="TOCbug"><a href="#toc">&nbsp;TOC&nbsp;</a></td></tr></table>
5924<a name="rfc.section.11"></a><h3>11.&nbsp;
5925XML Usage</h3>
5926
5927<a name="xml-restrictions"></a><br /><hr />
5928<table summary="layout" cellpadding="0" cellspacing="2" class="TOCbug" align="right"><tr><td class="TOCbug"><a href="#toc">&nbsp;TOC&nbsp;</a></td></tr></table>
5929<a name="rfc.section.11.1"></a><h3>11.1.&nbsp;
5930XML Restrictions</h3>
5931
5932<p>XMPP defines a class of data objects called XML streams as well as the behavior of computer programs that process XML streams. XMPP is an application profile or restricted form of the Extensible Markup Language <a class='info' href='#XML'>[XML]<span> (</span><span class='info'>Maler, E., Yergeau, F., Sperberg-McQueen, C., Paoli, J., and T. Bray, &ldquo;Extensible Markup Language (XML) 1.0 (Fifth Edition),&rdquo; November&nbsp;2008.</span><span>)</span></a>, and a complete XML stream (including start and end stream tags) is a conforming XML document.
5933</p>
5934<p>However, XMPP does not deal with XML documents but with XML streams. Because XMPP does not require the parsing of arbitrary and complete XML documents, there is no requirement that XMPP needs to support the full feature set of <a class='info' href='#XML'>[XML]<span> (</span><span class='info'>Maler, E., Yergeau, F., Sperberg-McQueen, C., Paoli, J., and T. Bray, &ldquo;Extensible Markup Language (XML) 1.0 (Fifth Edition),&rdquo; November&nbsp;2008.</span><span>)</span></a>. Furthermore, XMPP uses XML to define protocol data structures and extensions for the purpose of structured interactions between network entities and therefore adheres to the recommendations provided in <a class='info' href='#XML-GUIDE'>[XML&#8209;GUIDE]<span> (</span><span class='info'>Hollenbeck, S., Rose, M., and L. Masinter, &ldquo;Guidelines for the Use of Extensible Markup Language (XML) within IETF Protocols,&rdquo; January&nbsp;2003.</span><span>)</span></a> regarding restrictions on the use of XML in IETF protocols. As a result, the following features of XML are prohibited in XMPP:
5935</p>
5936<p>
5937 </p>
5938<ul class="text">
5939<li>comments (as defined in Section 2.5 of <a class='info' href='#XML'>[XML]<span> (</span><span class='info'>Maler, E., Yergeau, F., Sperberg-McQueen, C., Paoli, J., and T. Bray, &ldquo;Extensible Markup Language (XML) 1.0 (Fifth Edition),&rdquo; November&nbsp;2008.</span><span>)</span></a>)
5940</li>
5941<li>processing instructions (Section 2.6 therein)
5942</li>
5943<li>internal or external DTD subsets (Section 2.8 therein)
5944</li>
5945<li>internal or external entity references (Section 4.2 therein) with the exception of the predefined entities (Section 4.6 therein)
5946</li>
5947</ul><p>
5948
5949</p>
5950<p>An XMPP implementation MUST behave as follows with regard to these features:
5951</p>
5952<p>
5953 </p>
5954<ol class="text">
5955<li>An XMPP implementation MUST NOT inject characters matching such features into an XML stream.
5956</li>
5957<li>If an XMPP implementation receives characters matching such features over an XML stream, it MUST close the stream with a stream error, which SHOULD be &lt;restricted-xml/&gt; (<a class='info' href='#streams-error-conditions-restricted-xml'>Section&nbsp;4.9.3.18<span> (</span><span class='info'>restricted-xml</span><span>)</span></a>), although some existing implementations send &lt;bad-format/&gt; (<a class='info' href='#streams-error-conditions-bad-format'>Section&nbsp;4.9.3.1<span> (</span><span class='info'>bad-format</span><span>)</span></a>) instead.
5958</li>
5959</ol><p>
5960
5961</p>
5962<a name="xml-ns"></a><br /><hr />
5963<table summary="layout" cellpadding="0" cellspacing="2" class="TOCbug" align="right"><tr><td class="TOCbug"><a href="#toc">&nbsp;TOC&nbsp;</a></td></tr></table>
5964<a name="rfc.section.11.2"></a><h3>11.2.&nbsp;
5965XML Namespace Names and Prefixes</h3>
5966
5967<p>XML namespaces (see <a class='info' href='#XML-NAMES'>[XML&#8209;NAMES]<span> (</span><span class='info'>Thompson, H., Hollander, D., Layman, A., Bray, T., and R. Tobin, &ldquo;Namespaces in XML 1.0 (Third Edition),&rdquo; December&nbsp;2009.</span><span>)</span></a>) are used within XMPP streams to create strict boundaries of data ownership. The basic function of namespaces is to separate different vocabularies of XML elements that are structurally mixed together. Ensuring that XMPP streams are namespace-aware enables any allowable XML to be structurally mixed with any data element within XMPP. XMPP-specific rules for XML namespace names and prefixes are defined under <a class='info' href='#streams-ns'>Section&nbsp;4.8<span> (</span><span class='info'>XML Namespaces</span><span>)</span></a> for XML streams and <a class='info' href='#stanzas-extended'>Section&nbsp;8.4<span> (</span><span class='info'>Extended Content</span><span>)</span></a> for XML stanzas.
5968</p>
5969<a name="xml-wellformed"></a><br /><hr />
5970<table summary="layout" cellpadding="0" cellspacing="2" class="TOCbug" align="right"><tr><td class="TOCbug"><a href="#toc">&nbsp;TOC&nbsp;</a></td></tr></table>
5971<a name="rfc.section.11.3"></a><h3>11.3.&nbsp;
5972Well-Formedness</h3>
5973
5974<p>In XML, there are two varieties of well-formedness:
5975</p>
5976<p>
5977 </p>
5978<ul class="text">
5979<li>"XML-well-formedness" in accordance with the definition of "well-formed" from Section 2.1 of <a class='info' href='#XML'>[XML]<span> (</span><span class='info'>Maler, E., Yergeau, F., Sperberg-McQueen, C., Paoli, J., and T. Bray, &ldquo;Extensible Markup Language (XML) 1.0 (Fifth Edition),&rdquo; November&nbsp;2008.</span><span>)</span></a>.
5980</li>
5981<li>"Namespace-well-formedness" in accordance with the definition of "namespace-well-formed" from Section 7 of <a class='info' href='#XML-NAMES'>[XML&#8209;NAMES]<span> (</span><span class='info'>Thompson, H., Hollander, D., Layman, A., Bray, T., and R. Tobin, &ldquo;Namespaces in XML 1.0 (Third Edition),&rdquo; December&nbsp;2009.</span><span>)</span></a>.
5982</li>
5983</ul><p>
5984
5985</p>
5986<p>The following rules apply:
5987</p>
5988<p>
5989 </p>
5990<ol class="text">
5991<li>An XMPP entity MUST NOT generate data that is not XML-well-formed.
5992</li>
5993<li>An XMPP entity MUST NOT accept data that is not XML-well-formed; instead it MUST close the stream over which the data was received with a &lt;not-well-formed/&gt; stream error (<a class='info' href='#streams-error-conditions-not-well-formed'>Section&nbsp;4.9.3.13<span> (</span><span class='info'>not-well-formed</span><span>)</span></a>).
5994</li>
5995<li>An XMPP entity MUST NOT generate data that is not namespace-well-formed.
5996</li>
5997<li>An XMPP entity MUST NOT accept data that is not namespace-well-formed (in particular, an XMPP server MUST NOT route or deliver data that is not namespace-well-formed); instead it MUST return either a &lt;not-acceptable/&gt; stanza error (<a class='info' href='#stanzas-error-conditions-not-acceptable'>Section&nbsp;8.3.3.9<span> (</span><span class='info'>not-acceptable</span><span>)</span></a>) or close the stream with a &lt;not-well-formed/&gt; stream error (<a class='info' href='#streams-error-conditions-not-well-formed'>Section&nbsp;4.9.3.13<span> (</span><span class='info'>not-well-formed</span><span>)</span></a>), where it is preferable to close the stream with a stream error because accepting such data can open an entity to certain denial-of-service attacks.
5998</li>
5999</ol><p>
6000
6001</p>
6002<p></p>
6003<blockquote class="text">
6004<p>Interoperability Note: Because these restrictions were underspecified in <a class='info' href='#RFC3920'>[RFC3920]<span> (</span><span class='info'>Saint-Andre, P., Ed., &ldquo;Extensible Messaging and Presence Protocol (XMPP): Core,&rdquo; October&nbsp;2004.</span><span>)</span></a>, it is possible that implementations based on that specification will send data that does not comply with these restrictions.
6005</p>
6006</blockquote>
6007
6008<a name="xml-validation"></a><br /><hr />
6009<table summary="layout" cellpadding="0" cellspacing="2" class="TOCbug" align="right"><tr><td class="TOCbug"><a href="#toc">&nbsp;TOC&nbsp;</a></td></tr></table>
6010<a name="rfc.section.11.4"></a><h3>11.4.&nbsp;
6011Validation</h3>
6012
6013<p>A server is not responsible for ensuring that XML data delivered to a connected client or routed to a peer server is valid, in accordance with the definition of "valid" provided in Section 2.8 of <a class='info' href='#XML'>[XML]<span> (</span><span class='info'>Maler, E., Yergeau, F., Sperberg-McQueen, C., Paoli, J., and T. Bray, &ldquo;Extensible Markup Language (XML) 1.0 (Fifth Edition),&rdquo; November&nbsp;2008.</span><span>)</span></a>. An implementation MAY choose to accept or send only data that has been explicitly validated against the schemas provided in this document, but such behavior is OPTIONAL. Clients are advised not to rely on the ability to send data that does not conform to the schemas, and SHOULD ignore any non-conformant elements or attributes on the incoming XML stream.
6014</p>
6015<p></p>
6016<blockquote class="text">
6017<p>Informational Note: The terms "valid" and "well-formed" are distinct in XML.
6018</p>
6019</blockquote>
6020
6021<a name="xml-declaration"></a><br /><hr />
6022<table summary="layout" cellpadding="0" cellspacing="2" class="TOCbug" align="right"><tr><td class="TOCbug"><a href="#toc">&nbsp;TOC&nbsp;</a></td></tr></table>
6023<a name="rfc.section.11.5"></a><h3>11.5.&nbsp;
6024Inclusion of XML Declaration</h3>
6025
6026<p>Before sending a stream header, an implementation SHOULD send an XML declaration (matching the "XMLDecl" production from <a class='info' href='#XML'>[XML]<span> (</span><span class='info'>Maler, E., Yergeau, F., Sperberg-McQueen, C., Paoli, J., and T. Bray, &ldquo;Extensible Markup Language (XML) 1.0 (Fifth Edition),&rdquo; November&nbsp;2008.</span><span>)</span></a>). Applications MUST follow the rules provided in <a class='info' href='#XML'>[XML]<span> (</span><span class='info'>Maler, E., Yergeau, F., Sperberg-McQueen, C., Paoli, J., and T. Bray, &ldquo;Extensible Markup Language (XML) 1.0 (Fifth Edition),&rdquo; November&nbsp;2008.</span><span>)</span></a> regarding the format of the XML declaration and the circumstances under which the XML declaration is included.
6027</p>
6028<p>Because external markup declarations are prohibited in XMPP (as described under <a class='info' href='#xml-restrictions'>Section&nbsp;11.1<span> (</span><span class='info'>XML Restrictions</span><span>)</span></a>), the standalone document declaration (matching the "SDDecl" production from <a class='info' href='#XML'>[XML]<span> (</span><span class='info'>Maler, E., Yergeau, F., Sperberg-McQueen, C., Paoli, J., and T. Bray, &ldquo;Extensible Markup Language (XML) 1.0 (Fifth Edition),&rdquo; November&nbsp;2008.</span><span>)</span></a>) would have no meaning and therefore MUST NOT be included in an XML declaration sent over an XML stream. If an XMPP entity receives an XML declaration containing a standalone document declaration set to a value of "no", the entity MUST either ignore the standalone document declaration or close the stream with a stream error, which SHOULD be &lt;restricted-xml/&gt; (<a class='info' href='#streams-error-conditions-restricted-xml'>Section&nbsp;4.9.3.18<span> (</span><span class='info'>restricted-xml</span><span>)</span></a>).
6029</p>
6030<a name="xml-encoding"></a><br /><hr />
6031<table summary="layout" cellpadding="0" cellspacing="2" class="TOCbug" align="right"><tr><td class="TOCbug"><a href="#toc">&nbsp;TOC&nbsp;</a></td></tr></table>
6032<a name="rfc.section.11.6"></a><h3>11.6.&nbsp;
6033Character Encoding</h3>
6034
6035<p>Implementations MUST support the UTF-8 transformation of Universal Character Set <a class='info' href='#UCS2'>[UCS2]<span> (</span><span class='info'>International Organization for Standardization, &ldquo;Information Technology - Universal Multiple-octet coded Character Set (UCS) - Amendment 2: UCS Transformation Format 8 (UTF-8),&rdquo; October&nbsp;1996.</span><span>)</span></a> characters, as needed for conformance with <a class='info' href='#CHARSETS'>[CHARSETS]<span> (</span><span class='info'>Alvestrand, H., &ldquo;IETF Policy on Character Sets and Languages,&rdquo; January&nbsp;1998.</span><span>)</span></a> and as defined in <a class='info' href='#UTF-8'>[UTF&#8209;8]<span> (</span><span class='info'>Yergeau, F., &ldquo;UTF-8, a transformation format of ISO 10646,&rdquo; November&nbsp;2003.</span><span>)</span></a>. Implementations MUST NOT attempt to use any other encoding. If one party to an XML stream detects that the other party has attempted to send XML data with an encoding other than UTF-8, it MUST close the stream with a stream error, which SHOULD be &lt;unsupported-encoding/&gt; (<a class='info' href='#streams-error-conditions-unsupported-encoding'>Section&nbsp;4.9.3.22<span> (</span><span class='info'>unsupported-encoding</span><span>)</span></a>), although some existing implementations send &lt;bad-format/&gt; (<a class='info' href='#streams-error-conditions-bad-format'>Section&nbsp;4.9.3.1<span> (</span><span class='info'>bad-format</span><span>)</span></a>) instead.
6036</p>
6037<p>Because it is mandatory for an XMPP implementation to support all and only the UTF-8 encoding and because UTF-8 always has the same byte order, an implementation MUST NOT send a byte order mark ("BOM") at the beginning of the data stream. If an entity receives the <a class='info' href='#UNICODE'>[UNICODE]<span> (</span><span class='info'>The Unicode Consortium, &ldquo;The Unicode Standard, Version 6.0,&rdquo; 2010.</span><span>)</span></a> character U+FEFF anywhere in an XML stream (including as the first character of the stream), it MUST interpret that character as a zero width no-break space, not as a byte order mark.
6038</p>
6039<a name="xml-whitespace"></a><br /><hr />
6040<table summary="layout" cellpadding="0" cellspacing="2" class="TOCbug" align="right"><tr><td class="TOCbug"><a href="#toc">&nbsp;TOC&nbsp;</a></td></tr></table>
6041<a name="rfc.section.11.7"></a><h3>11.7.&nbsp;
6042Whitespace</h3>
6043
6044<p>Except where explicitly disallowed (e.g., during <a class='info' href='#tls'>TLS negotiation<span> (</span><span class='info'>STARTTLS Negotiation</span><span>)</span></a> and <a class='info' href='#sasl'>SASL negotiation<span> (</span><span class='info'>SASL Negotiation</span><span>)</span></a>), either entity MAY send whitespace as separators between XML stanzas or between any other first-level elements sent over the stream. One common use for sending such whitespace is explained under <a class='info' href='#streams-close'>Section&nbsp;4.4<span> (</span><span class='info'>Closing a Stream</span><span>)</span></a>.
6045</p>
6046<a name="xml-versions"></a><br /><hr />
6047<table summary="layout" cellpadding="0" cellspacing="2" class="TOCbug" align="right"><tr><td class="TOCbug"><a href="#toc">&nbsp;TOC&nbsp;</a></td></tr></table>
6048<a name="rfc.section.11.8"></a><h3>11.8.&nbsp;
6049XML Versions</h3>
6050
6051<p>XMPP is an application profile of XML 1.0. A future version of XMPP might be defined in terms of higher versions of XML, but this specification defines XMPP only in terms of XML 1.0.
6052</p>
6053<a name="i18n"></a><br /><hr />
6054<table summary="layout" cellpadding="0" cellspacing="2" class="TOCbug" align="right"><tr><td class="TOCbug"><a href="#toc">&nbsp;TOC&nbsp;</a></td></tr></table>
6055<a name="rfc.section.12"></a><h3>12.&nbsp;
6056Internationalization Considerations</h3>
6057
6058<p>As specified under <a class='info' href='#xml-encoding'>Section&nbsp;11.6<span> (</span><span class='info'>Character Encoding</span><span>)</span></a>, XML streams MUST be encoded in UTF-8.
6059</p>
6060<p>As specified under <a class='info' href='#streams-attr'>Section&nbsp;4.7<span> (</span><span class='info'>Stream Attributes</span><span>)</span></a>, an XML stream SHOULD include an 'xml:lang' attribute specifying the default language for any XML character data that is intended to be presented to a human user. As specified under <a class='info' href='#stanzas-attributes-lang'>Section&nbsp;8.1.5<span> (</span><span class='info'>xml:lang</span><span>)</span></a>, an XML stanza SHOULD include an 'xml:lang' attribute if the stanza contains XML character data that is intended to be presented to a human user. A server SHOULD apply the default 'xml:lang' attribute to stanzas it routes or delivers on behalf of connected entities, and MUST NOT modify or delete 'xml:lang' attributes on stanzas it receives from other entities.
6061</p>
6062<p>Internationalization of XMPP addresses is specified in <a class='info' href='#XMPP-ADDR'>[XMPP&#8209;ADDR]<span> (</span><span class='info'>Saint-Andre, P., &ldquo;Extensible Messaging and Presence Protocol (XMPP): Address Format,&rdquo; March&nbsp;2011.</span><span>)</span></a>.
6063</p>
6064<a name="security"></a><br /><hr />
6065<table summary="layout" cellpadding="0" cellspacing="2" class="TOCbug" align="right"><tr><td class="TOCbug"><a href="#toc">&nbsp;TOC&nbsp;</a></td></tr></table>
6066<a name="rfc.section.13"></a><h3>13.&nbsp;
6067Security Considerations</h3>
6068
6069<a name="security-fundamentals"></a><br /><hr />
6070<table summary="layout" cellpadding="0" cellspacing="2" class="TOCbug" align="right"><tr><td class="TOCbug"><a href="#toc">&nbsp;TOC&nbsp;</a></td></tr></table>
6071<a name="rfc.section.13.1"></a><h3>13.1.&nbsp;
6072Fundamentals</h3>
6073
6074<p>XMPP technologies are typically deployed using a decentralized client-server architecture. As a result, several paths are possible when two XMPP entities need to communicate:
6075</p>
6076<p>
6077 </p>
6078<ol class="text">
6079<li>Both entities are servers. In this case, the entities can establish a direct server-to-server stream between themselves.
6080</li>
6081<li>One entity is a server and the other entity is a client whose account is hosted on that server. In this case, the entities can establish a direct client-to-server stream between themselves.
6082</li>
6083<li>Both entities are clients whose accounts are hosted on the same server. In this case, the entities cannot establish a direct stream between themselves, but there is only one intermediate entity between them, whose policies they might understand and in which they might have some level of trust (e.g., the server might require the use of Transport Layer Security for all client connections).
6084</li>
6085<li>Both entities are clients but their accounts are hosted on different servers. In this case, the entities cannot establish a direct stream between themselves and there are two intermediate entities between them; each client might have some trust in the server that hosts its account but might know nothing about the policies of the server to which the other client connects.
6086</li>
6087</ol><p>
6088
6089</p>
6090<p>This specification covers only the security of a direct XML stream between two servers or between a client and a server (cases #1 and #2), where each stream can be considered a single "hop" along a communication path. The goal of security for a multi-hop path (cases #3 and #4), although very desirable, is out of scope for this specification.
6091</p>
6092<p>In accordance with <a class='info' href='#SEC-GUIDE'>[SEC&#8209;GUIDE]<span> (</span><span class='info'>Rescorla, E. and B. Korver, &ldquo;Guidelines for Writing RFC Text on Security Considerations,&rdquo; July&nbsp;2003.</span><span>)</span></a>, this specification covers communication security (confidentiality, data integrity, and peer entity authentication), non-repudiation, and systems security (unauthorized usage, inappropriate usage, and denial of service). We also discuss common security issues such as information leaks, firewalls, and directory harvesting, as well as best practices related to the reuse of technologies such as base 64, DNS, cryptographic hash functions, SASL, TLS, UTF-8, and XML.
6093</p>
6094<a name="security-threats"></a><br /><hr />
6095<table summary="layout" cellpadding="0" cellspacing="2" class="TOCbug" align="right"><tr><td class="TOCbug"><a href="#toc">&nbsp;TOC&nbsp;</a></td></tr></table>
6096<a name="rfc.section.13.2"></a><h3>13.2.&nbsp;
6097Threat Model</h3>
6098
6099<p>The threat model for XMPP is in essence the standard "Internet Threat Model" described in <a class='info' href='#SEC-GUIDE'>[SEC&#8209;GUIDE]<span> (</span><span class='info'>Rescorla, E. and B. Korver, &ldquo;Guidelines for Writing RFC Text on Security Considerations,&rdquo; July&nbsp;2003.</span><span>)</span></a>. Attackers are assumed to be interested in and capable of launching the following attacks against unprotected XMPP systems:
6100</p>
6101<p>
6102 </p>
6103<ul class="text">
6104<li>Eavesdropping
6105</li>
6106<li>Sniffing passwords
6107</li>
6108<li>Breaking passwords through dictionary attacks
6109</li>
6110<li>Discovering usernames through directory harvesting attacks
6111</li>
6112<li>Replaying, inserting, deleting, or modifying stanzas
6113</li>
6114<li>Spoofing users
6115</li>
6116<li>Gaining unauthorized entry to a server or account
6117</li>
6118<li>Using a server or account inappropriately
6119</li>
6120<li>Denying service to other entities
6121</li>
6122<li>Subverting communication streams through man-in-the-middle attacks
6123</li>
6124<li>Gaining control over on-path servers
6125</li>
6126</ul><p>
6127
6128</p>
6129<p>Where appropriate, the following sections describe methods for protecting against these threats.
6130</p>
6131<a name="security-layers"></a><br /><hr />
6132<table summary="layout" cellpadding="0" cellspacing="2" class="TOCbug" align="right"><tr><td class="TOCbug"><a href="#toc">&nbsp;TOC&nbsp;</a></td></tr></table>
6133<a name="rfc.section.13.3"></a><h3>13.3.&nbsp;
6134Order of Layers</h3>
6135
6136<p>The order of layers in which protocols MUST be stacked is as follows:
6137</p>
6138<p>
6139 </p>
6140<ol class="text">
6141<li>TCP
6142</li>
6143<li>TLS
6144</li>
6145<li>SASL
6146</li>
6147<li>XMPP
6148</li>
6149</ol><p>
6150
6151</p>
6152<p>This order has important security implications, as described throughout these security considerations.
6153</p>
6154<p>Within XMPP, XML stanzas are further ordered on top of XML streams, as described under <a class='info' href='#streams'>Section&nbsp;4<span> (</span><span class='info'>XML Streams</span><span>)</span></a>.
6155</p>
6156<a name="security-confidentiality"></a><br /><hr />
6157<table summary="layout" cellpadding="0" cellspacing="2" class="TOCbug" align="right"><tr><td class="TOCbug"><a href="#toc">&nbsp;TOC&nbsp;</a></td></tr></table>
6158<a name="rfc.section.13.4"></a><h3>13.4.&nbsp;
6159Confidentiality and Integrity</h3>
6160
6161<p>The use of Transport Layer Security (TLS) with appropriate ciphersuites provides a reliable mechanism to ensure the confidentiality and integrity of data exchanged between a client and a server or between two servers. Therefore, TLS can help to protect against eavesdropping, password sniffing, man-in-the-middle attacks, and stanza replays, insertion, deletion, and modification over an XML stream. XMPP clients and servers MUST support TLS as defined under <a class='info' href='#tls'>Section&nbsp;5<span> (</span><span class='info'>STARTTLS Negotiation</span><span>)</span></a>.
6162</p>
6163<p></p>
6164<blockquote class="text">
6165<p>Informational Note: The confidentiality and integrity of a stream can be protected by methods other than TLS, e.g., by means of a SASL mechanism that involves negotiation of a security layer.
6166</p>
6167</blockquote>
6168
6169<p></p>
6170<blockquote class="text">
6171<p>Security Warning: The use of TLS in XMPP applies to a single stream. Because XMPP is typically deployed using a distributed client-server architecture (as explained under <a class='info' href='#arch-network'>Section&nbsp;2.5<span> (</span><span class='info'>Distributed Network of Clients and Servers</span><span>)</span></a>), a stanza might traverse multiple streams, and not all of those streams might be TLS-protected. For example, a stanza sent from a client with a session at one server (e.g., &lt;romeo@example.net/orchard&gt;) and intended for delivery to a client with a session at another server (e.g., &lt;juliet@example.com/balcony&gt;) will traverse three streams: (1) the stream from the sender's client to its server, (2) the stream from the sender's server to the recipient's server, and (3) the stream from the recipient's server to the recipient's client. Furthermore, the stanza will be processed as cleartext within the sender's server and the recipient's server. Therefore, even if the stream from the sender's client to its server is protected, the confidentiality and integrity of a stanza sent over that protected stream cannot be guaranteed when the stanza is processed by the sender's server, sent from the sender's server to the recipient's server, processed by the recipient's server, or sent from the recipient's server to the recipient's client. Only a robust technology for end-to-end encryption could ensure the confidentiality and integrity of a stanza as it traverses all of the "hops" along a communication path (e.g., a technology that meets the requirements defined in <a class='info' href='#E2E-REQS'>[E2E&#8209;REQS]<span> (</span><span class='info'>Saint-Andre, P., &ldquo;Requirements for End-to-End Encryption in the Extensible Messaging and Presence Protocol (XMPP),&rdquo; March&nbsp;2010.</span><span>)</span></a>). Unfortunately, the XMPP community has so far failed to produce an end-to-end encryption technology that might be suitable for widespread implementation and deployment, and definition of such a technology is out of scope for this document.
6172</p>
6173</blockquote>
6174
6175<a name="security-authentication"></a><br /><hr />
6176<table summary="layout" cellpadding="0" cellspacing="2" class="TOCbug" align="right"><tr><td class="TOCbug"><a href="#toc">&nbsp;TOC&nbsp;</a></td></tr></table>
6177<a name="rfc.section.13.5"></a><h3>13.5.&nbsp;
6178Peer Entity Authentication</h3>
6179
6180<p>The use of the Simple Authentication and Security Layer (SASL) for authentication provides a reliable mechanism for peer entity authentication. Therefore, SASL helps to protect against user spoofing, unauthorized usage, and man-in-the middle attacks. XMPP clients and servers MUST support SASL as defined under <a class='info' href='#sasl'>Section&nbsp;6<span> (</span><span class='info'>SASL Negotiation</span><span>)</span></a>.
6181</p>
6182<a name="security-strong"></a><br /><hr />
6183<table summary="layout" cellpadding="0" cellspacing="2" class="TOCbug" align="right"><tr><td class="TOCbug"><a href="#toc">&nbsp;TOC&nbsp;</a></td></tr></table>
6184<a name="rfc.section.13.6"></a><h3>13.6.&nbsp;
6185Strong Security</h3>
6186
6187<p><a class='info' href='#STRONGSEC'>[STRONGSEC]<span> (</span><span class='info'>Schiller, J., &ldquo;Strong Security Requirements for Internet Engineering Task Force Standard Protocols,&rdquo; August&nbsp;2002.</span><span>)</span></a> defines "strong security" and its importance to communication over the Internet. For the purpose of XMPP communication over client-to-server and server-to-server streams, the term "strong security" refers to the use of security technologies that provide both mutual authentication and integrity checking (e.g., a combination of TLS encryption and SASL authentication using appropriate SASL mechanisms).
6188</p>
6189<p>Implementations MUST support strong security. Service provisioning SHOULD use strong security.
6190</p>
6191<p>An implementation SHOULD make it possible for an end user or service administrator to provision a deployment with specific trust anchors for the certificate presented by a connecting entity (either client or server); when an application is thus provisioned, it MUST NOT use a generic PKI trust store to authenticate the connecting entity. More detailed rules and guidelines regarding certificate validation are provided in the next section.
6192</p>
6193<p>The initial stream and the response stream MUST be secured separately, although security in both directions MAY be established via mechanisms that provide mutual authentication.
6194</p>
6195<a name="security-certificates"></a><br /><hr />
6196<table summary="layout" cellpadding="0" cellspacing="2" class="TOCbug" align="right"><tr><td class="TOCbug"><a href="#toc">&nbsp;TOC&nbsp;</a></td></tr></table>
6197<a name="rfc.section.13.7"></a><h3>13.7.&nbsp;
6198Certificates</h3>
6199
6200<p>Channel encryption of an XML stream using Transport Layer Security as described under <a class='info' href='#tls'>Section&nbsp;5<span> (</span><span class='info'>STARTTLS Negotiation</span><span>)</span></a>, and in some cases also authentication as described under <a class='info' href='#sasl'>Section&nbsp;6<span> (</span><span class='info'>SASL Negotiation</span><span>)</span></a>, is commonly based on a PKIX certificate presented by the receiving entity (or, in the case of mutual certificate authentication, both the receiving entity and the initiating entity). This section describes best practices regarding the generation of PKIX certificates to be presented by XMPP entities and the verification of PKIX certificates presented by XMPP entities.
6201</p>
6202<p>In general, the following sections rely on and extend the rules and guidelines provided in the <a class='info' href='#PKIX'>[PKIX]<span> (</span><span class='info'>Cooper, D., Santesson, S., Farrell, S., Boeyen, S., Housley, R., and W. Polk, &ldquo;Internet X.509 Public Key Infrastructure Certificate and Certificate Revocation List (CRL) Profile,&rdquo; May&nbsp;2008.</span><span>)</span></a> profile of <a class='info' href='#X509'>[X509]<span> (</span><span class='info'>International Telecommunications Union, &ldquo;Information technology - Open Systems Interconnection - The Directory: Public-key and attribute certificate frameworks,&rdquo; March&nbsp;2000.</span><span>)</span></a>, and in <a class='info' href='#TLS-CERTS'>[TLS&#8209;CERTS]<span> (</span><span class='info'>Saint-Andre, P. and J. Hodges, &ldquo;Representation and Verification of Domain-Based Application Service Identity within Internet Public Key Infrastructure Using X.509 (PKIX) Certificates in the Context of Transport Layer Security (TLS),&rdquo; March&nbsp;2011.</span><span>)</span></a>. The reader is referred to those specifications for a detailed understanding of PKIX certificates and their use in TLS.
6203</p>
6204<a name="security-certificates-generation"></a><br /><hr />
6205<table summary="layout" cellpadding="0" cellspacing="2" class="TOCbug" align="right"><tr><td class="TOCbug"><a href="#toc">&nbsp;TOC&nbsp;</a></td></tr></table>
6206<a name="rfc.section.13.7.1"></a><h3>13.7.1.&nbsp;
6207Certificate Generation</h3>
6208
6209<a name="security-certificates-generation-general"></a><br /><hr />
6210<table summary="layout" cellpadding="0" cellspacing="2" class="TOCbug" align="right"><tr><td class="TOCbug"><a href="#toc">&nbsp;TOC&nbsp;</a></td></tr></table>
6211<a name="rfc.section.13.7.1.1"></a><h3>13.7.1.1.&nbsp;
6212General Considerations</h3>
6213
6214<p>The following rules apply to end entity public key certificates that are issued to XMPP servers or clients:
6215</p>
6216<p>
6217 </p>
6218<ol class="text">
6219<li>The certificate MUST conform to <a class='info' href='#PKIX'>[PKIX]<span> (</span><span class='info'>Cooper, D., Santesson, S., Farrell, S., Boeyen, S., Housley, R., and W. Polk, &ldquo;Internet X.509 Public Key Infrastructure Certificate and Certificate Revocation List (CRL) Profile,&rdquo; May&nbsp;2008.</span><span>)</span></a>.
6220</li>
6221<li>The certificate MUST NOT contain a basicConstraints extension with the cA boolean set to TRUE.
6222</li>
6223<li>The subject field MUST NOT be null.
6224</li>
6225<li>The signatureAlgorithm SHOULD be the PKCS #1 version 1.5 signature algorithm with SHA-256 as defined by <a class='info' href='#PKIX-ALGO'>[PKIX&#8209;ALGO]<span> (</span><span class='info'>Jonsson, J. and B. Kaliski, &ldquo;Public-Key Cryptography Standards (PKCS) #1: RSA Cryptography Specifications Version 2.1,&rdquo; February&nbsp;2003.</span><span>)</span></a>, or a stronger algorithm if available.
6226</li>
6227<li>The certificate SHOULD include an Authority Information Access (AIA) extension that specifies the address of an Online Certificate Status Protocol <a class='info' href='#OCSP'>[OCSP]<span> (</span><span class='info'>Myers, M., Ankney, R., Malpani, A., Galperin, S., and C. Adams, &ldquo;X.509 Internet Public Key Infrastructure Online Certificate Status Protocol - OCSP,&rdquo; June&nbsp;1999.</span><span>)</span></a> responder (if not, a relying party would need to fall back on the use of Certificate Revocation Lists (CRLs) as described in <a class='info' href='#PKIX'>[PKIX]<span> (</span><span class='info'>Cooper, D., Santesson, S., Farrell, S., Boeyen, S., Housley, R., and W. Polk, &ldquo;Internet X.509 Public Key Infrastructure Certificate and Certificate Revocation List (CRL) Profile,&rdquo; May&nbsp;2008.</span><span>)</span></a>).
6228</li>
6229</ol><p>
6230
6231</p>
6232<p>The following rules apply to certification authority (CA) certificates that are used by issuers of XMPP end entity certificates:
6233</p>
6234<p>
6235 </p>
6236<ol class="text">
6237<li>The certificate MUST conform to <a class='info' href='#PKIX'>[PKIX]<span> (</span><span class='info'>Cooper, D., Santesson, S., Farrell, S., Boeyen, S., Housley, R., and W. Polk, &ldquo;Internet X.509 Public Key Infrastructure Certificate and Certificate Revocation List (CRL) Profile,&rdquo; May&nbsp;2008.</span><span>)</span></a>.
6238</li>
6239<li>The certificate MUST contain a keyUsage extension with the digitalSignature bit set.
6240</li>
6241<li>The subject field MUST NOT be null.
6242</li>
6243<li>The signatureAlgorithm SHOULD be the PKCS #1 version 1.5
6244signature algorithm with SHA-256 as defined by <a class='info' href='#PKIX-ALGO'>[PKIX&#8209;ALGO]<span> (</span><span class='info'>Jonsson, J. and B. Kaliski, &ldquo;Public-Key Cryptography Standards (PKCS) #1: RSA Cryptography Specifications Version 2.1,&rdquo; February&nbsp;2003.</span><span>)</span></a>, or a
6245stronger algorithm if available.
6246</li>
6247<li>For issuers of public key certificates, the issuer's certificate MUST contain a basicConstraints extension with the cA boolean set to TRUE.
6248</li>
6249</ol><p>
6250
6251</p>
6252<a name="security-certificates-generation-server"></a><br /><hr />
6253<table summary="layout" cellpadding="0" cellspacing="2" class="TOCbug" align="right"><tr><td class="TOCbug"><a href="#toc">&nbsp;TOC&nbsp;</a></td></tr></table>
6254<a name="rfc.section.13.7.1.2"></a><h3>13.7.1.2.&nbsp;
6255Server Certificates</h3>
6256
6257<a name="security-certificates-generation-server-rules"></a><br /><hr />
6258<table summary="layout" cellpadding="0" cellspacing="2" class="TOCbug" align="right"><tr><td class="TOCbug"><a href="#toc">&nbsp;TOC&nbsp;</a></td></tr></table>
6259<a name="rfc.section.13.7.1.2.1"></a><h3>13.7.1.2.1.&nbsp;
6260Rules</h3>
6261
6262<p>In a PKIX certificate to be presented by an XMPP server (i.e., a "server certificate"), the certificate SHOULD include one or more XMPP addresses (i.e., domainparts) associated with XMPP services hosted at the server. The rules and guidelines defined in <a class='info' href='#TLS-CERTS'>[TLS&#8209;CERTS]<span> (</span><span class='info'>Saint-Andre, P. and J. Hodges, &ldquo;Representation and Verification of Domain-Based Application Service Identity within Internet Public Key Infrastructure Using X.509 (PKIX) Certificates in the Context of Transport Layer Security (TLS),&rdquo; March&nbsp;2011.</span><span>)</span></a> apply to XMPP server certificates, with the following XMPP-specific considerations:
6263</p>
6264<p>
6265 </p>
6266<ul class="text">
6267<li>Support for the DNS-ID identifier type <a class='info' href='#PKIX'>[PKIX]<span> (</span><span class='info'>Cooper, D., Santesson, S., Farrell, S., Boeyen, S., Housley, R., and W. Polk, &ldquo;Internet X.509 Public Key Infrastructure Certificate and Certificate Revocation List (CRL) Profile,&rdquo; May&nbsp;2008.</span><span>)</span></a> is REQUIRED in XMPP client and server software implementations. Certification authorities that issue XMPP-specific certificates MUST support the DNS-ID identifier type. XMPP service providers SHOULD include the DNS-ID identifier type in certificate requests.
6268</li>
6269<li>Support for the SRV-ID identifier type <a class='info' href='#PKIX-SRV'>[PKIX&#8209;SRV]<span> (</span><span class='info'>Santesson, S., &ldquo;Internet X.509 Public Key Infrastructure Subject Alternative Name for Expression of Service Name,&rdquo; August&nbsp;2007.</span><span>)</span></a> is REQUIRED for XMPP client and server software implementations (for verification purposes XMPP client implementations need to support only the "_xmpp-client" service type, whereas XMPP server implementations need to support both the "_xmpp-client" and "_xmpp-server" service types). Certification authorities that issue XMPP-specific certificates SHOULD support the SRV-ID identifier type. XMPP service providers SHOULD include the SRV-ID identifier type in certificate requests.
6270</li>
6271<li>Support for the XmppAddr identifier type (specified under <a class='info' href='#security-certificates-generation-xmppaddr'>Section&nbsp;13.7.1.4<span> (</span><span class='info'>XmppAddr Identifier Type</span><span>)</span></a>) is encouraged in XMPP client and server software implementations for the sake of backward-compatibility, but is no longer encouraged in certificates issued by certification authorities or requested by XMPP service providers.
6272</li>
6273<li>DNS domain names in server certificates MAY contain the wildcard character '*' as the complete left-most label within the identifier.
6274</li>
6275</ul><p>
6276
6277</p>
6278<a name="security-certificates-generation-server-examples"></a><br /><hr />
6279<table summary="layout" cellpadding="0" cellspacing="2" class="TOCbug" align="right"><tr><td class="TOCbug"><a href="#toc">&nbsp;TOC&nbsp;</a></td></tr></table>
6280<a name="rfc.section.13.7.1.2.2"></a><h3>13.7.1.2.2.&nbsp;
6281Examples</h3>
6282
6283<p>For our first (relatively simple) example, consider a company called "Example Products, Inc." It hosts an XMPP service at "im.example.com" (i.e., user addresses at the service are of the form "user@im.example.com"), and SRV lookups for the xmpp-client and xmpp-server services at "im.example.com" yield one machine, called "x.example.com", as follows:
6284</p><div style='display: table; width: 0; margin-left: 3em; margin-right: auto'><pre>
6285_xmpp-client._tcp.im.example.com. 400 IN SRV 20 0 5222 x.example.com
6286_xmpp-server._tcp.im.example.com. 400 IN SRV 20 0 5269 x.example.com
6287</pre></div>
6288<p>The certificate presented by x.example.com contains the following representations:
6289</p>
6290<p>
6291 </p>
6292<ul class="text">
6293<li>An otherName type of SRVName (id-on-dnsSRV) containing an IA5String (ASCII) string of "_xmpp-client.im.example.com"
6294</li>
6295<li>An otherName type of SRVName (id-on-dnsSRV) containing an IA5String (ASCII) string of "_xmpp-server.im.example.com"
6296</li>
6297<li>A dNSName containing an ASCII string of "im.example.com"
6298</li>
6299<li>An otherName type of XmppAddr (id-on-xmppAddr) containing a UTF-8 string of "im.example.com"
6300</li>
6301<li>A CN containing an ASCII string of "Example Products, Inc."
6302</li>
6303</ul><p>
6304
6305</p>
6306<p>For our second (more complex) example, consider an ISP called "Example Internet Services". It hosts an XMPP service at "example.net" (i.e., user addresses at the service are of the form "user@example.net"), but SRV lookups for the xmpp-client and xmpp-server services at "example.net" yield two machines ("x1.example.net" and "x2.example.net"), as follows:
6307</p><div style='display: table; width: 0; margin-left: 3em; margin-right: auto'><pre>
6308_xmpp-client._tcp.example.net. 68400 IN SRV 20 0 5222 x1.example.net.
6309_xmpp-client._tcp.example.net. 68400 IN SRV 20 0 5222 x2.example.net.
6310_xmpp-server._tcp.example.net. 68400 IN SRV 20 0 5269 x1.example.net.
6311_xmpp-server._tcp.example.net. 68400 IN SRV 20 0 5269 x2.example.net.
6312</pre></div>
6313<p>Example Internet Services also hosts chatrooms at chat.example.net, and provides an xmpp-server SRV record for that service as well (thus enabling entities from remote domains to access that service). It also might provide other such services in the future, so it wishes to represent a wildcard in its certificate to handle such growth.
6314</p>
6315<p>The certificate presented by either x1.example.net or x2.example.net contains the following representations:
6316</p>
6317<p>
6318 </p>
6319<ul class="text">
6320<li>An otherName type of SRVName (id-on-dnsSRV) containing an IA5String (ASCII) string of "_xmpp-client.example.net"
6321</li>
6322<li>An otherName type of SRVName (id-on-dnsSRV) containing an IA5String (ASCII) string of "_xmpp-server.example.net"
6323</li>
6324<li>An otherName type of SRVName (id-on-dnsSRV) containing an IA5String (ASCII) string of "_xmpp-server.chat.example.net"
6325</li>
6326<li>A dNSName containing an ASCII string of "example.net"
6327</li>
6328<li>A dNSName containing an ASCII string of "*.example.net"
6329</li>
6330<li>An otherName type of XmppAddr (id-on-xmppAddr) containing a UTF-8 string of "example.net"
6331</li>
6332<li>An otherName type of XmppAddr (id-on-xmppAddr) containing a UTF-8 string of "chat.example.net"
6333</li>
6334<li>A CN containing an ASCII string of "Example Internet Services"
6335</li>
6336</ul><p>
6337
6338</p>
6339<a name="security-certificates-generation-client"></a><br /><hr />
6340<table summary="layout" cellpadding="0" cellspacing="2" class="TOCbug" align="right"><tr><td class="TOCbug"><a href="#toc">&nbsp;TOC&nbsp;</a></td></tr></table>
6341<a name="rfc.section.13.7.1.3"></a><h3>13.7.1.3.&nbsp;
6342Client Certificates</h3>
6343
6344<p>In a PKIX certificate to be presented by an XMPP client controlled by a human user (i.e., a "client certificate"), it is RECOMMENDED for the certificate to include one or more JIDs associated with an XMPP user. If included, a JID MUST be represented as an XmppAddr as specified under <a class='info' href='#security-certificates-generation-xmppaddr'>Section&nbsp;13.7.1.4<span> (</span><span class='info'>XmppAddr Identifier Type</span><span>)</span></a>.
6345</p>
6346<a name="security-certificates-generation-xmppaddr"></a><br /><hr />
6347<table summary="layout" cellpadding="0" cellspacing="2" class="TOCbug" align="right"><tr><td class="TOCbug"><a href="#toc">&nbsp;TOC&nbsp;</a></td></tr></table>
6348<a name="rfc.section.13.7.1.4"></a><h3>13.7.1.4.&nbsp;
6349XmppAddr Identifier Type</h3>
6350
6351<p>The XmppAddr identifier type is a UTF8String within an otherName entity inside the subjectAltName, using the <a class='info' href='#ASN.1'>[ASN.1]<span> (</span><span class='info'>CCITT, &ldquo;Recommendation X.208: Specification of Abstract Syntax Notation One (ASN.1),&rdquo; 1988.</span><span>)</span></a> Object Identifier "id-on-xmppAddr" specified below.
6352</p><div style='display: table; width: 0; margin-left: 3em; margin-right: auto'><pre>
6353id-pkix OBJECT IDENTIFIER ::= { iso(1) identified-organization(3)
6354 dod(6) internet(1) security(5) mechanisms(5) pkix(7) }
6355
6356id-on OBJECT IDENTIFIER ::= { id-pkix 8 } -- other name forms
6357
6358id-on-xmppAddr OBJECT IDENTIFIER ::= { id-on 5 }
6359
6360XmppAddr ::= UTF8String
6361</pre></div>
6362<p>As an alternative to the "id-on-xmppAddr" notation, this Object Identifier MAY be represented in dotted display format (i.e., "1.3.6.1.5.5.7.8.5") or in the Uniform Resource Name notation specified in <a class='info' href='#URN-OID'>[URN&#8209;OID]<span> (</span><span class='info'>Mealling, M., &ldquo;A URN Namespace of Object Identifiers,&rdquo; February&nbsp;2001.</span><span>)</span></a> (i.e., "urn:oid:1.3.6.1.5.5.7.8.5").
6363</p>
6364<p>Thus for example the JID &lt;juliet@im.example.com&gt; as included in a certificate could be formatted in any of the following three ways:
6365</p>
6366<p>
6367 </p>
6368<blockquote class="text"><dl>
6369<dt>id-on-xmppAddr:</dt>
6370<dd>subjectAltName=otherName:id-on-xmppAddr;UTF8:juliet@im.example.com
6371</dd>
6372<dt>dotted display format:</dt>
6373<dd>subjectAltName=otherName:1.3.6.1.5.5.7.8.5;UTF8:juliet@im.example.com
6374</dd>
6375<dt>URN notation:</dt>
6376<dd>subjectAltName=otherName:urn:oid:1.3.6.1.5.5.7.8.5;UTF8:juliet@im.example.com
6377</dd>
6378</dl></blockquote><p>
6379
6380</p>
6381<p>Use of the "id-on-xmppAddr" format is RECOMMENDED in the generation of certificates, but all three formats MUST be supported for the purpose of certificate validation.
6382</p>
6383<p>The "id-on-xmppAddr" object identifier MAY be used in conjunction with the extended key usage extension specified in Section 4.2.1.12 of <a class='info' href='#PKIX'>[PKIX]<span> (</span><span class='info'>Cooper, D., Santesson, S., Farrell, S., Boeyen, S., Housley, R., and W. Polk, &ldquo;Internet X.509 Public Key Infrastructure Certificate and Certificate Revocation List (CRL) Profile,&rdquo; May&nbsp;2008.</span><span>)</span></a> in order to explicitly define and limit the intended use of a certificate to the XMPP network.
6384</p>
6385<a name="security-certificates-validation"></a><br /><hr />
6386<table summary="layout" cellpadding="0" cellspacing="2" class="TOCbug" align="right"><tr><td class="TOCbug"><a href="#toc">&nbsp;TOC&nbsp;</a></td></tr></table>
6387<a name="rfc.section.13.7.2"></a><h3>13.7.2.&nbsp;
6388Certificate Validation</h3>
6389
6390<p>When an XMPP entity is presented with a server certificate or client certificate by a peer for the purpose of encryption or authentication of XML streams as described under <a class='info' href='#tls'>Section&nbsp;5<span> (</span><span class='info'>STARTTLS Negotiation</span><span>)</span></a> and <a class='info' href='#sasl'>Section&nbsp;6<span> (</span><span class='info'>SASL Negotiation</span><span>)</span></a>, the entity MUST attempt to validate the certificate to determine if the certificate will be considered a "trusted certificate", i.e., a certificate that is acceptable for encryption and/or authentication in accordance with the XMPP entity's local service policies or configured settings.
6391</p>
6392<p>For both server certificates and client certificates, the validating entity MUST do the following:
6393</p>
6394<p>
6395 </p>
6396<ol class="text">
6397<li>Attempt to verify the integrity of the certificate.
6398</li>
6399<li>Attempt to verify that the certificate has been properly signed by the issuing Certificate Authority.
6400</li>
6401<li>Attempt to validate the full certification path.
6402</li>
6403<li>Check the rules for end entity public key certificates and certification authority certificates specified under <a class='info' href='#security-certificates-generation-general'>Section&nbsp;13.7.1.1<span> (</span><span class='info'>General Considerations</span><span>)</span></a> for the general case and under either <a class='info' href='#security-certificates-generation-server'>Section&nbsp;13.7.1.2<span> (</span><span class='info'>Server Certificates</span><span>)</span></a> or <a class='info' href='#security-certificates-generation-client'>Section&nbsp;13.7.1.3<span> (</span><span class='info'>Client Certificates</span><span>)</span></a> for XMPP server or client certificates, respectively.
6404</li>
6405<li>Check certificate revocation messages via Certificate Revocation Lists (CRLs), the Online Certificate Status Protocol <a class='info' href='#OCSP'>[OCSP]<span> (</span><span class='info'>Myers, M., Ankney, R., Malpani, A., Galperin, S., and C. Adams, &ldquo;X.509 Internet Public Key Infrastructure Online Certificate Status Protocol - OCSP,&rdquo; June&nbsp;1999.</span><span>)</span></a>, or both.
6406</li>
6407</ol><p>
6408
6409</p>
6410<p>If any of those validation attempts fail, the validating entity MUST unilaterally terminate the session.
6411</p>
6412<p>The following sections describe the additional identity verification rules that apply to server-to-server and client-to-server streams.
6413</p>
6414<p>Once the identity of the stream peer has been validated, the validating entity SHOULD also correlate the validated identity with the 'from' address (if any) of the stream header it received from the peer. If the two identities do not match, the validating entity SHOULD terminate the connection attempt (however, there might be good reasons why the identities do not match, as described under <a class='info' href='#streams-attr-from'>Section&nbsp;4.7.1<span> (</span><span class='info'>from</span><span>)</span></a>).
6415</p>
6416<a name="security-certificates-validation-server"></a><br /><hr />
6417<table summary="layout" cellpadding="0" cellspacing="2" class="TOCbug" align="right"><tr><td class="TOCbug"><a href="#toc">&nbsp;TOC&nbsp;</a></td></tr></table>
6418<a name="rfc.section.13.7.2.1"></a><h3>13.7.2.1.&nbsp;
6419Server Certificates</h3>
6420
6421<p>For server certificates, the rules and guidelines defined in <a class='info' href='#TLS-CERTS'>[TLS&#8209;CERTS]<span> (</span><span class='info'>Saint-Andre, P. and J. Hodges, &ldquo;Representation and Verification of Domain-Based Application Service Identity within Internet Public Key Infrastructure Using X.509 (PKIX) Certificates in the Context of Transport Layer Security (TLS),&rdquo; March&nbsp;2011.</span><span>)</span></a> apply, with the proviso that the XmppAddr identifier specified under <a class='info' href='#security-certificates-generation-xmppaddr'>Section&nbsp;13.7.1.4<span> (</span><span class='info'>XmppAddr Identifier Type</span><span>)</span></a> is allowed as a reference identifier.
6422</p>
6423<p>The identities to be checked are set as follows:
6424</p>
6425<p>
6426 </p>
6427<ul class="text">
6428<li>The initiating entity sets the source domain of its reference
6429 identifiers to the 'to' address it communicates in the initial stream
6430 header; i.e., this is the identity it expects the receiving entity to
6431 provide in a PKIX certificate.
6432</li>
6433<li>The receiving entity sets the source domain of its reference
6434 identifiers to the 'from' address communicated by the initiating
6435 entity in the initial stream header; i.e., this is the identity that
6436 the initiating entity is trying to assert.
6437</li>
6438</ul><p>
6439
6440</p>
6441<p>
6442 In the case of server-to-server communication, the matching procedure
6443 described in <a class='info' href='#TLS-CERTS'>[TLS&#8209;CERTS]<span> (</span><span class='info'>Saint-Andre, P. and J. Hodges, &ldquo;Representation and Verification of Domain-Based Application Service Identity within Internet Public Key Infrastructure Using X.509 (PKIX) Certificates in the Context of Transport Layer Security (TLS),&rdquo; March&nbsp;2011.</span><span>)</span></a> can be performed by an application server
6444 (receiving entity) when verifying an incoming server-to-server
6445 connection from a peer server (initiating entity). In this case, the
6446 receiving entity verifies the identity of the initiating entity and
6447 uses as the source domain of its reference identifiers the DNS domain
6448 name asserted by the initiating entity in the 'from' attribute of the
6449 initial stream header. However, the matching procedure described in
6450 <a class='info' href='#TLS-CERTS'>[TLS&#8209;CERTS]<span> (</span><span class='info'>Saint-Andre, P. and J. Hodges, &ldquo;Representation and Verification of Domain-Based Application Service Identity within Internet Public Key Infrastructure Using X.509 (PKIX) Certificates in the Context of Transport Layer Security (TLS),&rdquo; March&nbsp;2011.</span><span>)</span></a> remains unchanged and is applied in the same way.
6451
6452</p>
6453<a name="security-certificates-validation-client"></a><br /><hr />
6454<table summary="layout" cellpadding="0" cellspacing="2" class="TOCbug" align="right"><tr><td class="TOCbug"><a href="#toc">&nbsp;TOC&nbsp;</a></td></tr></table>
6455<a name="rfc.section.13.7.2.2"></a><h3>13.7.2.2.&nbsp;
6456Client Certificates</h3>
6457
6458<p>When an XMPP server validates a certificate presented by a client, there are three possible cases, as discussed in the following sections.
6459</p>
6460<p>The identities to be checked are set as follows:
6461</p>
6462<p>
6463 </p>
6464<ul class="text">
6465<li>
6466 The client sets the source domain of its reference identifiers to
6467 the 'to' address it communicates in the initial stream header;
6468 i.e., this is the identity it expects the server to provide in a
6469 PKIX certificate.
6470
6471</li>
6472<li>
6473 The server sets the bare JID of its reference identifiers to the
6474 'from' address communicated by the initiating entity in the
6475 initial stream header; i.e., this is the identity that the client
6476 is trying to assert.
6477
6478</li>
6479</ul><p>
6480
6481</p>
6482<a name="security-certificates-validation-client-case1"></a><br /><hr />
6483<table summary="layout" cellpadding="0" cellspacing="2" class="TOCbug" align="right"><tr><td class="TOCbug"><a href="#toc">&nbsp;TOC&nbsp;</a></td></tr></table>
6484<a name="rfc.section.13.7.2.2.1"></a><h3>13.7.2.2.1.&nbsp;
6485Case #1</h3>
6486
6487<p>If the client certificate appears to be certified by a certification path terminating in a trust anchor (as described in Section 6.1 of <a class='info' href='#PKIX'>[PKIX]<span> (</span><span class='info'>Cooper, D., Santesson, S., Farrell, S., Boeyen, S., Housley, R., and W. Polk, &ldquo;Internet X.509 Public Key Infrastructure Certificate and Certificate Revocation List (CRL) Profile,&rdquo; May&nbsp;2008.</span><span>)</span></a>), the server MUST check the certificate for any instances of the XmppAddr as described under <a class='info' href='#security-certificates-generation-xmppaddr'>Section&nbsp;13.7.1.4<span> (</span><span class='info'>XmppAddr Identifier Type</span><span>)</span></a>. There are three possible sub-cases:
6488</p>
6489<p>
6490 </p>
6491<blockquote class="text"><dl>
6492<dt>Sub-Case #1:</dt>
6493<dd>The server finds one XmppAddr for which the domainpart of the represented JID matches one of the configured FQDNs of the server; the server SHOULD use this represented JID as the validated identity of the client.
6494</dd>
6495<dt>Sub-Case #2:</dt>
6496<dd>The server finds more than one XmppAddr for which the domainpart of the represented JID matches one of the configured FQDNs of the server; the server SHOULD use one of these represented JIDs as the validated identity of the client, choosing among them based on the bare JID contained in the 'from' address of the initial stream header (if any), based on the domainpart contained in the 'to' address of the initial stream header, or in accordance with local service policies (such as a lookup in a user database based on other information contained in the client certificate).
6497</dd>
6498<dt>Sub-Case #3:</dt>
6499<dd>The server finds no XmppAddrs, or finds at least one XmppAddr but the domainpart of the represented JID does not match one of the configured FQDNs of the server; the server MUST NOT use the represented JID (if any) as the validated identity of the client but instead MUST validate the identity of the client using other means in accordance with local service policies (such as a lookup in a user database based on other information contained in the client certificate). If the identity cannot be so validated, the server MAY abort the validation process and terminate the TLS negotiation.
6500</dd>
6501</dl></blockquote><p>
6502
6503</p>
6504<a name="security-certificates-validation-client-case2"></a><br /><hr />
6505<table summary="layout" cellpadding="0" cellspacing="2" class="TOCbug" align="right"><tr><td class="TOCbug"><a href="#toc">&nbsp;TOC&nbsp;</a></td></tr></table>
6506<a name="rfc.section.13.7.2.2.2"></a><h3>13.7.2.2.2.&nbsp;
6507Case #2</h3>
6508
6509<p>If the client certificate is certified by a Certificate Authority not known to the server, the server MUST proceed as under Case #1, Sub-Case #3.
6510</p>
6511<a name="security-certificates-validation-client-case3"></a><br /><hr />
6512<table summary="layout" cellpadding="0" cellspacing="2" class="TOCbug" align="right"><tr><td class="TOCbug"><a href="#toc">&nbsp;TOC&nbsp;</a></td></tr></table>
6513<a name="rfc.section.13.7.2.2.3"></a><h3>13.7.2.2.3.&nbsp;
6514Case #3</h3>
6515
6516<p>If the client certificate is self-signed, the server MUST proceed as under Case #1, Sub-Case #3.
6517</p>
6518<a name="security-certificates-validation-streams"></a><br /><hr />
6519<table summary="layout" cellpadding="0" cellspacing="2" class="TOCbug" align="right"><tr><td class="TOCbug"><a href="#toc">&nbsp;TOC&nbsp;</a></td></tr></table>
6520<a name="rfc.section.13.7.2.3"></a><h3>13.7.2.3.&nbsp;
6521Checking of Certificates in Long-Lived Streams</h3>
6522
6523<p>Because XMPP uses long-lived XML streams, it is possible that a certificate presented during stream negotiation might expire or be revoked while the stream is still live (this is especially relevant in the context of server-to-server streams). Therefore, each party to a long-lived stream SHOULD:
6524</p>
6525<p>
6526 </p>
6527<ol class="text">
6528<li>Cache the expiration date of the certificate presented by the other party and any certificates on which that certificate depends (such as a root or intermediate certificate for a certification authority), and close the stream when any such certificate expires, with a stream error of &lt;reset/&gt; (<a class='info' href='#streams-error-conditions-reset'>Section&nbsp;4.9.3.16<span> (</span><span class='info'>reset</span><span>)</span></a>).
6529</li>
6530<li>Periodically query the Online Certificate Status Protocol <a class='info' href='#OCSP'>[OCSP]<span> (</span><span class='info'>Myers, M., Ankney, R., Malpani, A., Galperin, S., and C. Adams, &ldquo;X.509 Internet Public Key Infrastructure Online Certificate Status Protocol - OCSP,&rdquo; June&nbsp;1999.</span><span>)</span></a> responder listed in the Authority Information Access (AIA) extension of the certificate presented by the other party and any certificates on which that certificate depends (such as a root or intermediate certificate for a certification authority), and close the stream if any such certificate has been revoked, with a stream error of &lt;reset/&gt; (<a class='info' href='#streams-error-conditions-reset'>Section&nbsp;4.9.3.16<span> (</span><span class='info'>reset</span><span>)</span></a>). It is RECOMMENDED to query the OSCP responder at or near the time communicated via the nextUpdate field received in the OCSP response or, if the nextUpdate field is not set, to query every 24 hours.
6531</li>
6532</ol><p>
6533
6534</p>
6535<p>After the stream is closed, the initiating entity from the closed stream will need to reconnect and the receiving entity will need to authenticate the initiating entity based on whatever certificate it presents during negotiation of the new stream.
6536</p>
6537<a name="security-certificates-validation-extensions"></a><br /><hr />
6538<table summary="layout" cellpadding="0" cellspacing="2" class="TOCbug" align="right"><tr><td class="TOCbug"><a href="#toc">&nbsp;TOC&nbsp;</a></td></tr></table>
6539<a name="rfc.section.13.7.2.4"></a><h3>13.7.2.4.&nbsp;
6540Use of Certificates in XMPP Extensions</h3>
6541
6542<p>Certificates MAY be used in extensions to XMPP for the purpose of application-layer encryption or authentication above the level of XML streams (e.g., for end-to-end encryption). Such extensions will define their own certificate handling rules. At a minimum, such extensions are encouraged to remain consistent with the rules defined in this specification, specifying additional rules only when necessary.
6543</p>
6544<a name="security-mti"></a><br /><hr />
6545<table summary="layout" cellpadding="0" cellspacing="2" class="TOCbug" align="right"><tr><td class="TOCbug"><a href="#toc">&nbsp;TOC&nbsp;</a></td></tr></table>
6546<a name="rfc.section.13.8"></a><h3>13.8.&nbsp;
6547Mandatory-to-Implement TLS and SASL Technologies</h3>
6548
6549<p>The following TLS ciphersuites and SASL mechanisms are mandatory-to-implement (naturally, implementations MAY support other ciphersuites and mechanisms as well). For security considerations related to TLS ciphersuites, see <a class='info' href='#security-reuse-sasl'>Section&nbsp;13.9.4<span> (</span><span class='info'>Use of SASL</span><span>)</span></a> and <a class='info' href='#TLS'>[TLS]<span> (</span><span class='info'>Dierks, T. and E. Rescorla, &ldquo;The Transport Layer Security (TLS) Protocol Version 1.2,&rdquo; August&nbsp;2008.</span><span>)</span></a>. For security considerations related to SASL mechanisms, see <a class='info' href='#security-reuse-sasl'>Section&nbsp;13.9.4<span> (</span><span class='info'>Use of SASL</span><span>)</span></a>, <a class='info' href='#SASL'>[SASL]<span> (</span><span class='info'>Melnikov, A. and K. Zeilenga, &ldquo;Simple Authentication and Security Layer (SASL),&rdquo; June&nbsp;2006.</span><span>)</span></a>, and specifications for particular SASL mechanisms such as <a class='info' href='#SCRAM'>[SCRAM]<span> (</span><span class='info'>Newman, C., Menon-Sen, A., Melnikov, A., and N. Williams, &ldquo;Salted Challenge Response Authentication Mechanism (SCRAM) SASL and GSS-API Mechanisms,&rdquo; July&nbsp;2010.</span><span>)</span></a>, <a class='info' href='#DIGEST-MD5'>[DIGEST&#8209;MD5]<span> (</span><span class='info'>Leach, P. and C. Newman, &ldquo;Using Digest Authentication as a SASL Mechanism,&rdquo; May&nbsp;2000.</span><span>)</span></a>, and <a class='info' href='#PLAIN'>[PLAIN]<span> (</span><span class='info'>Zeilenga, K., &ldquo;The PLAIN Simple Authentication and Security Layer (SASL) Mechanism,&rdquo; August&nbsp;2006.</span><span>)</span></a>.
6550</p>
6551<a name="security-mti-auth"></a><br /><hr />
6552<table summary="layout" cellpadding="0" cellspacing="2" class="TOCbug" align="right"><tr><td class="TOCbug"><a href="#toc">&nbsp;TOC&nbsp;</a></td></tr></table>
6553<a name="rfc.section.13.8.1"></a><h3>13.8.1.&nbsp;
6554For Authentication Only</h3>
6555
6556<p>For authentication only, servers and clients MUST support
6557 the SASL Salted Challenge Response Authentication Mechanism
6558 <a class='info' href='#SCRAM'>[SCRAM]<span> (</span><span class='info'>Newman, C., Menon-Sen, A., Melnikov, A., and N. Williams, &ldquo;Salted Challenge Response Authentication Mechanism (SCRAM) SASL and GSS-API Mechanisms,&rdquo; July&nbsp;2010.</span><span>)</span></a> -- in particular, the SCRAM-SHA-1 and SCRAM-SHA-1-PLUS variants.
6559</p>
6560<p></p>
6561<blockquote class="text">
6562<p>Security Warning: Even though it is possible to complete authentication only without confidentiality, it is RECOMMENDED for servers and clients to protect the stream with TLS before attempting authentication with SASL, both to help protect the information exchanged during SASL negotiation and to help prevent certain downgrade attacks as described under <a class='info' href='#security-reuse-sasl'>Section&nbsp;13.9.4<span> (</span><span class='info'>Use of SASL</span><span>)</span></a> and <a class='info' href='#security-reuse-tls'>Section&nbsp;13.9.5<span> (</span><span class='info'>Use of TLS</span><span>)</span></a>. Even if TLS is used, implementations SHOULD also enforce channel binding as described under <a class='info' href='#security-reuse-sasl'>Section&nbsp;13.9.4<span> (</span><span class='info'>Use of SASL</span><span>)</span></a>.
6563</p>
6564</blockquote>
6565
6566<p></p>
6567<blockquote class="text">
6568<p>Interoperability Note: The SCRAM-SHA-1 or SASL-SCRAM-SHA-1-PLUS variants of the SCRAM mechanism replace the SASL DIGEST-MD5 mechanism as XMPP's mandatory-to-implement password-based method for authentication only. For backward-compatibility with existing deployed infrastructure, implementations are encouraged to continue supporting the DIGEST-MD5 mechanism as specified in <a class='info' href='#DIGEST-MD5'>[DIGEST&#8209;MD5]<span> (</span><span class='info'>Leach, P. and C. Newman, &ldquo;Using Digest Authentication as a SASL Mechanism,&rdquo; May&nbsp;2000.</span><span>)</span></a>; however, there are known interoperability issues with DIGEST-MD5 that make it impractical in the long term.
6569</p>
6570</blockquote>
6571
6572<a name="security-mti-conf"></a><br /><hr />
6573<table summary="layout" cellpadding="0" cellspacing="2" class="TOCbug" align="right"><tr><td class="TOCbug"><a href="#toc">&nbsp;TOC&nbsp;</a></td></tr></table>
6574<a name="rfc.section.13.8.2"></a><h3>13.8.2.&nbsp;
6575For Confidentiality Only</h3>
6576
6577<p>For confidentiality only, servers MUST support TLS with the TLS_RSA_WITH_AES_128_CBC_SHA ciphersuite.
6578</p>
6579<p></p>
6580<blockquote class="text">
6581<p>Security Warning: Because a connection with confidentiality only has weaker security properties than a connection with both confidentiality and authentication, it is RECOMMENDED for servers and clients to prefer connections with both qualities (e.g., by protecting the stream with TLS before attempting authentication with SASL). In practice, confidentiality only is employed merely for server-to-server connections when the peer server does not present a trusted certificate and the servers use Server Dialback <a class='info' href='#XEP-0220'>[XEP&#8209;0220]<span> (</span><span class='info'>Miller, J., Saint-Andre, P., and P. Hancke, &ldquo;Server Dialback,&rdquo; March&nbsp;2010.</span><span>)</span></a> for weak identity verification, but TLS with confidentiality only is still desirable to protect the connection against casual eavesdropping.
6582</p>
6583</blockquote>
6584
6585<a name="security-mti-bothpass"></a><br /><hr />
6586<table summary="layout" cellpadding="0" cellspacing="2" class="TOCbug" align="right"><tr><td class="TOCbug"><a href="#toc">&nbsp;TOC&nbsp;</a></td></tr></table>
6587<a name="rfc.section.13.8.3"></a><h3>13.8.3.&nbsp;
6588For Confidentiality and Authentication with Passwords</h3>
6589
6590<p>For both confidentiality and authentication with passwords, servers and clients MUST implement TLS with the TLS_RSA_WITH_AES_128_CBC_SHA ciphersuite plus SASL SCRAM, in particular the SCRAM&#8209;SHA&#8209;1 and SCRAM&#8209;SHA&#8209;1&#8209;PLUS variants (with SCRAM&#8209;SHA1&#8209;PLUS being preferred, as described under <a class='info' href='#security-reuse-sasl'>Section&nbsp;13.9.4<span> (</span><span class='info'>Use of SASL</span><span>)</span></a>).
6591</p>
6592<p>As further explained in the following Security Warning, in certain circumstances a server MAY offer TLS with the TLS_RSA_WITH_AES_128_CBC_SHA ciphersuite plus SASL PLAIN when it is not possible to offer more secure alternatives; in addition, clients SHOULD implement PLAIN over TLS in order to maximize interoperability with servers that are not able to deploy more secure alternatives.
6593</p>
6594<p></p>
6595<blockquote class="text">
6596<p>Security Warning: In practice, many
6597 servers offer, and many clients use, TLS plus SASL PLAIN. The
6598 SCRAM-SHA-1 and especially SCRAM-SHA-1-PLUS variants of the
6599 SCRAM mechanism are strongly preferred over the PLAIN
6600 mechanism because of their superior security properties
6601 (including for SCRAM-SHA-1-PLUS the ability to enforce channel
6602 binding as described under
6603 <a class='info' href='#security-reuse-sasl'>Section&nbsp;13.9.4<span> (</span><span class='info'>Use of SASL</span><span>)</span></a>). A client SHOULD treat
6604 TLS plus SASL PLAIN as a technology of last resort to be used
6605 only when interacting with a server that does not offer SCRAM
6606 (or other alternatives that are more secure than TLS plus SASL
6607 PLAIN), MUST prefer more secure mechanisms (e.g., EXTERNAL,
6608 SCRAM-SHA-1-PLUS, SCRAM-SHA-1, or the older DIGEST-MD5
6609 mechanism) to the PLAIN mechanism, and MUST NOT use the PLAIN
6610 mechanism if the stream does not at a minimum have
6611 confidentiality and integrity protection via TLS with full
6612 certificate validation as described under
6613 <a class='info' href='#security-certificates-validation-server'>Section&nbsp;13.7.2.1<span> (</span><span class='info'>Server Certificates</span><span>)</span></a>. A
6614 server MUST NOT offer SASL PLAIN if the confidentiality and
6615 integrity of the stream are not protected via TLS or an
6616 equivalent security layer. A server SHOULD NOT offer TLS plus
6617 SASL PLAIN unless it is unable to offer some variant of SASL
6618 SCRAM (or other alternatives that are more secure than TLS
6619 plus SASL PLAIN), e.g., because the XMPP service depends for
6620 authentication purposes on a database or directory that is not
6621 under the control of the XMPP administrators, such as
6622 Pluggable Authentication Modules (PAM), an Lightweight
6623 Directory Access Protocol (LDAP) directory <a class='info' href='#LDAP'>[LDAP]<span> (</span><span class='info'>Zeilenga, K., &ldquo;Lightweight Directory Access Protocol (LDAP): Technical Specification Road Map,&rdquo; June&nbsp;2006.</span><span>)</span></a>, or an Authentication, Authorization, and Accounting (AAA) key management protocol (for guidance, refer to <a class='info' href='#AAA'>[AAA]<span> (</span><span class='info'>Housley, R. and B. Aboba, &ldquo;Guidance for Authentication, Authorization, and Accounting (AAA) Key Management,&rdquo; July&nbsp;2007.</span><span>)</span></a>). However, offering TLS plus SASL PLAIN even when the server supports more secure alternatives might be appropriate if the server needs to enable interoperability with an installed base of clients that do not yet support SCRAM or other alternatives that are more secure than TLS plus SASL PLAIN.
6624</p>
6625</blockquote>
6626
6627<a name="security-mti-bothnopass"></a><br /><hr />
6628<table summary="layout" cellpadding="0" cellspacing="2" class="TOCbug" align="right"><tr><td class="TOCbug"><a href="#toc">&nbsp;TOC&nbsp;</a></td></tr></table>
6629<a name="rfc.section.13.8.4"></a><h3>13.8.4.&nbsp;
6630For Confidentiality and Authentication without Passwords</h3>
6631
6632<p>For both confidentiality and authentication without passwords, servers MUST and clients SHOULD implement TLS with the TLS_RSA_WITH_AES_128_CBC_SHA ciphersuite plus the SASL EXTERNAL mechanism (see Appendix A of <a class='info' href='#SASL'>[SASL]<span> (</span><span class='info'>Melnikov, A. and K. Zeilenga, &ldquo;Simple Authentication and Security Layer (SASL),&rdquo; June&nbsp;2006.</span><span>)</span></a>) with PKIX certificates.
6633</p>
6634<a name="security-reuse"></a><br /><hr />
6635<table summary="layout" cellpadding="0" cellspacing="2" class="TOCbug" align="right"><tr><td class="TOCbug"><a href="#toc">&nbsp;TOC&nbsp;</a></td></tr></table>
6636<a name="rfc.section.13.9"></a><h3>13.9.&nbsp;
6637Technology Reuse</h3>
6638
6639<a name="security-reuse-base64"></a><br /><hr />
6640<table summary="layout" cellpadding="0" cellspacing="2" class="TOCbug" align="right"><tr><td class="TOCbug"><a href="#toc">&nbsp;TOC&nbsp;</a></td></tr></table>
6641<a name="rfc.section.13.9.1"></a><h3>13.9.1.&nbsp;
6642Use of Base 64 in SASL</h3>
6643
6644<p>Both the client and the server MUST verify any base 64 data received during <a class='info' href='#sasl'>SASL negotiation<span> (</span><span class='info'>SASL Negotiation</span><span>)</span></a>. An implementation MUST reject (not ignore) any characters that are not explicitly allowed by the base 64 alphabet; this helps to guard against creation of a covert channel that could be used to "leak" information.
6645</p>
6646<p>An implementation MUST NOT break on invalid input and MUST reject any sequence of base 64 characters containing the pad ('=') character if that character is included as something other than the last character of the data (e.g., "=AAA" or "BBBB=CCC"); this helps to guard against buffer overflow attacks and other attacks on the implementation.
6647</p>
6648<p>While base 64 encoding visually hides otherwise easily recognized information (such as passwords), it does not provide any computational confidentiality.
6649</p>
6650<p>All uses of base 64 encoding MUST follow the definition in Section 4 of <a class='info' href='#BASE64'>[BASE64]<span> (</span><span class='info'>Josefsson, S., &ldquo;The Base16, Base32, and Base64 Data Encodings,&rdquo; October&nbsp;2006.</span><span>)</span></a> and padding bits MUST be set to zero.
6651</p>
6652<a name="security-reuse-dns"></a><br /><hr />
6653<table summary="layout" cellpadding="0" cellspacing="2" class="TOCbug" align="right"><tr><td class="TOCbug"><a href="#toc">&nbsp;TOC&nbsp;</a></td></tr></table>
6654<a name="rfc.section.13.9.2"></a><h3>13.9.2.&nbsp;
6655Use of DNS</h3>
6656
6657<p>XMPP typically relies on the Domain Name System
6658 (specifically <a class='info' href='#DNS-SRV'>[DNS&#8209;SRV]<span> (</span><span class='info'>Gulbrandsen, A., Vixie, P., and L. Esibov, &ldquo;A DNS RR for specifying the location of services (DNS SRV),&rdquo; February&nbsp;2000.</span><span>)</span></a> records) to resolve a
6659 fully qualified domain name to an IP address before a client connects to a server or before a peer server connects to another server. Before attempting to negotiate an XML stream, the initiating entity MUST NOT proceed until it has resolved the DNS domain name of the receiving entity as specified under <a class='info' href='#tcp'>Section&nbsp;3<span> (</span><span class='info'>TCP Binding</span><span>)</span></a> (although it is not necessary to resolve the DNS domain name before each connection attempt, because DNS resolution results can be temporarily cached in accordance with time-to-live values). However, in the absence of a secure DNS option (e.g., as provided by <a class='info' href='#DNSSEC'>[DNSSEC]<span> (</span><span class='info'>Arends, R., Austein, R., Larson, M., Massey, D., and S. Rose, &ldquo;DNS Security Introduction and Requirements,&rdquo; March&nbsp;2005.</span><span>)</span></a>), a malicious attacker with access to the DNS server data, or able to cause spoofed answers to be cached in a recursive resolver, can potentially cause the initiating entity to connect to any XMPP server chosen by the attacker. Deployment and validation of server certificates help to prevent such attacks.
6660</p>
6661<a name="security-reuse-hash"></a><br /><hr />
6662<table summary="layout" cellpadding="0" cellspacing="2" class="TOCbug" align="right"><tr><td class="TOCbug"><a href="#toc">&nbsp;TOC&nbsp;</a></td></tr></table>
6663<a name="rfc.section.13.9.3"></a><h3>13.9.3.&nbsp;
6664Use of Hash Functions</h3>
6665
6666<p>XMPP itself does not directly mandate the use of any particular cryptographic hash function. However, technologies on which XMPP depends (e.g., TLS and particular SASL mechanisms), as well as various XMPP extensions, might make use of cryptographic hash functions. Those who implement XMPP technologies or who develop XMPP extensions are advised to closely monitor the state of the art regarding attacks against cryptographic hash functions in Internet protocols as they relate to XMPP. For helpful guidance, refer to <a class='info' href='#HASHES'>[HASHES]<span> (</span><span class='info'>Hoffman, P. and B. Schneier, &ldquo;Attacks on Cryptographic Hashes in Internet Protocols,&rdquo; November&nbsp;2005.</span><span>)</span></a>.
6667</p>
6668<a name="security-reuse-sasl"></a><br /><hr />
6669<table summary="layout" cellpadding="0" cellspacing="2" class="TOCbug" align="right"><tr><td class="TOCbug"><a href="#toc">&nbsp;TOC&nbsp;</a></td></tr></table>
6670<a name="rfc.section.13.9.4"></a><h3>13.9.4.&nbsp;
6671Use of SASL</h3>
6672
6673<p>Because the initiating entity chooses an acceptable SASL mechanism from the list presented by the receiving entity, the initiating entity depends on the receiving entity's list for authentication. This dependency introduces the possibility of a downgrade attack if an attacker can gain control of the channel and therefore present a weak list of mechanisms. To mitigate this attack, the parties SHOULD protect the channel using TLS before attempting SASL negotiation and either perform full certificate validation as described under <a class='info' href='#security-certificates-validation-server'>Section&nbsp;13.7.2.1<span> (</span><span class='info'>Server Certificates</span><span>)</span></a> or use a SASL mechanism that provides channel bindings, such as SCRAM-SHA-1-PLUS. (Protecting the channel via TLS with full certificate validation can help to ensure the confidentiality and integrity of the information exchanged during SASL negotiation.)
6674</p>
6675<p>The SASL framework itself does not provide a method for binding SASL authentication to a security layer providing confidentiality and integrity protection that was negotiated at a lower layer (e.g., TLS). Such a binding is known as a "channel binding" (see <a class='info' href='#CHANNEL'>[CHANNEL]<span> (</span><span class='info'>Williams, N., &ldquo;On the Use of Channel Bindings to Secure Channels,&rdquo; November&nbsp;2007.</span><span>)</span></a>). Some SASL mechanisms provide channel bindings, which in the case of XMPP would typically be a binding to TLS (see <a class='info' href='#CHANNEL-TLS'>[CHANNEL&#8209;TLS]<span> (</span><span class='info'>Altman, J., Williams, N., and L. Zhu, &ldquo;Channel Bindings for TLS,&rdquo; July&nbsp;2010.</span><span>)</span></a>). If a SASL mechanism provides a channel binding (e.g., this is true of <a class='info' href='#SCRAM'>[SCRAM]<span> (</span><span class='info'>Newman, C., Menon-Sen, A., Melnikov, A., and N. Williams, &ldquo;Salted Challenge Response Authentication Mechanism (SCRAM) SASL and GSS-API Mechanisms,&rdquo; July&nbsp;2010.</span><span>)</span></a>), then XMPP entities using that mechanism SHOULD prefer the channel binding variant (e.g., preferring "SCRAM-SHA-1-PLUS" over "SCRAM-SHA-1"). If a SASL mechanism does not provide a channel binding, then the mechanism cannot provide a way to verify that the source and destination end points to which the lower layer's security is bound are equivalent to the end points that SASL is authenticating; furthermore, if the end points are not identical, then the lower layer's security cannot be trusted to protect data transmitted between the SASL-authenticated entities. In such a situation, a SASL security layer SHOULD be negotiated that effectively ignores the presence of the lower-layer security.
6676</p>
6677<p>Many deployed XMPP services authenticate client connections by means of passwords. It is well known that most human users choose relatively weak passwords. Although service provisioning is out of scope for this document, XMPP servers that allow password-based authentication SHOULD enforce minimal criteria for password strength to help prevent dictionary attacks. Because all password-based authentication mechanisms are susceptible to password guessing attacks, XMPP servers MUST limit the number of retries allowed during SASL authentication, as described under <a class='info' href='#sasl-process-neg-failure'>Section&nbsp;6.4.5<span> (</span><span class='info'>SASL Failure</span><span>)</span></a>.
6678</p>
6679<p>Some SASL mechanisms (e.g., <a class='info' href='#ANONYMOUS'>[ANONYMOUS]<span> (</span><span class='info'>Zeilenga, K., &ldquo;Anonymous Simple Authentication and Security Layer (SASL) Mechanism,&rdquo; June&nbsp;2006.</span><span>)</span></a>) do not provide strong peer entity authentication of the client to the server. Service administrators are advised to enable such mechanisms with caution. Best practices for the use of the SASL ANONYMOUS mechanism in XMPP are described in <a class='info' href='#XEP-0175'>[XEP&#8209;0175]<span> (</span><span class='info'>Saint-Andre, P., &ldquo;Best Practices for Use of SASL ANONYMOUS,&rdquo; September&nbsp;2009.</span><span>)</span></a>.
6680</p>
6681<a name="security-reuse-tls"></a><br /><hr />
6682<table summary="layout" cellpadding="0" cellspacing="2" class="TOCbug" align="right"><tr><td class="TOCbug"><a href="#toc">&nbsp;TOC&nbsp;</a></td></tr></table>
6683<a name="rfc.section.13.9.5"></a><h3>13.9.5.&nbsp;
6684Use of TLS</h3>
6685
6686<p>Implementations of TLS typically support multiple versions of the Transport Layer Security protocol as well as the older Secure Sockets Layer (SSL) protocol. Because of known security vulnerabilities, XMPP servers and clients MUST NOT request, offer, or use SSL 2.0. For further details, see Appendix E.2 of <a class='info' href='#TLS'>[TLS]<span> (</span><span class='info'>Dierks, T. and E. Rescorla, &ldquo;The Transport Layer Security (TLS) Protocol Version 1.2,&rdquo; August&nbsp;2008.</span><span>)</span></a> along with <a class='info' href='#TLS-SSL2'>[TLS&#8209;SSL2]<span> (</span><span class='info'>Turner, S. and T. Polk, &ldquo;Prohibiting Secure Sockets Layer (SSL) Version 2.0,&rdquo; March&nbsp;2011.</span><span>)</span></a>.
6687</p>
6688<p>To prevent man-in-the-middle attacks, the TLS client (which might be an XMPP client or an XMPP server) MUST verify the certificate of the TLS server and MUST check its understanding of the server FQDN against the server's identity as presented in the TLS Certificate message as described under <a class='info' href='#security-certificates-validation-server'>Section&nbsp;13.7.2.1<span> (</span><span class='info'>Server Certificates</span><span>)</span></a> (for further details, see <a class='info' href='#TLS-CERTS'>[TLS&#8209;CERTS]<span> (</span><span class='info'>Saint-Andre, P. and J. Hodges, &ldquo;Representation and Verification of Domain-Based Application Service Identity within Internet Public Key Infrastructure Using X.509 (PKIX) Certificates in the Context of Transport Layer Security (TLS),&rdquo; March&nbsp;2011.</span><span>)</span></a>.
6689</p>
6690<p>Support for TLS renegotiation is strictly OPTIONAL. However, implementations that support TLS renegotiation MUST implement and use the TLS Renegotiation Extension <a class='info' href='#TLS-NEG'>[TLS&#8209;NEG]<span> (</span><span class='info'>Rescorla, E., Ray, M., Dispensa, S., and N. Oskov, &ldquo;Transport Layer Security (TLS) Renegotiation Indication Extension,&rdquo; February&nbsp;2010.</span><span>)</span></a>. Further details are provided under <a class='info' href='#tls-rules-renegotiation'>Section&nbsp;5.3.5<span> (</span><span class='info'>TLS Renegotiation</span><span>)</span></a>.
6691</p>
6692<a name="security-reuse-utf8"></a><br /><hr />
6693<table summary="layout" cellpadding="0" cellspacing="2" class="TOCbug" align="right"><tr><td class="TOCbug"><a href="#toc">&nbsp;TOC&nbsp;</a></td></tr></table>
6694<a name="rfc.section.13.9.6"></a><h3>13.9.6.&nbsp;
6695Use of UTF-8</h3>
6696
6697<p>The use of UTF-8 makes it possible to transport non-ASCII characters, and thus enables character "spoofing" scenarios, in which a displayed value appears to be something other than it is. Furthermore, there are known attack scenarios related to the decoding of UTF-8 data. On both of these points, refer to <a class='info' href='#UTF-8'>[UTF&#8209;8]<span> (</span><span class='info'>Yergeau, F., &ldquo;UTF-8, a transformation format of ISO 10646,&rdquo; November&nbsp;2003.</span><span>)</span></a> for more information.
6698</p>
6699<a name="security-reuse-xml"></a><br /><hr />
6700<table summary="layout" cellpadding="0" cellspacing="2" class="TOCbug" align="right"><tr><td class="TOCbug"><a href="#toc">&nbsp;TOC&nbsp;</a></td></tr></table>
6701<a name="rfc.section.13.9.7"></a><h3>13.9.7.&nbsp;
6702Use of XML</h3>
6703
6704<p>Because XMPP is an application profile of the Extensible Markup Language <a class='info' href='#XML'>[XML]<span> (</span><span class='info'>Maler, E., Yergeau, F., Sperberg-McQueen, C., Paoli, J., and T. Bray, &ldquo;Extensible Markup Language (XML) 1.0 (Fifth Edition),&rdquo; November&nbsp;2008.</span><span>)</span></a>, many of the security considerations described in <a class='info' href='#XML-MEDIA'>[XML&#8209;MEDIA]<span> (</span><span class='info'>Murata, M., St. Laurent, S., and D. Kohn, &ldquo;XML Media Types,&rdquo; January&nbsp;2001.</span><span>)</span></a> and <a class='info' href='#XML-GUIDE'>[XML&#8209;GUIDE]<span> (</span><span class='info'>Hollenbeck, S., Rose, M., and L. Masinter, &ldquo;Guidelines for the Use of Extensible Markup Language (XML) within IETF Protocols,&rdquo; January&nbsp;2003.</span><span>)</span></a> also apply to XMPP. Several aspects of XMPP mitigate the risks described there, such as the prohibitions specified under <a class='info' href='#xml-restrictions'>Section&nbsp;11.1<span> (</span><span class='info'>XML Restrictions</span><span>)</span></a> and the lack of external references to style sheets or transformations, but these mitigating factors are by no means comprehensive.
6705</p>
6706<a name="security-leaks"></a><br /><hr />
6707<table summary="layout" cellpadding="0" cellspacing="2" class="TOCbug" align="right"><tr><td class="TOCbug"><a href="#toc">&nbsp;TOC&nbsp;</a></td></tr></table>
6708<a name="rfc.section.13.10"></a><h3>13.10.&nbsp;
6709Information Leaks</h3>
6710
6711<a name="security-leaks-ipaddress"></a><br /><hr />
6712<table summary="layout" cellpadding="0" cellspacing="2" class="TOCbug" align="right"><tr><td class="TOCbug"><a href="#toc">&nbsp;TOC&nbsp;</a></td></tr></table>
6713<a name="rfc.section.13.10.1"></a><h3>13.10.1.&nbsp;
6714IP Addresses</h3>
6715
6716<p>A client's IP address and method of access MUST NOT be made public by a server (e.g., as typically occurs in <a class='info' href='#IRC'>[IRC]<span> (</span><span class='info'>Kalt, C., &ldquo;Internet Relay Chat: Architecture,&rdquo; April&nbsp;2000.</span><span>)</span></a>).
6717</p>
6718<a name="security-leaks-presence"></a><br /><hr />
6719<table summary="layout" cellpadding="0" cellspacing="2" class="TOCbug" align="right"><tr><td class="TOCbug"><a href="#toc">&nbsp;TOC&nbsp;</a></td></tr></table>
6720<a name="rfc.section.13.10.2"></a><h3>13.10.2.&nbsp;
6721Presence Information</h3>
6722
6723<p>One of the core aspects of XMPP is presence: information about the network availability of an XMPP entity (i.e., whether the entity is currently online or offline). A "presence leak" occurs when an entity's network availability is inadvertently and involuntarily revealed to a second entity that is not authorized to know the first entity's network availability.
6724</p>
6725<p>Although presence is discussed more fully in <a class='info' href='#XMPP-IM'>[XMPP&#8209;IM]<span> (</span><span class='info'>Saint-Andre, P., &ldquo;Extensible Messaging and Presence Protocol (XMPP): Instant Messaging and Presence,&rdquo; March&nbsp;2011.</span><span>)</span></a>, it is important to note that an XMPP server MUST NOT leak presence. In particular at the core XMPP level, real-time addressing and network availability is associated with a specific connected resource; therefore, any disclosure of a connected resource's full JID comprises a presence leak. To help prevent such a presence leak, a server MUST NOT return different stanza errors depending on whether a potential attacker sends XML stanzas to the entity's bare JID (&lt;localpart@domainpart&gt;) or full JID (&lt;localpart@domainpart/resourcepart&gt;).
6726</p>
6727<a name="security-harvesting"></a><br /><hr />
6728<table summary="layout" cellpadding="0" cellspacing="2" class="TOCbug" align="right"><tr><td class="TOCbug"><a href="#toc">&nbsp;TOC&nbsp;</a></td></tr></table>
6729<a name="rfc.section.13.11"></a><h3>13.11.&nbsp;
6730Directory Harvesting</h3>
6731
6732<p>If a server generates an error stanza in response to receiving a stanza for a user account that does not exist, using the &lt;service-unavailable/&gt; stanza error condition (<a class='info' href='#stanzas-error-conditions-service-unavailable'>Section&nbsp;8.3.3.19<span> (</span><span class='info'>service-unavailable</span><span>)</span></a>) can help protect against directory harvesting attacks, since this is the same error condition that is returned if, for instance, the namespace of an IQ child element is not understood, or if "offline message storage" (<a class='info' href='#XEP-0160'>[XEP&#8209;0160]<span> (</span><span class='info'>Saint-Andre, P., &ldquo;Best Practices for Handling Offline Messages,&rdquo; January&nbsp;2006.</span><span>)</span></a>) or message forwarding is not enabled for a domain. However, subtle differences in the exact XML of error stanzas, as well as in the timing with which such errors are returned, can enable an attacker to determine the network presence of a user when more advanced blocking technologies are not used (see for instance <a class='info' href='#XEP-0016'>[XEP&#8209;0016]<span> (</span><span class='info'>Millard, P. and P. Saint-Andre, &ldquo;Privacy Lists,&rdquo; February&nbsp;2007.</span><span>)</span></a> and <a class='info' href='#XEP-0191'>[XEP&#8209;0191]<span> (</span><span class='info'>Saint-Andre, P., &ldquo;Simple Communications Blocking,&rdquo; February&nbsp;2007.</span><span>)</span></a>). Therefore, a server that exercises a higher level of caution might not return any error at all in response to certain kinds of received stanzas, so that a non-existent user appears to behave like a user that has no interest in conversing with the sender.
6733</p>
6734<a name="security-dos"></a><br /><hr />
6735<table summary="layout" cellpadding="0" cellspacing="2" class="TOCbug" align="right"><tr><td class="TOCbug"><a href="#toc">&nbsp;TOC&nbsp;</a></td></tr></table>
6736<a name="rfc.section.13.12"></a><h3>13.12.&nbsp;
6737Denial of Service</h3>
6738
6739<p><a class='info' href='#DOS'>[DOS]<span> (</span><span class='info'>Handley, M., Rescorla, E., and IAB, &ldquo;Internet Denial-of-Service Considerations,&rdquo; December&nbsp;2006.</span><span>)</span></a> defines denial of service as follows:
6740</p>
6741<p>
6742 </p>
6743<blockquote class="text"><dl>
6744<dt></dt>
6745<dd>A denial-of-service (DoS) attack is an attack in which one or more machines target a victim and attempt to prevent the victim from doing useful work. The victim can be a network server, client or router, a network link or an entire network, an individual Internet user or a company doing business using the Internet, an Internet Service Provider (ISP), country, or any combination of or variant on these.
6746</dd>
6747</dl></blockquote><p>
6748
6749</p>
6750<p>Some considerations discussed in this document help to prevent denial-of-service attacks (e.g., the mandate that a server MUST NOT process XML stanzas from clients that have not yet provided appropriate authentication credentials and MUST NOT process XML stanzas from peer servers whose identity it has not either authenticated via SASL or weakly verified via Server Dialback).
6751</p>
6752<p>In addition, <a class='info' href='#XEP-0205'>[XEP&#8209;0205]<span> (</span><span class='info'>Saint-Andre, P., &ldquo;Best Practices to Discourage Denial of Service Attacks,&rdquo; January&nbsp;2009.</span><span>)</span></a> provides a detailed discussion of potential denial-of-service attacks against XMPP systems along with best practices for preventing such attacks. The recommendations include:
6753</p>
6754<p>
6755 </p>
6756<ol class="text">
6757<li>A server implementation SHOULD enable a server administrator to limit the number of TCP connections that it will accept from a given IP address at any one time. If an entity attempts to connect but the maximum number of TCP connections has been reached, the receiving server MUST NOT allow the new connection to proceed.
6758</li>
6759<li>A server implementation SHOULD enable a server administrator to limit the number of TCP connection attempts that it will accept from a given IP address in a given time period. If an entity attempts to connect but the maximum number of connection attempts has been reached, the receiving server MUST NOT allow the new connection to proceed.
6760</li>
6761<li>A server implementation SHOULD enable a server administrator to limit the number of connected resources it will allow an account to bind at any one time. If a client attempts to bind a resource but it has already reached the configured number of allowable resources, the receiving server MUST return a &lt;resource-constraint/&gt; stanza error (<a class='info' href='#stanzas-error-conditions-resource-constraint'>Section&nbsp;8.3.3.18<span> (</span><span class='info'>resource-constraint</span><span>)</span></a>).
6762</li>
6763<li>A server implementation SHOULD enable a server administrator to limit the size of stanzas it will accept from a connected client or peer server (where "size" is inclusive of all XML markup as defined in Section 2.4 of <a class='info' href='#XML'>[XML]<span> (</span><span class='info'>Maler, E., Yergeau, F., Sperberg-McQueen, C., Paoli, J., and T. Bray, &ldquo;Extensible Markup Language (XML) 1.0 (Fifth Edition),&rdquo; November&nbsp;2008.</span><span>)</span></a>, from the opening "&lt;" character of the stanza to the closing "&gt;" character). A deployed server's maximum stanza size MUST NOT be smaller than 10000 bytes, which reflects a reasonable compromise between the benefits of expressiveness for originating entities and the costs of stanza processing for servers. A server implementation SHOULD NOT blindly set 10000 bytes as the value for all deployments but instead SHOULD enable server administrators to set their own limits. If a connected resource or peer server sends a stanza that violates the upper limit, the receiving server MUST either return a &lt;policy-violation/&gt; stanza error (<a class='info' href='#stanzas-error-conditions-policy-violation'>Section&nbsp;8.3.3.12<span> (</span><span class='info'>policy-violation</span><span>)</span></a>), thus allowing the sender to recover, or close the stream with a &lt;policy-violation/&gt; stream error (<a class='info' href='#streams-error-conditions-policy-violation'>Section&nbsp;4.9.3.14<span> (</span><span class='info'>policy-violation</span><span>)</span></a>).
6764</li>
6765<li>A server implementation SHOULD enable a server administrator to limit the number of XML stanzas that a connected client is allowed to send to distinct recipients within a given time period. If a connected client sends too many stanzas to distinct recipients in a given time period, the receiving server SHOULD NOT process the stanza and instead SHOULD return a &lt;policy-violation/&gt; stanza error (<a class='info' href='#stanzas-error-conditions-policy-violation'>Section&nbsp;8.3.3.12<span> (</span><span class='info'>policy-violation</span><span>)</span></a>).
6766</li>
6767<li>A server implementation SHOULD enable a server administrator to limit the amount of bandwidth it will allow a connected client or peer server to use in a given time period.
6768</li>
6769<li>A server implementation MAY enable a server administrator to limit the types of stanzas (based on the extended content "payload") that it will allow a connected resource or peer server send over an active connection. Such limits and restrictions are a matter of deployment policy.
6770</li>
6771<li>A server implementation MAY refuse to route or deliver any stanza that it considers to be abusive, with or without returning an error to the sender.
6772</li>
6773</ol><p>
6774
6775</p>
6776<p>For more detailed recommendations regarding denial-of-service attacks in XMPP systems, refer to <a class='info' href='#XEP-0205'>[XEP&#8209;0205]<span> (</span><span class='info'>Saint-Andre, P., &ldquo;Best Practices to Discourage Denial of Service Attacks,&rdquo; January&nbsp;2009.</span><span>)</span></a>.
6777</p>
6778<a name="security-firewalls"></a><br /><hr />
6779<table summary="layout" cellpadding="0" cellspacing="2" class="TOCbug" align="right"><tr><td class="TOCbug"><a href="#toc">&nbsp;TOC&nbsp;</a></td></tr></table>
6780<a name="rfc.section.13.13"></a><h3>13.13.&nbsp;
6781Firewalls</h3>
6782
6783<p>Although DNS SRV records can instruct connecting entities to use TCP ports other than 5222 (client-to-server) and 5269 (server-to-server), communication using XMPP typically occurs over those ports, which are registered with the IANA (see <a class='info' href='#iana'>Section&nbsp;14<span> (</span><span class='info'>IANA Considerations</span><span>)</span></a>). Use of these well-known ports allows administrators to easily enable or disable XMPP activity through existing and commonly deployed firewalls.
6784</p>
6785<a name="security-federation"></a><br /><hr />
6786<table summary="layout" cellpadding="0" cellspacing="2" class="TOCbug" align="right"><tr><td class="TOCbug"><a href="#toc">&nbsp;TOC&nbsp;</a></td></tr></table>
6787<a name="rfc.section.13.14"></a><h3>13.14.&nbsp;
6788Interdomain Federation</h3>
6789
6790<p>The term "federation" is commonly used to describe communication between two servers.
6791</p>
6792<p>Because service provisioning is a matter of policy, it is OPTIONAL for any given server to support federation. If a particular server enables federation, it SHOULD enable strong security as previously described to ensure both authentication and confidentiality; compliant implementations SHOULD support TLS and SASL for this purpose.
6793</p>
6794<p>Before RFC 3920 defined TLS plus SASL EXTERNAL with certificates for encryption and authentication of server-to-server streams, the only method for weak identity verification of a peer server was Server Dialback as defined in <a class='info' href='#XEP-0220'>[XEP&#8209;0220]<span> (</span><span class='info'>Miller, J., Saint-Andre, P., and P. Hancke, &ldquo;Server Dialback,&rdquo; March&nbsp;2010.</span><span>)</span></a>. Even when <a class='info' href='#DNSSEC'>[DNSSEC]<span> (</span><span class='info'>Arends, R., Austein, R., Larson, M., Massey, D., and S. Rose, &ldquo;DNS Security Introduction and Requirements,&rdquo; March&nbsp;2005.</span><span>)</span></a> is used, Server Dialback provides only weak identity verification and provides no confidentiality or integrity. At the time of writing, Server Dialback is still the most widely used technique for some level of assurance over server-to-server streams. This reality introduces the possibility of a downgrade attack from TLS + SASL EXTERNAL to Server Dialback if an attacker can gain control of the channel and therefore convince the initiating server that the receiving server does not support TLS or does not have an appropriate certificate. To help prevent this attack, the parties SHOULD protect the channel using TLS before proceeding, even if the presented certificates are self-signed or otherwise untrusted.
6795</p>
6796<a name="security-nonrepudiation"></a><br /><hr />
6797<table summary="layout" cellpadding="0" cellspacing="2" class="TOCbug" align="right"><tr><td class="TOCbug"><a href="#toc">&nbsp;TOC&nbsp;</a></td></tr></table>
6798<a name="rfc.section.13.15"></a><h3>13.15.&nbsp;
6799Non-Repudiation</h3>
6800
6801<p>Systems that provide both peer entity authentication and data integrity have the potential to enable an entity to prove to a third party that another entity intended to send particular data. Although XMPP systems can provide both peer entity authentication and data integrity, XMPP was never designed to provide non-repudiation.
6802</p>
6803<a name="iana"></a><br /><hr />
6804<table summary="layout" cellpadding="0" cellspacing="2" class="TOCbug" align="right"><tr><td class="TOCbug"><a href="#toc">&nbsp;TOC&nbsp;</a></td></tr></table>
6805<a name="rfc.section.14"></a><h3>14.&nbsp;
6806IANA Considerations</h3>
6807
6808<p>The following subsections update the registrations provided in <a class='info' href='#RFC3920'>[RFC3920]<span> (</span><span class='info'>Saint-Andre, P., Ed., &ldquo;Extensible Messaging and Presence Protocol (XMPP): Core,&rdquo; October&nbsp;2004.</span><span>)</span></a>. This section is to be interpreted according to <a class='info' href='#IANA-GUIDE'>[IANA&#8209;GUIDE]<span> (</span><span class='info'>Narten, T. and H. Alvestrand, &ldquo;Guidelines for Writing an IANA Considerations Section in RFCs,&rdquo; May&nbsp;2008.</span><span>)</span></a>.
6809</p>
6810<a name="iana-ns-tls"></a><br /><hr />
6811<table summary="layout" cellpadding="0" cellspacing="2" class="TOCbug" align="right"><tr><td class="TOCbug"><a href="#toc">&nbsp;TOC&nbsp;</a></td></tr></table>
6812<a name="rfc.section.14.1"></a><h3>14.1.&nbsp;
6813XML Namespace Name for TLS Data</h3>
6814
6815<p>A URN sub-namespace for STARTTLS negotiation data in the Extensible Messaging and Presence Protocol (XMPP) is defined as follows. (This namespace name adheres to the format defined in <a class='info' href='#XML-REG'>[XML&#8209;REG]<span> (</span><span class='info'>Mealling, M., &ldquo;The IETF XML Registry,&rdquo; January&nbsp;2004.</span><span>)</span></a>.)
6816</p>
6817<p></p>
6818<blockquote class="text"><dl>
6819<dt>URI:</dt>
6820<dd>urn:ietf:params:xml:ns:xmpp-tls
6821</dd>
6822<dt>Specification:</dt>
6823<dd>RFC 6120
6824</dd>
6825<dt>Description:</dt>
6826<dd>This is the XML namespace name for STARTTLS negotiation data in the Extensible Messaging and Presence Protocol (XMPP) as defined by RFC 6120.
6827</dd>
6828<dt>Registrant Contact:</dt>
6829<dd>IESG &lt;iesg@ietf.org&gt;
6830</dd>
6831</dl></blockquote>
6832
6833<a name="iana-ns-sasl"></a><br /><hr />
6834<table summary="layout" cellpadding="0" cellspacing="2" class="TOCbug" align="right"><tr><td class="TOCbug"><a href="#toc">&nbsp;TOC&nbsp;</a></td></tr></table>
6835<a name="rfc.section.14.2"></a><h3>14.2.&nbsp;
6836XML Namespace Name for SASL Data</h3>
6837
6838<p>A URN sub-namespace for SASL negotiation data in the Extensible Messaging and Presence Protocol (XMPP) is defined as follows. (This namespace name adheres to the format defined in <a class='info' href='#XML-REG'>[XML&#8209;REG]<span> (</span><span class='info'>Mealling, M., &ldquo;The IETF XML Registry,&rdquo; January&nbsp;2004.</span><span>)</span></a>.)
6839</p>
6840<p></p>
6841<blockquote class="text"><dl>
6842<dt>URI:</dt>
6843<dd>urn:ietf:params:xml:ns:xmpp-sasl
6844</dd>
6845<dt>Specification:</dt>
6846<dd>RFC 6120
6847</dd>
6848<dt>Description:</dt>
6849<dd>This is the XML namespace name for SASL negotiation data in the Extensible Messaging and Presence Protocol (XMPP) as defined by RFC 6120.
6850</dd>
6851<dt>Registrant Contact:</dt>
6852<dd>IESG &lt;iesg@ietf.org&gt;
6853</dd>
6854</dl></blockquote>
6855
6856<a name="iana-ns-streams"></a><br /><hr />
6857<table summary="layout" cellpadding="0" cellspacing="2" class="TOCbug" align="right"><tr><td class="TOCbug"><a href="#toc">&nbsp;TOC&nbsp;</a></td></tr></table>
6858<a name="rfc.section.14.3"></a><h3>14.3.&nbsp;
6859XML Namespace Name for Stream Errors</h3>
6860
6861<p>A URN sub-namespace for stream error data in the Extensible Messaging and Presence Protocol (XMPP) is defined as follows. (This namespace name adheres to the format defined in <a class='info' href='#XML-REG'>[XML&#8209;REG]<span> (</span><span class='info'>Mealling, M., &ldquo;The IETF XML Registry,&rdquo; January&nbsp;2004.</span><span>)</span></a>.)
6862</p>
6863<p></p>
6864<blockquote class="text"><dl>
6865<dt>URI:</dt>
6866<dd>urn:ietf:params:xml:ns:xmpp-streams
6867</dd>
6868<dt>Specification:</dt>
6869<dd>RFC 6120
6870</dd>
6871<dt>Description:</dt>
6872<dd>This is the XML namespace name for stream error data in the Extensible Messaging and Presence Protocol (XMPP) as defined by RFC 6120.
6873</dd>
6874<dt>Registrant Contact:</dt>
6875<dd>IESG &lt;iesg@ietf.org&gt;
6876</dd>
6877</dl></blockquote>
6878
6879<a name="iana-ns-bind"></a><br /><hr />
6880<table summary="layout" cellpadding="0" cellspacing="2" class="TOCbug" align="right"><tr><td class="TOCbug"><a href="#toc">&nbsp;TOC&nbsp;</a></td></tr></table>
6881<a name="rfc.section.14.4"></a><h3>14.4.&nbsp;
6882XML Namespace Name for Resource Binding</h3>
6883
6884<p>A URN sub-namespace for resource binding in the Extensible Messaging and Presence Protocol (XMPP) is defined as follows. (This namespace name adheres to the format defined in <a class='info' href='#XML-REG'>[XML&#8209;REG]<span> (</span><span class='info'>Mealling, M., &ldquo;The IETF XML Registry,&rdquo; January&nbsp;2004.</span><span>)</span></a>.)
6885</p>
6886<p></p>
6887<blockquote class="text"><dl>
6888<dt>URI:</dt>
6889<dd>urn:ietf:params:xml:ns:xmpp-bind
6890</dd>
6891<dt>Specification:</dt>
6892<dd>RFC 6120
6893</dd>
6894<dt>Description:</dt>
6895<dd>This is the XML namespace name for resource binding in the Extensible Messaging and Presence Protocol (XMPP) as defined by RFC 6120.
6896</dd>
6897<dt>Registrant Contact:</dt>
6898<dd>IESG &lt;iesg@ietf.org&gt;
6899</dd>
6900</dl></blockquote>
6901
6902<a name="iana-ns-stanzas"></a><br /><hr />
6903<table summary="layout" cellpadding="0" cellspacing="2" class="TOCbug" align="right"><tr><td class="TOCbug"><a href="#toc">&nbsp;TOC&nbsp;</a></td></tr></table>
6904<a name="rfc.section.14.5"></a><h3>14.5.&nbsp;
6905XML Namespace Name for Stanza Errors</h3>
6906
6907<p>A URN sub-namespace for stanza error data in the Extensible Messaging and Presence Protocol (XMPP) is defined as follows. (This namespace name adheres to the format defined in <a class='info' href='#XML-REG'>[XML&#8209;REG]<span> (</span><span class='info'>Mealling, M., &ldquo;The IETF XML Registry,&rdquo; January&nbsp;2004.</span><span>)</span></a>.)
6908</p>
6909<p></p>
6910<blockquote class="text"><dl>
6911<dt>URI:</dt>
6912<dd>urn:ietf:params:xml:ns:xmpp-stanzas
6913</dd>
6914<dt>Specification:</dt>
6915<dd>RFC 6120
6916</dd>
6917<dt>Description:</dt>
6918<dd>This is the XML namespace name for stanza error data in the Extensible Messaging and Presence Protocol (XMPP) as defined by RFC 6120.
6919</dd>
6920<dt>Registrant Contact:</dt>
6921<dd>IESG &lt;iesg@ietf.org&gt;
6922</dd>
6923</dl></blockquote>
6924
6925<a name="iana-gssapi"></a><br /><hr />
6926<table summary="layout" cellpadding="0" cellspacing="2" class="TOCbug" align="right"><tr><td class="TOCbug"><a href="#toc">&nbsp;TOC&nbsp;</a></td></tr></table>
6927<a name="rfc.section.14.6"></a><h3>14.6.&nbsp;
6928GSSAPI Service Name</h3>
6929
6930<p>The IANA has registered "xmpp" as a <a class='info' href='#GSS-API'>[GSS&#8209;API]<span> (</span><span class='info'>Linn, J., &ldquo;Generic Security Service Application Program Interface Version 2, Update 1,&rdquo; January&nbsp;2000.</span><span>)</span></a> service name, as defined under <a class='info' href='#sasl-def'>Section&nbsp;6.6<span> (</span><span class='info'>SASL Definition</span><span>)</span></a>.
6931</p>
6932<a name="iana-ports"></a><br /><hr />
6933<table summary="layout" cellpadding="0" cellspacing="2" class="TOCbug" align="right"><tr><td class="TOCbug"><a href="#toc">&nbsp;TOC&nbsp;</a></td></tr></table>
6934<a name="rfc.section.14.7"></a><h3>14.7.&nbsp;
6935Port Numbers and Service Names</h3>
6936
6937<p>The IANA has registered "xmpp-client" and "xmpp-server" as keywords for <a class='info' href='#TCP'>[TCP]<span> (</span><span class='info'>Postel, J., &ldquo;Transmission Control Protocol,&rdquo; September&nbsp;1981.</span><span>)</span></a> ports 5222 and 5269, respectively. In accordance with <a class='info' href='#IANA-PORTS'>[IANA&#8209;PORTS]<span> (</span><span class='info'>Cotton, M., Eggert, L., Touch, J., Westerlund, M., and S. Cheshire, &ldquo;Internet Assigned Numbers Authority (IANA) Procedures for the Management of the Transport Protocol Port Number and Service Name Registry,&rdquo; February&nbsp;2011.</span><span>)</span></a>, this document updates the existing registration, as follows.
6938</p>
6939<p>
6940 </p>
6941<blockquote class="text"><dl>
6942<dt>Service Name:</dt>
6943<dd>xmpp-client
6944</dd>
6945<dt>Transport Protocol:</dt>
6946<dd>TCP
6947</dd>
6948<dt>Description:</dt>
6949<dd>A service offering support for connections by XMPP client applications
6950</dd>
6951<dt>Registrant:</dt>
6952<dd>IETF XMPP Working Group
6953</dd>
6954<dt>Contact:</dt>
6955<dd>IESG &lt;iesg@ietf.org&gt;
6956</dd>
6957<dt>Reference:</dt>
6958<dd>RFC 6120
6959</dd>
6960<dt>Port Number:</dt>
6961<dd>5222
6962</dd>
6963</dl></blockquote><p>
6964
6965</p>
6966<p>
6967 </p>
6968<blockquote class="text"><dl>
6969<dt>Service Name:</dt>
6970<dd>xmpp-server
6971</dd>
6972<dt>Transport Protocol:</dt>
6973<dd>TCP
6974</dd>
6975<dt>Description:</dt>
6976<dd>A service offering support for connections by XMPP server applications
6977</dd>
6978<dt>Registrant:</dt>
6979<dd>IETF XMPP Working Group
6980</dd>
6981<dt>Contact:</dt>
6982<dd>IESG &lt;iesg@ietf.org&gt;
6983</dd>
6984<dt>Reference:</dt>
6985<dd>RFC 6120
6986</dd>
6987<dt>Port Number:</dt>
6988<dd>5269
6989</dd>
6990</dl></blockquote><p>
6991
6992</p>
6993<a name="conformance"></a><br /><hr />
6994<table summary="layout" cellpadding="0" cellspacing="2" class="TOCbug" align="right"><tr><td class="TOCbug"><a href="#toc">&nbsp;TOC&nbsp;</a></td></tr></table>
6995<a name="rfc.section.15"></a><h3>15.&nbsp;
6996Conformance Requirements</h3>
6997
6998<p>This section describes a protocol feature set that summarizes the conformance requirements of this specification. This feature set is appropriate for use in software certification, interoperability testing, and implementation reports. For each feature, this section provides the following information:
6999</p>
7000<p>
7001 </p>
7002<ul class="text">
7003<li>A human-readable name
7004</li>
7005<li>An informational description
7006</li>
7007<li>A reference to the particular section of this document that normatively defines the feature
7008</li>
7009<li>Whether the feature applies to the Client role, the Server
7010 role, or both (where "N/A" signifies that the feature is not
7011 applicable to the specified role)
7012</li>
7013<li>Whether the feature MUST or SHOULD be implemented, where the capitalized terms are to be understood as described in <a class='info' href='#KEYWORDS'>[KEYWORDS]<span> (</span><span class='info'>Bradner, S., &ldquo;Key words for use in RFCs to Indicate Requirement Levels,&rdquo; March&nbsp;1997.</span><span>)</span></a>
7014</li>
7015</ul><p>
7016
7017</p>
7018<p>The feature set specified here attempts to adhere to the concepts and formats proposed by Larry Masinter within the IETF's NEWTRK Working Group in 2005, as captured in <a class='info' href='#INTEROP'>[INTEROP]<span> (</span><span class='info'>Masinter, L., &ldquo;Formalizing IETF Interoperability Reporting,&rdquo; October&nbsp;2005.</span><span>)</span></a>. Although this feature set is more detailed than called for by <a class='info' href='#REPORTS'>[REPORTS]<span> (</span><span class='info'>Dusseault, L. and R. Sparks, &ldquo;Guidance on Interoperation and Implementation Reports for Advancement to Draft Standard,&rdquo; September&nbsp;2009.</span><span>)</span></a>, it provides a suitable basis for the generation of implementation reports to be submitted in support of advancing this specification from Proposed Standard to Draft Standard in accordance with <a class='info' href='#PROCESS'>[PROCESS]<span> (</span><span class='info'>Bradner, S., &ldquo;The Internet Standards Process -- Revision 3,&rdquo; October&nbsp;1996.</span><span>)</span></a>.
7019</p>
7020<p>
7021 </p>
7022<blockquote class="text"><dl>
7023<dt>Feature:</dt>
7024<dd>bind-gen
7025</dd>
7026<dt>Description:</dt>
7027<dd>Generate a random resource on demand.
7028</dd>
7029<dt>Section:</dt>
7030<dd><a class='info' href='#bind-servergen'>Section&nbsp;7.6<span> (</span><span class='info'>Server-Generated Resource Identifier</span><span>)</span></a>
7031</dd>
7032<dt>Roles:</dt>
7033<dd>Client N/A, Server MUST.
7034</dd>
7035</dl></blockquote><p>
7036
7037</p>
7038<p>
7039 </p>
7040<blockquote class="text"><dl>
7041<dt>Feature:</dt>
7042<dd>bind-mtn
7043</dd>
7044<dt>Description:</dt>
7045<dd>Consider resource binding as mandatory-to-negotiate.
7046</dd>
7047<dt>Section:</dt>
7048<dd><a class='info' href='#bind-rules-mtn'>Section&nbsp;7.3.1<span> (</span><span class='info'>Mandatory-to-Negotiate</span><span>)</span></a>
7049</dd>
7050<dt>Roles:</dt>
7051<dd>Client MUST, Server MUST.
7052</dd>
7053</dl></blockquote><p>
7054
7055</p>
7056<p>
7057 </p>
7058<blockquote class="text"><dl>
7059<dt>Feature:</dt>
7060<dd>bind-restart
7061</dd>
7062<dt>Description:</dt>
7063<dd>Do not restart the stream after negotiation of resource binding.
7064</dd>
7065<dt>Section:</dt>
7066<dd><a class='info' href='#bind-rules-restart'>Section&nbsp;7.3.2<span> (</span><span class='info'>Restart</span><span>)</span></a>
7067</dd>
7068<dt>Roles:</dt>
7069<dd>Client MUST, Server MUST.
7070</dd>
7071</dl></blockquote><p>
7072
7073</p>
7074<p>
7075 </p>
7076<blockquote class="text"><dl>
7077<dt>Feature:</dt>
7078<dd>bind-support
7079</dd>
7080<dt>Description:</dt>
7081<dd>Support binding of client resources to an authenticated stream.
7082</dd>
7083<dt>Section:</dt>
7084<dd><a class='info' href='#bind'>Section&nbsp;7<span> (</span><span class='info'>Resource Binding</span><span>)</span></a>
7085</dd>
7086<dt>Roles:</dt>
7087<dd>Client MUST, Server MUST.
7088</dd>
7089</dl></blockquote><p>
7090
7091</p>
7092<p>
7093 </p>
7094<blockquote class="text"><dl>
7095<dt>Feature:</dt>
7096<dd>sasl-correlate
7097</dd>
7098<dt>Description:</dt>
7099<dd>When authenticating a stream peer using SASL, correlate the authentication identifier resulting from SASL negotiation with the 'from' address (if any) of the stream header it received from the peer.
7100</dd>
7101<dt>Section:</dt>
7102<dd><a class='info' href='#sasl-process-neg-success'>Section&nbsp;6.4.6<span> (</span><span class='info'>SASL Success</span><span>)</span></a>
7103</dd>
7104<dt>Roles:</dt>
7105<dd>Client SHOULD, Server SHOULD.
7106</dd>
7107</dl></blockquote><p>
7108
7109</p>
7110<p>
7111 </p>
7112<blockquote class="text"><dl>
7113<dt>Feature:</dt>
7114<dd>sasl-errors
7115</dd>
7116<dt>Description:</dt>
7117<dd>Support SASL errors during the negotiation process.
7118</dd>
7119<dt>Section:</dt>
7120<dd><a class='info' href='#sasl-errors'>Section&nbsp;6.5<span> (</span><span class='info'>SASL Errors</span><span>)</span></a>
7121</dd>
7122<dt>Roles:</dt>
7123<dd>Client MUST, Server MUST.
7124</dd>
7125</dl></blockquote><p>
7126
7127</p>
7128<p>
7129 </p>
7130<blockquote class="text"><dl>
7131<dt>Feature:</dt>
7132<dd>sasl-mtn
7133</dd>
7134<dt>Description:</dt>
7135<dd>Consider SASL as mandatory-to-negotiate.
7136</dd>
7137<dt>Section:</dt>
7138<dd><a class='info' href='#sasl-rules-mtn'>Section&nbsp;6.3.1<span> (</span><span class='info'>Mandatory-to-Negotiate</span><span>)</span></a>
7139</dd>
7140<dt>Roles:</dt>
7141<dd>Client MUST, Server MUST.
7142</dd>
7143</dl></blockquote><p>
7144
7145</p>
7146<p>
7147 </p>
7148<blockquote class="text"><dl>
7149<dt>Feature:</dt>
7150<dd>sasl-restart
7151</dd>
7152<dt>Description:</dt>
7153<dd>Initiate or handle a stream restart after SASL negotiation.
7154</dd>
7155<dt>Section:</dt>
7156<dd><a class='info' href='#sasl-rules-restart'>Section&nbsp;6.3.2<span> (</span><span class='info'>Restart</span><span>)</span></a>
7157</dd>
7158<dt>Roles:</dt>
7159<dd>Client MUST, Server MUST.
7160</dd>
7161</dl></blockquote><p>
7162
7163</p>
7164<p>
7165 </p>
7166<blockquote class="text"><dl>
7167<dt>Feature:</dt>
7168<dd>sasl-support
7169</dd>
7170<dt>Description:</dt>
7171<dd>Support the Simple Authentication and Security Layer for stream authentication.
7172</dd>
7173<dt>Section:</dt>
7174<dd><a class='info' href='#sasl'>Section&nbsp;6<span> (</span><span class='info'>SASL Negotiation</span><span>)</span></a>
7175</dd>
7176<dt>Roles:</dt>
7177<dd>Client MUST, Server MUST.
7178</dd>
7179</dl></blockquote><p>
7180
7181</p>
7182<p>
7183 </p>
7184<blockquote class="text"><dl>
7185<dt>Feature:</dt>
7186<dd>security-mti-auth-scram
7187</dd>
7188<dt>Description:</dt>
7189<dd>Support the SASL SCRAM mechanism for authentication only (this implies support for both the SCRAM&#8209;SHA&#8209;1 and SCRAM&#8209;SHA&#8209;1&#8209;PLUS variants).
7190</dd>
7191<dt>Section:</dt>
7192<dd><a class='info' href='#security-mti'>Section&nbsp;13.8<span> (</span><span class='info'>Mandatory-to-Implement TLS and SASL Technologies</span><span>)</span></a>
7193</dd>
7194<dt>Roles:</dt>
7195<dd>Client MUST, Server MUST.
7196</dd>
7197</dl></blockquote><p>
7198
7199</p>
7200<p>
7201 </p>
7202<blockquote class="text"><dl>
7203<dt>Feature:</dt>
7204<dd>security-mti-both-external
7205</dd>
7206<dt>Description:</dt>
7207<dd>Support TLS with SASL EXTERNAL for confidentiality and authentication.
7208</dd>
7209<dt>Section:</dt>
7210<dd><a class='info' href='#security-mti'>Section&nbsp;13.8<span> (</span><span class='info'>Mandatory-to-Implement TLS and SASL Technologies</span><span>)</span></a>
7211</dd>
7212<dt>Roles:</dt>
7213<dd>Client SHOULD, Server MUST.
7214</dd>
7215</dl></blockquote><p>
7216
7217</p>
7218<p>
7219 </p>
7220<blockquote class="text"><dl>
7221<dt>Feature:</dt>
7222<dd>security-mti-both-plain
7223</dd>
7224<dt>Description:</dt>
7225<dd>Support TLS using the TLS_RSA_WITH_AES_128_CBC_SHA ciphersuite plus the SASL PLAIN mechanism for confidentiality and authentication.
7226</dd>
7227<dt>Section:</dt>
7228<dd><a class='info' href='#security-mti'>Section&nbsp;13.8<span> (</span><span class='info'>Mandatory-to-Implement TLS and SASL Technologies</span><span>)</span></a>
7229</dd>
7230<dt>Roles:</dt>
7231<dd>Client SHOULD, Server MAY.
7232</dd>
7233</dl></blockquote><p>
7234
7235</p>
7236<p>
7237 </p>
7238<blockquote class="text"><dl>
7239<dt>Feature:</dt>
7240<dd>security-mti-both-scram
7241</dd>
7242<dt>Description:</dt>
7243<dd>Support TLS using the TLS_RSA_WITH_AES_128_CBC_SHA ciphersuite plus the SCRAM-SHA-1 and SCRAM-SHA-1-PLUS variants of the SASL SCRAM mechanism for confidentiality and authentication.
7244</dd>
7245<dt>Section:</dt>
7246<dd><a class='info' href='#security-mti'>Section&nbsp;13.8<span> (</span><span class='info'>Mandatory-to-Implement TLS and SASL Technologies</span><span>)</span></a>
7247</dd>
7248<dt>Roles:</dt>
7249<dd>Client MUST, Server MUST.
7250</dd>
7251</dl></blockquote><p>
7252
7253</p>
7254<p>
7255 </p>
7256<blockquote class="text"><dl>
7257<dt>Feature:</dt>
7258<dd>security-mti-confidentiality
7259</dd>
7260<dt>Description:</dt>
7261<dd>Support TLS using the TLS_RSA_WITH_AES_128_CBC_SHA ciphersuite for confidentiality only.
7262</dd>
7263<dt>Section:</dt>
7264<dd><a class='info' href='#security-mti'>Section&nbsp;13.8<span> (</span><span class='info'>Mandatory-to-Implement TLS and SASL Technologies</span><span>)</span></a>
7265</dd>
7266<dt>Roles:</dt>
7267<dd>Client N/A, Server SHOULD.
7268</dd>
7269</dl></blockquote><p>
7270
7271</p>
7272<p>
7273 </p>
7274<blockquote class="text"><dl>
7275<dt>Feature:</dt>
7276<dd>stanza-attribute-from
7277</dd>
7278<dt>Description:</dt>
7279<dd>Support the common 'from' attribute for all stanza kinds.
7280</dd>
7281<dt>Section:</dt>
7282<dd><a class='info' href='#stanzas-attributes-from'>Section&nbsp;8.1.2<span> (</span><span class='info'>from</span><span>)</span></a>
7283</dd>
7284<dt>Roles:</dt>
7285<dd>Client MUST, Server MUST.
7286</dd>
7287</dl></blockquote><p>
7288
7289</p>
7290<p>
7291 </p>
7292<blockquote class="text"><dl>
7293<dt>Feature:</dt>
7294<dd>stanza-attribute-from-stamp
7295</dd>
7296<dt>Description:</dt>
7297<dd>Stamp or rewrite the 'from' address of all stanzas received from connected clients.
7298</dd>
7299<dt>Section:</dt>
7300<dd><a class='info' href='#stanzas-attributes-from-c2s'>Section&nbsp;8.1.2.1<span> (</span><span class='info'>Client-to-Server Streams</span><span>)</span></a>
7301</dd>
7302<dt>Roles:</dt>
7303<dd>Client N/A, Server MUST.
7304</dd>
7305</dl></blockquote><p>
7306
7307</p>
7308<p>
7309 </p>
7310<blockquote class="text"><dl>
7311<dt>Feature:</dt>
7312<dd>stanza-attribute-from-validate
7313</dd>
7314<dt>Description:</dt>
7315<dd>Validate the 'from' address of all stanzas received from peer servers.
7316</dd>
7317<dt>Section:</dt>
7318<dd><a class='info' href='#stanzas-attributes-from-s2s'>Section&nbsp;8.1.2.2<span> (</span><span class='info'>Server-to-Server Streams</span><span>)</span></a>
7319</dd>
7320<dt>Roles:</dt>
7321<dd>Client N/A, Server MUST.
7322</dd>
7323</dl></blockquote><p>
7324
7325</p>
7326<p>
7327 </p>
7328<blockquote class="text"><dl>
7329<dt>Feature:</dt>
7330<dd>stanza-attribute-id
7331</dd>
7332<dt>Description:</dt>
7333<dd>Support the common 'id' attribute for all stanza kinds.
7334</dd>
7335<dt>Section:</dt>
7336<dd><a class='info' href='#stanzas-attributes-id'>Section&nbsp;8.1.3<span> (</span><span class='info'>id</span><span>)</span></a>
7337</dd>
7338<dt>Roles:</dt>
7339<dd>Client MUST, Server MUST.
7340</dd>
7341</dl></blockquote><p>
7342
7343</p>
7344<p>
7345 </p>
7346<blockquote class="text"><dl>
7347<dt>Feature:</dt>
7348<dd>stanza-attribute-to
7349</dd>
7350<dt>Description:</dt>
7351<dd>Support the common 'to' attribute for all stanza kinds.
7352</dd>
7353<dt>Section:</dt>
7354<dd><a class='info' href='#stanzas-attributes-to'>Section&nbsp;8.1.1<span> (</span><span class='info'>to</span><span>)</span></a>
7355</dd>
7356<dt>Roles:</dt>
7357<dd>Client MUST, Server MUST.
7358</dd>
7359</dl></blockquote><p>
7360
7361</p>
7362<p>
7363 </p>
7364<blockquote class="text"><dl>
7365<dt>Feature:</dt>
7366<dd>stanza-attribute-to-validate
7367</dd>
7368<dt>Description:</dt>
7369<dd>Ensure that all stanzas received from peer servers include a 'to' address.
7370</dd>
7371<dt>Section:</dt>
7372<dd><a class='info' href='#stanzas-attributes-to'>Section&nbsp;8.1.1<span> (</span><span class='info'>to</span><span>)</span></a>
7373</dd>
7374<dt>Roles:</dt>
7375<dd>Client N/A, Server MUST.
7376</dd>
7377</dl></blockquote><p>
7378
7379</p>
7380<p>
7381 </p>
7382<blockquote class="text"><dl>
7383<dt>Feature:</dt>
7384<dd>stanza-attribute-type
7385</dd>
7386<dt>Description:</dt>
7387<dd>Support the common 'type' attribute for all stanza kinds.
7388</dd>
7389<dt>Section:</dt>
7390<dd><a class='info' href='#stanzas-attributes-type'>Section&nbsp;8.1.4<span> (</span><span class='info'>type</span><span>)</span></a>
7391</dd>
7392<dt>Roles:</dt>
7393<dd>Client MUST, Server MUST.
7394</dd>
7395</dl></blockquote><p>
7396
7397</p>
7398<p>
7399 </p>
7400<blockquote class="text"><dl>
7401<dt>Feature:</dt>
7402<dd>stanza-attribute-xmllang
7403</dd>
7404<dt>Description:</dt>
7405<dd>Support the common 'xml:lang' attribute for all stanza kinds.
7406</dd>
7407<dt>Section:</dt>
7408<dd><a class='info' href='#stanzas-attributes-lang'>Section&nbsp;8.1.5<span> (</span><span class='info'>xml:lang</span><span>)</span></a>
7409</dd>
7410<dt>Roles:</dt>
7411<dd>Client MUST, Server MUST.
7412</dd>
7413</dl></blockquote><p>
7414
7415</p>
7416<p>
7417 </p>
7418<blockquote class="text"><dl>
7419<dt>Feature:</dt>
7420<dd>stanza-error
7421</dd>
7422<dt>Description:</dt>
7423<dd>Generate and handle stanzas of type "error" for all stanza kinds.
7424</dd>
7425<dt>Section:</dt>
7426<dd><a class='info' href='#stanzas-error'>Section&nbsp;8.3<span> (</span><span class='info'>Stanza Errors</span><span>)</span></a>
7427</dd>
7428<dt>Roles:</dt>
7429<dd>Client MUST, Server MUST.
7430</dd>
7431</dl></blockquote><p>
7432
7433</p>
7434<p>
7435 </p>
7436<blockquote class="text"><dl>
7437<dt>Feature:</dt>
7438<dd>stanza-error-child
7439</dd>
7440<dt>Description:</dt>
7441<dd>Ensure that stanzas of type "error" include an &lt;error/&gt; child element.
7442</dd>
7443<dt>Section:</dt>
7444<dd><a class='info' href='#stanzas-error'>Section&nbsp;8.3<span> (</span><span class='info'>Stanza Errors</span><span>)</span></a>
7445</dd>
7446<dt>Roles:</dt>
7447<dd>Client MUST, Server MUST.
7448</dd>
7449</dl></blockquote><p>
7450
7451</p>
7452<p>
7453 </p>
7454<blockquote class="text"><dl>
7455<dt>Feature:</dt>
7456<dd>stanza-error-id
7457</dd>
7458<dt>Description:</dt>
7459<dd>Ensure that stanzas of type "error" preserve the 'id' provided in the triggering stanza.
7460</dd>
7461<dt>Section:</dt>
7462<dd><a class='info' href='#stanzas-error'>Section&nbsp;8.3<span> (</span><span class='info'>Stanza Errors</span><span>)</span></a>
7463</dd>
7464<dt>Roles:</dt>
7465<dd>Client MUST, Server MUST.
7466</dd>
7467</dl></blockquote><p>
7468
7469</p>
7470<p>
7471 </p>
7472<blockquote class="text"><dl>
7473<dt>Feature:</dt>
7474<dd>stanza-error-reply
7475</dd>
7476<dt>Description:</dt>
7477<dd>Do not reply to a stanza of type "error" with another stanza of type "error".
7478</dd>
7479<dt>Section:</dt>
7480<dd><a class='info' href='#stanzas-error'>Section&nbsp;8.3<span> (</span><span class='info'>Stanza Errors</span><span>)</span></a>
7481</dd>
7482<dt>Roles:</dt>
7483<dd>Client MUST, Server MUST.
7484</dd>
7485</dl></blockquote><p>
7486
7487</p>
7488<p>
7489 </p>
7490<blockquote class="text"><dl>
7491<dt>Feature:</dt>
7492<dd>stanza-extension
7493</dd>
7494<dt>Description:</dt>
7495<dd>Correctly process XML data qualified by an unsupported XML namespace, where "correctly process" means to ignore that portion of the stanza in the case of a message or presence stanza and return an error in the case of an IQ stanza (for the intended recipient), and to route or deliver the stanza (for a routing entity such as a server).
7496</dd>
7497<dt>Section:</dt>
7498<dd><a class='info' href='#stanzas-extended'>Section&nbsp;8.4<span> (</span><span class='info'>Extended Content</span><span>)</span></a>
7499</dd>
7500<dt>Roles:</dt>
7501<dd>Client MUST, Server MUST.
7502</dd>
7503</dl></blockquote><p>
7504
7505</p>
7506<p>
7507 </p>
7508<blockquote class="text"><dl>
7509<dt>Feature:</dt>
7510<dd>stanza-iq-child
7511</dd>
7512<dt>Description:</dt>
7513<dd>Include exactly one child element in an &lt;iq/&gt; stanza of type "get" or "set", zero or one child elements in an &lt;iq/&gt; stanza of type "result", and one or two child elements in an &lt;iq/&gt; stanza of type "error".
7514</dd>
7515<dt>Section:</dt>
7516<dd><a class='info' href='#stanzas-semantics-iq'>Section&nbsp;8.2.3<span> (</span><span class='info'>IQ Semantics</span><span>)</span></a>
7517</dd>
7518<dt>Roles:</dt>
7519<dd>Client MUST, Server MUST.
7520</dd>
7521</dl></blockquote><p>
7522
7523</p>
7524<p>
7525 </p>
7526<blockquote class="text"><dl>
7527<dt>Feature:</dt>
7528<dd>stanza-iq-id
7529</dd>
7530<dt>Description:</dt>
7531<dd>Ensure that all &lt;iq/&gt; stanzas include an 'id' attribute.
7532</dd>
7533<dt>Section:</dt>
7534<dd><a class='info' href='#stanzas-semantics-iq'>Section&nbsp;8.2.3<span> (</span><span class='info'>IQ Semantics</span><span>)</span></a>
7535</dd>
7536<dt>Roles:</dt>
7537<dd>Client MUST, Server MUST.
7538</dd>
7539</dl></blockquote><p>
7540
7541</p>
7542<p>
7543 </p>
7544<blockquote class="text"><dl>
7545<dt>Feature:</dt>
7546<dd>stanza-iq-reply
7547</dd>
7548<dt>Description:</dt>
7549<dd>Reply to an &lt;iq/&gt; stanza of type "get" or "set" with an &lt;iq/&gt; stanza of type "result" or "error".
7550</dd>
7551<dt>Section:</dt>
7552<dd><a class='info' href='#stanzas-semantics-iq'>Section&nbsp;8.2.3<span> (</span><span class='info'>IQ Semantics</span><span>)</span></a>
7553</dd>
7554<dt>Roles:</dt>
7555<dd>Client MUST, Server MUST.
7556</dd>
7557</dl></blockquote><p>
7558
7559</p>
7560<p>
7561 </p>
7562<blockquote class="text"><dl>
7563<dt>Feature:</dt>
7564<dd>stanza-iq-type
7565</dd>
7566<dt>Description:</dt>
7567<dd>Ensure that all &lt;iq/&gt; stanzas include a 'type' attribute whose value is "get", "set", "result", or "error".
7568</dd>
7569<dt>Section:</dt>
7570<dd><a class='info' href='#stanzas-semantics-iq'>Section&nbsp;8.2.3<span> (</span><span class='info'>IQ Semantics</span><span>)</span></a>
7571</dd>
7572<dt>Roles:</dt>
7573<dd>Client MUST, Server MUST.
7574</dd>
7575</dl></blockquote><p>
7576
7577</p>
7578<p>
7579 </p>
7580<blockquote class="text"><dl>
7581<dt>Feature:</dt>
7582<dd>stanza-kind-iq
7583</dd>
7584<dt>Description:</dt>
7585<dd>Support the &lt;iq/&gt; stanza.
7586</dd>
7587<dt>Section:</dt>
7588<dd><a class='info' href='#stanzas-semantics-iq'>Section&nbsp;8.2.3<span> (</span><span class='info'>IQ Semantics</span><span>)</span></a>
7589</dd>
7590<dt>Roles:</dt>
7591<dd>Client MUST, Server MUST.
7592</dd>
7593</dl></blockquote><p>
7594
7595</p>
7596<p>
7597 </p>
7598<blockquote class="text"><dl>
7599<dt>Feature:</dt>
7600<dd>stanza-kind-message
7601</dd>
7602<dt>Description:</dt>
7603<dd>Support the &lt;message/&gt; stanza.
7604</dd>
7605<dt>Section:</dt>
7606<dd><a class='info' href='#stanzas-semantics-message'>Section&nbsp;8.2.1<span> (</span><span class='info'>Message Semantics</span><span>)</span></a>
7607</dd>
7608<dt>Roles:</dt>
7609<dd>Client MUST, Server MUST.
7610</dd>
7611</dl></blockquote><p>
7612
7613</p>
7614<p>
7615 </p>
7616<blockquote class="text"><dl>
7617<dt>Feature:</dt>
7618<dd>stanza-kind-presence
7619</dd>
7620<dt>Description:</dt>
7621<dd>Support the &lt;presence/&gt; stanza.
7622</dd>
7623<dt>Section:</dt>
7624<dd><a class='info' href='#stanzas-semantics-presence'>Section&nbsp;8.2.2<span> (</span><span class='info'>Presence Semantics</span><span>)</span></a>
7625</dd>
7626<dt>Roles:</dt>
7627<dd>Client MUST, Server MUST.
7628</dd>
7629</dl></blockquote><p>
7630
7631</p>
7632<p>
7633 </p>
7634<blockquote class="text"><dl>
7635<dt>Feature:</dt>
7636<dd>stream-attribute-initial-from
7637</dd>
7638<dt>Description:</dt>
7639<dd>Include a 'from' attribute in the initial stream header.
7640</dd>
7641<dt>Section:</dt>
7642<dd><a class='info' href='#streams-attr-from'>Section&nbsp;4.7.1<span> (</span><span class='info'>from</span><span>)</span></a>
7643</dd>
7644<dt>Roles:</dt>
7645<dd>Client SHOULD, Server MUST.
7646</dd>
7647</dl></blockquote><p>
7648
7649</p>
7650<p>
7651 </p>
7652<blockquote class="text"><dl>
7653<dt>Feature:</dt>
7654<dd>stream-attribute-initial-lang
7655</dd>
7656<dt>Description:</dt>
7657<dd>Include an 'xml:lang' attribute in the initial stream header.
7658</dd>
7659<dt>Section:</dt>
7660<dd><a class='info' href='#streams-attr-xmllang'>Section&nbsp;4.7.4<span> (</span><span class='info'>xml:lang</span><span>)</span></a>
7661</dd>
7662<dt>Roles:</dt>
7663<dd>Client SHOULD, Server SHOULD.
7664</dd>
7665</dl></blockquote><p>
7666
7667</p>
7668<p>
7669 </p>
7670<blockquote class="text"><dl>
7671<dt>Feature:</dt>
7672<dd>stream-attribute-initial-to
7673</dd>
7674<dt>Description:</dt>
7675<dd>Include a 'to' attribute in the initial stream header.
7676</dd>
7677<dt>Section:</dt>
7678<dd><a class='info' href='#streams-attr-to'>Section&nbsp;4.7.2<span> (</span><span class='info'>to</span><span>)</span></a>
7679</dd>
7680<dt>Roles:</dt>
7681<dd>Client MUST, Server MUST.
7682</dd>
7683</dl></blockquote><p>
7684
7685</p>
7686<p>
7687 </p>
7688<blockquote class="text"><dl>
7689<dt>Feature:</dt>
7690<dd>stream-attribute-response-from
7691</dd>
7692<dt>Description:</dt>
7693<dd>Include a 'from' attribute in the response stream header.
7694</dd>
7695<dt>Section:</dt>
7696<dd><a class='info' href='#streams-attr-from'>Section&nbsp;4.7.1<span> (</span><span class='info'>from</span><span>)</span></a>
7697</dd>
7698<dt>Roles:</dt>
7699<dd>Client N/A, Server MUST.
7700</dd>
7701</dl></blockquote><p>
7702
7703</p>
7704<p>
7705 </p>
7706<blockquote class="text"><dl>
7707<dt>Feature:</dt>
7708<dd>stream-attribute-response-id
7709</dd>
7710<dt>Description:</dt>
7711<dd>Include an 'id' attribute in the response stream header.
7712</dd>
7713<dt>Section:</dt>
7714<dd><a class='info' href='#streams-attr-id'>Section&nbsp;4.7.3<span> (</span><span class='info'>id</span><span>)</span></a>
7715</dd>
7716<dt>Roles:</dt>
7717<dd>Client N/A, Server MUST.
7718</dd>
7719</dl></blockquote><p>
7720
7721</p>
7722<p>
7723 </p>
7724<blockquote class="text"><dl>
7725<dt>Feature:</dt>
7726<dd>stream-attribute-response-id-unique
7727</dd>
7728<dt>Description:</dt>
7729<dd>Ensure that the 'id' attribute in the response stream header is unique within the context of the receiving entity.
7730</dd>
7731<dt>Section:</dt>
7732<dd><a class='info' href='#streams-attr-id'>Section&nbsp;4.7.3<span> (</span><span class='info'>id</span><span>)</span></a>
7733</dd>
7734<dt>Roles:</dt>
7735<dd>Client N/A, Server MUST.
7736</dd>
7737</dl></blockquote><p>
7738
7739</p>
7740<p>
7741 </p>
7742<blockquote class="text"><dl>
7743<dt>Feature:</dt>
7744<dd>stream-attribute-response-to
7745</dd>
7746<dt>Description:</dt>
7747<dd>Include a 'to' attribute in the response stream header.
7748</dd>
7749<dt>Section:</dt>
7750<dd><a class='info' href='#streams-attr-to'>Section&nbsp;4.7.2<span> (</span><span class='info'>to</span><span>)</span></a>
7751</dd>
7752<dt>Roles:</dt>
7753<dd>Client N/A, Server SHOULD.
7754</dd>
7755</dl></blockquote><p>
7756
7757</p>
7758<p>
7759 </p>
7760<blockquote class="text"><dl>
7761<dt>Feature:</dt>
7762<dd>stream-error-generate
7763</dd>
7764<dt>Description:</dt>
7765<dd>Generate a stream error (followed by a closing stream tag and termination of the TCP connection) upon detecting a stream-related error condition.
7766</dd>
7767<dt>Section:</dt>
7768<dd><a class='info' href='#streams-error'>Section&nbsp;4.9<span> (</span><span class='info'>Stream Errors</span><span>)</span></a>
7769</dd>
7770<dt>Roles:</dt>
7771<dd>Client MUST, Server MUST.
7772</dd>
7773</dl></blockquote><p>
7774
7775</p>
7776<p>
7777 </p>
7778<blockquote class="text"><dl>
7779<dt>Feature:</dt>
7780<dd>stream-fqdn-resolution
7781</dd>
7782<dt>Description:</dt>
7783<dd>Resolve FQDNs before opening a TCP connection to the receiving entity.
7784</dd>
7785<dt>Section:</dt>
7786<dd><a class='info' href='#tcp-resolution'>Section&nbsp;3.2<span> (</span><span class='info'>Resolution of Fully Qualified Domain Names</span><span>)</span></a>
7787</dd>
7788<dt>Roles:</dt>
7789<dd>Client MUST, Server MUST.
7790</dd>
7791</dl></blockquote><p>
7792
7793</p>
7794<p>
7795 </p>
7796<blockquote class="text"><dl>
7797<dt>Feature:</dt>
7798<dd>stream-negotiation-complete
7799</dd>
7800<dt>Description:</dt>
7801<dd>Do not consider the stream negotiation process to be complete until the receiving entity sends a stream features advertisement that is empty or that contains only voluntary-to-negotiate features.
7802</dd>
7803<dt>Section:</dt>
7804<dd><a class='info' href='#streams-negotiation-complete'>Section&nbsp;4.3.5<span> (</span><span class='info'>Completion of Stream Negotiation</span><span>)</span></a>
7805</dd>
7806<dt>Roles:</dt>
7807<dd>Client MUST, Server MUST.
7808</dd>
7809</dl></blockquote><p>
7810
7811</p>
7812<p>
7813 </p>
7814<blockquote class="text"><dl>
7815<dt>Feature:</dt>
7816<dd>stream-negotiation-features
7817</dd>
7818<dt>Description:</dt>
7819<dd>Send stream features after sending a response stream header.
7820</dd>
7821<dt>Section:</dt>
7822<dd><a class='info' href='#streams-negotiation-features'>Section&nbsp;4.3.2<span> (</span><span class='info'>Stream Features Format</span><span>)</span></a>
7823</dd>
7824<dt>Roles:</dt>
7825<dd>Client N/A, Server MUST.
7826</dd>
7827</dl></blockquote><p>
7828
7829</p>
7830<p>
7831 </p>
7832<blockquote class="text"><dl>
7833<dt>Feature:</dt>
7834<dd>stream-negotiation-restart
7835</dd>
7836<dt>Description:</dt>
7837<dd>Consider the previous stream to be replaced upon negotiation of a stream feature that necessitates a stream restart, and send or receive a new initial stream header after negotiation of such a stream feature.
7838</dd>
7839<dt>Section:</dt>
7840<dd><a class='info' href='#streams-negotiation-restart'>Section&nbsp;4.3.3<span> (</span><span class='info'>Restarts</span><span>)</span></a>
7841</dd>
7842<dt>Roles:</dt>
7843<dd>Client MUST, Server MUST.
7844</dd>
7845</dl></blockquote><p>
7846
7847</p>
7848<p>
7849 </p>
7850<blockquote class="text"><dl>
7851<dt>Feature:</dt>
7852<dd>stream-reconnect
7853</dd>
7854<dt>Description:</dt>
7855<dd>Reconnect with exponential backoff if a TCP connection is terminated unexpectedly.
7856</dd>
7857<dt>Section:</dt>
7858<dd><a class='info' href='#tcp-reconnect'>Section&nbsp;3.3<span> (</span><span class='info'>Reconnection</span><span>)</span></a>
7859</dd>
7860<dt>Roles:</dt>
7861<dd>Client MUST, Server MUST.
7862</dd>
7863</dl></blockquote><p>
7864
7865</p>
7866<p>
7867 </p>
7868<blockquote class="text"><dl>
7869<dt>Feature:</dt>
7870<dd>stream-tcp-binding
7871</dd>
7872<dt>Description:</dt>
7873<dd>Bind an XML stream to a TCP connection.
7874</dd>
7875<dt>Section:</dt>
7876<dd><a class='info' href='#tcp'>Section&nbsp;3<span> (</span><span class='info'>TCP Binding</span><span>)</span></a>
7877</dd>
7878<dt>Roles:</dt>
7879<dd>Client MUST, Server MUST.
7880</dd>
7881</dl></blockquote><p>
7882
7883</p>
7884<p>
7885 </p>
7886<blockquote class="text"><dl>
7887<dt>Feature:</dt>
7888<dd>tls-certs
7889</dd>
7890<dt>Description:</dt>
7891<dd>Check the identity specified in a certificate that is presented during TLS negotiation.
7892</dd>
7893<dt>Section:</dt>
7894<dd><a class='info' href='#security-certificates-validation'>Section&nbsp;13.7.2<span> (</span><span class='info'>Certificate Validation</span><span>)</span></a>
7895</dd>
7896<dt>Roles:</dt>
7897<dd>Client MUST, Server MUST.
7898</dd>
7899</dl></blockquote><p>
7900
7901</p>
7902<p>
7903 </p>
7904<blockquote class="text"><dl>
7905<dt>Feature:</dt>
7906<dd>tls-mtn
7907</dd>
7908<dt>Description:</dt>
7909<dd>Consider TLS as mandatory-to-negotiate if STARTTLS is the only feature advertised or if the STARTTLS feature advertisement includes an empty &lt;required/&gt; element.
7910</dd>
7911<dt>Section:</dt>
7912<dd><a class='info' href='#tls-rules-mtn'>Section&nbsp;5.3.1<span> (</span><span class='info'>Mandatory-to-Negotiate</span><span>)</span></a>
7913</dd>
7914<dt>Roles:</dt>
7915<dd>Client MUST, Server MUST.
7916</dd>
7917</dl></blockquote><p>
7918
7919</p>
7920<p>
7921 </p>
7922<blockquote class="text"><dl>
7923<dt>Feature:</dt>
7924<dd>tls-restart
7925</dd>
7926<dt>Description:</dt>
7927<dd>Initiate or handle a stream restart after TLS negotiation.
7928</dd>
7929<dt>Section:</dt>
7930<dd><a class='info' href='#tls-rules-restart'>Section&nbsp;5.3.2<span> (</span><span class='info'>Restart</span><span>)</span></a>
7931</dd>
7932<dt>Roles:</dt>
7933<dd>Client MUST, Server MUST.
7934</dd>
7935</dl></blockquote><p>
7936
7937</p>
7938<p>
7939 </p>
7940<blockquote class="text"><dl>
7941<dt>Feature:</dt>
7942<dd>tls-support
7943</dd>
7944<dt>Description:</dt>
7945<dd>Support Transport Layer Security for stream encryption.
7946</dd>
7947<dt>Section:</dt>
7948<dd><a class='info' href='#tls'>Section&nbsp;5<span> (</span><span class='info'>STARTTLS Negotiation</span><span>)</span></a>
7949</dd>
7950<dt>Roles:</dt>
7951<dd>Client MUST, Server MUST.
7952</dd>
7953</dl></blockquote><p>
7954
7955</p>
7956<p>
7957 </p>
7958<blockquote class="text"><dl>
7959<dt>Feature:</dt>
7960<dd>tls-correlate
7961</dd>
7962<dt>Description:</dt>
7963<dd>When validating a certificate presented by a stream peer during TLS negotiation, correlate the validated identity with the 'from' address (if any) of the stream header it received from the peer.
7964</dd>
7965<dt>Section:</dt>
7966<dd><a class='info' href='#security-certificates-validation'>Section&nbsp;13.7.2<span> (</span><span class='info'>Certificate Validation</span><span>)</span></a>
7967</dd>
7968<dt>Roles:</dt>
7969<dd>Client SHOULD, Server SHOULD.
7970</dd>
7971</dl></blockquote><p>
7972
7973</p>
7974<p>
7975 </p>
7976<blockquote class="text"><dl>
7977<dt>Feature:</dt>
7978<dd>xml-namespace-content-client
7979</dd>
7980<dt>Description:</dt>
7981<dd>Support 'jabber:client' as a content namespace.
7982</dd>
7983<dt>Section:</dt>
7984<dd><a class='info' href='#streams-ns-content'>Section&nbsp;4.8.2<span> (</span><span class='info'>Content Namespace</span><span>)</span></a>
7985</dd>
7986<dt>Roles:</dt>
7987<dd>Client MUST, Server MUST.
7988</dd>
7989</dl></blockquote><p>
7990
7991</p>
7992<p>
7993 </p>
7994<blockquote class="text"><dl>
7995<dt>Feature:</dt>
7996<dd>xml-namespace-content-server
7997</dd>
7998<dt>Description:</dt>
7999<dd>Support 'jabber:server' as a content namespace.
8000</dd>
8001<dt>Section:</dt>
8002<dd><a class='info' href='#streams-ns-content'>Section&nbsp;4.8.2<span> (</span><span class='info'>Content Namespace</span><span>)</span></a>
8003</dd>
8004<dt>Roles:</dt>
8005<dd>Client N/A, Server MUST.
8006</dd>
8007</dl></blockquote><p>
8008
8009</p>
8010<p>
8011 </p>
8012<blockquote class="text"><dl>
8013<dt>Feature:</dt>
8014<dd>xml-namespace-streams-declaration
8015</dd>
8016<dt>Description:</dt>
8017<dd>Ensure that there is a namespace declaration for the 'http://etherx.jabber.org/streams' namespace.
8018</dd>
8019<dt>Section:</dt>
8020<dd><a class='info' href='#streams-ns-stream'>Section&nbsp;4.8.1<span> (</span><span class='info'>Stream Namespace</span><span>)</span></a>
8021</dd>
8022<dt>Roles:</dt>
8023<dd>Client MUST, Server MUST.
8024</dd>
8025</dl></blockquote><p>
8026
8027</p>
8028<p>
8029 </p>
8030<blockquote class="text"><dl>
8031<dt>Feature:</dt>
8032<dd>xml-namespace-streams-prefix
8033</dd>
8034<dt>Description:</dt>
8035<dd>Ensure that all elements qualified by the 'http://etherx.jabber.org/streams' namespace are prefixed by the prefix (if any) defined in the namespace declaration.
8036</dd>
8037<dt>Section:</dt>
8038<dd><a class='info' href='#streams-ns-stream'>Section&nbsp;4.8.1<span> (</span><span class='info'>Stream Namespace</span><span>)</span></a>
8039</dd>
8040<dt>Roles:</dt>
8041<dd>Client MUST, Server MUST.
8042</dd>
8043</dl></blockquote><p>
8044
8045</p>
8046<p>
8047 </p>
8048<blockquote class="text"><dl>
8049<dt>Feature:</dt>
8050<dd>xml-restriction-comment
8051</dd>
8052<dt>Description:</dt>
8053<dd>Do not generate or accept XML comments.
8054</dd>
8055<dt>Section:</dt>
8056<dd><a class='info' href='#xml-restrictions'>Section&nbsp;11.1<span> (</span><span class='info'>XML Restrictions</span><span>)</span></a>
8057</dd>
8058<dt>Roles:</dt>
8059<dd>Client MUST, Server MUST.
8060</dd>
8061</dl></blockquote><p>
8062
8063</p>
8064<p>
8065 </p>
8066<blockquote class="text"><dl>
8067<dt>Feature:</dt>
8068<dd>xml-restriction-dtd
8069</dd>
8070<dt>Description:</dt>
8071<dd>Do not generate or accept internal or external DTD subsets.
8072</dd>
8073<dt>Section:</dt>
8074<dd><a class='info' href='#xml-restrictions'>Section&nbsp;11.1<span> (</span><span class='info'>XML Restrictions</span><span>)</span></a>
8075</dd>
8076<dt>Roles:</dt>
8077<dd>Client MUST, Server MUST.
8078</dd>
8079</dl></blockquote><p>
8080
8081</p>
8082<p>
8083 </p>
8084<blockquote class="text"><dl>
8085<dt>Feature:</dt>
8086<dd>xml-restriction-pi
8087</dd>
8088<dt>Description:</dt>
8089<dd>Do not generate or accept XML processing instructions.
8090</dd>
8091<dt>Section:</dt>
8092<dd><a class='info' href='#xml-restrictions'>Section&nbsp;11.1<span> (</span><span class='info'>XML Restrictions</span><span>)</span></a>
8093</dd>
8094<dt>Roles:</dt>
8095<dd>Client MUST, Server MUST.
8096</dd>
8097</dl></blockquote><p>
8098
8099</p>
8100<p>
8101 </p>
8102<blockquote class="text"><dl>
8103<dt>Feature:</dt>
8104<dd>xml-restriction-ref
8105</dd>
8106<dt>Description:</dt>
8107<dd>Do not generate or accept internal or external entity references with the exception of the predefined entities.
8108</dd>
8109<dt>Section:</dt>
8110<dd><a class='info' href='#xml-restrictions'>Section&nbsp;11.1<span> (</span><span class='info'>XML Restrictions</span><span>)</span></a>
8111</dd>
8112<dt>Roles:</dt>
8113<dd>Client MUST, Server MUST.
8114</dd>
8115</dl></blockquote><p>
8116
8117</p>
8118<p>
8119 </p>
8120<blockquote class="text"><dl>
8121<dt>Feature:</dt>
8122<dd>xml-wellformed-xml
8123</dd>
8124<dt>Description:</dt>
8125<dd>Do not generate or accept data that is not XML-well-formed.
8126</dd>
8127<dt>Section:</dt>
8128<dd><a class='info' href='#xml-wellformed'>Section&nbsp;11.3<span> (</span><span class='info'>Well-Formedness</span><span>)</span></a>
8129</dd>
8130<dt>Roles:</dt>
8131<dd>Client MUST, Server MUST.
8132</dd>
8133</dl></blockquote><p>
8134
8135</p>
8136<p>
8137 </p>
8138<blockquote class="text"><dl>
8139<dt>Feature:</dt>
8140<dd>xml-wellformed-ns
8141</dd>
8142<dt>Description:</dt>
8143<dd>Do not generate or accept data that is not namespace-well-formed.
8144</dd>
8145<dt>Section:</dt>
8146<dd><a class='info' href='#xml-wellformed'>Section&nbsp;11.3<span> (</span><span class='info'>Well-Formedness</span><span>)</span></a>
8147</dd>
8148<dt>Roles:</dt>
8149<dd>Client MUST, Server MUST.
8150</dd>
8151</dl></blockquote><p>
8152
8153</p>
8154<a name="rfc.references"></a><br /><hr />
8155<table summary="layout" cellpadding="0" cellspacing="2" class="TOCbug" align="right"><tr><td class="TOCbug"><a href="#toc">&nbsp;TOC&nbsp;</a></td></tr></table>
8156<a name="rfc.section.16"></a><h3>16.&nbsp;
8157References</h3>
8158
8159<a name="rfc.references1"></a><br /><hr />
8160<table summary="layout" cellpadding="0" cellspacing="2" class="TOCbug" align="right"><tr><td class="TOCbug"><a href="#toc">&nbsp;TOC&nbsp;</a></td></tr></table>
8161<h3>16.1.&nbsp;Normative References</h3>
8162<table width="99%" border="0">
8163<tr><td class="author-text" valign="top"><a name="BASE64">[BASE64]</a></td>
8164<td class="author-text">Josefsson, S., &ldquo;<a href="http://tools.ietf.org/html/rfc4648">The Base16, Base32, and Base64 Data Encodings</a>,&rdquo; RFC&nbsp;4648, October&nbsp;2006 (<a href="http://www.rfc-editor.org/rfc/rfc4648.txt">TXT</a>).</td></tr>
8165<tr><td class="author-text" valign="top"><a name="CHANNEL">[CHANNEL]</a></td>
8166<td class="author-text">Williams, N., &ldquo;<a href="http://tools.ietf.org/html/rfc5056">On the Use of Channel Bindings to Secure Channels</a>,&rdquo; RFC&nbsp;5056, November&nbsp;2007 (<a href="http://www.rfc-editor.org/rfc/rfc5056.txt">TXT</a>).</td></tr>
8167<tr><td class="author-text" valign="top"><a name="CHANNEL-TLS">[CHANNEL-TLS]</a></td>
8168<td class="author-text">Altman, J., Williams, N., and L. Zhu, &ldquo;<a href="http://tools.ietf.org/html/rfc5929">Channel Bindings for TLS</a>,&rdquo; RFC&nbsp;5929, July&nbsp;2010 (<a href="http://www.rfc-editor.org/rfc/rfc5929.txt">TXT</a>).</td></tr>
8169<tr><td class="author-text" valign="top"><a name="CHARSETS">[CHARSETS]</a></td>
8170<td class="author-text"><a href="mailto:Harald.T.Alvestrand@uninett.no">Alvestrand, H.</a>, &ldquo;<a href="http://tools.ietf.org/html/rfc2277">IETF Policy on Character Sets and Languages</a>,&rdquo; BCP&nbsp;18, RFC&nbsp;2277, January&nbsp;1998 (<a href="http://www.rfc-editor.org/rfc/rfc2277.txt">TXT</a>, <a href="http://xml.resource.org/public/rfc/html/rfc2277.html">HTML</a>, <a href="http://xml.resource.org/public/rfc/xml/rfc2277.xml">XML</a>).</td></tr>
8171<tr><td class="author-text" valign="top"><a name="DNS-CONCEPTS">[DNS-CONCEPTS]</a></td>
8172<td class="author-text">Mockapetris, P., &ldquo;<a href="http://tools.ietf.org/html/rfc1034">Domain names - concepts and facilities</a>,&rdquo; STD&nbsp;13, RFC&nbsp;1034, November&nbsp;1987 (<a href="http://www.rfc-editor.org/rfc/rfc1034.txt">TXT</a>).</td></tr>
8173<tr><td class="author-text" valign="top"><a name="DNS-SRV">[DNS-SRV]</a></td>
8174<td class="author-text"><a href="mailto:arnt@troll.no">Gulbrandsen, A.</a>, Vixie, P., and <a href="mailto:levone@microsoft.com">L. Esibov</a>, &ldquo;<a href="http://tools.ietf.org/html/rfc2782">A DNS RR for specifying the location of services (DNS SRV)</a>,&rdquo; RFC&nbsp;2782, February&nbsp;2000 (<a href="http://www.rfc-editor.org/rfc/rfc2782.txt">TXT</a>).</td></tr>
8175<tr><td class="author-text" valign="top"><a name="IPv6-ADDR">[IPv6-ADDR]</a></td>
8176<td class="author-text">Kawamura, S. and M. Kawashima, &ldquo;<a href="http://tools.ietf.org/html/rfc5952">A Recommendation for IPv6 Address Text Representation</a>,&rdquo; RFC&nbsp;5952, August&nbsp;2010 (<a href="http://www.rfc-editor.org/rfc/rfc5952.txt">TXT</a>).</td></tr>
8177<tr><td class="author-text" valign="top"><a name="KEYWORDS">[KEYWORDS]</a></td>
8178<td class="author-text"><a href="mailto:sob@harvard.edu">Bradner, S.</a>, &ldquo;<a href="http://tools.ietf.org/html/rfc2119">Key words for use in RFCs to Indicate Requirement Levels</a>,&rdquo; BCP&nbsp;14, RFC&nbsp;2119, March&nbsp;1997 (<a href="http://www.rfc-editor.org/rfc/rfc2119.txt">TXT</a>, <a href="http://xml.resource.org/public/rfc/html/rfc2119.html">HTML</a>, <a href="http://xml.resource.org/public/rfc/xml/rfc2119.xml">XML</a>).</td></tr>
8179<tr><td class="author-text" valign="top"><a name="LANGMATCH">[LANGMATCH]</a></td>
8180<td class="author-text">Phillips, A. and M. Davis, &ldquo;<a href="http://tools.ietf.org/html/rfc4647">Matching of Language Tags</a>,&rdquo; BCP&nbsp;47, RFC&nbsp;4647, September&nbsp;2006 (<a href="http://www.rfc-editor.org/rfc/rfc4647.txt">TXT</a>).</td></tr>
8181<tr><td class="author-text" valign="top"><a name="LANGTAGS">[LANGTAGS]</a></td>
8182<td class="author-text">Phillips, A. and M. Davis, &ldquo;<a href="http://tools.ietf.org/html/rfc5646">Tags for Identifying Languages</a>,&rdquo; BCP&nbsp;47, RFC&nbsp;5646, September&nbsp;2009 (<a href="http://www.rfc-editor.org/rfc/rfc5646.txt">TXT</a>).</td></tr>
8183<tr><td class="author-text" valign="top"><a name="OCSP">[OCSP]</a></td>
8184<td class="author-text"><a href="mailto:mmyers@verisign.com">Myers, M.</a>, <a href="mailto:rankney@erols.com">Ankney, R.</a>, <a href="mailto:ambarish@valicert.com">Malpani, A.</a>, <a href="mailto:galperin@mycfo.com">Galperin, S.</a>, and <a href="mailto:cadams@entrust.com">C. Adams</a>, &ldquo;<a href="http://tools.ietf.org/html/rfc2560">X.509 Internet Public Key Infrastructure Online Certificate Status Protocol - OCSP</a>,&rdquo; RFC&nbsp;2560, June&nbsp;1999 (<a href="http://www.rfc-editor.org/rfc/rfc2560.txt">TXT</a>).</td></tr>
8185<tr><td class="author-text" valign="top"><a name="PKIX">[PKIX]</a></td>
8186<td class="author-text">Cooper, D., Santesson, S., Farrell, S., Boeyen, S., Housley, R., and W. Polk, &ldquo;<a href="http://tools.ietf.org/html/rfc5280">Internet X.509 Public Key Infrastructure Certificate and Certificate Revocation List (CRL) Profile</a>,&rdquo; RFC&nbsp;5280, May&nbsp;2008 (<a href="http://www.rfc-editor.org/rfc/rfc5280.txt">TXT</a>).</td></tr>
8187<tr><td class="author-text" valign="top"><a name="PKIX-ALGO">[PKIX-ALGO]</a></td>
8188<td class="author-text">Jonsson, J. and B. Kaliski, &ldquo;<a href="http://tools.ietf.org/html/rfc3447">Public-Key Cryptography Standards (PKCS) #1: RSA Cryptography Specifications Version 2.1</a>,&rdquo; RFC&nbsp;3447, February&nbsp;2003 (<a href="http://www.rfc-editor.org/rfc/rfc3447.txt">TXT</a>).</td></tr>
8189<tr><td class="author-text" valign="top"><a name="PKIX-SRV">[PKIX-SRV]</a></td>
8190<td class="author-text">Santesson, S., &ldquo;<a href="http://tools.ietf.org/html/rfc4985">Internet X.509 Public Key Infrastructure Subject Alternative Name for Expression of Service Name</a>,&rdquo; RFC&nbsp;4985, August&nbsp;2007 (<a href="http://www.rfc-editor.org/rfc/rfc4985.txt">TXT</a>).</td></tr>
8191<tr><td class="author-text" valign="top"><a name="PLAIN">[PLAIN]</a></td>
8192<td class="author-text">Zeilenga, K., &ldquo;<a href="http://tools.ietf.org/html/rfc4616">The PLAIN Simple Authentication and Security Layer (SASL) Mechanism</a>,&rdquo; RFC&nbsp;4616, August&nbsp;2006 (<a href="http://www.rfc-editor.org/rfc/rfc4616.txt">TXT</a>).</td></tr>
8193<tr><td class="author-text" valign="top"><a name="RANDOM">[RANDOM]</a></td>
8194<td class="author-text">Eastlake, D., Schiller, J., and S. Crocker, &ldquo;<a href="http://tools.ietf.org/html/rfc4086">Randomness Requirements for Security</a>,&rdquo; BCP&nbsp;106, RFC&nbsp;4086, June&nbsp;2005 (<a href="http://www.rfc-editor.org/rfc/rfc4086.txt">TXT</a>).</td></tr>
8195<tr><td class="author-text" valign="top"><a name="SASL">[SASL]</a></td>
8196<td class="author-text">Melnikov, A. and K. Zeilenga, &ldquo;<a href="http://tools.ietf.org/html/rfc4422">Simple Authentication and Security Layer (SASL)</a>,&rdquo; RFC&nbsp;4422, June&nbsp;2006 (<a href="http://www.rfc-editor.org/rfc/rfc4422.txt">TXT</a>).</td></tr>
8197<tr><td class="author-text" valign="top"><a name="SCRAM">[SCRAM]</a></td>
8198<td class="author-text">Newman, C., Menon-Sen, A., Melnikov, A., and N. Williams, &ldquo;<a href="http://tools.ietf.org/html/rfc5802">Salted Challenge Response Authentication Mechanism (SCRAM) SASL and GSS-API Mechanisms</a>,&rdquo; RFC&nbsp;5802, July&nbsp;2010 (<a href="http://www.rfc-editor.org/rfc/rfc5802.txt">TXT</a>).</td></tr>
8199<tr><td class="author-text" valign="top"><a name="STRONGSEC">[STRONGSEC]</a></td>
8200<td class="author-text">Schiller, J., &ldquo;<a href="http://tools.ietf.org/html/rfc3365">Strong Security Requirements for Internet Engineering Task Force Standard Protocols</a>,&rdquo; BCP&nbsp;61, RFC&nbsp;3365, August&nbsp;2002 (<a href="http://www.rfc-editor.org/rfc/rfc3365.txt">TXT</a>).</td></tr>
8201<tr><td class="author-text" valign="top"><a name="TCP">[TCP]</a></td>
8202<td class="author-text">Postel, J., &ldquo;<a href="http://tools.ietf.org/html/rfc793">Transmission Control Protocol</a>,&rdquo; STD&nbsp;7, RFC&nbsp;793, September&nbsp;1981 (<a href="http://www.rfc-editor.org/rfc/rfc793.txt">TXT</a>).</td></tr>
8203<tr><td class="author-text" valign="top"><a name="TLS">[TLS]</a></td>
8204<td class="author-text">Dierks, T. and E. Rescorla, &ldquo;<a href="http://tools.ietf.org/html/rfc5246">The Transport Layer Security (TLS) Protocol Version 1.2</a>,&rdquo; RFC&nbsp;5246, August&nbsp;2008 (<a href="http://www.rfc-editor.org/rfc/rfc5246.txt">TXT</a>).</td></tr>
8205<tr><td class="author-text" valign="top"><a name="TLS-CERTS">[TLS-CERTS]</a></td>
8206<td class="author-text">Saint-Andre, P. and J. Hodges, &ldquo;<a href="http://tools.ietf.org/html/rfc6125">Representation and Verification of Domain-Based Application Service Identity within Internet Public Key Infrastructure Using X.509 (PKIX) Certificates in the Context of Transport Layer Security (TLS)</a>,&rdquo; RFC&nbsp;6125, March&nbsp;2011.</td></tr>
8207<tr><td class="author-text" valign="top"><a name="TLS-NEG">[TLS-NEG]</a></td>
8208<td class="author-text">Rescorla, E., Ray, M., Dispensa, S., and N. Oskov, &ldquo;<a href="http://tools.ietf.org/html/rfc5746">Transport Layer Security (TLS) Renegotiation Indication Extension</a>,&rdquo; RFC&nbsp;5746, February&nbsp;2010 (<a href="http://www.rfc-editor.org/rfc/rfc5746.txt">TXT</a>).</td></tr>
8209<tr><td class="author-text" valign="top"><a name="TLS-SSL2">[TLS-SSL2]</a></td>
8210<td class="author-text">Turner, S. and T. Polk, &ldquo;<a href="http://tools.ietf.org/html/rfc6176">Prohibiting Secure Sockets Layer (SSL) Version 2.0</a>,&rdquo; RFC&nbsp;6176, March&nbsp;2011.</td></tr>
8211<tr><td class="author-text" valign="top"><a name="UCS2">[UCS2]</a></td>
8212<td class="author-text">International Organization for Standardization, &ldquo;Information Technology - Universal Multiple-octet coded Character Set (UCS) - Amendment 2: UCS Transformation Format 8 (UTF-8),&rdquo; ISO&nbsp;Standard 10646-1 Addendum 2, October&nbsp;1996.</td></tr>
8213<tr><td class="author-text" valign="top"><a name="UNICODE">[UNICODE]</a></td>
8214<td class="author-text">The Unicode Consortium, &ldquo;<a href="http://www.unicode.org/versions/Unicode6.0.0/">The Unicode Standard, Version 6.0</a>,&rdquo; 2010.</td></tr>
8215<tr><td class="author-text" valign="top"><a name="UTF-8">[UTF-8]</a></td>
8216<td class="author-text">Yergeau, F., &ldquo;<a href="http://tools.ietf.org/html/rfc3629">UTF-8, a transformation format of ISO 10646</a>,&rdquo; STD&nbsp;63, RFC&nbsp;3629, November&nbsp;2003 (<a href="http://www.rfc-editor.org/rfc/rfc3629.txt">TXT</a>).</td></tr>
8217<tr><td class="author-text" valign="top"><a name="URI">[URI]</a></td>
8218<td class="author-text"><a href="mailto:timbl@w3.org">Berners-Lee, T.</a>, <a href="mailto:fielding@gbiv.com">Fielding, R.</a>, and <a href="mailto:LMM@acm.org">L. Masinter</a>, &ldquo;<a href="http://tools.ietf.org/html/rfc3986">Uniform Resource Identifier (URI): Generic Syntax</a>,&rdquo; STD&nbsp;66, RFC&nbsp;3986, January&nbsp;2005 (<a href="http://www.rfc-editor.org/rfc/rfc3986.txt">TXT</a>, <a href="http://xml.resource.org/public/rfc/html/rfc3986.html">HTML</a>, <a href="http://xml.resource.org/public/rfc/xml/rfc3986.xml">XML</a>).</td></tr>
8219<tr><td class="author-text" valign="top"><a name="X509">[X509]</a></td>
8220<td class="author-text">International Telecommunications Union, &ldquo;Information technology - Open Systems Interconnection - The Directory:
8221Public-key and attribute certificate frameworks,&rdquo; ITU-T&nbsp;Recommendation X.509, ISO&nbsp;Standard 9594-8, March&nbsp;2000.</td></tr>
8222<tr><td class="author-text" valign="top"><a name="XML">[XML]</a></td>
8223<td class="author-text">Maler, E., Yergeau, F., Sperberg-McQueen, C., Paoli, J., and T. Bray, &ldquo;<a href="http://www.w3.org/TR/2008/REC-xml-20081126">Extensible Markup Language (XML) 1.0 (Fifth Edition)</a>,&rdquo; World Wide Web Consortium Recommendation&nbsp;REC-xml-20081126, November&nbsp;2008 (<a href="http://www.w3.org/TR/2008/REC-xml-20081126">HTML</a>).</td></tr>
8224<tr><td class="author-text" valign="top"><a name="XML-GUIDE">[XML-GUIDE]</a></td>
8225<td class="author-text"><a href="mailto:shollenbeck@verisign.com">Hollenbeck, S.</a>, <a href="mailto:mrose@dbc.mtview.ca.us">Rose, M.</a>, and <a href="mailto:LMM@acm.org">L. Masinter</a>, &ldquo;<a href="http://tools.ietf.org/html/rfc3470">Guidelines for the Use of Extensible Markup Language (XML) within IETF Protocols</a>,&rdquo; BCP&nbsp;70, RFC&nbsp;3470, January&nbsp;2003 (<a href="http://www.rfc-editor.org/rfc/rfc3470.txt">TXT</a>, <a href="http://xml.resource.org/public/rfc/html/rfc3470.html">HTML</a>, <a href="http://xml.resource.org/public/rfc/xml/rfc3470.xml">XML</a>).</td></tr>
8226<tr><td class="author-text" valign="top"><a name="XML-MEDIA">[XML-MEDIA]</a></td>
8227<td class="author-text">Murata, M., St. Laurent, S., and D. Kohn, &ldquo;<a href="http://tools.ietf.org/html/rfc3023">XML Media Types</a>,&rdquo; RFC&nbsp;3023, January&nbsp;2001 (<a href="http://www.rfc-editor.org/rfc/rfc3023.txt">TXT</a>).</td></tr>
8228<tr><td class="author-text" valign="top"><a name="XML-NAMES">[XML-NAMES]</a></td>
8229<td class="author-text">Thompson, H., Hollander, D., Layman, A., Bray, T., and R. Tobin, &ldquo;<a href="http://www.w3.org/TR/2009/REC-xml-names-20091208">Namespaces in XML 1.0 (Third Edition)</a>,&rdquo; World Wide Web Consortium Recommendation&nbsp;REC-xml-names-20091208, December&nbsp;2009 (<a href="http://www.w3.org/TR/2009/REC-xml-names-20091208">HTML</a>).</td></tr>
8230<tr><td class="author-text" valign="top"><a name="XMPP-ADDR">[XMPP-ADDR]</a></td>
8231<td class="author-text">Saint-Andre, P., &ldquo;<a href="http://tools.ietf.org/html/rfc6122">Extensible Messaging and Presence Protocol (XMPP): Address Format</a>,&rdquo; RFC&nbsp;6122, March&nbsp;2011.</td></tr>
8232<tr><td class="author-text" valign="top"><a name="XMPP-IM">[XMPP-IM]</a></td>
8233<td class="author-text">Saint-Andre, P., &ldquo;<a href="http://tools.ietf.org/html/rfc6121">Extensible Messaging and Presence Protocol (XMPP): Instant Messaging and Presence</a>,&rdquo; RFC&nbsp;6121, March&nbsp;2011.</td></tr>
8234</table>
8235
8236<a name="rfc.references2"></a><br /><hr />
8237<table summary="layout" cellpadding="0" cellspacing="2" class="TOCbug" align="right"><tr><td class="TOCbug"><a href="#toc">&nbsp;TOC&nbsp;</a></td></tr></table>
8238<h3>16.2.&nbsp;Informative References</h3>
8239<table width="99%" border="0">
8240<tr><td class="author-text" valign="top"><a name="AAA">[AAA]</a></td>
8241<td class="author-text">Housley, R. and B. Aboba, &ldquo;<a href="http://tools.ietf.org/html/rfc4962">Guidance for Authentication, Authorization, and Accounting (AAA) Key Management</a>,&rdquo; BCP&nbsp;132, RFC&nbsp;4962, July&nbsp;2007 (<a href="http://www.rfc-editor.org/rfc/rfc4962.txt">TXT</a>).</td></tr>
8242<tr><td class="author-text" valign="top"><a name="ABNF">[ABNF]</a></td>
8243<td class="author-text">Crocker, D. and P. Overell, &ldquo;<a href="http://tools.ietf.org/html/rfc5234">Augmented BNF for Syntax Specifications: ABNF</a>,&rdquo; STD&nbsp;68, RFC&nbsp;5234, January&nbsp;2008 (<a href="http://www.rfc-editor.org/rfc/rfc5234.txt">TXT</a>).</td></tr>
8244<tr><td class="author-text" valign="top"><a name="ACAP">[ACAP]</a></td>
8245<td class="author-text"><a href="mailto:chris.newman@innosoft.com">Newman, C.</a> and <a href="mailto:jgmyers@netscape.com">J. Myers</a>, &ldquo;<a href="http://tools.ietf.org/html/rfc2244">ACAP -- Application Configuration Access Protocol</a>,&rdquo; RFC&nbsp;2244, November&nbsp;1997 (<a href="http://www.rfc-editor.org/rfc/rfc2244.txt">TXT</a>).</td></tr>
8246<tr><td class="author-text" valign="top"><a name="ANONYMOUS">[ANONYMOUS]</a></td>
8247<td class="author-text">Zeilenga, K., &ldquo;<a href="http://tools.ietf.org/html/rfc4505">Anonymous Simple Authentication and Security Layer (SASL) Mechanism</a>,&rdquo; RFC&nbsp;4505, June&nbsp;2006 (<a href="http://www.rfc-editor.org/rfc/rfc4505.txt">TXT</a>).</td></tr>
8248<tr><td class="author-text" valign="top"><a name="ASN.1">[ASN.1]</a></td>
8249<td class="author-text">CCITT, &ldquo;Recommendation X.208: Specification of Abstract Syntax Notation One (ASN.1),&rdquo; 1988.</td></tr>
8250<tr><td class="author-text" valign="top"><a name="DIGEST-MD5">[DIGEST-MD5]</a></td>
8251<td class="author-text">Leach, P. and C. Newman, &ldquo;<a href="http://tools.ietf.org/html/rfc2831">Using Digest Authentication as a SASL Mechanism</a>,&rdquo; RFC&nbsp;2831, May&nbsp;2000 (<a href="http://www.rfc-editor.org/rfc/rfc2831.txt">TXT</a>).</td></tr>
8252<tr><td class="author-text" valign="top"><a name="DNSSEC">[DNSSEC]</a></td>
8253<td class="author-text">Arends, R., Austein, R., Larson, M., Massey, D., and S. Rose, &ldquo;<a href="http://tools.ietf.org/html/rfc4033">DNS Security Introduction and Requirements</a>,&rdquo; RFC&nbsp;4033, March&nbsp;2005 (<a href="http://www.rfc-editor.org/rfc/rfc4033.txt">TXT</a>).</td></tr>
8254<tr><td class="author-text" valign="top"><a name="DNS-TXT">[DNS-TXT]</a></td>
8255<td class="author-text"><a href="mailto:rosenbaum@lkg.dec.com">Rosenbaum, R.</a>, &ldquo;<a href="http://tools.ietf.org/html/rfc1464">Using the Domain Name System To Store Arbitrary String Attributes</a>,&rdquo; RFC&nbsp;1464, May&nbsp;1993 (<a href="http://www.rfc-editor.org/rfc/rfc1464.txt">TXT</a>).</td></tr>
8256<tr><td class="author-text" valign="top"><a name="DOS">[DOS]</a></td>
8257<td class="author-text">Handley, M., Rescorla, E., and IAB, &ldquo;<a href="http://tools.ietf.org/html/rfc4732">Internet Denial-of-Service Considerations</a>,&rdquo; RFC&nbsp;4732, December&nbsp;2006 (<a href="http://www.rfc-editor.org/rfc/rfc4732.txt">TXT</a>).</td></tr>
8258<tr><td class="author-text" valign="top"><a name="E2E-REQS">[E2E-REQS]</a></td>
8259<td class="author-text">Saint-Andre, P., &ldquo;Requirements for End-to-End Encryption in the Extensible Messaging and Presence Protocol (XMPP),&rdquo; Work in&nbsp;Progress, March&nbsp;2010.</td></tr>
8260<tr><td class="author-text" valign="top"><a name="EMAIL-ARCH">[EMAIL-ARCH]</a></td>
8261<td class="author-text">Crocker, D., &ldquo;<a href="http://tools.ietf.org/html/rfc5598">Internet Mail Architecture</a>,&rdquo; RFC&nbsp;5598, July&nbsp;2009 (<a href="http://www.rfc-editor.org/rfc/rfc5598.txt">TXT</a>).</td></tr>
8262<tr><td class="author-text" valign="top"><a name="ETHERNET">[ETHERNET]</a></td>
8263<td class="author-text">&ldquo;Information technology - Telecommunications and information exchange between systems - Local and metropolitan area networks - Specific requirements - Part 3: Carrier sense multiple access with collision detection (CSMA/CD) access method and physical layer specifications,&rdquo; IEEE&nbsp;Standard 802.3, September&nbsp;1998.</td></tr>
8264<tr><td class="author-text" valign="top"><a name="GSS-API">[GSS-API]</a></td>
8265<td class="author-text"><a href="mailto:jlinn@rsasecurity.com">Linn, J.</a>, &ldquo;<a href="http://tools.ietf.org/html/rfc2743">Generic Security Service Application Program Interface Version 2, Update 1</a>,&rdquo; RFC&nbsp;2743, January&nbsp;2000 (<a href="http://www.rfc-editor.org/rfc/rfc2743.txt">TXT</a>).</td></tr>
8266<tr><td class="author-text" valign="top"><a name="HASHES">[HASHES]</a></td>
8267<td class="author-text">Hoffman, P. and B. Schneier, &ldquo;<a href="http://tools.ietf.org/html/rfc4270">Attacks on Cryptographic Hashes in Internet Protocols</a>,&rdquo; RFC&nbsp;4270, November&nbsp;2005 (<a href="http://www.rfc-editor.org/rfc/rfc4270.txt">TXT</a>).</td></tr>
8268<tr><td class="author-text" valign="top"><a name="HTTP">[HTTP]</a></td>
8269<td class="author-text"><a href="mailto:fielding@ics.uci.edu">Fielding, R.</a>, <a href="mailto:jg@w3.org">Gettys, J.</a>, <a href="mailto:mogul@wrl.dec.com">Mogul, J.</a>, <a href="mailto:frystyk@w3.org">Frystyk, H.</a>, <a href="mailto:masinter@parc.xerox.com">Masinter, L.</a>, <a href="mailto:paulle@microsoft.com">Leach, P.</a>, and <a href="mailto:timbl@w3.org">T. Berners-Lee</a>, &ldquo;<a href="http://tools.ietf.org/html/rfc2616">Hypertext Transfer Protocol -- HTTP/1.1</a>,&rdquo; RFC&nbsp;2616, June&nbsp;1999 (<a href="http://www.rfc-editor.org/rfc/rfc2616.txt">TXT</a>, <a href="http://www.rfc-editor.org/rfc/rfc2616.ps">PS</a>, <a href="http://www.rfc-editor.org/rfc/rfc2616.pdf">PDF</a>, <a href="http://xml.resource.org/public/rfc/html/rfc2616.html">HTML</a>, <a href="http://xml.resource.org/public/rfc/xml/rfc2616.xml">XML</a>).</td></tr>
8270<tr><td class="author-text" valign="top"><a name="IANA-GUIDE">[IANA-GUIDE]</a></td>
8271<td class="author-text">Narten, T. and H. Alvestrand, &ldquo;<a href="http://tools.ietf.org/html/rfc5226">Guidelines for Writing an IANA Considerations Section in RFCs</a>,&rdquo; BCP&nbsp;26, RFC&nbsp;5226, May&nbsp;2008 (<a href="http://www.rfc-editor.org/rfc/rfc5226.txt">TXT</a>).</td></tr>
8272<tr><td class="author-text" valign="top"><a name="IANA-PORTS">[IANA-PORTS]</a></td>
8273<td class="author-text">Cotton, M., Eggert, L., Touch, J., Westerlund, M., and S. Cheshire, &ldquo;Internet Assigned Numbers Authority (IANA) Procedures for the Management of the Transport Protocol Port Number and Service Name Registry,&rdquo; Work in&nbsp;Progress, February&nbsp;2011.</td></tr>
8274<tr><td class="author-text" valign="top"><a name="IMAP">[IMAP]</a></td>
8275<td class="author-text">Crispin, M., &ldquo;<a href="http://tools.ietf.org/html/rfc3501">INTERNET MESSAGE ACCESS PROTOCOL - VERSION 4rev1</a>,&rdquo; RFC&nbsp;3501, March&nbsp;2003 (<a href="http://www.rfc-editor.org/rfc/rfc3501.txt">TXT</a>).</td></tr>
8276<tr><td class="author-text" valign="top"><a name="IMP-REQS">[IMP-REQS]</a></td>
8277<td class="author-text"><a href="mailto:mday@alum.mit.edu">Day, M.</a>, <a href="mailto:sonuag@microsoft.com">Aggarwal, S.</a>, and <a href="mailto:jesse@intonet.com">J. Vincent</a>, &ldquo;<a href="http://tools.ietf.org/html/rfc2779">Instant Messaging / Presence Protocol Requirements</a>,&rdquo; RFC&nbsp;2779, February&nbsp;2000 (<a href="http://www.rfc-editor.org/rfc/rfc2779.txt">TXT</a>).</td></tr>
8278<tr><td class="author-text" valign="top"><a name="INTEROP">[INTEROP]</a></td>
8279<td class="author-text">Masinter, L., &ldquo;Formalizing IETF Interoperability Reporting,&rdquo; Work in&nbsp;Progress, October&nbsp;2005.</td></tr>
8280<tr><td class="author-text" valign="top"><a name="IRC">[IRC]</a></td>
8281<td class="author-text">Kalt, C., &ldquo;<a href="http://tools.ietf.org/html/rfc2810">Internet Relay Chat: Architecture</a>,&rdquo; RFC&nbsp;2810, April&nbsp;2000 (<a href="http://www.rfc-editor.org/rfc/rfc2810.txt">TXT</a>).</td></tr>
8282<tr><td class="author-text" valign="top"><a name="IRI">[IRI]</a></td>
8283<td class="author-text">Duerst, M. and M. Suignard, &ldquo;<a href="http://tools.ietf.org/html/rfc3987">Internationalized Resource Identifiers (IRIs)</a>,&rdquo; RFC&nbsp;3987, January&nbsp;2005 (<a href="http://www.rfc-editor.org/rfc/rfc3987.txt">TXT</a>).</td></tr>
8284<tr><td class="author-text" valign="top"><a name="LDAP">[LDAP]</a></td>
8285<td class="author-text">Zeilenga, K., &ldquo;<a href="http://tools.ietf.org/html/rfc4510">Lightweight Directory Access Protocol (LDAP): Technical Specification Road Map</a>,&rdquo; RFC&nbsp;4510, June&nbsp;2006 (<a href="http://www.rfc-editor.org/rfc/rfc4510.txt">TXT</a>).</td></tr>
8286<tr><td class="author-text" valign="top"><a name="LINKLOCAL">[LINKLOCAL]</a></td>
8287<td class="author-text">Cheshire, S., Aboba, B., and E. Guttman, &ldquo;<a href="http://tools.ietf.org/html/rfc3927">Dynamic Configuration of IPv4 Link-Local Addresses</a>,&rdquo; RFC&nbsp;3927, May&nbsp;2005 (<a href="http://www.rfc-editor.org/rfc/rfc3927.txt">TXT</a>).</td></tr>
8288<tr><td class="author-text" valign="top"><a name="MAILBOXES">[MAILBOXES]</a></td>
8289<td class="author-text"><a href="mailto:dcrocker@imc.org">Crocker, D.</a>, &ldquo;<a href="http://tools.ietf.org/html/rfc2142">MAILBOX NAMES FOR COMMON SERVICES, ROLES AND FUNCTIONS</a>,&rdquo; RFC&nbsp;2142, May&nbsp;1997 (<a href="http://www.rfc-editor.org/rfc/rfc2142.txt">TXT</a>, <a href="http://xml.resource.org/public/rfc/html/rfc2142.html">HTML</a>, <a href="http://xml.resource.org/public/rfc/xml/rfc2142.xml">XML</a>).</td></tr>
8290<tr><td class="author-text" valign="top"><a name="POP3">[POP3]</a></td>
8291<td class="author-text"><a href="mailto:jgm+@cmu.edu">Myers, J.</a> and <a href="mailto:mrose@dbc.mtview.ca.us">M. Rose</a>, &ldquo;<a href="http://tools.ietf.org/html/rfc1939">Post Office Protocol - Version 3</a>,&rdquo; STD&nbsp;53, RFC&nbsp;1939, May&nbsp;1996 (<a href="http://www.rfc-editor.org/rfc/rfc1939.txt">TXT</a>).</td></tr>
8292<tr><td class="author-text" valign="top"><a name="PROCESS">[PROCESS]</a></td>
8293<td class="author-text"><a href="mailto:sob@harvard.edu">Bradner, S.</a>, &ldquo;<a href="http://tools.ietf.org/html/rfc2026">The Internet Standards Process -- Revision 3</a>,&rdquo; BCP&nbsp;9, RFC&nbsp;2026, October&nbsp;1996 (<a href="http://www.rfc-editor.org/rfc/rfc2026.txt">TXT</a>).</td></tr>
8294<tr><td class="author-text" valign="top"><a name="REPORTS">[REPORTS]</a></td>
8295<td class="author-text">Dusseault, L. and R. Sparks, &ldquo;<a href="http://tools.ietf.org/html/rfc5657">Guidance on Interoperation and Implementation Reports for Advancement to Draft Standard</a>,&rdquo; BCP&nbsp;9, RFC&nbsp;5657, September&nbsp;2009 (<a href="http://www.rfc-editor.org/rfc/rfc5657.txt">TXT</a>).</td></tr>
8296<tr><td class="author-text" valign="top"><a name="REST">[REST]</a></td>
8297<td class="author-text">Fielding, R., &ldquo;<a href="http://www.ics.uci.edu/~fielding/pubs/dissertation/fielding_dissertation.pdf">Architectural Styles and the Design of Network-based Software Architectures</a>,&rdquo; &nbsp;2000.</td></tr>
8298<tr><td class="author-text" valign="top"><a name="RFC3920">[RFC3920]</a></td>
8299<td class="author-text"><a href="mailto:stpeter@jabber.org">Saint-Andre, P., Ed.</a>, &ldquo;<a href="http://tools.ietf.org/html/rfc3920">Extensible Messaging and Presence Protocol (XMPP): Core</a>,&rdquo; RFC&nbsp;3920, October&nbsp;2004 (<a href="http://www.rfc-editor.org/rfc/rfc3920.txt">TXT</a>, <a href="http://xml.resource.org/public/rfc/html/rfc3920.html">HTML</a>, <a href="http://xml.resource.org/public/rfc/xml/rfc3920.xml">XML</a>).</td></tr>
8300<tr><td class="author-text" valign="top"><a name="RFC3921">[RFC3921]</a></td>
8301<td class="author-text"><a href="mailto:stpeter@jabber.org">Saint-Andre, P., Ed.</a>, &ldquo;<a href="http://tools.ietf.org/html/rfc3921">Extensible Messaging and Presence Protocol (XMPP): Instant Messaging and Presence</a>,&rdquo; RFC&nbsp;3921, October&nbsp;2004 (<a href="http://www.rfc-editor.org/rfc/rfc3921.txt">TXT</a>, <a href="http://xml.resource.org/public/rfc/html/rfc3921.html">HTML</a>, <a href="http://xml.resource.org/public/rfc/xml/rfc3921.xml">XML</a>).</td></tr>
8302<tr><td class="author-text" valign="top"><a name="SASLPREP">[SASLPREP]</a></td>
8303<td class="author-text">Zeilenga, K., &ldquo;<a href="http://tools.ietf.org/html/rfc4013">SASLprep: Stringprep Profile for User Names and Passwords</a>,&rdquo; RFC&nbsp;4013, February&nbsp;2005 (<a href="http://www.rfc-editor.org/rfc/rfc4013.txt">TXT</a>).</td></tr>
8304<tr><td class="author-text" valign="top"><a name="SEC-TERMS">[SEC-TERMS]</a></td>
8305<td class="author-text">Shirey, R., &ldquo;<a href="http://tools.ietf.org/html/rfc4949">Internet Security Glossary, Version 2</a>,&rdquo; RFC&nbsp;4949, August&nbsp;2007 (<a href="http://www.rfc-editor.org/rfc/rfc4949.txt">TXT</a>).</td></tr>
8306<tr><td class="author-text" valign="top"><a name="SMTP">[SMTP]</a></td>
8307<td class="author-text">Klensin, J., &ldquo;<a href="http://tools.ietf.org/html/rfc5321">Simple Mail Transfer Protocol</a>,&rdquo; RFC&nbsp;5321, October&nbsp;2008 (<a href="http://www.rfc-editor.org/rfc/rfc5321.txt">TXT</a>).</td></tr>
8308<tr><td class="author-text" valign="top"><a name="SEC-GUIDE">[SEC-GUIDE]</a></td>
8309<td class="author-text">Rescorla, E. and B. Korver, &ldquo;<a href="http://tools.ietf.org/html/rfc3552">Guidelines for Writing RFC Text on Security Considerations</a>,&rdquo; BCP&nbsp;72, RFC&nbsp;3552, July&nbsp;2003 (<a href="http://www.rfc-editor.org/rfc/rfc3552.txt">TXT</a>).</td></tr>
8310<tr><td class="author-text" valign="top"><a name="TLS-EXT">[TLS-EXT]</a></td>
8311<td class="author-text">Eastlake 3rd, D., &ldquo;<a href="http://tools.ietf.org/html/rfc6066">Transport Layer Security (TLS) Extensions: Extension Definitions</a>,&rdquo; RFC&nbsp;6066, January&nbsp;2011 (<a href="http://www.rfc-editor.org/rfc/rfc6066.txt">TXT</a>).</td></tr>
8312<tr><td class="author-text" valign="top"><a name="TLS-RESUME">[TLS-RESUME]</a></td>
8313<td class="author-text">Salowey, J., Zhou, H., Eronen, P., and H. Tschofenig, &ldquo;<a href="http://tools.ietf.org/html/rfc5077">Transport Layer Security (TLS) Session Resumption without Server-Side State</a>,&rdquo; RFC&nbsp;5077, January&nbsp;2008 (<a href="http://www.rfc-editor.org/rfc/rfc5077.txt">TXT</a>).</td></tr>
8314<tr><td class="author-text" valign="top"><a name="URN-OID">[URN-OID]</a></td>
8315<td class="author-text">Mealling, M., &ldquo;<a href="http://tools.ietf.org/html/rfc3061">A URN Namespace of Object Identifiers</a>,&rdquo; RFC&nbsp;3061, February&nbsp;2001 (<a href="http://www.rfc-editor.org/rfc/rfc3061.txt">TXT</a>).</td></tr>
8316<tr><td class="author-text" valign="top"><a name="USINGTLS">[USINGTLS]</a></td>
8317<td class="author-text"><a href="mailto:chris.newman@innosoft.com">Newman, C.</a>, &ldquo;<a href="http://tools.ietf.org/html/rfc2595">Using TLS with IMAP, POP3 and ACAP</a>,&rdquo; RFC&nbsp;2595, June&nbsp;1999 (<a href="http://www.rfc-editor.org/rfc/rfc2595.txt">TXT</a>).</td></tr>
8318<tr><td class="author-text" valign="top"><a name="UUID">[UUID]</a></td>
8319<td class="author-text"><a href="mailto:paulle@microsoft.com">Leach, P.</a>, <a href="mailto:michael@refactored-networks.com">Mealling, M.</a>, and <a href="mailto:rsalz@datapower.com">R. Salz</a>, &ldquo;<a href="http://tools.ietf.org/html/rfc4122">A Universally Unique IDentifier (UUID) URN Namespace</a>,&rdquo; RFC&nbsp;4122, July&nbsp;2005 (<a href="http://www.rfc-editor.org/rfc/rfc4122.txt">TXT</a>, <a href="http://xml.resource.org/public/rfc/html/rfc4122.html">HTML</a>, <a href="http://xml.resource.org/public/rfc/xml/rfc4122.xml">XML</a>).</td></tr>
8320<tr><td class="author-text" valign="top"><a name="XEP-0001">[XEP-0001]</a></td>
8321<td class="author-text"><a href="mailto:stpeter@jabber.org">Saint-Andre, P.</a>, &ldquo;<a href="http://www.xmpp.org/extensions/xep-0001.html">XMPP Extension Protocols</a>,&rdquo; XSF XEP&nbsp;0001, March&nbsp;2010.</td></tr>
8322<tr><td class="author-text" valign="top"><a name="XEP-0016">[XEP-0016]</a></td>
8323<td class="author-text">Millard, P. and <a href="mailto:stpeter@jabber.org">P. Saint-Andre</a>, &ldquo;<a href="http://www.xmpp.org/extensions/xep-0016.html">Privacy Lists</a>,&rdquo; XSF XEP&nbsp;0016, February&nbsp;2007.</td></tr>
8324<tr><td class="author-text" valign="top"><a name="XEP-0045">[XEP-0045]</a></td>
8325<td class="author-text"><a href="mailto:stpeter@jabber.org">Saint-Andre, P.</a>, &ldquo;<a href="http://www.xmpp.org/extensions/xep-0045.html">Multi-User Chat</a>,&rdquo; XSF XEP&nbsp;0045, July&nbsp;2007.</td></tr>
8326<tr><td class="author-text" valign="top"><a name="XEP-0060">[XEP-0060]</a></td>
8327<td class="author-text"><a href="mailto:">Millard, P.</a>, <a href="mailto:stpeter@jabber.org">Saint-Andre, P.</a>, and <a href="mailto:ralphm@ik.nu">R. Meijer</a>, &ldquo;<a href="http://www.xmpp.org/extensions/xep-0060.html">Publish-Subscribe</a>,&rdquo; XSF XEP&nbsp;0060, July&nbsp;2010.</td></tr>
8328<tr><td class="author-text" valign="top"><a name="XEP-0071">[XEP-0071]</a></td>
8329<td class="author-text"><a href="mailto:stpeter@jabber.org">Saint-Andre, P.</a>, &ldquo;<a href="http://www.xmpp.org/extensions/xep-0071.html">XHTML-IM</a>,&rdquo; XSF XEP&nbsp;0071, September&nbsp;2008.</td></tr>
8330<tr><td class="author-text" valign="top"><a name="XEP-0077">[XEP-0077]</a></td>
8331<td class="author-text"><a href="mailto:stpeter@jabber.org">Saint-Andre, P.</a>, &ldquo;<a href="http://www.xmpp.org/extensions/xep-0077.html">In-Band Registration</a>,&rdquo; XSF XEP&nbsp;0077, September&nbsp;2009.</td></tr>
8332<tr><td class="author-text" valign="top"><a name="XEP-0086">[XEP-0086]</a></td>
8333<td class="author-text"><a href="mailto:rob@cataclysm.cx">Norris, R.</a> and <a href="mailto:stpeter@jabber.org">P. Saint-Andre</a>, &ldquo;<a href="http://xmpp.org/extensions/xep-0086.html">Error Condition Mappings</a>,&rdquo; XSF XEP&nbsp;0086, February&nbsp;2004.</td></tr>
8334<tr><td class="author-text" valign="top"><a name="XEP-0100">[XEP-0100]</a></td>
8335<td class="author-text"><a href="mailto:stpeter@jabber.org">Saint-Andre, P.</a> and <a href="mailto:dizzyd@jabber.org">D. Smith</a>, &ldquo;<a href="http://xmpp.org/extensions/xep-0100.html">Gateway Interaction</a>,&rdquo; XSF XEP&nbsp;0100, October&nbsp;2005.</td></tr>
8336<tr><td class="author-text" valign="top"><a name="XEP-0114">[XEP-0114]</a></td>
8337<td class="author-text"><a href="mailto:stpeter@jabber.org">Saint-Andre, P.</a>, &ldquo;<a href="http://xmpp.org/extensions/xep-0114.html">Jabber Component Protocol</a>,&rdquo; XSF XEP&nbsp;0114, March&nbsp;2005.</td></tr>
8338<tr><td class="author-text" valign="top"><a name="XEP-0124">[XEP-0124]</a></td>
8339<td class="author-text"><a href="mailto:ian.paterson@clientside.co.uk">Paterson, I.</a>, <a href="mailto:dizzyd@jabber.org">Smith, D.</a>, and <a href="mailto:stpeter@jabber.org">P. Saint-Andre</a>, &ldquo;<a href="http://www.xmpp.org/extensions/xep-0124.html">Bidirectional-streams Over Synchronous HTTP (BOSH)</a>,&rdquo; XSF XEP&nbsp;0124, July&nbsp;2010.</td></tr>
8340<tr><td class="author-text" valign="top"><a name="XEP-0138">[XEP-0138]</a></td>
8341<td class="author-text"><a href="mailto:jhildebr@cisco.com">Hildebrand, J.</a> and <a href="mailto:stpeter@jabber.org">P. Saint-Andre</a>, &ldquo;<a href="http://xmpp.org/extensions/xep-0138.html">Stream Compression</a>,&rdquo; XSF XEP&nbsp;0138, May&nbsp;2009.</td></tr>
8342<tr><td class="author-text" valign="top"><a name="XEP-0156">[XEP-0156]</a></td>
8343<td class="author-text"><a href="mailto:jhildebrand@jabber.com">Hildebrand, J.</a> and <a href="mailto:stpeter@jabber.org">P. Saint-Andre</a>, &ldquo;<a href="http://www.xmpp.org/extensions/xep-0156.html">Discovering Alternative XMPP Connection Methods</a>,&rdquo; XSF XEP&nbsp;0156, June&nbsp;2007.</td></tr>
8344<tr><td class="author-text" valign="top"><a name="XEP-0160">[XEP-0160]</a></td>
8345<td class="author-text"><a href="mailto:stpeter@jabber.org">Saint-Andre, P.</a>, &ldquo;<a href="http://www.xmpp.org/extensions/xep-0160.html">Best Practices for Handling Offline Messages</a>,&rdquo; XSF XEP&nbsp;0160, January&nbsp;2006.</td></tr>
8346<tr><td class="author-text" valign="top"><a name="XEP-0174">[XEP-0174]</a></td>
8347<td class="author-text"><a href="mailto:stpeter@jabber.org">Saint-Andre, P.</a>, &ldquo;<a href="http://www.xmpp.org/extensions/xep-0174.html">Link-Local Messaging</a>,&rdquo; XSF XEP&nbsp;0174, November&nbsp;2008.</td></tr>
8348<tr><td class="author-text" valign="top"><a name="XEP-0175">[XEP-0175]</a></td>
8349<td class="author-text"><a href="mailto:stpeter@jabber.org">Saint-Andre, P.</a>, &ldquo;<a href="http://www.xmpp.org/extensions/xep-0175.html">Best Practices for Use of SASL ANONYMOUS</a>,&rdquo; XSF XEP&nbsp;0175, September&nbsp;2009.</td></tr>
8350<tr><td class="author-text" valign="top"><a name="XEP-0178">[XEP-0178]</a></td>
8351<td class="author-text"><a href="mailto:stpeter@jabber.org">Saint-Andre, P.</a> and <a href="mailto:">P. Millard</a>, &ldquo;<a href="http://www.xmpp.org/extensions/xep-0178.html">Best Practices for Use of SASL EXTERNAL with Certificates</a>,&rdquo; XSF XEP&nbsp;0178, February&nbsp;2007.</td></tr>
8352<tr><td class="author-text" valign="top"><a name="XEP-0191">[XEP-0191]</a></td>
8353<td class="author-text"><a href="mailto:">Saint-Andre, P.</a>, &ldquo;<a href="http://www.xmpp.org/extensions/xep-0191.html">Simple Communications Blocking</a>,&rdquo; XSF XEP&nbsp;0191, February&nbsp;2007.</td></tr>
8354<tr><td class="author-text" valign="top"><a name="XEP-0198">[XEP-0198]</a></td>
8355<td class="author-text"><a href="mailto:justin@affinix.com">Karneges, J.</a>, <a href="mailto:jhildebr@cisco.com">Hildebrand, J.</a>, <a href="mailto:">Saint-Andre, P.</a>, <a href="mailto:fabio.forno@gmail.com">Forno, F.</a>, Cridland, D., and M. Wild, &ldquo;<a href="http://xmpp.org/extensions/xep-0198.html">Stream Management</a>,&rdquo; XSF XEP&nbsp;0198, February&nbsp;2011.</td></tr>
8356<tr><td class="author-text" valign="top"><a name="XEP-0199">[XEP-0199]</a></td>
8357<td class="author-text"><a href="mailto:">Saint-Andre, P.</a>, &ldquo;<a href="http://xmpp.org/extensions/xep-0199.html">XMPP Ping</a>,&rdquo; XSF XEP&nbsp;0199, June&nbsp;2009.</td></tr>
8358<tr><td class="author-text" valign="top"><a name="XEP-0205">[XEP-0205]</a></td>
8359<td class="author-text"><a href="mailto:stpeter@jabber.org">Saint-Andre, P.</a>, &ldquo;<a href="http://www.xmpp.org/extensions/xep-0205.html">Best Practices to Discourage Denial of Service Attacks</a>,&rdquo; XSF XEP&nbsp;0205, January&nbsp;2009.</td></tr>
8360<tr><td class="author-text" valign="top"><a name="XEP-0206">[XEP-0206]</a></td>
8361<td class="author-text"><a href="mailto:ian.paterson@clientside.co.uk">Paterson, I.</a> and <a href="mailto:stpeter@jabber.org">P. Saint-Andre</a>, &ldquo;<a href="http://www.xmpp.org/extensions/xep-0206.html">XMPP Over BOSH</a>,&rdquo; XSF XEP&nbsp;0206, July&nbsp;2010.</td></tr>
8362<tr><td class="author-text" valign="top"><a name="XEP-0220">[XEP-0220]</a></td>
8363<td class="author-text"><a href="mailto:jer@jabber.org">Miller, J.</a>, <a href="mailto:stpeter@jabber.org">Saint-Andre, P.</a>, and <a href="mailto:">P. Hancke</a>, &ldquo;<a href="http://xmpp.org/extensions/xep-0220.html">Server Dialback</a>,&rdquo; XSF XEP&nbsp;0220, March&nbsp;2010.</td></tr>
8364<tr><td class="author-text" valign="top"><a name="XEP-0225">[XEP-0225]</a></td>
8365<td class="author-text"><a href="mailto:stpeter@jabber.org">Saint-Andre, P.</a>, &ldquo;<a href="http://xmpp.org/extensions/xep-0225.html">Component Connections</a>,&rdquo; XSF XEP&nbsp;0225, October&nbsp;2008.</td></tr>
8366<tr><td class="author-text" valign="top"><a name="XEP-0233">[XEP-0233]</a></td>
8367<td class="author-text"><a href="mailto:linuxwolf@outer-planes.net">Miller, M.</a>, <a href="mailto:stpeter@jabber.org">Saint-Andre, P.</a>, and <a href="mailto:jhildebr@cisco.com">J. Hildebrand</a>, &ldquo;<a href="http://xmpp.org/extensions/xep-0233.html">Domain-Based Service Names in XMPP SASL Negotiation</a>,&rdquo; XSF XEP&nbsp;0233, June&nbsp;2010.</td></tr>
8368<tr><td class="author-text" valign="top"><a name="XEP-0288">[XEP-0288]</a></td>
8369<td class="author-text"><a href="mailto:">Hancke, P.</a> and <a href="mailto:dave.cridland@isode.com">D. Cridland</a>, &ldquo;<a href="http://xmpp.org/extensions/xep-0288.html">Bidirectional Server-to-Server Connections</a>,&rdquo; XSF XEP&nbsp;0288, October&nbsp;2010.</td></tr>
8370<tr><td class="author-text" valign="top"><a name="XML-FRAG">[XML-FRAG]</a></td>
8371<td class="author-text">Grosso, P. and D. Veillard, &ldquo;<a href="http://www.w3.org/TR/2001/CR-xml-fragment-20010212">XML Fragment Interchange</a>,&rdquo; World Wide Web Consortium CR&nbsp;CR-xml-fragment-20010212, February&nbsp;2001 (<a href="http://www.w3.org/TR/2001/CR-xml-fragment-20010212">HTML</a>).</td></tr>
8372<tr><td class="author-text" valign="top"><a name="XML-REG">[XML-REG]</a></td>
8373<td class="author-text">Mealling, M., &ldquo;<a href="http://tools.ietf.org/html/rfc3688">The IETF XML Registry</a>,&rdquo; BCP&nbsp;81, RFC&nbsp;3688, January&nbsp;2004 (<a href="http://www.rfc-editor.org/rfc/rfc3688.txt">TXT</a>).</td></tr>
8374<tr><td class="author-text" valign="top"><a name="XML-SCHEMA">[XML-SCHEMA]</a></td>
8375<td class="author-text">Thompson, H., Maloney, M., Mendelsohn, N., and D. Beech, &ldquo;<a href="http://www.w3.org/TR/2004/REC-xmlschema-1-20041028">XML Schema Part 1: Structures Second Edition</a>,&rdquo; World Wide Web Consortium Recommendation&nbsp;REC-xmlschema-1-20041028, October&nbsp;2004 (<a href="http://www.w3.org/TR/2004/REC-xmlschema-1-20041028">HTML</a>).</td></tr>
8376<tr><td class="author-text" valign="top"><a name="XMPP-URI">[XMPP-URI]</a></td>
8377<td class="author-text">Saint-Andre, P., &ldquo;<a href="http://tools.ietf.org/html/rfc5122">Internationalized Resource Identifiers (IRIs) and Uniform Resource Identifiers (URIs) for the Extensible Messaging and Presence Protocol (XMPP)</a>,&rdquo; RFC&nbsp;5122, February&nbsp;2008 (<a href="http://www.rfc-editor.org/rfc/rfc5122.txt">TXT</a>).</td></tr>
8378</table>
8379
8380<a name="schema"></a><br /><hr />
8381<table summary="layout" cellpadding="0" cellspacing="2" class="TOCbug" align="right"><tr><td class="TOCbug"><a href="#toc">&nbsp;TOC&nbsp;</a></td></tr></table>
8382<a name="rfc.section.A"></a><h3>Appendix A.&nbsp;
8383XML Schemas</h3>
8384
8385<p>The following schemas formally define various namespaces used in this document, in conformance with <a class='info' href='#XML-SCHEMA'>[XML&#8209;SCHEMA]<span> (</span><span class='info'>Thompson, H., Maloney, M., Mendelsohn, N., and D. Beech, &ldquo;XML Schema Part 1: Structures Second Edition,&rdquo; October&nbsp;2004.</span><span>)</span></a>. Because validation of XML streams and stanzas is optional, these schemas are not normative and are provided for descriptive purposes only.
8386</p>
8387<a name="schemas-stream"></a><br /><hr />
8388<table summary="layout" cellpadding="0" cellspacing="2" class="TOCbug" align="right"><tr><td class="TOCbug"><a href="#toc">&nbsp;TOC&nbsp;</a></td></tr></table>
8389<a name="rfc.section.A.1"></a><h3>A.1.&nbsp;
8390Stream Namespace</h3>
8391<div style='display: table; width: 0; margin-left: 3em; margin-right: auto'><pre>
8392&lt;?xml version='1.0' encoding='UTF-8'?&gt;
8393
8394&lt;xs:schema
8395 xmlns:xs='http://www.w3.org/2001/XMLSchema'
8396 targetNamespace='http://etherx.jabber.org/streams'
8397 xmlns='http://etherx.jabber.org/streams'
8398 elementFormDefault='unqualified'&gt;
8399
8400 &lt;xs:import namespace='jabber:client'/&gt;
8401 &lt;xs:import namespace='jabber:server'/&gt;
8402 &lt;xs:import namespace='urn:ietf:params:xml:ns:xmpp-sasl'/&gt;
8403 &lt;xs:import namespace='urn:ietf:params:xml:ns:xmpp-streams'/&gt;
8404 &lt;xs:import namespace='urn:ietf:params:xml:ns:xmpp-tls'/&gt;
8405
8406 &lt;xs:element name='stream'&gt;
8407 &lt;xs:complexType&gt;
8408 &lt;xs:sequence xmlns:client='jabber:client'
8409 xmlns:server='jabber:server'&gt;
8410 &lt;xs:element ref='features'
8411 minOccurs='0'
8412 maxOccurs='1'/&gt;
8413 &lt;xs:any namespace='urn:ietf:params:xml:ns:xmpp-tls'
8414 minOccurs='0'
8415 maxOccurs='1'/&gt;
8416 &lt;xs:any namespace='urn:ietf:params:xml:ns:xmpp-sasl'
8417 minOccurs='0'
8418 maxOccurs='1'/&gt;
8419 &lt;xs:any namespace='##other'
8420 minOccurs='0'
8421 maxOccurs='unbounded'
8422 processContents='lax'/&gt;
8423 &lt;xs:choice minOccurs='0' maxOccurs='1'&gt;
8424 &lt;xs:choice minOccurs='0' maxOccurs='unbounded'&gt;
8425 &lt;xs:element ref='client:message'/&gt;
8426 &lt;xs:element ref='client:presence'/&gt;
8427 &lt;xs:element ref='client:iq'/&gt;
8428 &lt;/xs:choice&gt;
8429 &lt;xs:choice minOccurs='0' maxOccurs='unbounded'&gt;
8430 &lt;xs:element ref='server:message'/&gt;
8431 &lt;xs:element ref='server:presence'/&gt;
8432 &lt;xs:element ref='server:iq'/&gt;
8433 &lt;/xs:choice&gt;
8434 &lt;/xs:choice&gt;
8435 &lt;xs:element ref='error' minOccurs='0' maxOccurs='1'/&gt;
8436 &lt;/xs:sequence&gt;
8437 &lt;xs:attribute name='from' type='xs:string' use='optional'/&gt;
8438 &lt;xs:attribute name='id' type='xs:string' use='optional'/&gt;
8439 &lt;xs:attribute name='to' type='xs:string' use='optional'/&gt;
8440 &lt;xs:attribute name='version' type='xs:decimal' use='optional'/&gt;
8441 &lt;xs:attribute ref='xml:lang' use='optional'/&gt;
8442 &lt;xs:anyAttribute namespace='##other' processContents='lax'/&gt;
8443 &lt;/xs:complexType&gt;
8444 &lt;/xs:element&gt;
8445
8446 &lt;xs:element name='features'&gt;
8447 &lt;xs:complexType&gt;
8448 &lt;xs:sequence&gt;
8449 &lt;xs:any namespace='##other'
8450 minOccurs='0'
8451 maxOccurs='unbounded'
8452 processContents='lax'/&gt;
8453 &lt;/xs:sequence&gt;
8454 &lt;/xs:complexType&gt;
8455 &lt;/xs:element&gt;
8456
8457 &lt;xs:element name='error'&gt;
8458 &lt;xs:complexType&gt;
8459 &lt;xs:sequence xmlns:err='urn:ietf:params:xml:ns:xmpp-streams'&gt;
8460 &lt;xs:group ref='err:streamErrorGroup'/&gt;
8461 &lt;xs:element ref='err:text'
8462 minOccurs='0'
8463 maxOccurs='1'/&gt;
8464 &lt;xs:any namespace='##other'
8465 minOccurs='0'
8466 maxOccurs='1'
8467 processContents='lax'/&gt;
8468 &lt;/xs:sequence&gt;
8469 &lt;/xs:complexType&gt;
8470 &lt;/xs:element&gt;
8471
8472&lt;/xs:schema&gt;
8473</pre></div>
8474<a name="schemas-streamerror"></a><br /><hr />
8475<table summary="layout" cellpadding="0" cellspacing="2" class="TOCbug" align="right"><tr><td class="TOCbug"><a href="#toc">&nbsp;TOC&nbsp;</a></td></tr></table>
8476<a name="rfc.section.A.2"></a><h3>A.2.&nbsp;
8477Stream Error Namespace</h3>
8478<div style='display: table; width: 0; margin-left: 3em; margin-right: auto'><pre>
8479&lt;?xml version='1.0' encoding='UTF-8'?&gt;
8480
8481&lt;xs:schema
8482 xmlns:xs='http://www.w3.org/2001/XMLSchema'
8483 targetNamespace='urn:ietf:params:xml:ns:xmpp-streams'
8484 xmlns='urn:ietf:params:xml:ns:xmpp-streams'
8485 elementFormDefault='qualified'&gt;
8486
8487 &lt;xs:element name='bad-format' type='empty'/&gt;
8488 &lt;xs:element name='bad-namespace-prefix' type='empty'/&gt;
8489 &lt;xs:element name='conflict' type='empty'/&gt;
8490 &lt;xs:element name='connection-timeout' type='empty'/&gt;
8491 &lt;xs:element name='host-gone' type='empty'/&gt;
8492 &lt;xs:element name='host-unknown' type='empty'/&gt;
8493 &lt;xs:element name='improper-addressing' type='empty'/&gt;
8494 &lt;xs:element name='internal-server-error' type='empty'/&gt;
8495 &lt;xs:element name='invalid-from' type='empty'/&gt;
8496 &lt;xs:element name='invalid-id' type='empty'/&gt;
8497 &lt;xs:element name='invalid-namespace' type='empty'/&gt;
8498 &lt;xs:element name='invalid-xml' type='empty'/&gt;
8499 &lt;xs:element name='not-authorized' type='empty'/&gt;
8500 &lt;xs:element name='not-well-formed' type='empty'/&gt;
8501 &lt;xs:element name='policy-violation' type='empty'/&gt;
8502 &lt;xs:element name='remote-connection-failed' type='empty'/&gt;
8503 &lt;xs:element name='reset' type='empty'/&gt;
8504 &lt;xs:element name='resource-constraint' type='empty'/&gt;
8505 &lt;xs:element name='restricted-xml' type='empty'/&gt;
8506 &lt;xs:element name='see-other-host' type='xs:string'/&gt;
8507 &lt;xs:element name='system-shutdown' type='empty'/&gt;
8508 &lt;xs:element name='undefined-condition' type='empty'/&gt;
8509 &lt;xs:element name='unsupported-encoding' type='empty'/&gt;
8510 &lt;xs:element name='unsupported-stanza-type' type='empty'/&gt;
8511 &lt;xs:element name='unsupported-version' type='empty'/&gt;
8512
8513 &lt;xs:group name='streamErrorGroup'&gt;
8514 &lt;xs:choice&gt;
8515 &lt;xs:element ref='bad-format'/&gt;
8516 &lt;xs:element ref='bad-namespace-prefix'/&gt;
8517 &lt;xs:element ref='conflict'/&gt;
8518 &lt;xs:element ref='connection-timeout'/&gt;
8519 &lt;xs:element ref='host-gone'/&gt;
8520 &lt;xs:element ref='host-unknown'/&gt;
8521 &lt;xs:element ref='improper-addressing'/&gt;
8522 &lt;xs:element ref='internal-server-error'/&gt;
8523 &lt;xs:element ref='invalid-from'/&gt;
8524 &lt;xs:element ref='invalid-id'/&gt;
8525 &lt;xs:element ref='invalid-namespace'/&gt;
8526 &lt;xs:element ref='invalid-xml'/&gt;
8527 &lt;xs:element ref='not-authorized'/&gt;
8528 &lt;xs:element ref='not-well-formed'/&gt;
8529 &lt;xs:element ref='policy-violation'/&gt;
8530 &lt;xs:element ref='remote-connection-failed'/&gt;
8531 &lt;xs:element ref='reset'/&gt;
8532 &lt;xs:element ref='resource-constraint'/&gt;
8533 &lt;xs:element ref='restricted-xml'/&gt;
8534 &lt;xs:element ref='see-other-host'/&gt;
8535 &lt;xs:element ref='system-shutdown'/&gt;
8536 &lt;xs:element ref='undefined-condition'/&gt;
8537 &lt;xs:element ref='unsupported-encoding'/&gt;
8538 &lt;xs:element ref='unsupported-stanza-type'/&gt;
8539 &lt;xs:element ref='unsupported-version'/&gt;
8540 &lt;/xs:choice&gt;
8541 &lt;/xs:group&gt;
8542
8543 &lt;xs:element name='text'&gt;
8544 &lt;xs:complexType&gt;
8545 &lt;xs:simpleContent&gt;
8546 &lt;xs:extension base='xs:string'&gt;
8547 &lt;xs:attribute ref='xml:lang' use='optional'/&gt;
8548 &lt;/xs:extension&gt;
8549 &lt;/xs:simpleContent&gt;
8550 &lt;/xs:complexType&gt;
8551 &lt;/xs:element&gt;
8552
8553 &lt;xs:simpleType name='empty'&gt;
8554 &lt;xs:restriction base='xs:string'&gt;
8555 &lt;xs:enumeration value=''/&gt;
8556 &lt;/xs:restriction&gt;
8557 &lt;/xs:simpleType&gt;
8558
8559&lt;/xs:schema&gt;
8560</pre></div>
8561<a name="schemas-starttls"></a><br /><hr />
8562<table summary="layout" cellpadding="0" cellspacing="2" class="TOCbug" align="right"><tr><td class="TOCbug"><a href="#toc">&nbsp;TOC&nbsp;</a></td></tr></table>
8563<a name="rfc.section.A.3"></a><h3>A.3.&nbsp;
8564STARTTLS Namespace</h3>
8565<div style='display: table; width: 0; margin-left: 3em; margin-right: auto'><pre>
8566&lt;?xml version='1.0' encoding='UTF-8'?&gt;
8567
8568&lt;xs:schema
8569 xmlns:xs='http://www.w3.org/2001/XMLSchema'
8570 targetNamespace='urn:ietf:params:xml:ns:xmpp-tls'
8571 xmlns='urn:ietf:params:xml:ns:xmpp-tls'
8572 elementFormDefault='qualified'&gt;
8573
8574 &lt;xs:element name='starttls'&gt;
8575 &lt;xs:complexType&gt;
8576 &lt;xs:choice minOccurs='0' maxOccurs='1'&gt;
8577 &lt;xs:element name='required' type='empty'/&gt;
8578 &lt;/xs:choice&gt;
8579 &lt;/xs:complexType&gt;
8580 &lt;/xs:element&gt;
8581
8582 &lt;xs:element name='proceed' type='empty'/&gt;
8583
8584 &lt;xs:element name='failure' type='empty'/&gt;
8585
8586 &lt;xs:simpleType name='empty'&gt;
8587 &lt;xs:restriction base='xs:string'&gt;
8588 &lt;xs:enumeration value=''/&gt;
8589 &lt;/xs:restriction&gt;
8590 &lt;/xs:simpleType&gt;
8591
8592&lt;/xs:schema&gt;
8593</pre></div>
8594<a name="schemas-sasl"></a><br /><hr />
8595<table summary="layout" cellpadding="0" cellspacing="2" class="TOCbug" align="right"><tr><td class="TOCbug"><a href="#toc">&nbsp;TOC&nbsp;</a></td></tr></table>
8596<a name="rfc.section.A.4"></a><h3>A.4.&nbsp;
8597SASL Namespace</h3>
8598<div style='display: table; width: 0; margin-left: 3em; margin-right: auto'><pre>
8599&lt;?xml version='1.0' encoding='UTF-8'?&gt;
8600
8601&lt;xs:schema
8602 xmlns:xs='http://www.w3.org/2001/XMLSchema'
8603 targetNamespace='urn:ietf:params:xml:ns:xmpp-sasl'
8604 xmlns='urn:ietf:params:xml:ns:xmpp-sasl'
8605 elementFormDefault='qualified'&gt;
8606
8607 &lt;xs:element name='mechanisms'&gt;
8608 &lt;xs:complexType&gt;
8609 &lt;xs:sequence&gt;
8610 &lt;xs:element name='mechanism'
8611 minOccurs='1'
8612 maxOccurs='unbounded'
8613 type='xs:NMTOKEN'/&gt;
8614 &lt;xs:any namespace='##other'
8615 minOccurs='0'
8616 maxOccurs='unbounded'
8617 processContents='lax'/&gt;
8618 &lt;/xs:sequence&gt;
8619 &lt;/xs:complexType&gt;
8620 &lt;/xs:element&gt;
8621
8622 &lt;xs:element name='abort' type='empty'/&gt;
8623
8624 &lt;xs:element name='auth'&gt;
8625 &lt;xs:complexType&gt;
8626 &lt;xs:simpleContent&gt;
8627 &lt;xs:extension base='xs:string'&gt;
8628 &lt;xs:attribute name='mechanism'
8629 type='xs:NMTOKEN'
8630 use='required'/&gt;
8631 &lt;/xs:extension&gt;
8632 &lt;/xs:simpleContent&gt;
8633 &lt;/xs:complexType&gt;
8634 &lt;/xs:element&gt;
8635
8636 &lt;xs:element name='challenge' type='xs:string'/&gt;
8637
8638 &lt;xs:element name='response' type='xs:string'/&gt;
8639
8640 &lt;xs:element name='success' type='xs:string'/&gt;
8641
8642 &lt;xs:element name='failure'&gt;
8643 &lt;xs:complexType&gt;
8644 &lt;xs:sequence&gt;
8645 &lt;xs:choice minOccurs='0'&gt;
8646 &lt;xs:element name='aborted' type='empty'/&gt;
8647 &lt;xs:element name='account-disabled' type='empty'/&gt;
8648 &lt;xs:element name='credentials-expired' type='empty'/&gt;
8649 &lt;xs:element name='encryption-required' type='empty'/&gt;
8650 &lt;xs:element name='incorrect-encoding' type='empty'/&gt;
8651 &lt;xs:element name='invalid-authzid' type='empty'/&gt;
8652 &lt;xs:element name='invalid-mechanism' type='empty'/&gt;
8653 &lt;xs:element name='malformed-request' type='empty'/&gt;
8654 &lt;xs:element name='mechanism-too-weak' type='empty'/&gt;
8655 &lt;xs:element name='not-authorized' type='empty'/&gt;
8656 &lt;xs:element name='temporary-auth-failure' type='empty'/&gt;
8657 &lt;/xs:choice&gt;
8658 &lt;xs:element ref='text' minOccurs='0' maxOccurs='1'/&gt;
8659 &lt;/xs:sequence&gt;
8660 &lt;/xs:complexType&gt;
8661 &lt;/xs:element&gt;
8662
8663 &lt;xs:element name='text'&gt;
8664 &lt;xs:complexType&gt;
8665 &lt;xs:simpleContent&gt;
8666 &lt;xs:extension base='xs:string'&gt;
8667 &lt;xs:attribute ref='xml:lang' use='optional'/&gt;
8668 &lt;/xs:extension&gt;
8669 &lt;/xs:simpleContent&gt;
8670 &lt;/xs:complexType&gt;
8671 &lt;/xs:element&gt;
8672
8673 &lt;xs:simpleType name='empty'&gt;
8674 &lt;xs:restriction base='xs:string'&gt;
8675 &lt;xs:enumeration value=''/&gt;
8676 &lt;/xs:restriction&gt;
8677 &lt;/xs:simpleType&gt;
8678
8679&lt;/xs:schema&gt;
8680</pre></div>
8681<a name="schemas-client"></a><br /><hr />
8682<table summary="layout" cellpadding="0" cellspacing="2" class="TOCbug" align="right"><tr><td class="TOCbug"><a href="#toc">&nbsp;TOC&nbsp;</a></td></tr></table>
8683<a name="rfc.section.A.5"></a><h3>A.5.&nbsp;
8684Client Namespace</h3>
8685<div style='display: table; width: 0; margin-left: 3em; margin-right: auto'><pre>
8686&lt;?xml version='1.0' encoding='UTF-8'?&gt;
8687
8688&lt;xs:schema
8689 xmlns:xs='http://www.w3.org/2001/XMLSchema'
8690 targetNamespace='jabber:client'
8691 xmlns='jabber:client'
8692 elementFormDefault='qualified'&gt;
8693
8694 &lt;xs:import
8695 namespace='urn:ietf:params:xml:ns:xmpp-stanzas'/&gt;
8696
8697 &lt;xs:element name='message'&gt;
8698 &lt;xs:complexType&gt;
8699 &lt;xs:sequence&gt;
8700 &lt;xs:choice minOccurs='0' maxOccurs='unbounded'&gt;
8701 &lt;xs:element ref='subject'/&gt;
8702 &lt;xs:element ref='body'/&gt;
8703 &lt;xs:element ref='thread'/&gt;
8704 &lt;/xs:choice&gt;
8705 &lt;xs:any namespace='##other'
8706 minOccurs='0'
8707 maxOccurs='unbounded'
8708 processContents='lax'/&gt;
8709 &lt;xs:element ref='error'
8710 minOccurs='0'/&gt;
8711 &lt;/xs:sequence&gt;
8712 &lt;xs:attribute name='from'
8713 type='xs:string'
8714 use='optional'/&gt;
8715 &lt;xs:attribute name='id'
8716 type='xs:NMTOKEN'
8717 use='optional'/&gt;
8718 &lt;xs:attribute name='to'
8719 type='xs:string'
8720 use='optional'/&gt;
8721 &lt;xs:attribute name='type'
8722 use='optional'
8723 default='normal'&gt;
8724 &lt;xs:simpleType&gt;
8725 &lt;xs:restriction base='xs:NMTOKEN'&gt;
8726 &lt;xs:enumeration value='chat'/&gt;
8727 &lt;xs:enumeration value='error'/&gt;
8728 &lt;xs:enumeration value='groupchat'/&gt;
8729 &lt;xs:enumeration value='headline'/&gt;
8730 &lt;xs:enumeration value='normal'/&gt;
8731 &lt;/xs:restriction&gt;
8732 &lt;/xs:simpleType&gt;
8733 &lt;/xs:attribute&gt;
8734 &lt;xs:attribute ref='xml:lang' use='optional'/&gt;
8735 &lt;/xs:complexType&gt;
8736 &lt;/xs:element&gt;
8737
8738 &lt;xs:element name='body'&gt;
8739 &lt;xs:complexType&gt;
8740 &lt;xs:simpleContent&gt;
8741 &lt;xs:extension base='xs:string'&gt;
8742 &lt;xs:attribute ref='xml:lang' use='optional'/&gt;
8743 &lt;/xs:extension&gt;
8744 &lt;/xs:simpleContent&gt;
8745 &lt;/xs:complexType&gt;
8746 &lt;/xs:element&gt;
8747
8748 &lt;xs:element name='subject'&gt;
8749 &lt;xs:complexType&gt;
8750 &lt;xs:simpleContent&gt;
8751 &lt;xs:extension base='xs:string'&gt;
8752 &lt;xs:attribute ref='xml:lang' use='optional'/&gt;
8753 &lt;/xs:extension&gt;
8754 &lt;/xs:simpleContent&gt;
8755 &lt;/xs:complexType&gt;
8756 &lt;/xs:element&gt;
8757
8758 &lt;xs:element name='thread'&gt;
8759 &lt;xs:complexType&gt;
8760 &lt;xs:simpleContent&gt;
8761 &lt;xs:extension base='xs:NMTOKEN'&gt;
8762 &lt;xs:attribute name='parent'
8763 type='xs:NMTOKEN'
8764 use='optional'/&gt;
8765 &lt;/xs:extension&gt;
8766 &lt;/xs:simpleContent&gt;
8767 &lt;/xs:complexType&gt;
8768 &lt;/xs:element&gt;
8769
8770 &lt;xs:element name='presence'&gt;
8771 &lt;xs:complexType&gt;
8772 &lt;xs:sequence&gt;
8773 &lt;xs:choice minOccurs='0' maxOccurs='unbounded'&gt;
8774 &lt;xs:element ref='show'/&gt;
8775 &lt;xs:element ref='status'/&gt;
8776 &lt;xs:element ref='priority'/&gt;
8777 &lt;/xs:choice&gt;
8778 &lt;xs:any namespace='##other'
8779 minOccurs='0'
8780 maxOccurs='unbounded'
8781 processContents='lax'/&gt;
8782 &lt;xs:element ref='error'
8783 minOccurs='0'/&gt;
8784 &lt;/xs:sequence&gt;
8785 &lt;xs:attribute name='from'
8786 type='xs:string'
8787 use='optional'/&gt;
8788 &lt;xs:attribute name='id'
8789 type='xs:NMTOKEN'
8790 use='optional'/&gt;
8791 &lt;xs:attribute name='to'
8792 type='xs:string'
8793 use='optional'/&gt;
8794 &lt;xs:attribute name='type' use='optional'&gt;
8795 &lt;xs:simpleType&gt;
8796 &lt;xs:restriction base='xs:NMTOKEN'&gt;
8797 &lt;xs:enumeration value='error'/&gt;
8798 &lt;xs:enumeration value='probe'/&gt;
8799 &lt;xs:enumeration value='subscribe'/&gt;
8800 &lt;xs:enumeration value='subscribed'/&gt;
8801 &lt;xs:enumeration value='unavailable'/&gt;
8802 &lt;xs:enumeration value='unsubscribe'/&gt;
8803 &lt;xs:enumeration value='unsubscribed'/&gt;
8804 &lt;/xs:restriction&gt;
8805 &lt;/xs:simpleType&gt;
8806 &lt;/xs:attribute&gt;
8807 &lt;xs:attribute ref='xml:lang' use='optional'/&gt;
8808 &lt;/xs:complexType&gt;
8809 &lt;/xs:element&gt;
8810
8811 &lt;xs:element name='show'&gt;
8812 &lt;xs:simpleType&gt;
8813 &lt;xs:restriction base='xs:NMTOKEN'&gt;
8814 &lt;xs:enumeration value='away'/&gt;
8815 &lt;xs:enumeration value='chat'/&gt;
8816 &lt;xs:enumeration value='dnd'/&gt;
8817 &lt;xs:enumeration value='xa'/&gt;
8818 &lt;/xs:restriction&gt;
8819 &lt;/xs:simpleType&gt;
8820 &lt;/xs:element&gt;
8821
8822 &lt;xs:element name='status'&gt;
8823 &lt;xs:complexType&gt;
8824 &lt;xs:simpleContent&gt;
8825 &lt;xs:extension base='string1024'&gt;
8826 &lt;xs:attribute ref='xml:lang' use='optional'/&gt;
8827 &lt;/xs:extension&gt;
8828 &lt;/xs:simpleContent&gt;
8829 &lt;/xs:complexType&gt;
8830 &lt;/xs:element&gt;
8831
8832 &lt;xs:simpleType name='string1024'&gt;
8833 &lt;xs:restriction base='xs:string'&gt;
8834 &lt;xs:minLength value='1'/&gt;
8835 &lt;xs:maxLength value='1024'/&gt;
8836 &lt;/xs:restriction&gt;
8837 &lt;/xs:simpleType&gt;
8838
8839 &lt;xs:element name='priority' type='xs:byte'/&gt;
8840
8841 &lt;xs:element name='iq'&gt;
8842 &lt;xs:complexType&gt;
8843 &lt;xs:sequence&gt;
8844 &lt;xs:any namespace='##other'
8845 minOccurs='0'
8846 maxOccurs='1'
8847 processContents='lax'/&gt;
8848 &lt;xs:element ref='error'
8849 minOccurs='0'/&gt;
8850 &lt;/xs:sequence&gt;
8851 &lt;xs:attribute name='from'
8852 type='xs:string'
8853 use='optional'/&gt;
8854 &lt;xs:attribute name='id'
8855 type='xs:NMTOKEN'
8856 use='required'/&gt;
8857 &lt;xs:attribute name='to'
8858 type='xs:string'
8859 use='optional'/&gt;
8860 &lt;xs:attribute name='type' use='required'&gt;
8861 &lt;xs:simpleType&gt;
8862 &lt;xs:restriction base='xs:NMTOKEN'&gt;
8863 &lt;xs:enumeration value='error'/&gt;
8864 &lt;xs:enumeration value='get'/&gt;
8865 &lt;xs:enumeration value='result'/&gt;
8866 &lt;xs:enumeration value='set'/&gt;
8867 &lt;/xs:restriction&gt;
8868 &lt;/xs:simpleType&gt;
8869 &lt;/xs:attribute&gt;
8870 &lt;xs:attribute ref='xml:lang' use='optional'/&gt;
8871 &lt;/xs:complexType&gt;
8872 &lt;/xs:element&gt;
8873
8874 &lt;xs:element name='error'&gt;
8875 &lt;xs:complexType&gt;
8876 &lt;xs:sequence xmlns:err='urn:ietf:params:xml:ns:xmpp-stanzas'&gt;
8877 &lt;xs:group ref='err:stanzaErrorGroup'/&gt;
8878 &lt;xs:element ref='err:text'
8879 minOccurs='0'/&gt;
8880 &lt;/xs:sequence&gt;
8881 &lt;xs:attribute name='by'
8882 type='xs:string'
8883 use='optional'/&gt;
8884 &lt;xs:attribute name='type' use='required'&gt;
8885 &lt;xs:simpleType&gt;
8886 &lt;xs:restriction base='xs:NMTOKEN'&gt;
8887 &lt;xs:enumeration value='auth'/&gt;
8888 &lt;xs:enumeration value='cancel'/&gt;
8889 &lt;xs:enumeration value='continue'/&gt;
8890 &lt;xs:enumeration value='modify'/&gt;
8891 &lt;xs:enumeration value='wait'/&gt;
8892 &lt;/xs:restriction&gt;
8893 &lt;/xs:simpleType&gt;
8894 &lt;/xs:attribute&gt;
8895 &lt;/xs:complexType&gt;
8896 &lt;/xs:element&gt;
8897
8898&lt;/xs:schema&gt;
8899</pre></div>
8900<a name="schemas-server"></a><br /><hr />
8901<table summary="layout" cellpadding="0" cellspacing="2" class="TOCbug" align="right"><tr><td class="TOCbug"><a href="#toc">&nbsp;TOC&nbsp;</a></td></tr></table>
8902<a name="rfc.section.A.6"></a><h3>A.6.&nbsp;
8903Server Namespace</h3>
8904<div style='display: table; width: 0; margin-left: 3em; margin-right: auto'><pre>
8905&lt;?xml version='1.0' encoding='UTF-8'?&gt;
8906
8907&lt;xs:schema
8908 xmlns:xs='http://www.w3.org/2001/XMLSchema'
8909 targetNamespace='jabber:server'
8910 xmlns='jabber:server'
8911 elementFormDefault='qualified'&gt;
8912
8913 &lt;xs:import
8914 namespace='urn:ietf:params:xml:ns:xmpp-stanzas'/&gt;
8915
8916 &lt;xs:element name='message'&gt;
8917 &lt;xs:complexType&gt;
8918 &lt;xs:sequence&gt;
8919 &lt;xs:choice minOccurs='0' maxOccurs='unbounded'&gt;
8920 &lt;xs:element ref='subject'/&gt;
8921 &lt;xs:element ref='body'/&gt;
8922 &lt;xs:element ref='thread'/&gt;
8923 &lt;/xs:choice&gt;
8924 &lt;xs:any namespace='##other'
8925 minOccurs='0'
8926 maxOccurs='unbounded'
8927 processContents='lax'/&gt;
8928 &lt;xs:element ref='error'
8929 minOccurs='0'/&gt;
8930 &lt;/xs:sequence&gt;
8931 &lt;xs:attribute name='from'
8932 type='xs:string'
8933 use='required'/&gt;
8934 &lt;xs:attribute name='id'
8935 type='xs:NMTOKEN'
8936 use='optional'/&gt;
8937 &lt;xs:attribute name='to'
8938 type='xs:string'
8939 use='required'/&gt;
8940 &lt;xs:attribute name='type'
8941 use='optional'
8942 default='normal'&gt;
8943 &lt;xs:simpleType&gt;
8944 &lt;xs:restriction base='xs:NMTOKEN'&gt;
8945 &lt;xs:enumeration value='chat'/&gt;
8946 &lt;xs:enumeration value='error'/&gt;
8947 &lt;xs:enumeration value='groupchat'/&gt;
8948 &lt;xs:enumeration value='headline'/&gt;
8949 &lt;xs:enumeration value='normal'/&gt;
8950 &lt;/xs:restriction&gt;
8951 &lt;/xs:simpleType&gt;
8952 &lt;/xs:attribute&gt;
8953 &lt;xs:attribute ref='xml:lang' use='optional'/&gt;
8954 &lt;/xs:complexType&gt;
8955 &lt;/xs:element&gt;
8956
8957 &lt;xs:element name='body'&gt;
8958 &lt;xs:complexType&gt;
8959 &lt;xs:simpleContent&gt;
8960 &lt;xs:extension base='xs:string'&gt;
8961 &lt;xs:attribute ref='xml:lang' use='optional'/&gt;
8962 &lt;/xs:extension&gt;
8963 &lt;/xs:simpleContent&gt;
8964 &lt;/xs:complexType&gt;
8965 &lt;/xs:element&gt;
8966
8967 &lt;xs:element name='subject'&gt;
8968 &lt;xs:complexType&gt;
8969 &lt;xs:simpleContent&gt;
8970 &lt;xs:extension base='xs:string'&gt;
8971 &lt;xs:attribute ref='xml:lang' use='optional'/&gt;
8972 &lt;/xs:extension&gt;
8973 &lt;/xs:simpleContent&gt;
8974 &lt;/xs:complexType&gt;
8975 &lt;/xs:element&gt;
8976
8977 &lt;xs:element name='thread'&gt;
8978 &lt;xs:complexType&gt;
8979 &lt;xs:simpleContent&gt;
8980 &lt;xs:extension base='xs:NMTOKEN'&gt;
8981 &lt;xs:attribute name='parent'
8982 type='xs:NMTOKEN'
8983 use='optional'/&gt;
8984 &lt;/xs:extension&gt;
8985 &lt;/xs:simpleContent&gt;
8986 &lt;/xs:complexType&gt;
8987 &lt;/xs:element&gt;
8988
8989 &lt;xs:element name='subject'&gt;
8990 &lt;xs:complexType&gt;
8991 &lt;xs:simpleContent&gt;
8992 &lt;xs:extension base='xs:NMTOKEN'&gt;
8993 &lt;xs:attribute name='parent'
8994 type='xs:NMTOKEN'
8995 use='optional'/&gt;
8996 &lt;/xs:extension&gt;
8997 &lt;/xs:simpleContent&gt;
8998 &lt;/xs:complexType&gt;
8999 &lt;/xs:element&gt;
9000
9001 &lt;xs:element name='presence'&gt;
9002 &lt;xs:complexType&gt;
9003 &lt;xs:sequence&gt;
9004 &lt;xs:choice minOccurs='0' maxOccurs='unbounded'&gt;
9005 &lt;xs:element ref='show'/&gt;
9006 &lt;xs:element ref='status'/&gt;
9007 &lt;xs:element ref='priority'/&gt;
9008 &lt;/xs:choice&gt;
9009 &lt;xs:any namespace='##other'
9010 minOccurs='0'
9011 maxOccurs='unbounded'
9012 processContents='lax'/&gt;
9013 &lt;xs:element ref='error'
9014 minOccurs='0'/&gt;
9015 &lt;/xs:sequence&gt;
9016 &lt;xs:attribute name='from'
9017 type='xs:string'
9018 use='required'/&gt;
9019 &lt;xs:attribute name='id'
9020 type='xs:NMTOKEN'
9021 use='optional'/&gt;
9022 &lt;xs:attribute name='to'
9023 type='xs:string'
9024 use='required'/&gt;
9025 &lt;xs:attribute name='type' use='optional'&gt;
9026 &lt;xs:simpleType&gt;
9027 &lt;xs:restriction base='xs:NMTOKEN'&gt;
9028 &lt;xs:enumeration value='error'/&gt;
9029 &lt;xs:enumeration value='probe'/&gt;
9030 &lt;xs:enumeration value='subscribe'/&gt;
9031 &lt;xs:enumeration value='subscribed'/&gt;
9032 &lt;xs:enumeration value='unavailable'/&gt;
9033 &lt;xs:enumeration value='unsubscribe'/&gt;
9034 &lt;xs:enumeration value='unsubscribed'/&gt;
9035 &lt;/xs:restriction&gt;
9036 &lt;/xs:simpleType&gt;
9037 &lt;/xs:attribute&gt;
9038 &lt;xs:attribute ref='xml:lang' use='optional'/&gt;
9039 &lt;/xs:complexType&gt;
9040 &lt;/xs:element&gt;
9041
9042 &lt;xs:element name='show'&gt;
9043 &lt;xs:simpleType&gt;
9044 &lt;xs:restriction base='xs:NMTOKEN'&gt;
9045 &lt;xs:enumeration value='away'/&gt;
9046 &lt;xs:enumeration value='chat'/&gt;
9047 &lt;xs:enumeration value='dnd'/&gt;
9048 &lt;xs:enumeration value='xa'/&gt;
9049 &lt;/xs:restriction&gt;
9050 &lt;/xs:simpleType&gt;
9051 &lt;/xs:element&gt;
9052
9053 &lt;xs:element name='status'&gt;
9054 &lt;xs:complexType&gt;
9055 &lt;xs:simpleContent&gt;
9056 &lt;xs:extension base='string1024'&gt;
9057 &lt;xs:attribute ref='xml:lang' use='optional'/&gt;
9058 &lt;/xs:extension&gt;
9059 &lt;/xs:simpleContent&gt;
9060 &lt;/xs:complexType&gt;
9061 &lt;/xs:element&gt;
9062
9063 &lt;xs:simpleType name='string1024'&gt;
9064 &lt;xs:restriction base='xs:string'&gt;
9065 &lt;xs:minLength value='1'/&gt;
9066 &lt;xs:maxLength value='1024'/&gt;
9067 &lt;/xs:restriction&gt;
9068 &lt;/xs:simpleType&gt;
9069
9070 &lt;xs:element name='priority' type='xs:byte' default='0'/&gt;
9071
9072 &lt;xs:element name='iq'&gt;
9073 &lt;xs:complexType&gt;
9074 &lt;xs:sequence&gt;
9075 &lt;xs:any namespace='##other'
9076 minOccurs='0'
9077 maxOccurs='1'
9078 processContents='lax'/&gt;
9079 &lt;xs:element ref='error'
9080 minOccurs='0'/&gt;
9081 &lt;/xs:sequence&gt;
9082 &lt;xs:attribute name='from'
9083 type='xs:string'
9084 use='required'/&gt;
9085 &lt;xs:attribute name='id'
9086 type='xs:NMTOKEN'
9087 use='required'/&gt;
9088 &lt;xs:attribute name='to'
9089 type='xs:string'
9090 use='required'/&gt;
9091 &lt;xs:attribute name='type' use='required'&gt;
9092 &lt;xs:simpleType&gt;
9093 &lt;xs:restriction base='xs:NMTOKEN'&gt;
9094 &lt;xs:enumeration value='error'/&gt;
9095 &lt;xs:enumeration value='get'/&gt;
9096 &lt;xs:enumeration value='result'/&gt;
9097 &lt;xs:enumeration value='set'/&gt;
9098 &lt;/xs:restriction&gt;
9099 &lt;/xs:simpleType&gt;
9100 &lt;/xs:attribute&gt;
9101 &lt;xs:attribute ref='xml:lang' use='optional'/&gt;
9102 &lt;/xs:complexType&gt;
9103 &lt;/xs:element&gt;
9104
9105 &lt;xs:element name='error'&gt;
9106 &lt;xs:complexType&gt;
9107 &lt;xs:sequence xmlns:err='urn:ietf:params:xml:ns:xmpp-stanzas'&gt;
9108 &lt;xs:group ref='err:stanzaErrorGroup'/&gt;
9109 &lt;xs:element ref='err:text'
9110 minOccurs='0'/&gt;
9111 &lt;/xs:sequence&gt;
9112 &lt;xs:attribute name='by'
9113 type='xs:string'
9114 use='optional'/&gt;
9115 &lt;xs:attribute name='type' use='required'&gt;
9116 &lt;xs:simpleType&gt;
9117 &lt;xs:restriction base='xs:NMTOKEN'&gt;
9118 &lt;xs:enumeration value='auth'/&gt;
9119 &lt;xs:enumeration value='cancel'/&gt;
9120 &lt;xs:enumeration value='continue'/&gt;
9121 &lt;xs:enumeration value='modify'/&gt;
9122 &lt;xs:enumeration value='wait'/&gt;
9123 &lt;/xs:restriction&gt;
9124 &lt;/xs:simpleType&gt;
9125 &lt;/xs:attribute&gt;
9126 &lt;/xs:complexType&gt;
9127 &lt;/xs:element&gt;
9128
9129&lt;/xs:schema&gt;
9130</pre></div>
9131<a name="schemas-bind"></a><br /><hr />
9132<table summary="layout" cellpadding="0" cellspacing="2" class="TOCbug" align="right"><tr><td class="TOCbug"><a href="#toc">&nbsp;TOC&nbsp;</a></td></tr></table>
9133<a name="rfc.section.A.7"></a><h3>A.7.&nbsp;
9134Resource Binding Namespace</h3>
9135<div style='display: table; width: 0; margin-left: 3em; margin-right: auto'><pre>
9136&lt;?xml version='1.0' encoding='UTF-8'?&gt;
9137
9138&lt;xs:schema
9139 xmlns:xs='http://www.w3.org/2001/XMLSchema'
9140 targetNamespace='urn:ietf:params:xml:ns:xmpp-bind'
9141 xmlns='urn:ietf:params:xml:ns:xmpp-bind'
9142 elementFormDefault='qualified'&gt;
9143
9144 &lt;xs:element name='bind'&gt;
9145 &lt;xs:complexType&gt;
9146 &lt;xs:choice&gt;
9147 &lt;xs:element name='resource' type='resourceType'/&gt;
9148 &lt;xs:element name='jid' type='fullJIDType'/&gt;
9149 &lt;/xs:choice&gt;
9150 &lt;/xs:complexType&gt;
9151 &lt;/xs:element&gt;
9152
9153 &lt;xs:simpleType name='fullJIDType'&gt;
9154 &lt;xs:restriction base='xs:string'&gt;
9155 &lt;xs:minLength value='8'/&gt;
9156 &lt;xs:maxLength value='3071'/&gt;
9157 &lt;/xs:restriction&gt;
9158 &lt;/xs:simpleType&gt;
9159
9160 &lt;xs:simpleType name='resourceType'&gt;
9161 &lt;xs:restriction base='xs:string'&gt;
9162 &lt;xs:minLength value='1'/&gt;
9163 &lt;xs:maxLength value='1023'/&gt;
9164 &lt;/xs:restriction&gt;
9165 &lt;/xs:simpleType&gt;
9166
9167&lt;/xs:schema&gt;
9168</pre></div>
9169<a name="schemas-stanzaerror"></a><br /><hr />
9170<table summary="layout" cellpadding="0" cellspacing="2" class="TOCbug" align="right"><tr><td class="TOCbug"><a href="#toc">&nbsp;TOC&nbsp;</a></td></tr></table>
9171<a name="rfc.section.A.8"></a><h3>A.8.&nbsp;
9172Stanza Error Namespace</h3>
9173<div style='display: table; width: 0; margin-left: 3em; margin-right: auto'><pre>
9174&lt;?xml version='1.0' encoding='UTF-8'?&gt;
9175
9176&lt;xs:schema
9177 xmlns:xs='http://www.w3.org/2001/XMLSchema'
9178 targetNamespace='urn:ietf:params:xml:ns:xmpp-stanzas'
9179 xmlns='urn:ietf:params:xml:ns:xmpp-stanzas'
9180 elementFormDefault='qualified'&gt;
9181
9182 &lt;xs:element name='bad-request' type='empty'/&gt;
9183 &lt;xs:element name='conflict' type='empty'/&gt;
9184 &lt;xs:element name='feature-not-implemented' type='empty'/&gt;
9185 &lt;xs:element name='forbidden' type='empty'/&gt;
9186 &lt;xs:element name='gone' type='xs:string'/&gt;
9187 &lt;xs:element name='internal-server-error' type='empty'/&gt;
9188 &lt;xs:element name='item-not-found' type='empty'/&gt;
9189 &lt;xs:element name='jid-malformed' type='empty'/&gt;
9190 &lt;xs:element name='not-acceptable' type='empty'/&gt;
9191 &lt;xs:element name='not-allowed' type='empty'/&gt;
9192 &lt;xs:element name='not-authorized' type='empty'/&gt;
9193 &lt;xs:element name='policy-violation' type='empty'/&gt;
9194 &lt;xs:element name='recipient-unavailable' type='empty'/&gt;
9195 &lt;xs:element name='redirect' type='xs:string'/&gt;
9196 &lt;xs:element name='registration-required' type='empty'/&gt;
9197 &lt;xs:element name='remote-server-not-found' type='empty'/&gt;
9198 &lt;xs:element name='remote-server-timeout' type='empty'/&gt;
9199 &lt;xs:element name='resource-constraint' type='empty'/&gt;
9200 &lt;xs:element name='service-unavailable' type='empty'/&gt;
9201 &lt;xs:element name='subscription-required' type='empty'/&gt;
9202 &lt;xs:element name='undefined-condition' type='empty'/&gt;
9203 &lt;xs:element name='unexpected-request' type='empty'/&gt;
9204
9205 &lt;xs:group name='stanzaErrorGroup'&gt;
9206 &lt;xs:choice&gt;
9207 &lt;xs:element ref='bad-request'/&gt;
9208 &lt;xs:element ref='conflict'/&gt;
9209 &lt;xs:element ref='feature-not-implemented'/&gt;
9210 &lt;xs:element ref='forbidden'/&gt;
9211 &lt;xs:element ref='gone'/&gt;
9212 &lt;xs:element ref='internal-server-error'/&gt;
9213 &lt;xs:element ref='item-not-found'/&gt;
9214 &lt;xs:element ref='jid-malformed'/&gt;
9215 &lt;xs:element ref='not-acceptable'/&gt;
9216 &lt;xs:element ref='not-authorized'/&gt;
9217 &lt;xs:element ref='not-allowed'/&gt;
9218 &lt;xs:element ref='policy-violation'/&gt;
9219 &lt;xs:element ref='recipient-unavailable'/&gt;
9220 &lt;xs:element ref='redirect'/&gt;
9221 &lt;xs:element ref='registration-required'/&gt;
9222 &lt;xs:element ref='remote-server-not-found'/&gt;
9223 &lt;xs:element ref='remote-server-timeout'/&gt;
9224 &lt;xs:element ref='resource-constraint'/&gt;
9225 &lt;xs:element ref='service-unavailable'/&gt;
9226 &lt;xs:element ref='subscription-required'/&gt;
9227 &lt;xs:element ref='undefined-condition'/&gt;
9228 &lt;xs:element ref='unexpected-request'/&gt;
9229 &lt;/xs:choice&gt;
9230 &lt;/xs:group&gt;
9231
9232 &lt;xs:element name='text'&gt;
9233 &lt;xs:complexType&gt;
9234 &lt;xs:simpleContent&gt;
9235 &lt;xs:extension base='xs:string'&gt;
9236 &lt;xs:attribute ref='xml:lang' use='optional'/&gt;
9237 &lt;/xs:extension&gt;
9238 &lt;/xs:simpleContent&gt;
9239 &lt;/xs:complexType&gt;
9240 &lt;/xs:element&gt;
9241
9242 &lt;xs:simpleType name='empty'&gt;
9243 &lt;xs:restriction base='xs:string'&gt;
9244 &lt;xs:enumeration value=''/&gt;
9245 &lt;/xs:restriction&gt;
9246 &lt;/xs:simpleType&gt;
9247
9248&lt;/xs:schema&gt;
9249</pre></div>
9250<a name="contact"></a><br /><hr />
9251<table summary="layout" cellpadding="0" cellspacing="2" class="TOCbug" align="right"><tr><td class="TOCbug"><a href="#toc">&nbsp;TOC&nbsp;</a></td></tr></table>
9252<a name="rfc.section.B"></a><h3>Appendix B.&nbsp;
9253Contact Addresses</h3>
9254
9255<p>Consistent with <a class='info' href='#MAILBOXES'>[MAILBOXES]<span> (</span><span class='info'>Crocker, D., &ldquo;MAILBOX NAMES FOR COMMON SERVICES, ROLES AND FUNCTIONS,&rdquo; May&nbsp;1997.</span><span>)</span></a>, organization that offer XMPP services are encouraged to provide an Internet mailbox of "XMPP" for inquiries related to that service, where the host portion of the resulting mailto URI is the organization's domain, not the domain of the XMPP service itself (e.g., the XMPP service might be offered at im.example.com but the Internet mailbox would be &lt;xmpp@example.com&gt;).
9256</p>
9257<a name="provisioning"></a><br /><hr />
9258<table summary="layout" cellpadding="0" cellspacing="2" class="TOCbug" align="right"><tr><td class="TOCbug"><a href="#toc">&nbsp;TOC&nbsp;</a></td></tr></table>
9259<a name="rfc.section.C"></a><h3>Appendix C.&nbsp;
9260Account Provisioning</h3>
9261
9262<p>Account provisioning is out of scope for this specification.
9263 Possible methods for account provisioning include account
9264 creation by a server administrator and in-band account
9265 registration using the 'jabber:iq:register' namespace as
9266 documented in <a class='info' href='#XEP-0077'>[XEP&#8209;0077]<span> (</span><span class='info'>Saint-Andre, P., &ldquo;In-Band Registration,&rdquo; September&nbsp;2009.</span><span>)</span></a>. An XMPP server
9267 implementation or administrative function MUST ensure that any
9268 JID assigned during account provisioning (including localpart,
9269 domainpart, resourcepart, and separator characters) conforms to
9270 the canonical format for XMPP addresses defined in
9271 <a class='info' href='#XMPP-ADDR'>[XMPP&#8209;ADDR]<span> (</span><span class='info'>Saint-Andre, P., &ldquo;Extensible Messaging and Presence Protocol (XMPP): Address Format,&rdquo; March&nbsp;2011.</span><span>)</span></a>.
9272</p>
9273<a name="diffs"></a><br /><hr />
9274<table summary="layout" cellpadding="0" cellspacing="2" class="TOCbug" align="right"><tr><td class="TOCbug"><a href="#toc">&nbsp;TOC&nbsp;</a></td></tr></table>
9275<a name="rfc.section.D"></a><h3>Appendix D.&nbsp;
9276Differences from RFC 3920</h3>
9277
9278<p>Based on consensus derived from implementation and deployment experience as well as formal interoperability testing, the following substantive modifications were made from RFC 3920 (in addition to numerous changes of an editorial nature).
9279</p>
9280<p>
9281 </p>
9282<ul class="text">
9283<li>Moved specification of the XMPP address format to a separate document.
9284</li>
9285<li>Recommended or mandated use of the 'from' and 'to' attributes on stream headers.
9286</li>
9287<li>More fully specified the stream closing handshake.
9288</li>
9289<li>Specified the recommended stream reconnection algorithm.
9290</li>
9291<li>Changed the name of the &lt;xml-not-well-formed/&gt; stream error condition to &lt;not-well-formed/&gt; for compliance with the XML specification.
9292</li>
9293<li>Removed the unnecessary and unused &lt;invalid-id/&gt; stream error (see RFC 3920 for historical documentation).
9294</li>
9295<li>Specified return of the &lt;restricted-xml/&gt; stream error in response to receipt of prohibited XML features.
9296</li>
9297<li>More completely specified the format and handling of the &lt;see-other-host/&gt; stream error, including consistency with RFC 3986 and RFC 5952 with regard to IPv6 addresses (e.g., enclosing the IPv6 address in square brackets '[' and ']').
9298</li>
9299<li>Specified that the SASL SCRAM mechanism is a mandatory-to-implement technology for client-to-server streams.
9300</li>
9301<li>Specified that TLS plus the SASL PLAIN mechanism is a mandatory-to-implement technology for client-to-server streams.
9302</li>
9303<li>Specified that support for the SASL EXTERNAL mechanism is required for servers but only recommended for clients (since end-user X.509 certificates are difficult to obtain and not yet widely deployed).
9304</li>
9305<li>Removed the hard two-connection rule for server-to-server streams.
9306</li>
9307<li>More clearly specified the certificate profile for both public key certificates and issuer certificates.
9308</li>
9309<li>Added the &lt;reset/&gt; stream error (<a class='info' href='#streams-error-conditions-reset'>Section&nbsp;4.9.3.16<span> (</span><span class='info'>reset</span><span>)</span></a>) condition to handle expired/revoked certificates or the addition of security-critical features to an existing stream.
9310</li>
9311<li>Added the &lt;account-disabled/&gt;, &lt;credentials-expired/&gt;, &lt;encryption-required/&gt;, and &lt;malformed-request/&gt; SASL error conditions to handle error flows mistakenly left out of RFC 3920 or discussed in RFC 4422 but not in RFC 2222.
9312</li>
9313<li>Removed the unused &lt;payment-required/&gt; stanza error.
9314</li>
9315<li>Removed the unnecessary requirement for escaping of characters that map to certain predefined entities, since they do not need to be escaped in XML.
9316</li>
9317<li>Clarified the process of DNS SRV lookups and fallbacks.
9318</li>
9319<li>Clarified the handling of SASL security layers.
9320</li>
9321<li>Clarified that a SASL simple user name is the localpart, not the bare JID.
9322</li>
9323<li>Clarified the stream negotiation process and associated flow chart.
9324</li>
9325<li>Clarified the handling of stream features.
9326</li>
9327<li>Added a 'by' attribute to the &lt;error/&gt; element for stanza errors so that the entity that has detected the error can include its JID for diagnostic or tracking purposes.
9328</li>
9329<li>Clarified the handling of data that violates the well-formedness definitions for XML 1.0 and XML namespaces.
9330</li>
9331<li>Specified the security considerations in more detail, especially with regard to presence leaks and denial-of-service attacks.
9332</li>
9333<li>Moved documentation of the Server Dialback protocol from this specification to a separate specification maintained by the XMPP Standards Foundation.
9334</li>
9335</ul><p>
9336
9337</p>
9338<a name="intro-ack"></a><br /><hr />
9339<table summary="layout" cellpadding="0" cellspacing="2" class="TOCbug" align="right"><tr><td class="TOCbug"><a href="#toc">&nbsp;TOC&nbsp;</a></td></tr></table>
9340<a name="rfc.section.E"></a><h3>Appendix E.&nbsp;
9341Acknowledgements</h3>
9342
9343<p>This document is an update to, and derived from, RFC 3920. This document would have been impossible without the work of the contributors and commenters acknowledged there.
9344</p>
9345<p>Hundreds of people have provided implementation feedback, bug reports, requests for clarification, and suggestions for improvement since publication of RFC 3920. Although the document editor has endeavored to address all such feedback, he is solely responsible for any remaining errors and ambiguities.
9346</p>
9347<p>Special thanks are due to Kevin Smith, Matthew Wild, Dave Cridland, Philipp Hancke, Waqas Hussain, Florian Zeitz, Ben Campbell, Jehan Pages, Paul Aurich, Justin Karneges, Kurt Zeilenga, Simon Josefsson, Ralph Meijer, Curtis King, and others for their comments during Working Group Last Call.
9348</p>
9349<p>Thanks also to Yaron Sheffer and Elwyn Davies for their reviews on behalf of the Security Directorate and the General Area Review Team, respectively.
9350</p>
9351<p>The Working Group chairs were Ben Campbell and Joe Hildebrand. The responsible Area Director was Gonzalo Camarillo.
9352</p>
9353<a name="rfc.authors"></a><br /><hr />
9354<table summary="layout" cellpadding="0" cellspacing="2" class="TOCbug" align="right"><tr><td class="TOCbug"><a href="#toc">&nbsp;TOC&nbsp;</a></td></tr></table>
9355<h3>Author's Address</h3>
9356<table width="99%" border="0" cellpadding="0" cellspacing="0">
9357<tr><td class="author-text">&nbsp;</td>
9358<td class="author-text">Peter Saint-Andre</td></tr>
9359<tr><td class="author-text">&nbsp;</td>
9360<td class="author-text">Cisco</td></tr>
9361<tr><td class="author-text">&nbsp;</td>
9362<td class="author-text">1899 Wyknoop Street, Suite 600</td></tr>
9363<tr><td class="author-text">&nbsp;</td>
9364<td class="author-text">Denver, CO 80202</td></tr>
9365<tr><td class="author-text">&nbsp;</td>
9366<td class="author-text">USA</td></tr>
9367<tr><td class="author" align="right">Phone:&nbsp;</td>
9368<td class="author-text">+1-303-308-3282</td></tr>
9369<tr><td class="author" align="right">EMail:&nbsp;</td>
9370<td class="author-text"><a href="mailto:psaintan@cisco.com">psaintan@cisco.com</a></td></tr>
9371</table>
9372</body></html>
diff --git a/doc/rfc6121.html b/doc/rfc6121.html
new file mode 100644
index 00000000..bd00706c
--- /dev/null
+++ b/doc/rfc6121.html
@@ -0,0 +1,4738 @@
1<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
2<html lang="en"><head><title>Extensible Messaging and Presence Protocol
3 (XMPP): Instant&nbsp;Messaging&nbsp;and&nbsp;Presence</title>
4<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
5<meta name="description" content="Extensible Messaging and Presence Protocol
6 (XMPP): Instant&nbsp;Messaging&nbsp;and&nbsp;Presence">
7<meta name="keywords" content="XMPP, Extensible Messaging and Presence Protocol, Jabber, IM, Instant Messaging, Presence, XML, Extensible Markup Language">
8<meta name="generator" content="xml2rfc v1.36 (http://xml.resource.org/)">
9<style type='text/css'><!--
10 body {
11 font-family: verdana, charcoal, helvetica, arial, sans-serif;
12 font-size: small; color: #000; background-color: #FFF;
13 margin: 2em;
14 }
15 h1, h2, h3, h4, h5, h6 {
16 font-family: helvetica, monaco, "MS Sans Serif", arial, sans-serif;
17 font-weight: bold; font-style: normal;
18 }
19 h1 { color: #900; background-color: transparent; text-align: right; }
20 h3 { color: #333; background-color: transparent; }
21
22 td.RFCbug {
23 font-size: x-small; text-decoration: none;
24 width: 30px; height: 30px; padding-top: 2px;
25 text-align: justify; vertical-align: middle;
26 background-color: #000;
27 }
28 td.RFCbug span.RFC {
29 font-family: monaco, charcoal, geneva, "MS Sans Serif", helvetica, verdana, sans-serif;
30 font-weight: bold; color: #666;
31 }
32 td.RFCbug span.hotText {
33 font-family: charcoal, monaco, geneva, "MS Sans Serif", helvetica, verdana, sans-serif;
34 font-weight: normal; text-align: center; color: #FFF;
35 }
36
37 table.TOCbug { width: 30px; height: 15px; }
38 td.TOCbug {
39 text-align: center; width: 30px; height: 15px;
40 color: #FFF; background-color: #900;
41 }
42 td.TOCbug a {
43 font-family: monaco, charcoal, geneva, "MS Sans Serif", helvetica, sans-serif;
44 font-weight: bold; font-size: x-small; text-decoration: none;
45 color: #FFF; background-color: transparent;
46 }
47
48 td.header {
49 font-family: arial, helvetica, sans-serif; font-size: x-small;
50 vertical-align: top; width: 33%;
51 color: #FFF; background-color: #666;
52 }
53 td.author { font-weight: bold; font-size: x-small; margin-left: 4em; }
54 td.author-text { font-size: x-small; }
55
56 /* info code from SantaKlauss at http://www.madaboutstyle.com/tooltip2.html */
57 a.info {
58 /* This is the key. */
59 position: relative;
60 z-index: 24;
61 text-decoration: none;
62 }
63 a.info:hover {
64 z-index: 25;
65 color: #FFF; background-color: #900;
66 }
67 a.info span { display: none; }
68 a.info:hover span.info {
69 /* The span will display just on :hover state. */
70 display: block;
71 position: absolute;
72 font-size: smaller;
73 top: 2em; left: -5em; width: 15em;
74 padding: 2px; border: 1px solid #333;
75 color: #900; background-color: #EEE;
76 text-align: left;
77 }
78
79 a { font-weight: bold; }
80 a:link { color: #900; background-color: transparent; }
81 a:visited { color: #633; background-color: transparent; }
82 a:active { color: #633; background-color: transparent; }
83
84 p { margin-left: 2em; margin-right: 2em; }
85 p.copyright { font-size: x-small; }
86 p.toc { font-size: small; font-weight: bold; margin-left: 3em; }
87 table.toc { margin: 0 0 0 3em; padding: 0; border: 0; vertical-align: text-top; }
88 td.toc { font-size: small; font-weight: bold; vertical-align: text-top; }
89
90 ol.text { margin-left: 2em; margin-right: 2em; }
91 ul.text { margin-left: 2em; margin-right: 2em; }
92 li { margin-left: 3em; }
93
94 /* RFC-2629 <spanx>s and <artwork>s. */
95 em { font-style: italic; }
96 strong { font-weight: bold; }
97 dfn { font-weight: bold; font-style: normal; }
98 cite { font-weight: normal; font-style: normal; }
99 tt { color: #036; }
100 tt, pre, pre dfn, pre em, pre cite, pre span {
101 font-family: "Courier New", Courier, monospace; font-size: small;
102 }
103 pre {
104 text-align: left; padding: 4px;
105 color: #000; background-color: #CCC;
106 }
107 pre dfn { color: #900; }
108 pre em { color: #66F; background-color: #FFC; font-weight: normal; }
109 pre .key { color: #33C; font-weight: bold; }
110 pre .id { color: #900; }
111 pre .str { color: #000; background-color: #CFF; }
112 pre .val { color: #066; }
113 pre .rep { color: #909; }
114 pre .oth { color: #000; background-color: #FCF; }
115 pre .err { background-color: #FCC; }
116
117 /* RFC-2629 <texttable>s. */
118 table.all, table.full, table.headers, table.none {
119 font-size: small; text-align: center; border-width: 2px;
120 vertical-align: top; border-collapse: collapse;
121 }
122 table.all, table.full { border-style: solid; border-color: black; }
123 table.headers, table.none { border-style: none; }
124 th {
125 font-weight: bold; border-color: black;
126 border-width: 2px 2px 3px 2px;
127 }
128 table.all th, table.full th { border-style: solid; }
129 table.headers th { border-style: none none solid none; }
130 table.none th { border-style: none; }
131 table.all td {
132 border-style: solid; border-color: #333;
133 border-width: 1px 2px;
134 }
135 table.full td, table.headers td, table.none td { border-style: none; }
136
137 hr { height: 1px; }
138 hr.insert {
139 width: 80%; border-style: none; border-width: 0;
140 color: #CCC; background-color: #CCC;
141 }
142--></style>
143</head>
144<body>
145
146<table border="0" cellpadding="0" cellspacing="2" width="30" align="right">
147 <tr>
148 <td class="RFCbug">
149 <span class="RFC">&nbsp;RFC&nbsp;</span><br /><span class="hotText">&nbsp;6121&nbsp;</span>
150 </td>
151 </tr>
152 <tr><td class="TOCbug"><a href="#toc">&nbsp;TOC&nbsp;</a><br /></td></tr>
153</table>
154<table summary="layout" width="66%" border="0" cellpadding="0" cellspacing="0"><tr><td><table summary="layout" width="100%" border="0" cellpadding="2" cellspacing="1">
155<tr><td class="header">Internet Engineering Task Force (IETF)</td><td class="header">P. Saint-Andre</td></tr>
156<tr><td class="header">Request for Comments: 6121</td><td class="header">Cisco</td></tr>
157<tr><td class="header">Obsoletes: <a href='http://tools.ietf.org/html/rfc3921'>3921</a></td><td class="header">March 2011</td></tr>
158<tr><td class="header">Category: Standards Track</td><td class="header">&nbsp;</td></tr>
159<tr><td class="header">ISSN: 2070-1721</td><td class="header">&nbsp;</td></tr>
160</table></td></tr></table>
161<h1><br />Extensible Messaging and Presence Protocol
162 (XMPP): Instant&nbsp;Messaging&nbsp;and&nbsp;Presence</h1>
163
164<h3>Abstract</h3>
165
166<p>This document defines extensions to core features of the Extensible Messaging and Presence Protocol (XMPP) that provide basic instant messaging (IM) and presence functionality in conformance with the requirements in RFC 2779. This document obsoletes RFC 3921.
167</p>
168<h3>Status of This Memo</h3>
169<p>
170This is an Internet Standards Track document.</p>
171<p>
172This document is a product of the Internet Engineering Task Force (IETF). It represents the consensus of the IETF community. It has received public review and has been approved for publication by the Internet Engineering Steering Group (IESG). Further information on Internet Standards is available in Section 2 of RFC 5741.</p>
173<p>
174Information about the current status of this document, any errata, and how to provide feedback on it may be obtained at http://www.rfc-editor.org/info/rfc6121.</p>
175
176<h3>Copyright Notice</h3>
177<p>
178Copyright (c) 2011 IETF Trust and the persons identified as the
179document authors. All rights reserved.</p>
180<p>
181This document is subject to BCP 78 and the IETF Trust's Legal
182Provisions Relating to IETF Documents
183(http://trustee.ietf.org/license-info) in effect on the date of
184publication of this document. Please review these documents
185carefully, as they describe your rights and restrictions with respect
186to this document. Code Components extracted from this document must
187include Simplified BSD License text as described in Section 4.e of
188the Trust Legal Provisions and are provided without warranty as
189described in the Simplified BSD License.</p>
190<a name="toc"></a><hr />
191
192<table border="0" cellpadding="0" cellspacing="2" width="30" align="right">
193 <tr>
194 <td class="RFCbug">
195 <span class="RFC">&nbsp;RFC&nbsp;</span><br /><span class="hotText">&nbsp;6121&nbsp;</span>
196 </td>
197 </tr>
198 <tr><td class="TOCbug"><a href="#toc">&nbsp;TOC&nbsp;</a><br /></td></tr>
199</table>
200<h3>Table of Contents</h3>
201<p class="toc">
202<a href="#intro">1.</a>&nbsp;
203Introduction<br />
204&nbsp;&nbsp;&nbsp;&nbsp;<a href="#intro-overview">1.1.</a>&nbsp;
205Overview<br />
206&nbsp;&nbsp;&nbsp;&nbsp;<a href="#intro-history">1.2.</a>&nbsp;
207History<br />
208&nbsp;&nbsp;&nbsp;&nbsp;<a href="#intro-requirements">1.3.</a>&nbsp;
209Requirements<br />
210&nbsp;&nbsp;&nbsp;&nbsp;<a href="#intro-summary">1.4.</a>&nbsp;
211Functional Summary<br />
212&nbsp;&nbsp;&nbsp;&nbsp;<a href="#intro-terms">1.5.</a>&nbsp;
213Terminology<br />
214<a href="#roster">2.</a>&nbsp;
215Managing the Roster<br />
216&nbsp;&nbsp;&nbsp;&nbsp;<a href="#roster-syntax">2.1.</a>&nbsp;
217Syntax and Semantics<br />
218&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<a href="#roster-syntax-ver">2.1.1.</a>&nbsp;
219Ver Attribute<br />
220&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<a href="#roster-syntax-items">2.1.2.</a>&nbsp;
221Roster Items<br />
222&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<a href="#roster-syntax-items-approved">2.1.2.1.</a>&nbsp;
223Approved Attribute<br />
224&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<a href="#roster-syntax-items-ask">2.1.2.2.</a>&nbsp;
225Ask Attribute<br />
226&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<a href="#roster-syntax-items-jid">2.1.2.3.</a>&nbsp;
227JID Attribute<br />
228&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<a href="#roster-syntax-items-name">2.1.2.4.</a>&nbsp;
229Name Attribute<br />
230&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<a href="#roster-syntax-items-subscription">2.1.2.5.</a>&nbsp;
231Subscription Attribute<br />
232&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<a href="#roster-syntax-items-group">2.1.2.6.</a>&nbsp;
233Group Element<br />
234&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<a href="#roster-syntax-actions-get">2.1.3.</a>&nbsp;
235Roster Get<br />
236&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<a href="#roster-syntax-actions-result">2.1.4.</a>&nbsp;
237Roster Result<br />
238&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<a href="#roster-syntax-actions-set">2.1.5.</a>&nbsp;
239Roster Set<br />
240&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<a href="#roster-syntax-actions-push">2.1.6.</a>&nbsp;
241Roster Push<br />
242&nbsp;&nbsp;&nbsp;&nbsp;<a href="#roster-login">2.2.</a>&nbsp;
243Retrieving the Roster on Login<br />
244&nbsp;&nbsp;&nbsp;&nbsp;<a href="#roster-add">2.3.</a>&nbsp;
245Adding a Roster Item<br />
246&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<a href="#roster-add-request">2.3.1.</a>&nbsp;
247Request<br />
248&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<a href="#roster-add-success">2.3.2.</a>&nbsp;
249Success Case<br />
250&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<a href="#roster-add-errors">2.3.3.</a>&nbsp;
251Error Cases<br />
252&nbsp;&nbsp;&nbsp;&nbsp;<a href="#roster-update">2.4.</a>&nbsp;
253Updating a Roster Item<br />
254&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<a href="#roster-update-request">2.4.1.</a>&nbsp;
255Request<br />
256&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<a href="#roster-update-success">2.4.2.</a>&nbsp;
257Success Case<br />
258&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<a href="#roster-update-error">2.4.3.</a>&nbsp;
259Error Cases<br />
260&nbsp;&nbsp;&nbsp;&nbsp;<a href="#roster-delete">2.5.</a>&nbsp;
261Deleting a Roster Item<br />
262&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<a href="#roster-delete-request">2.5.1.</a>&nbsp;
263Request<br />
264&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<a href="#roster-delete-success">2.5.2.</a>&nbsp;
265Success Case<br />
266&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<a href="#roster-delete-error">2.5.3.</a>&nbsp;
267Error Cases<br />
268&nbsp;&nbsp;&nbsp;&nbsp;<a href="#roster-versioning">2.6.</a>&nbsp;
269Roster Versioning<br />
270&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<a href="#roster-versioning-feature">2.6.1.</a>&nbsp;
271Stream Feature<br />
272&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<a href="#roster-versioning-request">2.6.2.</a>&nbsp;
273Request<br />
274&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<a href="#roster-versioning-success">2.6.3.</a>&nbsp;
275Success Case<br />
276<a href="#sub">3.</a>&nbsp;
277Managing Presence Subscriptions<br />
278&nbsp;&nbsp;&nbsp;&nbsp;<a href="#sub-request">3.1.</a>&nbsp;
279Requesting a Subscription<br />
280&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<a href="#sub-request-gen">3.1.1.</a>&nbsp;
281Client Generation of Outbound Subscription Request<br />
282&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<a href="#sub-request-outbound">3.1.2.</a>&nbsp;
283Server Processing of Outbound Subscription Request<br />
284&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<a href="#sub-request-inbound">3.1.3.</a>&nbsp;
285Server Processing of Inbound Subscription Request<br />
286&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<a href="#sub-request-handle">3.1.4.</a>&nbsp;
287Client Processing of Inbound Subscription Request<br />
288&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<a href="#sub-request-approvalout">3.1.5.</a>&nbsp;
289Server Processing of Outbound Subscription Approval<br />
290&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<a href="#sub-request-approvalin">3.1.6.</a>&nbsp;
291Server Processing of Inbound Subscription Approval<br />
292&nbsp;&nbsp;&nbsp;&nbsp;<a href="#sub-cancel">3.2.</a>&nbsp;
293Canceling a Subscription<br />
294&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<a href="#sub-cancel-gen">3.2.1.</a>&nbsp;
295Client Generation of Subscription Cancellation<br />
296&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<a href="#sub-cancel-outbound">3.2.2.</a>&nbsp;
297Server Processing of Outbound Subscription Cancellation<br />
298&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<a href="#sub-cancel-inbound">3.2.3.</a>&nbsp;
299Server Processing of Inbound Subscription Cancellation<br />
300&nbsp;&nbsp;&nbsp;&nbsp;<a href="#sub-unsub">3.3.</a>&nbsp;
301Unsubscribing<br />
302&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<a href="#sub-unsub-gen">3.3.1.</a>&nbsp;
303Client Generation of Unsubscribe<br />
304&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<a href="#sub-unsub-outbound">3.3.2.</a>&nbsp;
305Server Processing of Outbound Unsubscribe<br />
306&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<a href="#sub-unsub-inbound">3.3.3.</a>&nbsp;
307Server Processing of Inbound Unsubscribe<br />
308&nbsp;&nbsp;&nbsp;&nbsp;<a href="#sub-preapproval">3.4.</a>&nbsp;
309Pre-Approving a Subscription Request<br />
310&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<a href="#sub-preapproval-gen">3.4.1.</a>&nbsp;
311Client Generation of Subscription Pre-Approval<br />
312&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<a href="#sub-preapproval-proc">3.4.2.</a>&nbsp;
313Server Processing of Subscription Pre-Approval<br />
314<a href="#presence">4.</a>&nbsp;
315Exchanging Presence Information<br />
316&nbsp;&nbsp;&nbsp;&nbsp;<a href="#presence-fundamentals">4.1.</a>&nbsp;
317Presence Fundamentals<br />
318&nbsp;&nbsp;&nbsp;&nbsp;<a href="#presence-initial">4.2.</a>&nbsp;
319Initial Presence<br />
320&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<a href="#presence-initial-gen">4.2.1.</a>&nbsp;
321Client Generation of Initial Presence<br />
322&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<a href="#presence-initial-outbound">4.2.2.</a>&nbsp;
323Server Processing of Outbound Initial Presence<br />
324&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<a href="#presence-initial-inbound">4.2.3.</a>&nbsp;
325Server Processing of Inbound Initial Presence<br />
326&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<a href="#presence-initial-client">4.2.4.</a>&nbsp;
327Client Processing of Initial Presence<br />
328&nbsp;&nbsp;&nbsp;&nbsp;<a href="#presence-probe">4.3.</a>&nbsp;
329Presence Probes<br />
330&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<a href="#presence-probe-outbound">4.3.1.</a>&nbsp;
331Server Generation of Outbound Presence Probe<br />
332&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<a href="#presence-probe-inbound">4.3.2.</a>&nbsp;
333Server Processing of Inbound Presence Probe<br />
334&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<a href="#presence-probe-inbound-id">4.3.2.1.</a>&nbsp;
335Handling of the 'id' Attribute<br />
336&nbsp;&nbsp;&nbsp;&nbsp;<a href="#presence-broadcast">4.4.</a>&nbsp;
337Subsequent Presence Broadcast<br />
338&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<a href="#presence-broadcast-gen">4.4.1.</a>&nbsp;
339Client Generation of Subsequent Presence Broadcast<br />
340&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<a href="#presence-broadcast-outbound">4.4.2.</a>&nbsp;
341Server Processing of Subsequent Outbound Presence<br />
342&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<a href="#presence-broadcast-inbound">4.4.3.</a>&nbsp;
343Server Processing of Subsequent Inbound Presence<br />
344&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<a href="#presence-broadcast-client">4.4.4.</a>&nbsp;
345Client Processing of Subsequent Presence<br />
346&nbsp;&nbsp;&nbsp;&nbsp;<a href="#presence-unavailable">4.5.</a>&nbsp;
347Unavailable Presence<br />
348&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<a href="#presence-unavailable-gen">4.5.1.</a>&nbsp;
349Client Generation of Unavailable Presence<br />
350&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<a href="#presence-unavailable-outbound">4.5.2.</a>&nbsp;
351Server Processing of Outbound Unavailable Presence<br />
352&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<a href="#presence-unavailable-inbound">4.5.3.</a>&nbsp;
353Server Processing of Inbound Unavailable Presence<br />
354&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<a href="#presence-unavailable-client">4.5.4.</a>&nbsp;
355Client Processing of Unavailable Presence<br />
356&nbsp;&nbsp;&nbsp;&nbsp;<a href="#presence-directed">4.6.</a>&nbsp;
357Directed Presence<br />
358&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<a href="#presence-directed-considerations">4.6.1.</a>&nbsp;
359General Considerations<br />
360&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<a href="#presence-directed-gen">4.6.2.</a>&nbsp;
361Client Generation of Directed Presence<br />
362&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<a href="#presence-directed-outbound">4.6.3.</a>&nbsp;
363Server Processing of Outbound Directed Presence<br />
364&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<a href="#presence-directed-inbound">4.6.4.</a>&nbsp;
365Server Processing of Inbound Directed Presence<br />
366&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<a href="#presence-directed-client">4.6.5.</a>&nbsp;
367Client Processing of Inbound Directed Presence<br />
368&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<a href="#presence-directed-probe">4.6.6.</a>&nbsp;
369Server Processing of Presence Probes<br />
370&nbsp;&nbsp;&nbsp;&nbsp;<a href="#presence-syntax">4.7.</a>&nbsp;
371Presence Syntax<br />
372&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<a href="#presence-syntax-type">4.7.1.</a>&nbsp;
373Type Attribute<br />
374&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<a href="#presence-syntax-children">4.7.2.</a>&nbsp;
375Child Elements<br />
376&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<a href="#presence-syntax-children-show">4.7.2.1.</a>&nbsp;
377Show Element<br />
378&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<a href="#presence-syntax-children-status">4.7.2.2.</a>&nbsp;
379Status Element<br />
380&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<a href="#presence-syntax-children-priority">4.7.2.3.</a>&nbsp;
381Priority Element<br />
382&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<a href="#presence-extended">4.7.3.</a>&nbsp;
383Extended Content<br />
384<a href="#message">5.</a>&nbsp;
385Exchanging Messages<br />
386&nbsp;&nbsp;&nbsp;&nbsp;<a href="#message-chat">5.1.</a>&nbsp;
387One-to-One Chat Sessions<br />
388&nbsp;&nbsp;&nbsp;&nbsp;<a href="#message-syntax">5.2.</a>&nbsp;
389Message Syntax<br />
390&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<a href="#message-syntax-to">5.2.1.</a>&nbsp;
391To Attribute<br />
392&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<a href="#message-syntax-type">5.2.2.</a>&nbsp;
393Type Attribute<br />
394&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<a href="#message-syntax-body">5.2.3.</a>&nbsp;
395Body Element<br />
396&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<a href="#message-syntax-subject">5.2.4.</a>&nbsp;
397Subject Element<br />
398&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<a href="#message-syntax-thread">5.2.5.</a>&nbsp;
399Thread Element<br />
400&nbsp;&nbsp;&nbsp;&nbsp;<a href="#message-syntax-extended">5.3.</a>&nbsp;
401Extended Content<br />
402<a href="#iq">6.</a>&nbsp;
403Exchanging IQ Stanzas<br />
404<a href="#session">7.</a>&nbsp;
405A Sample Session<br />
406<a href="#rules">8.</a>&nbsp;
407Server Rules for Processing XML Stanzas<br />
408&nbsp;&nbsp;&nbsp;&nbsp;<a href="#rules-general">8.1.</a>&nbsp;
409General Considerations<br />
410&nbsp;&nbsp;&nbsp;&nbsp;<a href="#rules-noto">8.2.</a>&nbsp;
411No 'to' Address<br />
412&nbsp;&nbsp;&nbsp;&nbsp;<a href="#rules-remote">8.3.</a>&nbsp;
413Remote Domain<br />
414&nbsp;&nbsp;&nbsp;&nbsp;<a href="#rules-local">8.4.</a>&nbsp;
415Local Domain<br />
416&nbsp;&nbsp;&nbsp;&nbsp;<a href="#rules-localpart">8.5.</a>&nbsp;
417Local User<br />
418&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<a href="#rules-localpart-nosuchuser">8.5.1.</a>&nbsp;
419No Such User<br />
420&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<a href="#rules-localpart-barejid">8.5.2.</a>&nbsp;
421localpart@domainpart<br />
422&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<a href="#rules-localpart-barejid-resource">8.5.2.1.</a>&nbsp;
423Available or Connected Resources<br />
424&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<a href="#rules-localpart-barejid-noresource">8.5.2.2.</a>&nbsp;
425No Available or Connected Resources<br />
426&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<a href="#rules-localpart-fulljid">8.5.3.</a>&nbsp;
427localpart@domainpart/resourcepart<br />
428&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<a href="#rules-localpart-fulljid-match">8.5.3.1.</a>&nbsp;
429Resource Matches<br />
430&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<a href="#rules-localpart-fulljid-nomatch">8.5.3.2.</a>&nbsp;
431No Resource Matches<br />
432&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<a href="#rules-local-message">8.5.4.</a>&nbsp;
433Summary of Message Delivery Rules<br />
434<a href="#uri">9.</a>&nbsp;
435Handling of URIs<br />
436<a href="#i18n">10.</a>&nbsp;
437Internationalization Considerations<br />
438<a href="#security">11.</a>&nbsp;
439Security Considerations<br />
440<a href="#conformance">12.</a>&nbsp;
441Conformance Requirements<br />
442<a href="#rfc.references1">13.</a>&nbsp;
443References<br />
444&nbsp;&nbsp;&nbsp;&nbsp;<a href="#rfc.references1">13.1.</a>&nbsp;
445Normative References<br />
446&nbsp;&nbsp;&nbsp;&nbsp;<a href="#rfc.references2">13.2.</a>&nbsp;
447Informative References<br />
448<a href="#substates">Appendix&nbsp;A.</a>&nbsp;
449Subscription States<br />
450&nbsp;&nbsp;&nbsp;&nbsp;<a href="#substates-defined">A.1.</a>&nbsp;
451Defined States<br />
452&nbsp;&nbsp;&nbsp;&nbsp;<a href="#substates-out">A.2.</a>&nbsp;
453Server Processing of Outbound Presence Subscription Stanzas<br />
454&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<a href="#substates-out-subscribe">A.2.1.</a>&nbsp;
455Subscribe<br />
456&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<a href="#substates-out-unsubscribe">A.2.2.</a>&nbsp;
457Unsubscribe<br />
458&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<a href="#substates-out-subscribed">A.2.3.</a>&nbsp;
459Subscribed<br />
460&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<a href="#substates-out-unsubscribed">A.2.4.</a>&nbsp;
461Unsubscribed<br />
462&nbsp;&nbsp;&nbsp;&nbsp;<a href="#substates-in">A.3.</a>&nbsp;
463Server Processing of Inbound Presence Subscription Stanzas<br />
464&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<a href="#substates-in-subscribe">A.3.1.</a>&nbsp;
465Subscribe<br />
466&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<a href="#substates-in-unsubscribe">A.3.2.</a>&nbsp;
467Unsubscribe<br />
468&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<a href="#substates-in-subscribed">A.3.3.</a>&nbsp;
469Subscribed<br />
470&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<a href="#substates-in-unsubscribed">A.3.4.</a>&nbsp;
471Unsubscribed<br />
472<a href="#blocking">Appendix&nbsp;B.</a>&nbsp;
473Blocking Communication<br />
474<a href="#vcard">Appendix&nbsp;C.</a>&nbsp;
475vCards<br />
476<a href="#schema">Appendix&nbsp;D.</a>&nbsp;
477XML Schema for jabber:iq:roster<br />
478<a href="#diffs">Appendix&nbsp;E.</a>&nbsp;
479Differences From RFC 3921<br />
480<a href="#acks">Appendix&nbsp;F.</a>&nbsp;
481Acknowledgements<br />
482</p>
483<br clear="all" />
484
485<a name="intro"></a><br /><hr />
486<table summary="layout" cellpadding="0" cellspacing="2" class="TOCbug" align="right"><tr><td class="TOCbug"><a href="#toc">&nbsp;TOC&nbsp;</a></td></tr></table>
487<a name="rfc.section.1"></a><h3>1.&nbsp;
488Introduction</h3>
489
490<a name="intro-overview"></a><br /><hr />
491<table summary="layout" cellpadding="0" cellspacing="2" class="TOCbug" align="right"><tr><td class="TOCbug"><a href="#toc">&nbsp;TOC&nbsp;</a></td></tr></table>
492<a name="rfc.section.1.1"></a><h3>1.1.&nbsp;
493Overview</h3>
494
495<p>The Extensible Messaging and Presence Protocol (XMPP) is an application profile of the Extensible Markup Language <a class='info' href='#XML'>[XML]<span> (</span><span class='info'>Maler, E., Yergeau, F., Sperberg-McQueen, C., Paoli, J., and T. Bray, &ldquo;Extensible Markup Language (XML) 1.0 (Fifth Edition),&rdquo; November&nbsp;2008.</span><span>)</span></a> that enables the near-real-time exchange of structured yet extensible data between any two or more network entities. The core features of XMPP defined in <a class='info' href='#XMPP-CORE'>[XMPP&#8209;CORE]<span> (</span><span class='info'>Saint-Andre, P., &ldquo;Extensible Messaging and Presence Protocol (XMPP): Core,&rdquo; March&nbsp;2011.</span><span>)</span></a> provide the building blocks for many types of near-real-time applications, which can be layered on top of the core by sending application-specific data qualified by particular XML namespaces (refer to <a class='info' href='#XML-NAMES'>[XML&#8209;NAMES]<span> (</span><span class='info'>Bray, T., Hollander, D., and A. Layman, &ldquo;Namespaces in XML,&rdquo; January&nbsp;1999.</span><span>)</span></a>). This document defines XMPP extensions that provide the basic functionality expected of an instant messaging (IM) and presence application as described in <a class='info' href='#IMP-REQS'>[IMP&#8209;REQS]<span> (</span><span class='info'>Day, M., Aggarwal, S., and J. Vincent, &ldquo;Instant Messaging / Presence Protocol Requirements,&rdquo; February&nbsp;2000.</span><span>)</span></a>.
496</p>
497<a name="intro-history"></a><br /><hr />
498<table summary="layout" cellpadding="0" cellspacing="2" class="TOCbug" align="right"><tr><td class="TOCbug"><a href="#toc">&nbsp;TOC&nbsp;</a></td></tr></table>
499<a name="rfc.section.1.2"></a><h3>1.2.&nbsp;
500History</h3>
501
502<p>The basic syntax and semantics of XMPP were developed originally within the Jabber open-source community, mainly in 1999. In late 2002, the XMPP Working Group was chartered with developing an adaptation of the core Jabber protocol that would be suitable as an IETF IM and presence technology in accordance with <a class='info' href='#IMP-REQS'>[IMP&#8209;REQS]<span> (</span><span class='info'>Day, M., Aggarwal, S., and J. Vincent, &ldquo;Instant Messaging / Presence Protocol Requirements,&rdquo; February&nbsp;2000.</span><span>)</span></a>. In October 2004, <a class='info' href='#RFC3920'>[RFC3920]<span> (</span><span class='info'>Saint-Andre, P., Ed., &ldquo;Extensible Messaging and Presence Protocol (XMPP): Core,&rdquo; October&nbsp;2004.</span><span>)</span></a> and <a class='info' href='#RFC3921'>[RFC3921]<span> (</span><span class='info'>Saint-Andre, P., Ed., &ldquo;Extensible Messaging and Presence Protocol (XMPP): Instant Messaging and Presence,&rdquo; October&nbsp;2004.</span><span>)</span></a> were published, representing the most complete definition of XMPP at that time.
503</p>
504<p>Since 2004 the Internet community has gained extensive implementation and deployment experience with XMPP, including formal interoperability testing carried out under the auspices of the XMPP Standards Foundation (XSF). This document incorporates comprehensive feedback from software developers and service providers, including a number of backward-compatible modifications summarized under <a class='info' href='#diffs'>Appendix&nbsp;E<span> (</span><span class='info'>Differences From RFC 3921</span><span>)</span></a>. As a result, this document reflects the rough consensus of the Internet community regarding the IM and presence features of XMPP 1.0, thus obsoleting RFC 3921.
505</p>
506<a name="intro-requirements"></a><br /><hr />
507<table summary="layout" cellpadding="0" cellspacing="2" class="TOCbug" align="right"><tr><td class="TOCbug"><a href="#toc">&nbsp;TOC&nbsp;</a></td></tr></table>
508<a name="rfc.section.1.3"></a><h3>1.3.&nbsp;
509Requirements</h3>
510
511<p>Traditionally, IM applications have combined the following factors:
512</p>
513<p>
514 </p>
515<ol class="text">
516<li>The central point of focus is a list of one's contacts or "buddies" (in XMPP this list is called a "roster").
517</li>
518<li>The purpose of using such an application is to exchange relatively brief text messages with particular contacts in close to real time -- often relatively large numbers of such messages in rapid succession, in the form of a one-to-one "chat session" as described under <a class='info' href='#message-chat'>Section&nbsp;5.1<span> (</span><span class='info'>One-to-One Chat Sessions</span><span>)</span></a>.
519</li>
520<li>The catalyst for exchanging messages is "presence" -- i.e., information about the network availability of particular contacts (thus knowing who is online and available for a one-to-one chat session).
521</li>
522<li>Presence information is provided only to contacts that one has authorized by means of an explicit agreement called a "presence subscription".
523</li>
524</ol><p>
525
526</p>
527<p>Thus at a high level this document assumes that a user needs to be able to complete the following use cases:
528</p>
529<p>
530 </p>
531<ul class="text">
532<li>Manage items in one's contact list
533</li>
534<li>Exchange messages with one's contacts
535</li>
536<li>Exchange presence information with one's contacts
537</li>
538<li>Manage presence subscriptions to and from one's contacts
539</li>
540</ul><p>
541
542</p>
543<p>Detailed definitions of these functionality areas are contained in RFC 2779 <a class='info' href='#IMP-REQS'>[IMP&#8209;REQS]<span> (</span><span class='info'>Day, M., Aggarwal, S., and J. Vincent, &ldquo;Instant Messaging / Presence Protocol Requirements,&rdquo; February&nbsp;2000.</span><span>)</span></a>, and the interested reader is referred to that document regarding in-depth requirements. Although the XMPP IM and presence extensions specified herein meet the requirements of RFC 2779, they were not designed explicitly with that specification in mind, since the base protocol evolved through an open development process within the Jabber open-source community before RFC 2779 was written. Although XMPP protocol extensions addressing many other functionality areas have been defined in the XMPP Standards Foundation's XEP series (e.g., multi-user text chat as specified in <a class='info' href='#XEP-0045'>[XEP&#8209;0045]<span> (</span><span class='info'>Saint-Andre, P., &ldquo;Multi-User Chat,&rdquo; July&nbsp;2008.</span><span>)</span></a>), such extensions are not specified in this document because they are not mandated by RFC 2779.
544</p>
545<p></p>
546<blockquote class="text">
547<p>Implementation Note: RFC 2779 stipulates that presence services must be separable from IM services and vice-versa; i.e., it must be possible to use the protocol to provide a presence service, a messaging service, or both. Although the text of this document assumes that implementations and deployments will want to offer a unified IM and presence service, it is not mandatory for an XMPP service to offer both a presence service and a messaging service, and the protocol makes it possible to offer separate and distinct services for presence and for messaging. (For example, a presence-only service could return a &lt;service-unavailable/&gt; stanza error if a client attempts to send a &lt;message/&gt; stanza.)
548</p>
549</blockquote>
550
551<a name="intro-summary"></a><br /><hr />
552<table summary="layout" cellpadding="0" cellspacing="2" class="TOCbug" align="right"><tr><td class="TOCbug"><a href="#toc">&nbsp;TOC&nbsp;</a></td></tr></table>
553<a name="rfc.section.1.4"></a><h3>1.4.&nbsp;
554Functional Summary</h3>
555
556<p>This non-normative section provides a developer-friendly, functional summary of XMPP-based IM and presence features; consult the sections that follow for a normative definition of these features.
557</p>
558<p><a class='info' href='#XMPP-CORE'>[XMPP&#8209;CORE]<span> (</span><span class='info'>Saint-Andre, P., &ldquo;Extensible Messaging and Presence Protocol (XMPP): Core,&rdquo; March&nbsp;2011.</span><span>)</span></a> specifies how an XMPP client connects to an XMPP server. In particular, it specifies the preconditions that need to be fulfilled before a client is allowed to send XML stanzas (the basic unit of meaning in XMPP) to other entities on an XMPP network. These preconditions comprise negotiation of the XML stream and include exchange of XML stream headers, optional channel encryption via Transport Layer Security <a class='info' href='#TLS'>[TLS]<span> (</span><span class='info'>Dierks, T. and E. Rescorla, &ldquo;The Transport Layer Security (TLS) Protocol Version 1.2,&rdquo; August&nbsp;2008.</span><span>)</span></a>, mandatory authentication via Simple Authentication and Security Layer <a class='info' href='#SASL'>[SASL]<span> (</span><span class='info'>Melnikov, A. and K. Zeilenga, &ldquo;Simple Authentication and Security Layer (SASL),&rdquo; June&nbsp;2006.</span><span>)</span></a>, and binding of a resource to the stream for client addressing. The reader is referred to <a class='info' href='#XMPP-CORE'>[XMPP&#8209;CORE]<span> (</span><span class='info'>Saint-Andre, P., &ldquo;Extensible Messaging and Presence Protocol (XMPP): Core,&rdquo; March&nbsp;2011.</span><span>)</span></a> for details regarding these preconditions, and knowledge of <a class='info' href='#XMPP-CORE'>[XMPP&#8209;CORE]<span> (</span><span class='info'>Saint-Andre, P., &ldquo;Extensible Messaging and Presence Protocol (XMPP): Core,&rdquo; March&nbsp;2011.</span><span>)</span></a> is assumed herein.
559</p>
560<p></p>
561<blockquote class="text">
562<p>Interoperability Note: <a class='info' href='#RFC3921'>[RFC3921]<span> (</span><span class='info'>Saint-Andre, P., Ed., &ldquo;Extensible Messaging and Presence Protocol (XMPP): Instant Messaging and Presence,&rdquo; October&nbsp;2004.</span><span>)</span></a> specified one additional precondition: formal establishment of an instant messaging and presence session. Implementation and deployment experience has shown that this additional step is unnecessary. However, for backward compatibility an implementation MAY still offer that feature. This enables older software to connect while letting newer software save a round trip.
563</p>
564</blockquote>
565
566<p>Upon fulfillment of the preconditions specified in <a class='info' href='#XMPP-CORE'>[XMPP&#8209;CORE]<span> (</span><span class='info'>Saint-Andre, P., &ldquo;Extensible Messaging and Presence Protocol (XMPP): Core,&rdquo; March&nbsp;2011.</span><span>)</span></a>, an XMPP client has a long-lived XML stream with an XMPP server, which enables the user controlling that client to send and receive a potentially unlimited number of XML stanzas over the stream. Such a stream can be used to exchange messages, share presence information, and engage in structured request-response interactions in close to real time. After negotiation of the XML stream, the typical flow for an instant messaging and presence session is as follows:
567</p>
568<p>
569 </p>
570<ol class="text">
571<li>Retrieve one's roster. (See <a class='info' href='#roster-login'>Section&nbsp;2.2<span> (</span><span class='info'>Retrieving the Roster on Login</span><span>)</span></a>.)
572</li>
573<li>Send initial presence to the server for broadcast to all subscribed contacts, thus "going online" from the perspective of XMPP communication. (See <a class='info' href='#presence-initial'>Section&nbsp;4.2<span> (</span><span class='info'>Initial Presence</span><span>)</span></a>.)
574</li>
575<li>Exchange messages, manage presence subscriptions, perform roster
576updates, and in general process and generate other XML stanzas with particular
577semantics throughout the life of the session. (See Sections <a class='info' href='#message'>5<span> (</span><span class='info'>Exchanging Messages</span><span>)</span></a>, <a class='info' href='#sub'>3<span> (</span><span class='info'>Managing Presence Subscriptions</span><span>)</span></a>,
578<a class='info' href='#roster'>2<span> (</span><span class='info'>Managing the Roster</span><span>)</span></a>, and <a class='info' href='#iq'>6<span> (</span><span class='info'>Exchanging IQ Stanzas</span><span>)</span></a>.)
579</li>
580<li>Terminate the session when desired by sending unavailable presence and closing the underlying XML stream. (See <a class='info' href='#presence-unavailable'>Section&nbsp;4.5<span> (</span><span class='info'>Unavailable Presence</span><span>)</span></a>.)
581</li>
582</ol><p>
583
584</p>
585<a name="intro-terms"></a><br /><hr />
586<table summary="layout" cellpadding="0" cellspacing="2" class="TOCbug" align="right"><tr><td class="TOCbug"><a href="#toc">&nbsp;TOC&nbsp;</a></td></tr></table>
587<a name="rfc.section.1.5"></a><h3>1.5.&nbsp;
588Terminology</h3>
589
590<p>The key words "MUST", "MUST NOT", "REQUIRED", "SHALL", "SHALL NOT", "SHOULD", "SHOULD NOT", "RECOMMENDED", "NOT RECOMMENDED", "MAY", and "OPTIONAL" in this document are to be interpreted as described in RFC 2119 <a class='info' href='#KEYWORDS'>[KEYWORDS]<span> (</span><span class='info'>Bradner, S., &ldquo;Key words for use in RFCs to Indicate Requirement Levels,&rdquo; March&nbsp;1997.</span><span>)</span></a>.
591</p>
592<p>This document inherits the terminology defined in <a class='info' href='#XMPP-CORE'>[XMPP&#8209;CORE]<span> (</span><span class='info'>Saint-Andre, P., &ldquo;Extensible Messaging and Presence Protocol (XMPP): Core,&rdquo; March&nbsp;2011.</span><span>)</span></a>.
593</p>
594<p>The terms "automated client" and "interactive client" are to be understood in the sense defined in <a class='info' href='#TLS-CERTS'>[TLS&#8209;CERTS]<span> (</span><span class='info'>Saint-Andre, P. and J. Hodges, &ldquo;Representation and Verification of Domain-Based Application Service Identity within Internet Public Key Infrastructure Using X.509 (PKIX) Certificates in the Context of Transport Layer Security (TLS),&rdquo; March&nbsp;2011.</span><span>)</span></a>.
595</p>
596<p>For convenience, this document employs the term "user" to refer to the owner of an XMPP account; however, account owners need not be humans and can be bots, devices, or other automated applications.
597</p>
598<p>Several other terms, such as "interested resource", are defined within the body of this document.
599</p>
600<p>Following the "XML Notation" used in <a class='info' href='#IRI'>[IRI]<span> (</span><span class='info'>Duerst, M. and M. Suignard, &ldquo;Internationalized Resource Identifiers (IRIs),&rdquo; January&nbsp;2005.</span><span>)</span></a> to represent characters that cannot be rendered in ASCII-only documents, some examples in this document use the form "&amp;#x...." as a notational device to represent <a class='info' href='#UNICODE'>[UNICODE]<span> (</span><span class='info'>The Unicode Consortium, &ldquo;The Unicode Standard, Version 6.0,&rdquo; 2010.</span><span>)</span></a> characters (e.g., the string "&amp;#x0159;" stands for the Unicode character LATIN SMALL LETTER R WITH CARON); this form is definitely not to be sent over the wire in XMPP systems.
601</p>
602<p>In examples, lines have been wrapped for improved readability, "[...]" means elision, and the following prepended strings are used (these prepended strings are not to be sent over the wire):
603</p>
604<p>
605 </p>
606<ul class="text">
607<li>C: = client
608</li>
609<li>CC: = contact's client
610</li>
611<li>CS: = contact's server
612</li>
613<li>S: = server
614</li>
615<li>UC: = user's client
616</li>
617<li>US: = user's server
618</li>
619</ul><p>
620
621</p>
622<p>Readers need to be aware that the examples are not exhaustive
623 and that, in examples for some protocol flows, the alternate
624 steps shown would not necessarily be triggered by the exact data
625 sent in the previous step; in all cases, the protocol definitions specified in this document or in normatively referenced documents rule over any examples provided here. All examples are fictional and the information exchanged (e.g., usernames and passwords) does not represent any existing users or servers.
626</p>
627<a name="roster"></a><br /><hr />
628<table summary="layout" cellpadding="0" cellspacing="2" class="TOCbug" align="right"><tr><td class="TOCbug"><a href="#toc">&nbsp;TOC&nbsp;</a></td></tr></table>
629<a name="rfc.section.2"></a><h3>2.&nbsp;
630Managing the Roster</h3>
631
632<p>In XMPP, a user's roster contains any number of specific contacts. A user's roster is stored by the user's server on the user's behalf so that the user can access roster information from any device. When the user adds items to the roster or modifies existing items, if an error does not occur then the server SHOULD store that data unmodified if at all possible and MUST return the data it has stored when an authorized client requests the roster.
633</p>
634<p></p>
635<blockquote class="text">
636<p>Security Warning: Because the user's roster can contain confidential data, the server MUST restrict access to this data so that only authorized entities (typically limited to the account owner) are able to retrieve, modify, or delete it.
637</p>
638</blockquote>
639
640<p>RFC 3921 assumed that the only place where a user stores their roster is the server where the user's account is registered and at which the user authenticates for access to the XMPP network. This specification removes that strict coupling of roster storage to account registration and network authentication, with the result that a user could store their roster at another location, or could have multiple rosters that are stored in multiple locations. However, in the absence of implementation and deployment experience with a more flexible roster storage model, this specification retains the terminology of RFC 3921 by using the terms "client" and "server" (and "the roster" instead of "a roster"), rather than coining a new term for "a place where a user stores a roster". Future documents might provide normative rules for non-server roster storage or for the management of multiple rosters, but such rules are out of scope for this document.
641</p>
642<a name="roster-syntax"></a><br /><hr />
643<table summary="layout" cellpadding="0" cellspacing="2" class="TOCbug" align="right"><tr><td class="TOCbug"><a href="#toc">&nbsp;TOC&nbsp;</a></td></tr></table>
644<a name="rfc.section.2.1"></a><h3>2.1.&nbsp;
645Syntax and Semantics</h3>
646
647<p>Rosters are managed using &lt;iq/&gt; stanzas (see Section 8.2.3 of
648<a class='info' href='#XMPP-CORE'>[XMPP&#8209;CORE]<span> (</span><span class='info'>Saint-Andre, P., &ldquo;Extensible Messaging and Presence Protocol (XMPP): Core,&rdquo; March&nbsp;2011.</span><span>)</span></a>), specifically by means of a &lt;query/&gt; child element qualified by the 'jabber:iq:roster' namespace. The detailed syntax and semantics are defined in the following sections.
649</p>
650<a name="roster-syntax-ver"></a><br /><hr />
651<table summary="layout" cellpadding="0" cellspacing="2" class="TOCbug" align="right"><tr><td class="TOCbug"><a href="#toc">&nbsp;TOC&nbsp;</a></td></tr></table>
652<a name="rfc.section.2.1.1"></a><h3>2.1.1.&nbsp;
653Ver Attribute</h3>
654
655<p>The 'ver' attribute is a string that identifies a particular version of the roster information. The value MUST be generated only by the server and MUST be treated by the client as opaque. The server can use any appropriate method for generating the version ID, such as a hash of the roster data or a strictly increasing sequence number.
656</p>
657<p>Inclusion of the 'ver' attribute is RECOMMENDED.
658</p>
659<p>Use of the 'ver' attribute is described more fully under <a class='info' href='#roster-versioning'>Section&nbsp;2.6<span> (</span><span class='info'>Roster Versioning</span><span>)</span></a>.
660</p>
661<p></p>
662<blockquote class="text">
663<p>Interoperability Note: The 'ver' attribute of the &lt;query/&gt; element was not defined in RFC 3921 and is newly defined in this specification.
664</p>
665</blockquote>
666
667<a name="roster-syntax-items"></a><br /><hr />
668<table summary="layout" cellpadding="0" cellspacing="2" class="TOCbug" align="right"><tr><td class="TOCbug"><a href="#toc">&nbsp;TOC&nbsp;</a></td></tr></table>
669<a name="rfc.section.2.1.2"></a><h3>2.1.2.&nbsp;
670Roster Items</h3>
671
672<p>The &lt;query/&gt; element inside a <a class='info' href='#roster-syntax-actions-set'>roster set<span> (</span><span class='info'>Roster Set</span><span>)</span></a> contains one &lt;item/&gt; child, and a <a class='info' href='#roster-syntax-actions-result'>roster result<span> (</span><span class='info'>Roster Result</span><span>)</span></a> typically contains multiple &lt;item/&gt; children. Each &lt;item/&gt; element describes a unique "roster item" (sometimes also called a "contact").
673</p>
674<p>The syntax of the &lt;item/&gt; element is described in the following sections.
675</p>
676<a name="roster-syntax-items-approved"></a><br /><hr />
677<table summary="layout" cellpadding="0" cellspacing="2" class="TOCbug" align="right"><tr><td class="TOCbug"><a href="#toc">&nbsp;TOC&nbsp;</a></td></tr></table>
678<a name="rfc.section.2.1.2.1"></a><h3>2.1.2.1.&nbsp;
679Approved Attribute</h3>
680
681<p>The boolean 'approved' attribute with a value of "true" is used to signal subscription pre-approval as described under <a class='info' href='#sub-preapproval'>Section&nbsp;3.4<span> (</span><span class='info'>Pre-Approving a Subscription Request</span><span>)</span></a> (the default is "false", in accordance with <a class='info' href='#XML-DATATYPES'>[XML&#8209;DATATYPES]<span> (</span><span class='info'>Biron, P. and A. Malhotra, &ldquo;XML Schema Part 2: Datatypes Second Edition,&rdquo; October&nbsp;2004.</span><span>)</span></a>).
682</p>
683<p>A server SHOULD include the 'approved' attribute to inform the client of subscription pre-approvals. A client MUST NOT include the 'approved' attribute in the roster sets it sends to the server, but instead MUST use presence stanzas of type "subscribed" and "unsubscribed" to manage pre-approvals as described under <a class='info' href='#sub-preapproval'>Section&nbsp;3.4<span> (</span><span class='info'>Pre-Approving a Subscription Request</span><span>)</span></a>.
684</p>
685<p></p>
686<blockquote class="text">
687<p>Interoperability Note: The 'approved' attribute of the &lt;item/&gt; element was not defined in RFC 3921 and is newly defined in this specification.
688</p>
689</blockquote>
690
691<a name="roster-syntax-items-ask"></a><br /><hr />
692<table summary="layout" cellpadding="0" cellspacing="2" class="TOCbug" align="right"><tr><td class="TOCbug"><a href="#toc">&nbsp;TOC&nbsp;</a></td></tr></table>
693<a name="rfc.section.2.1.2.2"></a><h3>2.1.2.2.&nbsp;
694Ask Attribute</h3>
695
696<p>The 'ask' attribute of the &lt;item/&gt; element with a value of "subscribe" is used to signal various subscription sub-states that include a "Pending Out" aspect as described under <a class='info' href='#sub-request-outbound'>Section&nbsp;3.1.2<span> (</span><span class='info'>Server Processing of Outbound Subscription Request</span><span>)</span></a>.
697</p>
698<p>A server SHOULD include the 'ask' attribute to inform the client of "Pending Out" sub-states. A client MUST NOT include the 'ask' attribute in the roster sets it sends to the server, but instead MUST use presence stanzas of type "subscribe" and "unsubscribe" to manage such sub-states as described under <a class='info' href='#sub-request-outbound'>Section&nbsp;3.1.2<span> (</span><span class='info'>Server Processing of Outbound Subscription Request</span><span>)</span></a>.
699</p>
700<a name="roster-syntax-items-jid"></a><br /><hr />
701<table summary="layout" cellpadding="0" cellspacing="2" class="TOCbug" align="right"><tr><td class="TOCbug"><a href="#toc">&nbsp;TOC&nbsp;</a></td></tr></table>
702<a name="rfc.section.2.1.2.3"></a><h3>2.1.2.3.&nbsp;
703JID Attribute</h3>
704
705<p>The 'jid' attribute of the &lt;item/&gt; element specifies the Jabber Identifier (JID) that uniquely identifies the roster item.
706</p>
707<p>The 'jid' attribute is REQUIRED whenever a client or server adds, updates, deletes, or returns a roster item.
708</p>
709<a name="roster-syntax-items-name"></a><br /><hr />
710<table summary="layout" cellpadding="0" cellspacing="2" class="TOCbug" align="right"><tr><td class="TOCbug"><a href="#toc">&nbsp;TOC&nbsp;</a></td></tr></table>
711<a name="rfc.section.2.1.2.4"></a><h3>2.1.2.4.&nbsp;
712Name Attribute</h3>
713
714<p>The 'name' attribute of the &lt;item/&gt; element specifies the "handle" to be associated with the JID, as determined by the user (not the contact). Although the value of the 'name' attribute MAY have meaning to a human user, it is opaque to the server. However, the 'name' attribute MAY be used by the server for matching purposes within the context of various XMPP extensions (one possible comparison method is that described for XMPP resourceparts in <a class='info' href='#XMPP-ADDR'>[XMPP&#8209;ADDR]<span> (</span><span class='info'>Saint-Andre, P., &ldquo;Extensible Messaging and Presence Protocol (XMPP): Address Format,&rdquo; March&nbsp;2011.</span><span>)</span></a>).
715</p>
716<p>It is OPTIONAL for a client to include the 'name' attribute when adding or updating a roster item.
717</p>
718<a name="roster-syntax-items-subscription"></a><br /><hr />
719<table summary="layout" cellpadding="0" cellspacing="2" class="TOCbug" align="right"><tr><td class="TOCbug"><a href="#toc">&nbsp;TOC&nbsp;</a></td></tr></table>
720<a name="rfc.section.2.1.2.5"></a><h3>2.1.2.5.&nbsp;
721Subscription Attribute</h3>
722
723<p>The state of the presence subscription is captured in the 'subscription' attribute of the &lt;item/&gt; element. The defined subscription-related values are:
724</p>
725<p>
726 </p>
727<blockquote class="text"><dl>
728<dt>none:</dt>
729<dd>the user does not have a subscription to the contact's presence, and the contact does not have a subscription to the user's presence; this is the default value, so if the subscription attribute is not included then the state is to be understood as "none"
730</dd>
731<dt>to:</dt>
732<dd>the user has a subscription to the contact's presence, but the contact does not have a subscription to the user's presence
733</dd>
734<dt>from:</dt>
735<dd>the contact has a subscription to the user's presence, but the user does not have a subscription to the contact's presence
736</dd>
737<dt>both:</dt>
738<dd>the user and the contact have subscriptions to each other's presence (also called a "mutual subscription")
739</dd>
740</dl></blockquote><p>
741
742</p>
743<p>In a <a class='info' href='#roster-syntax-actions-result'>roster result<span> (</span><span class='info'>Roster Result</span><span>)</span></a>, the client MUST ignore values of the 'subscription' attribute other than "none", "to", "from", or "both".
744</p>
745<p>In a <a class='info' href='#roster-syntax-actions-push'>roster push<span> (</span><span class='info'>Roster Push</span><span>)</span></a>, the client MUST ignore values of the 'subscription' attribute other than "none", "to", "from", "both", or "remove".
746</p>
747<p>In a <a class='info' href='#roster-syntax-actions-set'>roster set<span> (</span><span class='info'>Roster Set</span><span>)</span></a>, the 'subscription' attribute MAY be included with a value of "remove", which indicates that the item is to be removed from the roster; in a roster set the server MUST ignore all values of the 'subscription' attribute other than "remove".
748</p>
749<p>Inclusion of the 'subscription' attribute is OPTIONAL.
750</p>
751<a name="roster-syntax-items-group"></a><br /><hr />
752<table summary="layout" cellpadding="0" cellspacing="2" class="TOCbug" align="right"><tr><td class="TOCbug"><a href="#toc">&nbsp;TOC&nbsp;</a></td></tr></table>
753<a name="rfc.section.2.1.2.6"></a><h3>2.1.2.6.&nbsp;
754Group Element</h3>
755
756<p>The &lt;group/&gt; child element specifies a category or "bucket" into which the roster item is to be grouped by a client. An &lt;item/&gt; element MAY contain more than one &lt;group/&gt; element, which means that roster groups are not exclusive. Although the XML character data of the &lt;group/&gt; element MAY have meaning to a human user, it is opaque to the server. However, the &lt;group/&gt; element MAY be used by the server for matching purposes within the context of various XMPP extensions (one possible comparison method is that described for XMPP resourceparts in <a class='info' href='#XMPP-ADDR'>[XMPP&#8209;ADDR]<span> (</span><span class='info'>Saint-Andre, P., &ldquo;Extensible Messaging and Presence Protocol (XMPP): Address Format,&rdquo; March&nbsp;2011.</span><span>)</span></a>).
757</p>
758<p>It is OPTIONAL for a client to include the &lt;group/&gt; element when adding or updating a roster item. If a <a class='info' href='#roster-syntax-actions-set'>roster set<span> (</span><span class='info'>Roster Set</span><span>)</span></a> includes no &lt;group/&gt; element, then the item is to be interpreted as being affiliated with no group.
759</p>
760<a name="roster-syntax-actions-get"></a><br /><hr />
761<table summary="layout" cellpadding="0" cellspacing="2" class="TOCbug" align="right"><tr><td class="TOCbug"><a href="#toc">&nbsp;TOC&nbsp;</a></td></tr></table>
762<a name="rfc.section.2.1.3"></a><h3>2.1.3.&nbsp;
763Roster Get</h3>
764
765<p>A "roster get" is a client's request for the server to return the roster; syntactically it is an IQ stanza of type "get" sent from client to server and containing a &lt;query/&gt; element qualified by the 'jabber:iq:roster' namespace, where the &lt;query/&gt; element MUST NOT contain any &lt;item/&gt; child elements.
766</p><div style='display: table; width: 0; margin-left: 3em; margin-right: auto'><pre>
767C: &lt;iq from='juliet@example.com/balcony'
768 id='bv1bs71f'
769 type='get'&gt;
770 &lt;query xmlns='jabber:iq:roster'/&gt;
771 &lt;/iq&gt;
772</pre></div>
773<p>The expected outcome of sending a roster get is for the server to return a roster result.
774</p>
775<a name="roster-syntax-actions-result"></a><br /><hr />
776<table summary="layout" cellpadding="0" cellspacing="2" class="TOCbug" align="right"><tr><td class="TOCbug"><a href="#toc">&nbsp;TOC&nbsp;</a></td></tr></table>
777<a name="rfc.section.2.1.4"></a><h3>2.1.4.&nbsp;
778Roster Result</h3>
779
780<p>A "roster result" is the server's response to a roster get; syntactically it is an IQ stanza of type "result" sent from server to client and containing a &lt;query/&gt; element qualified by the 'jabber:iq:roster' namespace.
781</p>
782<p>The &lt;query/&gt; element in a roster result contains one &lt;item/&gt; element for each contact and therefore can contain more than one &lt;item/&gt; element.
783</p><div style='display: table; width: 0; margin-left: 3em; margin-right: auto'><pre>
784S: &lt;iq id='bv1bs71f'
785 to='juliet@example.com/chamber'
786 type='result'&gt;
787 &lt;query xmlns='jabber:iq:roster' ver='ver7'&gt;
788 &lt;item jid='nurse@example.com'/&gt;
789 &lt;item jid='romeo@example.net'/&gt;
790 &lt;/query&gt;
791 &lt;/iq&gt;
792</pre></div>
793<p>If the roster exists but there are no contacts in the roster, then the server MUST return an IQ-result containing a child &lt;query/&gt; element that in turn contains no &lt;item/&gt; children (i.e., the server MUST NOT return an empty &lt;iq/&gt; stanza of type "error").
794</p><div style='display: table; width: 0; margin-left: 3em; margin-right: auto'><pre>
795S: &lt;iq id='bv1bs71f'
796 to='juliet@example.com/chamber'
797 type='result'&gt;
798 &lt;query xmlns='jabber:iq:roster' ver='ver9'/&gt;
799 &lt;/iq&gt;
800</pre></div>
801<p>If the roster does not exist, then the server MUST return a stanza error with a condition of &lt;item-not-found/&gt;.
802</p><div style='display: table; width: 0; margin-left: 3em; margin-right: auto'><pre>
803S: &lt;iq id='bv1bs71f'
804 to='juliet@example.com/chamber'
805 type='error'&gt;
806 &lt;error type='cancel'&gt;
807 &lt;item-not-found
808 xmlns='urn:ietf:params:xml:ns:xmpp-stanzas'/&gt;
809 &lt;/error&gt;
810 &lt;/iq&gt;
811</pre></div>
812<a name="roster-syntax-actions-set"></a><br /><hr />
813<table summary="layout" cellpadding="0" cellspacing="2" class="TOCbug" align="right"><tr><td class="TOCbug"><a href="#toc">&nbsp;TOC&nbsp;</a></td></tr></table>
814<a name="rfc.section.2.1.5"></a><h3>2.1.5.&nbsp;
815Roster Set</h3>
816
817<p>A "roster set" is a client's request for the server to modify (i.e., create, update, or delete) a roster item; syntactically it is an IQ stanza of type "set" sent from client to server and containing a &lt;query/&gt; element qualified by the 'jabber:iq:roster' namespace.
818</p>
819<p>The following rules apply to roster sets:
820</p>
821<p>
822 </p>
823<ol class="text">
824<li>The &lt;query/&gt; element MUST contain one and only one &lt;item/&gt; element.
825</li>
826<li>The server MUST ignore any value of the 'subscription' attribute other than "remove" (see <a class='info' href='#roster-syntax-items-subscription'>Section&nbsp;2.1.2.5<span> (</span><span class='info'>Subscription Attribute</span><span>)</span></a>).
827</li>
828</ol><p>
829
830</p>
831<p></p>
832<blockquote class="text">
833<p>Security Warning: Traditionally, the IQ stanza of the roster set included no 'to' address, with the result that all roster sets were sent from an authenticated resource (full JID) of the account whose roster was being updated. Furthermore, RFC 3921 required a server to perform special-case checking of roster sets to ignore the 'to' address; however, this specification has removed that special-casing, which means that a roster set might include a 'to' address other than that of the sender. Therefore, the entity that processes a roster set MUST verify that the sender of the roster set is authorized to update the roster, and if not return a &lt;forbidden/&gt; error.
834</p>
835</blockquote>
836<div style='display: table; width: 0; margin-left: 3em; margin-right: auto'><pre>
837C: &lt;iq from='juliet@example.com/balcony'
838 id='rs1'
839 type='set'&gt;
840 &lt;query xmlns='jabber:iq:roster'&gt;
841 &lt;item jid='nurse@example.com'/&gt;
842 &lt;/query&gt;
843 &lt;/iq&gt;
844</pre></div>
845<a name="roster-syntax-actions-push"></a><br /><hr />
846<table summary="layout" cellpadding="0" cellspacing="2" class="TOCbug" align="right"><tr><td class="TOCbug"><a href="#toc">&nbsp;TOC&nbsp;</a></td></tr></table>
847<a name="rfc.section.2.1.6"></a><h3>2.1.6.&nbsp;
848Roster Push</h3>
849
850<p>A "roster push" is a newly created, updated, or deleted roster item that is sent from the server to the client; syntactically it is an IQ stanza of type "set" sent from server to client and containing a &lt;query/&gt; element qualified by the 'jabber:iq:roster' namespace.
851</p>
852<p>The following rules apply to roster pushes:
853</p>
854<p>
855 </p>
856<ol class="text">
857<li>The &lt;query/&gt; element in a roster push MUST contain one and only one &lt;item/&gt; element.
858</li>
859<li>A receiving client MUST ignore the stanza unless it has no 'from' attribute (i.e., implicitly from the bare JID of the user's account) or it has a 'from' attribute whose value matches the user's bare JID &lt;user@domainpart&gt;.
860</li>
861</ol><p>
862
863</p><div style='display: table; width: 0; margin-left: 3em; margin-right: auto'><pre>
864S: &lt;iq id='a78b4q6ha463'
865 to='juliet@example.com/chamber'
866 type='set'&gt;
867 &lt;query xmlns='jabber:iq:roster'&gt;
868 &lt;item jid='nurse@example.com'/&gt;
869 &lt;/query&gt;
870 &lt;/iq&gt;
871</pre></div>
872<p>As mandated by the semantics of the IQ stanza as defined in <a class='info' href='#XMPP-CORE'>[XMPP&#8209;CORE]<span> (</span><span class='info'>Saint-Andre, P., &ldquo;Extensible Messaging and Presence Protocol (XMPP): Core,&rdquo; March&nbsp;2011.</span><span>)</span></a>, each resource that receives a roster push from the server is supposed to reply with an IQ stanza of type "result" or "error" (however, it is known that many existing clients do not reply to roster pushes).
873</p><div style='display: table; width: 0; margin-left: 3em; margin-right: auto'><pre>
874C: &lt;iq from='juliet@example.com/balcony'
875 id='a78b4q6ha463'
876 type='result'/&gt;
877
878C: &lt;iq from='juliet@example.com/chamber'
879 id='a78b4q6ha463'
880 type='result'/&gt;
881</pre></div>
882<p></p>
883<blockquote class="text">
884<p>Security Warning: Traditionally, a roster push included no 'from' address, with the result that all roster pushes were sent implicitly from the bare JID of the account itself. However, this specification allows entities other than the user's server to maintain roster information, which means that a roster push might include a 'from' address other than the bare JID of the user's account. Therefore, the client MUST check the 'from' address to verify that the sender of the roster push is authorized to update the roster. If the client receives a roster push from an unauthorized entity, it MUST NOT process the pushed data; in addition, the client can either return a stanza error of &lt;service-unavailable/&gt; error or refuse to return a stanza error at all (the latter behavior overrides a MUST-level requirement from <a class='info' href='#XMPP-CORE'>[XMPP&#8209;CORE]<span> (</span><span class='info'>Saint-Andre, P., &ldquo;Extensible Messaging and Presence Protocol (XMPP): Core,&rdquo; March&nbsp;2011.</span><span>)</span></a> for the purpose of preventing a presence leak).
885</p>
886</blockquote>
887
888<p></p>
889<blockquote class="text">
890<p>Implementation Note: There is no error case for client processing of roster pushes; if the server receives an IQ of type "error" in response to a roster push then it SHOULD ignore the error.
891</p>
892</blockquote>
893
894<a name="roster-login"></a><br /><hr />
895<table summary="layout" cellpadding="0" cellspacing="2" class="TOCbug" align="right"><tr><td class="TOCbug"><a href="#toc">&nbsp;TOC&nbsp;</a></td></tr></table>
896<a name="rfc.section.2.2"></a><h3>2.2.&nbsp;
897Retrieving the Roster on Login</h3>
898
899<p>Upon authenticating with a server and binding a resource (thus becoming a connected resource as defined in <a class='info' href='#XMPP-CORE'>[XMPP&#8209;CORE]<span> (</span><span class='info'>Saint-Andre, P., &ldquo;Extensible Messaging and Presence Protocol (XMPP): Core,&rdquo; March&nbsp;2011.</span><span>)</span></a>), a client SHOULD request the roster before sending initial presence (however, because receiving the roster is not necessarily desirable for all resources, e.g., a connection with limited bandwidth, the client's request for the roster is not mandatory). After a connected resource sends initial presence (see <a class='info' href='#presence-initial'>Section&nbsp;4.2<span> (</span><span class='info'>Initial Presence</span><span>)</span></a>), it is referred to as an "available resource". If a connected resource or available resource requests the roster, it is referred to as an "interested resource". The server MUST send roster pushes to all interested resources.
900</p>
901<p></p>
902<blockquote class="text">
903<p>Implementation Note: Presence subscription requests are sent to available resources, whereas the roster pushes associated with subscription state changes are sent to interested resources. Therefore, if a resource wishes to receive both subscription requests and roster pushes, it MUST both send initial presence and request the roster.
904</p>
905</blockquote>
906
907<p>A client requests the roster by sending a roster get over its stream with the server.
908</p><div style='display: table; width: 0; margin-left: 3em; margin-right: auto'><pre>
909C: &lt;iq from='juliet@example.com/balcony'
910 id='hu2bac18'
911 type='get'&gt;
912 &lt;query xmlns='jabber:iq:roster'/&gt;
913 &lt;/iq&gt;
914</pre></div><div style='display: table; width: 0; margin-left: 3em; margin-right: auto'><pre>
915S: &lt;iq id='hu2bac18'
916 to='juliet@example.com/balcony'
917 type='result'&gt;
918 &lt;query xmlns='jabber:iq:roster' ver='ver11'&gt;
919 &lt;item jid='romeo@example.net'
920 name='Romeo'
921 subscription='both'&gt;
922 &lt;group&gt;Friends&lt;/group&gt;
923 &lt;/item&gt;
924 &lt;item jid='mercutio@example.com'
925 name='Mercutio'
926 subscription='from'/&gt;
927 &lt;item jid='benvolio@example.net'
928 name='Benvolio'
929 subscription='both'/&gt;
930 &lt;/query&gt;
931 &lt;/iq&gt;
932</pre></div>
933<p>If the server cannot process the roster get, it MUST return an appropriate stanza error as described in <a class='info' href='#XMPP-CORE'>[XMPP&#8209;CORE]<span> (</span><span class='info'>Saint-Andre, P., &ldquo;Extensible Messaging and Presence Protocol (XMPP): Core,&rdquo; March&nbsp;2011.</span><span>)</span></a> (such as &lt;service-unavailable/&gt; if the roster namespace is not supported or &lt;internal-server-error/&gt; if the server experiences trouble processing or returning the roster).
934</p>
935<a name="roster-add"></a><br /><hr />
936<table summary="layout" cellpadding="0" cellspacing="2" class="TOCbug" align="right"><tr><td class="TOCbug"><a href="#toc">&nbsp;TOC&nbsp;</a></td></tr></table>
937<a name="rfc.section.2.3"></a><h3>2.3.&nbsp;
938Adding a Roster Item</h3>
939
940<a name="roster-add-request"></a><br /><hr />
941<table summary="layout" cellpadding="0" cellspacing="2" class="TOCbug" align="right"><tr><td class="TOCbug"><a href="#toc">&nbsp;TOC&nbsp;</a></td></tr></table>
942<a name="rfc.section.2.3.1"></a><h3>2.3.1.&nbsp;
943Request</h3>
944
945<p>At any time, a client can add an item to the roster. This is done by sending a roster set containing a new item.
946</p><div style='display: table; width: 0; margin-left: 3em; margin-right: auto'><pre>
947C: &lt;iq from='juliet@example.com/balcony'
948 id='ph1xaz53'
949 type='set'&gt;
950 &lt;query xmlns='jabber:iq:roster'&gt;
951 &lt;item jid='nurse@example.com'
952 name='Nurse'&gt;
953 &lt;group&gt;Servants&lt;/group&gt;
954 &lt;/item&gt;
955 &lt;/query&gt;
956 &lt;/iq&gt;
957</pre></div>
958<a name="roster-add-success"></a><br /><hr />
959<table summary="layout" cellpadding="0" cellspacing="2" class="TOCbug" align="right"><tr><td class="TOCbug"><a href="#toc">&nbsp;TOC&nbsp;</a></td></tr></table>
960<a name="rfc.section.2.3.2"></a><h3>2.3.2.&nbsp;
961Success Case</h3>
962
963<p>If the server can successfully process the roster set for the new item (i.e., if no error occurs), it MUST create the item in the user's roster and proceed as follows.
964</p>
965<p>The server MUST return an IQ stanza of type "result" to the connected resource that sent the roster set.
966</p><div style='display: table; width: 0; margin-left: 3em; margin-right: auto'><pre>
967S: &lt;iq id='ph1xaz53'
968 to='juliet@example.com/balcony'
969 type='result'/&gt;
970</pre></div>
971<p>The server MUST also send a roster push containing the new roster item to all of the user's interested resources, including the resource that generated the roster set.
972</p><div style='display: table; width: 0; margin-left: 3em; margin-right: auto'><pre>
973S: &lt;iq to='juliet@example.com/balcony'
974 id='a78b4q6ha463'
975 type='set'&gt;
976 &lt;query xmlns='jabber:iq:roster' ver='ver13'&gt;
977 &lt;item jid='nurse@example.com'
978 name='Nurse'
979 subscription='none'&gt;
980 &lt;group&gt;Servants&lt;/group&gt;
981 &lt;/item&gt;
982 &lt;/query&gt;
983 &lt;/iq&gt;
984
985S: &lt;iq to='juliet@example.com/chamber'
986 id='x81g3bdy4n19'
987 type='set'&gt;
988 &lt;query xmlns='jabber:iq:roster' ver='ver13'&gt;
989 &lt;item jid='nurse@example.com'
990 name='Nurse'
991 subscription='none'&gt;
992 &lt;group&gt;Servants&lt;/group&gt;
993 &lt;/item&gt;
994 &lt;/query&gt;
995 &lt;/iq&gt;
996</pre></div>
997<p>As mandated by the semantics of the IQ stanza as defined in <a class='info' href='#XMPP-CORE'>[XMPP&#8209;CORE]<span> (</span><span class='info'>Saint-Andre, P., &ldquo;Extensible Messaging and Presence Protocol (XMPP): Core,&rdquo; March&nbsp;2011.</span><span>)</span></a>, each resource that receives a roster push from the server is supposed to reply with an IQ stanza of type "result" or "error" (however, it is known that many existing clients do not reply to roster pushes).
998</p><div style='display: table; width: 0; margin-left: 3em; margin-right: auto'><pre>
999C: &lt;iq from='juliet@example.com/balcony'
1000 id='a78b4q6ha463'
1001 type='result'/&gt;
1002
1003C: &lt;iq from='juliet@example.com/chamber'
1004 id='x81g3bdy4n19'
1005 type='result'/&gt;
1006</pre></div>
1007<a name="roster-add-errors"></a><br /><hr />
1008<table summary="layout" cellpadding="0" cellspacing="2" class="TOCbug" align="right"><tr><td class="TOCbug"><a href="#toc">&nbsp;TOC&nbsp;</a></td></tr></table>
1009<a name="rfc.section.2.3.3"></a><h3>2.3.3.&nbsp;
1010Error Cases</h3>
1011
1012<p>If the server cannot successfully process the roster set, it MUST return a stanza error. The following error cases are defined. Naturally, other stanza errors can occur, such as &lt;internal-server-error/&gt; if the server experiences an internal problem with processing the roster get, or even &lt;not-allowed/&gt; if the server only allows roster modifications by means of a non-XMPP method such as a web interface.
1013</p>
1014<p>The server MUST return a &lt;forbidden/&gt; stanza error to the client if the sender of the roster set is not authorized to update the roster (where typically only an authenticated resource of the account itself is authorized).
1015</p>
1016<p>The server MUST return a &lt;bad-request/&gt; stanza error to the client if the roster set contains any of the following violations:
1017</p>
1018<p>
1019 </p>
1020<ol class="text">
1021<li>The &lt;query/&gt; element contains more than one &lt;item/&gt; child element.
1022</li>
1023<li>The &lt;item/&gt; element contains more than one &lt;group/&gt; element, but there are duplicate groups (one possible comparison method for determining duplicates is that described for XMPP resourceparts in <a class='info' href='#XMPP-ADDR'>[XMPP&#8209;ADDR]<span> (</span><span class='info'>Saint-Andre, P., &ldquo;Extensible Messaging and Presence Protocol (XMPP): Address Format,&rdquo; March&nbsp;2011.</span><span>)</span></a>).
1024</li>
1025</ol><p>
1026
1027</p>
1028<p>The server MUST return a &lt;not-acceptable/&gt; stanza error to the client if the roster set contains any of the following violations:
1029</p>
1030<p>
1031 </p>
1032<ol class="text">
1033<li>The length of the 'name' attribute is greater than a server-configured limit.
1034</li>
1035<li>The XML character data of the &lt;group/&gt; element is of zero length (to remove an item from all groups, the client instead needs to exclude any &lt;group/&gt; element from the roster set).
1036</li>
1037<li>The XML character data of the &lt;group/&gt; element is larger than a server-configured limit.
1038</li>
1039</ol><p>
1040
1041</p>
1042<p>Error: Roster set initiated by unauthorized entity
1043</p><div style='display: table; width: 0; margin-left: 3em; margin-right: auto'><pre>
1044C: &lt;iq from='juliet@example.com/balcony'
1045 id='ix7s53v2'
1046 to='romeo@example.net'
1047 type='set'&gt;
1048 &lt;query xmlns='jabber:iq:roster'&gt;
1049 &lt;item jid='nurse@example.com'/&gt;
1050 &lt;/query&gt;
1051 &lt;/iq&gt;
1052
1053S: &lt;iq id='ix7s53v2'
1054 to='juliet@example.com/balcony'
1055 type='error'&gt;
1056 &lt;error type='auth'&gt;
1057 &lt;forbidden xmlns='urn:ietf:params:xml:ns:xmpp-stanzas'/&gt;
1058 &lt;/error&gt;
1059 &lt;/iq&gt;
1060</pre></div>
1061<p>Error: Roster set contains more than one item
1062</p><div style='display: table; width: 0; margin-left: 3em; margin-right: auto'><pre>
1063C: &lt;iq from='juliet@example.com/balcony'
1064 id='nw83vcj4'
1065 type='set'&gt;
1066 &lt;query xmlns='jabber:iq:roster'&gt;
1067 &lt;item jid='nurse@example.com'
1068 name='Nurse'&gt;
1069 &lt;group&gt;Servants&lt;/group&gt;
1070 &lt;/item&gt;
1071 &lt;item jid='mother@example.com'
1072 name='Mom'&gt;
1073 &lt;group&gt;Family&lt;/group&gt;
1074 &lt;/item&gt;
1075 &lt;/query&gt;
1076 &lt;/iq&gt;
1077
1078S: &lt;iq id='nw83vcj4'
1079 to='juliet@example.com/balcony'
1080 type='error'&gt;
1081 &lt;error type='modify'&gt;
1082 &lt;bad-request xmlns='urn:ietf:params:xml:ns:xmpp-stanzas'/&gt;
1083 &lt;/error&gt;
1084 &lt;/iq&gt;
1085</pre></div>
1086<p>Error: Roster set contains item with oversized handle
1087</p><div style='display: table; width: 0; margin-left: 3em; margin-right: auto'><pre>
1088C: &lt;iq from='juliet@example.com/balcony'
1089 id='yl491b3d'
1090 type='set'&gt;
1091 &lt;query xmlns='jabber:iq:roster'&gt;
1092 &lt;item jid='nurse@example.com'
1093 name='[ ... some-very-long-handle ... ]'&gt;
1094 &lt;group&gt;Servants&lt;/group&gt;
1095 &lt;/item&gt;
1096 &lt;/query&gt;
1097 &lt;/iq&gt;
1098
1099S: &lt;iq id='yl491b3d'
1100 to='juliet@example.com/balcony'
1101 type='error'&gt;
1102 &lt;error type='modify'&gt;
1103 &lt;not-acceptable xmlns='urn:ietf:params:xml:ns:xmpp-stanzas'/&gt;
1104 &lt;/error&gt;
1105 &lt;/iq&gt;
1106</pre></div>
1107<p>Error: Roster set contains duplicate groups
1108</p><div style='display: table; width: 0; margin-left: 3em; margin-right: auto'><pre>
1109C: &lt;iq from='juliet@example.com/balcony'
1110 id='tk3va749'
1111 type='set'&gt;
1112 &lt;query xmlns='jabber:iq:roster'&gt;
1113 &lt;item jid='nurse@example.com'
1114 name='Nurse'&gt;
1115 &lt;group&gt;Servants&lt;/group&gt;
1116 &lt;group&gt;Servants&lt;/group&gt;
1117 &lt;/item&gt;
1118 &lt;/query&gt;
1119 &lt;/iq&gt;
1120
1121S: &lt;iq id='tk3va749'
1122 to='juliet@example.com/balcony'
1123 type='error'&gt;
1124 &lt;error type='modify'&gt;
1125 &lt;bad-request xmlns='urn:ietf:params:xml:ns:xmpp-stanzas'/&gt;
1126 &lt;/error&gt;
1127 &lt;/iq&gt;
1128</pre></div>
1129<p>Error: Roster set contains empty group
1130</p><div style='display: table; width: 0; margin-left: 3em; margin-right: auto'><pre>
1131C: &lt;iq from='juliet@example.com/balcony'
1132 id='fl3b486u'
1133 type='set'&gt;
1134 &lt;query xmlns='jabber:iq:roster'&gt;
1135 &lt;item jid='nurse@example.com'
1136 name='Nurse'&gt;
1137 &lt;group&gt;&lt;/group&gt;
1138 &lt;/item&gt;
1139 &lt;/query&gt;
1140 &lt;/iq&gt;
1141
1142S: &lt;iq id='fl3b486u'
1143 to='juliet@example.com/balcony'
1144 type='error'&gt;
1145 &lt;error type='modify'&gt;
1146 &lt;not-acceptable xmlns='urn:ietf:params:xml:ns:xmpp-stanzas'/&gt;
1147 &lt;/error&gt;
1148 &lt;/iq&gt;
1149</pre></div>
1150<p>Error: Roster set contains oversized group name
1151</p><div style='display: table; width: 0; margin-left: 3em; margin-right: auto'><pre>
1152C: &lt;iq from='juliet@example.com/balcony'
1153 id='qh3b4v19'
1154 type='set'&gt;
1155 &lt;query xmlns='jabber:iq:roster'&gt;
1156 &lt;item jid='nurse@example.com'
1157 name='Nurse'&gt;
1158 &lt;group&gt;[ ... some-very-long-group-name ... ]&lt;/group&gt;
1159 &lt;/item&gt;
1160 &lt;/query&gt;
1161 &lt;/iq&gt;
1162
1163S: &lt;iq id='qh3b4v19'
1164 to='juliet@example.com/balcony'
1165 type='error'&gt;
1166 &lt;error type='modify'&gt;
1167 &lt;not-acceptable xmlns='urn:ietf:params:xml:ns:xmpp-stanzas'/&gt;
1168 &lt;/error&gt;
1169 &lt;/iq&gt;
1170</pre></div>
1171<p></p>
1172<blockquote class="text">
1173<p>Interoperability Note: Some servers return a &lt;not-allowed/&gt; stanza error to the client if the value of the &lt;item/&gt; element's 'jid' attribute matches the bare JID &lt;localpart@domainpart&gt; of the user's account.
1174</p>
1175</blockquote>
1176
1177<a name="roster-update"></a><br /><hr />
1178<table summary="layout" cellpadding="0" cellspacing="2" class="TOCbug" align="right"><tr><td class="TOCbug"><a href="#toc">&nbsp;TOC&nbsp;</a></td></tr></table>
1179<a name="rfc.section.2.4"></a><h3>2.4.&nbsp;
1180Updating a Roster Item</h3>
1181
1182<a name="roster-update-request"></a><br /><hr />
1183<table summary="layout" cellpadding="0" cellspacing="2" class="TOCbug" align="right"><tr><td class="TOCbug"><a href="#toc">&nbsp;TOC&nbsp;</a></td></tr></table>
1184<a name="rfc.section.2.4.1"></a><h3>2.4.1.&nbsp;
1185Request</h3>
1186
1187<p>Updating an existing roster item is done in the same way as adding a new roster item, i.e., by sending a roster set to the server. Because a roster item is atomic, the item MUST be updated exactly as provided in the roster set.
1188</p>
1189<p>There are several reasons why a client might update a roster item:
1190</p>
1191<p>
1192 </p>
1193<ol class="text">
1194<li>Adding a group
1195</li>
1196<li>Deleting a group
1197</li>
1198<li>Changing the handle
1199</li>
1200<li>Deleting the handle
1201</li>
1202</ol><p>
1203
1204</p>
1205<p>Consider a roster item that is defined as follows:
1206</p><div style='display: table; width: 0; margin-left: 3em; margin-right: auto'><pre>
1207 &lt;item jid='romeo@example.net'
1208 name='Romeo'&gt;
1209 &lt;group&gt;Friends&lt;/group&gt;
1210 &lt;/item&gt;
1211</pre></div>
1212<p>The user who has this item in her roster might want to add the item to another group.
1213</p><div style='display: table; width: 0; margin-left: 3em; margin-right: auto'><pre>
1214C: &lt;iq from='juliet@example.com/balcony'
1215 id='di43b2x9'
1216 type='set'&gt;
1217 &lt;query xmlns='jabber:iq:roster'&gt;
1218 &lt;item jid='romeo@example.net'
1219 name='Romeo'&gt;
1220 &lt;group&gt;Friends&lt;/group&gt;
1221 &lt;group&gt;Lovers&lt;/group&gt;
1222 &lt;/item&gt;
1223 &lt;/query&gt;
1224 &lt;/iq&gt;
1225</pre></div>
1226<p>Sometime later, the user might want to remove the item from the original group.
1227</p><div style='display: table; width: 0; margin-left: 3em; margin-right: auto'><pre>
1228C: &lt;iq from='juliet@example.com/balcony'
1229 id='lf72v157'
1230 type='set'&gt;
1231 &lt;query xmlns='jabber:iq:roster'&gt;
1232 &lt;item jid='romeo@example.net'
1233 name='Romeo'&gt;
1234 &lt;group&gt;Lovers&lt;/group&gt;
1235 &lt;/item&gt;
1236 &lt;/query&gt;
1237 &lt;/iq&gt;
1238</pre></div>
1239<p>The user might want to remove the item from all groups.
1240</p><div style='display: table; width: 0; margin-left: 3em; margin-right: auto'><pre>
1241C: &lt;iq from='juliet@example.com/balcony'
1242 id='ju4b62a5'
1243 type='set'&gt;
1244 &lt;query xmlns='jabber:iq:roster'&gt;
1245 &lt;item jid='romeo@example.net'/&gt;
1246 &lt;/query&gt;
1247 &lt;/iq&gt;
1248</pre></div>
1249<p>The user might also want to change the handle for the item.
1250</p><div style='display: table; width: 0; margin-left: 3em; margin-right: auto'><pre>
1251C: &lt;iq from='juliet@example.com/balcony'
1252 id='gb3sv487'
1253 type='set'&gt;
1254 &lt;query xmlns='jabber:iq:roster'&gt;
1255 &lt;item jid='romeo@example.net'
1256 name='MyRomeo'/&gt;
1257 &lt;/query&gt;
1258 &lt;/iq&gt;
1259</pre></div>
1260<p>The user might then want to remove the handle altogether.
1261</p><div style='display: table; width: 0; margin-left: 3em; margin-right: auto'><pre>
1262C: &lt;iq from='juliet@example.com/balcony'
1263 id='o3bx66s5'
1264 type='set'&gt;
1265 &lt;query xmlns='jabber:iq:roster'&gt;
1266 &lt;item jid='romeo@example.net'
1267 name=''/&gt;
1268 &lt;/query&gt;
1269 &lt;/iq&gt;
1270</pre></div>
1271<p></p>
1272<blockquote class="text">
1273<p>Implementation Note: Including an empty 'name' attribute is equivalent to including no 'name' attribute; both actions set the name to the empty string.
1274</p>
1275</blockquote>
1276
1277<a name="roster-update-success"></a><br /><hr />
1278<table summary="layout" cellpadding="0" cellspacing="2" class="TOCbug" align="right"><tr><td class="TOCbug"><a href="#toc">&nbsp;TOC&nbsp;</a></td></tr></table>
1279<a name="rfc.section.2.4.2"></a><h3>2.4.2.&nbsp;
1280Success Case</h3>
1281
1282<p>As with adding a roster item, if the roster item can be successfully processed then the server MUST update the item in the user's roster, send a roster push to all of the user's interested resources, and send an IQ result to the initiating resource; details are provided under <a class='info' href='#roster-add'>Section&nbsp;2.3<span> (</span><span class='info'>Adding a Roster Item</span><span>)</span></a>.
1283</p>
1284<a name="roster-update-error"></a><br /><hr />
1285<table summary="layout" cellpadding="0" cellspacing="2" class="TOCbug" align="right"><tr><td class="TOCbug"><a href="#toc">&nbsp;TOC&nbsp;</a></td></tr></table>
1286<a name="rfc.section.2.4.3"></a><h3>2.4.3.&nbsp;
1287Error Cases</h3>
1288
1289<p>The error cases described under <a class='info' href='#roster-add-errors'>Section&nbsp;2.3.3<span> (</span><span class='info'>Error Cases</span><span>)</span></a> also apply to updating a roster item.
1290</p>
1291<a name="roster-delete"></a><br /><hr />
1292<table summary="layout" cellpadding="0" cellspacing="2" class="TOCbug" align="right"><tr><td class="TOCbug"><a href="#toc">&nbsp;TOC&nbsp;</a></td></tr></table>
1293<a name="rfc.section.2.5"></a><h3>2.5.&nbsp;
1294Deleting a Roster Item</h3>
1295
1296<a name="roster-delete-request"></a><br /><hr />
1297<table summary="layout" cellpadding="0" cellspacing="2" class="TOCbug" align="right"><tr><td class="TOCbug"><a href="#toc">&nbsp;TOC&nbsp;</a></td></tr></table>
1298<a name="rfc.section.2.5.1"></a><h3>2.5.1.&nbsp;
1299Request</h3>
1300
1301<p>At any time, a client can delete an item from his or her roster by sending a roster set and specifying a value of "remove" for the 'subscription' attribute.
1302</p><div style='display: table; width: 0; margin-left: 3em; margin-right: auto'><pre>
1303C: &lt;iq from='juliet@example.com/balcony'
1304 id='hm4hs97y'
1305 type='set'&gt;
1306 &lt;query xmlns='jabber:iq:roster'&gt;
1307 &lt;item jid='nurse@example.com'
1308 subscription='remove'/&gt;
1309 &lt;/query&gt;
1310 &lt;/iq&gt;
1311</pre></div>
1312<a name="roster-delete-success"></a><br /><hr />
1313<table summary="layout" cellpadding="0" cellspacing="2" class="TOCbug" align="right"><tr><td class="TOCbug"><a href="#toc">&nbsp;TOC&nbsp;</a></td></tr></table>
1314<a name="rfc.section.2.5.2"></a><h3>2.5.2.&nbsp;
1315Success Case</h3>
1316
1317<p>As with adding a roster item, if the server can successfully process the roster set then it MUST update the item in the user's roster, send a roster push to all of the user's interested resources (with the 'subscription' attribute set to a value of "remove"), and send an IQ result to the initiating resource; details are provided under <a class='info' href='#roster-add'>Section&nbsp;2.3<span> (</span><span class='info'>Adding a Roster Item</span><span>)</span></a>.
1318</p>
1319<p>In addition, the user's server might need to generate one or more subscription-related presence stanzas, as follows:
1320</p>
1321<p>
1322 </p>
1323<ol class="text">
1324<li>If the user has a presence subscription to the contact, then the user's server MUST send a presence stanza of type "unsubscribe" to the contact (in order to unsubscribe from the contact's presence).
1325</li>
1326<li>If the contact has a presence subscription to the user, then the user's server MUST send a presence stanza of type "unsubscribed" to the contact (in order to cancel the contact's subscription to the user).
1327</li>
1328<li>If the presence subscription is mutual, then the user's server MUST send both a presence stanza of type "unsubscribe" and a presence stanza of type "unsubscribed" to the contact.
1329</li>
1330</ol><p>
1331
1332</p><div style='display: table; width: 0; margin-left: 3em; margin-right: auto'><pre>
1333S: &lt;presence from='juliet@example.com'
1334 id='lm3ba81g'
1335 to='nurse@example.com'
1336 type='unsubscribe'/&gt;
1337
1338S: &lt;presence from='juliet@example.com'
1339 id='xb2c1v4k'
1340 to='nurse@example.com'
1341 type='unsubscribed'/&gt;
1342</pre></div>
1343<a name="roster-delete-error"></a><br /><hr />
1344<table summary="layout" cellpadding="0" cellspacing="2" class="TOCbug" align="right"><tr><td class="TOCbug"><a href="#toc">&nbsp;TOC&nbsp;</a></td></tr></table>
1345<a name="rfc.section.2.5.3"></a><h3>2.5.3.&nbsp;
1346Error Cases</h3>
1347
1348<p>If the value of the 'jid' attribute specifies an item that is not in the roster, then the server MUST return an &lt;item-not-found/&gt; stanza error.
1349</p>
1350<p>Error: Roster item not found
1351</p><div style='display: table; width: 0; margin-left: 3em; margin-right: auto'><pre>
1352C: &lt;iq from='juliet@example.com/balcony'
1353 id='uj4b1ca8'
1354 type='set'&gt;
1355 &lt;query xmlns='jabber:iq:roster'&gt;
1356 &lt;item jid='[ ... non-existent-jid ... ]'
1357 subscription='remove'/&gt;
1358 &lt;/query&gt;
1359 &lt;/iq&gt;
1360
1361S: &lt;iq id='uj4b1ca8'
1362 to='juliet@example.com/balcony'
1363 type='error'&gt;
1364 &lt;error type='modify'&gt;
1365 &lt;item-not-found
1366 xmlns='urn:ietf:params:xml:ns:xmpp-stanzas'/&gt;
1367 &lt;/error&gt;
1368 &lt;/iq&gt;
1369</pre></div>
1370<a name="roster-versioning"></a><br /><hr />
1371<table summary="layout" cellpadding="0" cellspacing="2" class="TOCbug" align="right"><tr><td class="TOCbug"><a href="#toc">&nbsp;TOC&nbsp;</a></td></tr></table>
1372<a name="rfc.section.2.6"></a><h3>2.6.&nbsp;
1373Roster Versioning</h3>
1374
1375<a name="roster-versioning-feature"></a><br /><hr />
1376<table summary="layout" cellpadding="0" cellspacing="2" class="TOCbug" align="right"><tr><td class="TOCbug"><a href="#toc">&nbsp;TOC&nbsp;</a></td></tr></table>
1377<a name="rfc.section.2.6.1"></a><h3>2.6.1.&nbsp;
1378Stream Feature</h3>
1379
1380<p>If a server supports roster versioning, then it MUST advertise the following stream feature during stream negotiation.
1381</p><div style='display: table; width: 0; margin-left: 3em; margin-right: auto'><pre>
1382&lt;ver xmlns='urn:xmpp:features:rosterver'/&gt;
1383</pre></div>
1384<p> The roster versioning stream feature is merely informative and
1385 therefore is never mandatory-to-negotiate.
1386</p>
1387<a name="roster-versioning-request"></a><br /><hr />
1388<table summary="layout" cellpadding="0" cellspacing="2" class="TOCbug" align="right"><tr><td class="TOCbug"><a href="#toc">&nbsp;TOC&nbsp;</a></td></tr></table>
1389<a name="rfc.section.2.6.2"></a><h3>2.6.2.&nbsp;
1390Request</h3>
1391
1392<p>If a client supports roster versioning and the server to which it has connected advertises support for roster versioning as described in the foregoing section, then the client SHOULD include the 'ver' element in its request for the roster. If the server does not advertise support for roster versioning, the client MUST NOT include the 'ver' attribute. If the client includes the 'ver' attribute in its roster get, it sets the attribute's value to the version ID associated with its last cache of the roster.
1393</p><div style='display: table; width: 0; margin-left: 3em; margin-right: auto'><pre>
1394C: &lt;iq from='romeo@example.net/home'
1395 id='r1h3vzp7'
1396 to='romeo@example.net'
1397 type='get'&gt;
1398 &lt;query xmlns='jabber:iq:roster' ver='ver14'/&gt;
1399 &lt;/iq&gt;
1400</pre></div>
1401<p>If the client has not yet cached the roster or the cache is lost or corrupted, but the client wishes to bootstrap the use of roster versioning, it MUST set the 'ver' attribute to the empty string (i.e., ver="").
1402</p>
1403<p>Naturally, if the client does not support roster versioning or does not wish to bootstrap the use of roster versioning, it will not include the 'ver' attribute.
1404</p>
1405<a name="roster-versioning-success"></a><br /><hr />
1406<table summary="layout" cellpadding="0" cellspacing="2" class="TOCbug" align="right"><tr><td class="TOCbug"><a href="#toc">&nbsp;TOC&nbsp;</a></td></tr></table>
1407<a name="rfc.section.2.6.3"></a><h3>2.6.3.&nbsp;
1408Success Case</h3>
1409
1410<p>Whether or not the roster has been modified since the version ID enumerated by the client, the server MUST either return the complete roster as described under <a class='info' href='#roster-syntax-actions-result'>Section&nbsp;2.1.4<span> (</span><span class='info'>Roster Result</span><span>)</span></a> (including a 'ver' attribute that signals the latest version) or return an empty IQ-result (thus indicating that any roster modifications will be sent via roster pushes, as described below). In general, unless returning the complete roster would (1) use less bandwidth than sending individual roster pushes to the client (e.g., if the roster contains only a few items) or (2) the server cannot associate the version ID with any previous version it has on file, the server SHOULD send an empty IQ-result and then send the modifications (if any) via roster pushes.
1411</p><div style='display: table; width: 0; margin-left: 3em; margin-right: auto'><pre>
1412S: &lt;iq from='romeo@example.net'
1413 id='r1h3vzp7'
1414 to='romeo@example.net/home'
1415 type='result'/&gt;
1416</pre></div>
1417<p></p>
1418<blockquote class="text">
1419<p>Implementation Note: This empty IQ-result is different from an empty &lt;query/&gt; element, thus disambiguating this usage from an empty roster.
1420</p>
1421</blockquote>
1422
1423<p>If roster versioning is enabled and the roster has not been modified since the version ID enumerated by the client, the server will simply not send any roster pushes to the client (until and unless some relevant event triggers a roster push during the lifetime of the client's session).
1424</p>
1425<p>If the roster has been modified since the version ID enumerated by the client, the server MUST then send one roster push to the client for each roster item that has been modified since the version ID enumerated by the client. (We call a roster push that is sent for purposes of roster version synchronization an "interim roster push".)
1426</p>
1427<p></p>
1428<blockquote class="text">
1429<p>Definition: A "roster modification" is any change to the roster data that would result in a roster push to a connected client. Therefore, internal states related to roster processing within the server that would not result in a roster push to a connected client do not necessitate a change to the version.
1430</p>
1431</blockquote>
1432<div style='display: table; width: 0; margin-left: 3em; margin-right: auto'><pre>
1433S: &lt;iq from='romeo@example.net'
1434 id='ah382g67'
1435 to='romeo@example.net/home'
1436 type='set'&gt;
1437 &lt;query xmlns='jabber:iq:roster' ver='ver34'&gt;
1438 &lt;item jid='tybalt@example.org' subscription='remove'/&gt;
1439 &lt;/query&gt;
1440 &lt;/iq&gt;
1441
1442S: &lt;iq from='romeo@example.net'
1443 id='b2gs90j5'
1444 to='romeo@example.net/home'
1445 type='set'&gt;
1446 &lt;query xmlns='jabber:iq:roster' ver='ver42'&gt;
1447 &lt;item jid='bill@example.org' subscription='both'/&gt;
1448 &lt;/query&gt;
1449 &lt;/iq&gt;
1450
1451S: &lt;iq from='romeo@example.net'
1452 id='c73gs419'
1453 to='romeo@example.net/home'
1454 type='set'&gt;
1455 &lt;query xmlns='jabber:iq:roster' ver='ver72'&gt;
1456 &lt;item jid='nurse@example.org'
1457 name='Nurse'
1458 subscription='to'&gt;
1459 &lt;group&gt;Servants&lt;/group&gt;
1460 &lt;/item&gt;
1461 &lt;/query&gt;
1462 &lt;/iq&gt;
1463
1464S: &lt;iq from='romeo@example.net'
1465 id='dh361f35'
1466 to='romeo@example.net/home'
1467 type='set'&gt;
1468 &lt;query xmlns='jabber:iq:roster' ver='ver96'&gt;
1469 &lt;item jid='juliet@example.org'
1470 name='Juliet'
1471 subscription='both'&gt;
1472 &lt;group&gt;VIPs&lt;/group&gt;
1473 &lt;/item&gt;
1474 &lt;/query&gt;
1475 &lt;/iq&gt;
1476</pre></div>
1477<p>These "interim roster pushes" can be understood as follows:
1478</p>
1479<p>
1480 </p>
1481<ol class="text">
1482<li>Imagine that the client had an active presence session for the entire time between its cached roster version (say, "ver14") and the new roster version (say, "ver96").
1483</li>
1484<li>During that time, the client might have received roster pushes related to various roster versions (which might have been, say, "ver51" and "ver79"). However, some of those roster pushes might have contained intermediate updates to the same roster item (e.g., modifications to the subscription state for bill@example.org from "none" to "to" and from "to" to "both").
1485</li>
1486<li>The interim roster pushes would not include all of the intermediate steps, only the final result of all modifications applied to each item while the client was in fact offline (which might have been, say, "ver34", "ver42", "ver72", and "ver96").
1487</li>
1488</ol><p>
1489
1490</p>
1491<p>The client MUST handle an "interim roster push" in the same way it handles any roster push (indeed, from the client's perspective it cannot tell the difference between an "interim" roster push and a "live" roster push and therefore it has no way of knowing when it has received all of the interim roster pushes). When requesting the roster after reconnection, the client SHOULD request the version associated with the last roster push it received during its previous session, not the version associated with the roster result it received at the start of its previous session.
1492</p>
1493<p>When roster versioning is enabled, the server MUST include the updated roster version with each roster push. Roster pushes MUST occur in order of modification and the version contained in a roster push MUST be unique. Even if the client has not included the 'ver' attribute in its roster gets or sets, the server SHOULD include the 'ver' attribute on all roster pushes and results that it sends to the client.
1494</p>
1495<p></p>
1496<blockquote class="text">
1497<p>Implementation Note: Guidelines and more detailed examples for roster versioning are provided in <a class='info' href='#XEP-0237'>[XEP&#8209;0237]<span> (</span><span class='info'>Saint-Andre, P. and D. Cridland, &ldquo;Roster Versioning,&rdquo; March&nbsp;2010.</span><span>)</span></a>.
1498</p>
1499</blockquote>
1500
1501<a name="sub"></a><br /><hr />
1502<table summary="layout" cellpadding="0" cellspacing="2" class="TOCbug" align="right"><tr><td class="TOCbug"><a href="#toc">&nbsp;TOC&nbsp;</a></td></tr></table>
1503<a name="rfc.section.3"></a><h3>3.&nbsp;
1504Managing Presence Subscriptions</h3>
1505
1506<p>In order to protect the privacy of XMPP users, presence information is disclosed only to other entities that a user has approved. When a user has agreed that another entity is allowed to view its presence, the entity is said to have a "subscription" to the user's presence. An entity that has a subscription to a user's presence or to which a user has a presence subscription is called a "contact" (in this document the term "contact" is also used in a less strict sense to refer to a potential contact or any item in a user's roster).
1507</p>
1508<p>In XMPP, a subscription lasts across presence sessions; indeed, it lasts until the contact unsubscribes or the user cancels the previously granted subscription. (This model is different from that used for presence subscriptions in the Session Initiation Protocol (SIP), as defined in <a class='info' href='#SIP-PRES'>[SIP&#8209;PRES]<span> (</span><span class='info'>Rosenberg, J., &ldquo;A Presence Event Package for the Session Initiation Protocol (SIP),&rdquo; August&nbsp;2004.</span><span>)</span></a>.)
1509</p>
1510<p>Subscriptions are managed within XMPP by sending presence stanzas containing specially defined attributes ("subscribe", "unsubscribe", "subscribed", and "unsubscribed").
1511</p>
1512<p></p>
1513<blockquote class="text">
1514<p>Implementation Note: When a server processes or generates an outbound presence stanza of type "subscribe", "subscribed", "unsubscribe", or "unsubscribed", the server MUST stamp the outgoing presence stanza with the bare JID &lt;localpart@domainpart&gt; of the sending entity, not the full JID &lt;localpart@domainpart/resourcepart&gt;. Enforcement of this rule simplifies the presence subscription model and helps to prevent presence leaks; for information about presence leaks, refer to the security considerations of <a class='info' href='#XMPP-CORE'>[XMPP&#8209;CORE]<span> (</span><span class='info'>Saint-Andre, P., &ldquo;Extensible Messaging and Presence Protocol (XMPP): Core,&rdquo; March&nbsp;2011.</span><span>)</span></a>.
1515</p>
1516</blockquote>
1517
1518<p>Subscription states are reflected in the rosters of both the user and the contact. This section does not cover every possible case related to presence subscriptions, and mainly narrates the protocol flows for bootstrapping a mutual subscription between a user and a contact. Complete details regarding subscription states can be found under <a class='info' href='#substates'>Appendix&nbsp;A<span> (</span><span class='info'>Subscription States</span><span>)</span></a>.
1519</p>
1520<a name="sub-request"></a><br /><hr />
1521<table summary="layout" cellpadding="0" cellspacing="2" class="TOCbug" align="right"><tr><td class="TOCbug"><a href="#toc">&nbsp;TOC&nbsp;</a></td></tr></table>
1522<a name="rfc.section.3.1"></a><h3>3.1.&nbsp;
1523Requesting a Subscription</h3>
1524
1525<p>A "subscription request" is a request from a user for authorization to permanently subscribe to a contact's presence information; syntactically it is a presence stanza whose 'type' attribute has a value of "subscribe". A subscription request is generated by a user's client, processed by the (potential) contact's server, and acted on by the contact via the contact's client. The workflow is described in the following sections.
1526</p>
1527<p></p>
1528<blockquote class="text">
1529<p>Implementation Note: Presence subscription requests are sent to available resources, whereas the roster pushes associated with subscription state changes are sent to interested resources. Therefore, if a resource wishes to receive both subscription requests and roster pushes, it MUST both send initial presence and request the roster.
1530</p>
1531</blockquote>
1532
1533<a name="sub-request-gen"></a><br /><hr />
1534<table summary="layout" cellpadding="0" cellspacing="2" class="TOCbug" align="right"><tr><td class="TOCbug"><a href="#toc">&nbsp;TOC&nbsp;</a></td></tr></table>
1535<a name="rfc.section.3.1.1"></a><h3>3.1.1.&nbsp;
1536Client Generation of Outbound Subscription Request</h3>
1537
1538<p>A user's client generates a subscription request by sending a presence stanza of type "subscribe" and specifying a 'to' address of the potential contact's bare JID &lt;contact@domainpart&gt;.
1539</p><div style='display: table; width: 0; margin-left: 3em; margin-right: auto'><pre>
1540UC: &lt;presence id='xk3h1v69'
1541 to='juliet@example.com'
1542 type='subscribe'/&gt;
1543</pre></div>
1544<p>When a user sends a presence subscription request to a potential instant messaging and presence contact, the value of the 'to' attribute MUST be a bare JID &lt;contact@domainpart&gt; rather than a full JID &lt;contact@domainpart/resourcepart&gt;, since the desired result is for the user to receive presence from all of the contact's resources, not merely the particular resource specified in the 'to' attribute. Use of bare JIDs also simplifies subscription processing, presence probes, and presence notifications by the user's server and the contact's server.
1545</p>
1546<p>For tracking purposes, a client SHOULD include an 'id' attribute in a presence subscription request.
1547</p>
1548<p></p>
1549<blockquote class="text">
1550<p>Implementation Note: Many XMPP clients prompt the user for information about the potential contact (e.g., "handle" and desired roster group) when generating an outbound presence subscription request and therefore send a roster set before sending the outbound presence subscription request. This behavior is OPTIONAL, because a client MAY instead wait until receiving the initial roster push from the server before uploading user-provided information about the contact. A server MUST process a roster set and outbound presence subscription request in either order (i.e., in whatever order generated by the client).
1551</p>
1552</blockquote>
1553
1554<a name="sub-request-outbound"></a><br /><hr />
1555<table summary="layout" cellpadding="0" cellspacing="2" class="TOCbug" align="right"><tr><td class="TOCbug"><a href="#toc">&nbsp;TOC&nbsp;</a></td></tr></table>
1556<a name="rfc.section.3.1.2"></a><h3>3.1.2.&nbsp;
1557Server Processing of Outbound Subscription Request</h3>
1558
1559<p>Upon receiving the outbound presence subscription request, the user's server MUST proceed as follows.
1560</p>
1561<p>
1562 </p>
1563<ol class="text">
1564<li>Before processing the request, the user's server MUST check the syntax of the JID contained in the 'to' attribute (however, it is known that some existing implementations do not perform this check). If the JID is of the form &lt;contact@domainpart/resourcepart&gt; instead of &lt;contact@domainpart&gt;, the user's server SHOULD treat it as if the request had been directed to the contact's bare JID and modify the 'to' address accordingly. The server MAY also verify that the JID adheres to the format defined in <a class='info' href='#XMPP-ADDR'>[XMPP&#8209;ADDR]<span> (</span><span class='info'>Saint-Andre, P., &ldquo;Extensible Messaging and Presence Protocol (XMPP): Address Format,&rdquo; March&nbsp;2011.</span><span>)</span></a> and possibly return a &lt;jid-malformed/&gt; stanza error.
1565</li>
1566<li>If the potential contact is hosted on the same server as the
1567user, then the server MUST adhere to the rules specified under <a class='info' href='#sub-request-inbound'>Section&nbsp;3.1.3<span> (</span><span class='info'>Server Processing of Inbound Subscription Request</span><span>)</span></a> when processing the subscription request and delivering it to the (local) contact.
1568</li>
1569<li>If the potential contact is hosted on a remote server, subject to local service policies the user's server MUST then route the stanza to that remote domain in accordance with core XMPP stanza processing rules. (This can result in returning an appropriate stanza error to the user, such as &lt;remote-server-timeout/&gt;.)
1570</li>
1571</ol><p>
1572
1573</p>
1574<p>As mentioned, before locally delivering or remotely routing the presence subscription request, the user's server MUST stamp the outbound subscription request with the bare JID &lt;user@domainpart&gt; of the user.
1575</p><div style='display: table; width: 0; margin-left: 3em; margin-right: auto'><pre>
1576US: &lt;presence from='romeo@example.net'
1577 id='xk3h1v69'
1578 to='juliet@example.com'
1579 type='subscribe'/&gt;
1580</pre></div>
1581<p>If the presence subscription request cannot be locally delivered or remotely routed (e.g., because the request is malformed, the local contact does not exist, the remote server does not exist, an attempt to contact the remote server times out, or any other error is determined or experienced by the user's server), then the user's server MUST return an appropriate error stanza to the user. An example follows.
1582</p><div style='display: table; width: 0; margin-left: 3em; margin-right: auto'><pre>
1583US: &lt;presence from='juliet@example.com'
1584 id='xk3h1v69'
1585 to='romeo@example.net'
1586 type='error'&gt;
1587 &lt;error type='modify'&gt;
1588 &lt;remote-server-not-found
1589 xmlns='urn:ietf:params:xml:ns:xmpp-stanzas'/&gt;
1590 &lt;/error&gt;
1591 &lt;/presence&gt;
1592</pre></div>
1593<p>After locally delivering or remotely routing the presence subscription request, the user's server MUST then send a roster push to all of the user's interested resources, containing the potential contact with a subscription state of "none" and with notation that the subscription is pending (via an 'ask' attribute whose value is "subscribe").
1594</p><div style='display: table; width: 0; margin-left: 3em; margin-right: auto'><pre>
1595US: &lt;iq id='b89c5r7ib574'
1596 to='romeo@example.net/foo'
1597 type='set'&gt;
1598 &lt;query xmlns='jabber:iq:roster'&gt;
1599 &lt;item ask='subscribe'
1600 jid='juliet@example.com'
1601 subscription='none'/&gt;
1602 &lt;/query&gt;
1603 &lt;/iq&gt;
1604
1605US: &lt;iq id='b89c5r7ib575'
1606 to='romeo@example.net/bar'
1607 type='set'&gt;
1608 &lt;query xmlns='jabber:iq:roster'&gt;
1609 &lt;item ask='subscribe'
1610 jid='juliet@example.com'
1611 subscription='none'/&gt;
1612 &lt;/query&gt;
1613 &lt;/iq&gt;
1614</pre></div>
1615<p>If a remote contact does not approve or deny the subscription request within some configurable amount of time, the user's server SHOULD resend the subscription request to the contact based on an implementation-specific algorithm (e.g., whenever a new resource becomes available for the user, or after a certain amount of time has elapsed); this helps to recover from transient, silent errors that might have occurred when the original subscription request was routed to the remote domain. When doing so, it is RECOMMENDED for the server to include an 'id' attribute so that it can track responses to the resent subscription request.
1616</p>
1617<a name="sub-request-inbound"></a><br /><hr />
1618<table summary="layout" cellpadding="0" cellspacing="2" class="TOCbug" align="right"><tr><td class="TOCbug"><a href="#toc">&nbsp;TOC&nbsp;</a></td></tr></table>
1619<a name="rfc.section.3.1.3"></a><h3>3.1.3.&nbsp;
1620Server Processing of Inbound Subscription Request</h3>
1621
1622<p>Before processing the inbound presence subscription request, the contact's server SHOULD check the syntax of the JID contained in the 'to' attribute. If the JID is of the form &lt;contact@domainpart/resourcepart&gt; instead of &lt;contact@domainpart&gt;, the contact's server SHOULD treat it as if the request had been directed to the contact's bare JID and modify the 'to' address accordingly. The server MAY also verify that the JID adheres to the format defined in <a class='info' href='#XMPP-ADDR'>[XMPP&#8209;ADDR]<span> (</span><span class='info'>Saint-Andre, P., &ldquo;Extensible Messaging and Presence Protocol (XMPP): Address Format,&rdquo; March&nbsp;2011.</span><span>)</span></a> and possibly return a &lt;jid-malformed/&gt; stanza error.
1623</p>
1624<p>When processing the inbound presence subscription request, the contact's server MUST adhere to the following rules:
1625</p>
1626<p>
1627 </p>
1628<ol class="text">
1629<li>Above all, the contact's server MUST NOT automatically approve subscription requests on the contact's behalf -- unless the contact has (a) pre-approved subscription requests from the user as described under <a class='info' href='#sub-preapproval'>Section&nbsp;3.4<span> (</span><span class='info'>Pre-Approving a Subscription Request</span><span>)</span></a>, (b) configured its account to automatically approve subscription requests, or (c) accepted an agreement with its service provider that allows automatic approval (for instance, via an employment agreement within an enterprise deployment). Instead, if a subscription request requires approval then the contact's server MUST deliver that request to the contact's available resource(s) for approval or denial by the contact.
1630</li>
1631<li>If the contact exists and the user already has a subscription to the contact's presence, then the contact's server MUST auto-reply on behalf of the contact by sending a presence stanza of type "subscribed" from the contact's bare JID to the user's bare JID. Likewise, if the contact previously sent a presence stanza of type "subscribed" and the contact's server treated that as indicating "pre-approval" for the user's presence subscription (see <a class='info' href='#sub-preapproval'>Section&nbsp;3.4<span> (</span><span class='info'>Pre-Approving a Subscription Request</span><span>)</span></a>), then the contact's server SHOULD also auto-reply on behalf of the contact.
1632 <div style='display: table; width: 0; margin-left: 3em; margin-right: auto'><pre>
1633CS: &lt;presence from='juliet@example.com'
1634 id='xk3h1v69'
1635 to='romeo@example.net'
1636 type='subscribed'/&gt;
1637</pre></div>
1638
1639</li>
1640<li>Otherwise, if there is at least one available resource associated with the contact when the subscription request is received by the contact's server, then the contact's server MUST send that subscription request to all available resources in accordance with <a class='info' href='#rules'>Section&nbsp;8<span> (</span><span class='info'>Server Rules for Processing XML Stanzas</span><span>)</span></a>.
1641
1642 As a way of acknowledging receipt of the presence subscription request, the contact's server MAY send a presence stanza of type "unavailable" from the bare JID of the contact to the bare JID of the user (the user's client MUST NOT assume that this acknowledgement provides presence information about the contact, since it comes from the contact's bare JID and is received before the subscription request has been approved).
1643</li>
1644<li>Otherwise, if the contact has no available resources when the subscription request is received by the contact's server, then the contact's server MUST keep a record of the complete presence stanza comprising the subscription request, including any extended content contained therein (see Section 8.4 of <a class='info' href='#XMPP-CORE'>[XMPP&#8209;CORE]<span> (</span><span class='info'>Saint-Andre, P., &ldquo;Extensible Messaging and Presence Protocol (XMPP): Core,&rdquo; March&nbsp;2011.</span><span>)</span></a>), and then deliver the request when the contact next has an available resource. The contact's server MUST continue to deliver the subscription request whenever the contact creates an available resource, until the contact either approves or denies the request. (The contact's server MUST NOT deliver more than one subscription request from any given user when the contact next has an available resource; e.g., if the user sends multiple subscription requests to the contact while the contact is offline, the contact's server SHOULD store only one of those requests, such as the first request or last request, and MUST deliver only one of the requests when the contact next has an available resource; this helps to prevent "subscription request spam".)
1645</li>
1646</ol><p>
1647
1648</p>
1649<p></p>
1650<blockquote class="text">
1651<p>Security Warning: Until and unless the contact approves the subscription request as described under <a class='info' href='#sub-request-handle'>Section&nbsp;3.1.4<span> (</span><span class='info'>Client Processing of Inbound Subscription Request</span><span>)</span></a>, the contact's server MUST NOT add an item for the user to the contact's roster.
1652</p>
1653</blockquote>
1654
1655<p></p>
1656<blockquote class="text">
1657<p>Security Warning: The mandate for the contact's server to store the complete stanza of the presence subscription request introduces the possibility of an application resource exhaustion attack (see Section 2.1.2 of <a class='info' href='#DOS'>[DOS]<span> (</span><span class='info'>Handley, M., Rescorla, E., and IAB, &ldquo;Internet Denial-of-Service Considerations,&rdquo; December&nbsp;2006.</span><span>)</span></a>), for example, by a rogue server or a coordinated group of users (e.g., a botnet) against the contact's server or particular contact. Server implementers are advised to consider the possibility of such attacks and provide tools for counteracting it, such as enabling service administrators to set limits on the number or size of inbound presence subscription requests that the server will store in aggregate or for any given contact.
1658</p>
1659</blockquote>
1660
1661<a name="sub-request-handle"></a><br /><hr />
1662<table summary="layout" cellpadding="0" cellspacing="2" class="TOCbug" align="right"><tr><td class="TOCbug"><a href="#toc">&nbsp;TOC&nbsp;</a></td></tr></table>
1663<a name="rfc.section.3.1.4"></a><h3>3.1.4.&nbsp;
1664Client Processing of Inbound Subscription Request</h3>
1665
1666<p>When an interactive client receives a subscription request, it MUST present the request to the natural person controlling the client (i.e., the "contact") for approval, unless the contact has explicitly configured the client to automatically approve or deny some or all subscription requests as described above. An automated client that is not controlled by a natural person will have its own application-specific rules for approving or denying subscription requests.
1667</p>
1668<p>A client approves a subscription request by sending a presence stanza of type "subscribed", which is processed as described under <a class='info' href='#sub-request-approvalout'>Section&nbsp;3.1.5<span> (</span><span class='info'>Server Processing of Outbound Subscription Approval</span><span>)</span></a> for the contact's server and <a class='info' href='#sub-request-approvalin'>Section&nbsp;3.1.6<span> (</span><span class='info'>Server Processing of Inbound Subscription Approval</span><span>)</span></a> for the user's server.
1669</p><div style='display: table; width: 0; margin-left: 3em; margin-right: auto'><pre>
1670CC: &lt;presence id='h4v1c4kj'
1671 to='romeo@example.net'
1672 type='subscribed'/&gt;
1673</pre></div>
1674<p>A client denies a subscription request by sending a presence stanza of type "unsubscribed", which is processed as described under <a class='info' href='#sub-cancel'>Section&nbsp;3.2<span> (</span><span class='info'>Canceling a Subscription</span><span>)</span></a> for both the contact's server and the user's server.
1675</p><div style='display: table; width: 0; margin-left: 3em; margin-right: auto'><pre>
1676CC: &lt;presence id='tb2m1b59'
1677 to='romeo@example.net'
1678 type='unsubscribed'/&gt;
1679</pre></div>
1680<p>For tracking purposes, a client SHOULD include an 'id' attribute in a subscription approval or subscription denial; this 'id' attribute MUST NOT mirror the 'id' attribute of the subscription request.
1681</p>
1682<a name="sub-request-approvalout"></a><br /><hr />
1683<table summary="layout" cellpadding="0" cellspacing="2" class="TOCbug" align="right"><tr><td class="TOCbug"><a href="#toc">&nbsp;TOC&nbsp;</a></td></tr></table>
1684<a name="rfc.section.3.1.5"></a><h3>3.1.5.&nbsp;
1685Server Processing of Outbound Subscription Approval</h3>
1686
1687<p>When the contact's client sends the subscription approval, the contact's server MUST stamp the outbound stanza with the bare JID &lt;contact@domainpart&gt; of the contact and locally deliver or remotely route the stanza to the user.
1688</p><div style='display: table; width: 0; margin-left: 3em; margin-right: auto'><pre>
1689CS: &lt;presence from='juliet@example.com'
1690 id='h4v1c4kj'
1691 to='romeo@example.net'
1692 type='subscribed'/&gt;
1693</pre></div>
1694<p>The contact's server then MUST send an updated roster push to all of the contact's interested resources, with the 'subscription' attribute set to a value of "from". (Here we assume that the contact does not already have a subscription to the user; if that were the case, the 'subscription' attribute would be set to a value of "both", as explained under <a class='info' href='#substates'>Appendix&nbsp;A<span> (</span><span class='info'>Subscription States</span><span>)</span></a>.)
1695</p><div style='display: table; width: 0; margin-left: 3em; margin-right: auto'><pre>
1696CS: &lt;iq id='a78b4q6ha463'
1697 to='juliet@example.com/balcony'
1698 type='set'&gt;
1699 &lt;query xmlns='jabber:iq:roster'&gt;
1700 &lt;item jid='romeo@example.net'
1701 subscription='from'/&gt;
1702 &lt;/query&gt;
1703 &lt;/iq&gt;
1704
1705CS: &lt;iq id='x81g3bdy4n19'
1706 to='juliet@example.com/chamber'
1707 type='set'&gt;
1708 &lt;query xmlns='jabber:iq:roster'&gt;
1709 &lt;item jid='romeo@example.net'
1710 subscription='from'/&gt;
1711 &lt;/query&gt;
1712 &lt;/iq&gt;
1713</pre></div>
1714<p>From the perspective of the contact, there now exists a subscription from the user, which is why the 'subscription' attribute is set to a value of "from". (Here we assume that the contact does not already have a subscription to the user; if that were the case, the 'subscription' attribute would be set to a value of "both", as explained under <a class='info' href='#substates'>Appendix&nbsp;A<span> (</span><span class='info'>Subscription States</span><span>)</span></a>.)
1715</p>
1716<p>The contact's server MUST then also send current presence to the user from each of the contact's available resources.
1717</p><div style='display: table; width: 0; margin-left: 3em; margin-right: auto'><pre>
1718CS: &lt;presence from='juliet@example.com/balcony'
1719 id='pw72bc5j'
1720 to='romeo@example.net'/&gt;
1721
1722CS: &lt;presence from='juliet@example.com/chamber'
1723 id='ux31da4q'
1724 to='romeo@example.net'/&gt;
1725</pre></div>
1726<p>In order to subscribe to the user's presence, the contact would then need to send a subscription request to the user. (XMPP clients will often automatically send the subscription request instead of requiring the contact to initiate the subscription request, since it is assumed that the desired end state is a mutual subscription.) Naturally, when the contact sends a subscription request to the user, the subscription states will be different from those shown in the foregoing examples (see <a class='info' href='#substates'>Appendix&nbsp;A<span> (</span><span class='info'>Subscription States</span><span>)</span></a>) and the roles will be reversed.
1727</p>
1728<a name="sub-request-approvalin"></a><br /><hr />
1729<table summary="layout" cellpadding="0" cellspacing="2" class="TOCbug" align="right"><tr><td class="TOCbug"><a href="#toc">&nbsp;TOC&nbsp;</a></td></tr></table>
1730<a name="rfc.section.3.1.6"></a><h3>3.1.6.&nbsp;
1731Server Processing of Inbound Subscription Approval</h3>
1732
1733<p>When the user's server receives a subscription approval, it MUST first check if the contact is in the user's roster with subscription='none' or subscription='from' and the 'ask' flag set to "subscribe" (i.e., a subscription state of "None + Pending Out", "None + Pending Out+In", or "From + Pending Out"; see <a class='info' href='#substates'>Appendix&nbsp;A<span> (</span><span class='info'>Subscription States</span><span>)</span></a>). If this check is successful, then the user's server MUST:
1734</p>
1735<p>
1736 </p>
1737<ol class="text">
1738<li>Deliver the inbound subscription approval to all of the user's interested resources (this helps to give the user's client(s) proper context regarding the subscription approval so that they can differentiate between a roster push originated by another of the user's resources and a subscription approval received from the contact). This MUST occur before sending the roster push described in the next step.
1739 <div style='display: table; width: 0; margin-left: 3em; margin-right: auto'><pre>
1740US: &lt;presence from='juliet@example.com'
1741 id='h4v1c4kj'
1742 to='romeo@example.net'
1743 type='subscribed'/&gt;
1744</pre></div>
1745
1746</li>
1747<li>Initiate a roster push to all of the user's interested resources, containing an updated roster item for the contact with the 'subscription' attribute set to a value of "to" (if the subscription state was "None + Pending Out" or "None + Pending Out+In") or "both" (if the subscription state was "From + Pending Out").
1748 <div style='display: table; width: 0; margin-left: 3em; margin-right: auto'><pre>
1749US: &lt;iq id='b89c5r7ib576'
1750 to='romeo@example.net/foo'
1751 type='set'&gt;
1752 &lt;query xmlns='jabber:iq:roster'&gt;
1753 &lt;item jid='juliet@example.com'
1754 subscription='to'/&gt;
1755 &lt;/query&gt;
1756 &lt;/iq&gt;
1757
1758US: &lt;iq id='b89c5r7ib577'
1759 to='romeo@example.net/bar'
1760 type='set'&gt;
1761 &lt;query xmlns='jabber:iq:roster'&gt;
1762 &lt;item jid='juliet@example.com'
1763 subscription='to'/&gt;
1764 &lt;/query&gt;
1765 &lt;/iq&gt;
1766</pre></div>
1767
1768
1769</li>
1770<li>The user's server MUST also deliver the available presence stanza received from each of the contact's available resources to each of the user's available resources.
1771 <div style='display: table; width: 0; margin-left: 3em; margin-right: auto'><pre>
1772[ ... to resource1 ... ]
1773
1774US: &lt;presence from='juliet@example.com/balcony'
1775 id='pw72bc5j'
1776 to='romeo@example.net'/&gt;
1777
1778[ ... to resource2 ... ]
1779
1780US: &lt;presence from='juliet@example.com/balcony'
1781 id='pw72bc5j'
1782 to='romeo@example.net'/&gt;
1783
1784[ ... to resource1 ... ]
1785
1786US: &lt;presence from='juliet@example.com/chamber'
1787 id='ux31da4q'
1788 to='romeo@example.net'/&gt;
1789
1790[ ... to resource2 ... ]
1791
1792US: &lt;presence from='juliet@example.com/chamber'
1793 id='ux31da4q'
1794 to='romeo@example.net'/&gt;
1795</pre></div>
1796
1797</li>
1798</ol><p>
1799
1800</p>
1801<p></p>
1802<blockquote class="text">
1803<p>Implementation Note: If the user's account has no available resources when the inbound subscription approval notification is received, the user's server MAY keep a record of the notification (ideally the complete presence stanza) and then deliver the notification when the account next has an available resource. This behavior provides more complete signaling to the user regarding the reasons for the roster change that occurred while the user was offline.
1804</p>
1805</blockquote>
1806
1807<p>Otherwise -- that is, if the user does not exist, if the contact is not in the user's roster, or if the contact is in the user's roster with a subscription state other than those described in the foregoing check -- then the user's server MUST silently ignore the subscription approval notification by not delivering it to the user, not modifying the user's roster, and not generating a roster push to the user's interested resources.
1808</p>
1809<p>From the perspective of the user, there now exists a subscription to the contact's presence (which is why the 'subscription' attribute is set to a value of "to").
1810</p>
1811<a name="sub-cancel"></a><br /><hr />
1812<table summary="layout" cellpadding="0" cellspacing="2" class="TOCbug" align="right"><tr><td class="TOCbug"><a href="#toc">&nbsp;TOC&nbsp;</a></td></tr></table>
1813<a name="rfc.section.3.2"></a><h3>3.2.&nbsp;
1814Canceling a Subscription</h3>
1815
1816<a name="sub-cancel-gen"></a><br /><hr />
1817<table summary="layout" cellpadding="0" cellspacing="2" class="TOCbug" align="right"><tr><td class="TOCbug"><a href="#toc">&nbsp;TOC&nbsp;</a></td></tr></table>
1818<a name="rfc.section.3.2.1"></a><h3>3.2.1.&nbsp;
1819Client Generation of Subscription Cancellation</h3>
1820
1821<p>If a contact would like to cancel a subscription that it has previously granted to a user, to cancel a subscription pre-approval (<a class='info' href='#sub-preapproval'>Section&nbsp;3.4<span> (</span><span class='info'>Pre-Approving a Subscription Request</span><span>)</span></a>), or to deny a subscription request, it sends a presence stanza of type "unsubscribed".
1822</p><div style='display: table; width: 0; margin-left: 3em; margin-right: auto'><pre>
1823CC: &lt;presence id='ij5b1v7g'
1824 to='romeo@example.net'
1825 type='unsubscribed'/&gt;
1826</pre></div>
1827<a name="sub-cancel-outbound"></a><br /><hr />
1828<table summary="layout" cellpadding="0" cellspacing="2" class="TOCbug" align="right"><tr><td class="TOCbug"><a href="#toc">&nbsp;TOC&nbsp;</a></td></tr></table>
1829<a name="rfc.section.3.2.2"></a><h3>3.2.2.&nbsp;
1830Server Processing of Outbound Subscription Cancellation</h3>
1831
1832<p>Upon receiving the outbound subscription cancellation, the contact's server MUST proceed as follows.
1833</p>
1834<p>
1835 </p>
1836<ol class="text">
1837<li>If the user's bare JID is not yet in the contact's roster or is in the contact's roster with a state of "None", "None + Pending Out", or "To", the contact's server SHOULD NOT route or deliver the presence stanza of type "unsubscribed" to the user and MUST NOT send presence notifications of type "unavailable" to the user as described below.
1838</li>
1839<li>If the user's bare JID is in the contact's roster with a state of "None", "None + Pending Out", or "To" and the 'approved' flag is set to "true" (thus signaling a subscription pre-approval as described under <a class='info' href='#sub-preapproval'>Section&nbsp;3.4<span> (</span><span class='info'>Pre-Approving a Subscription Request</span><span>)</span></a>), the contact's server MUST remove the pre-approval and MUST NOT route or deliver the presence stanza of type "unsubscribed" to the user.
1840</li>
1841<li>Otherwise, as shown in the following examples, the contact's server MUST route or deliver both presence notifications of type "unavailable" and presence stanzas of type "unsubscribed" to the user and MUST send a roster push to the contact.
1842</li>
1843</ol><p>
1844
1845</p>
1846<p>While the user is still subscribed to the contact's presence (i.e., before the contact's server routes or delivers the presence stanza of type "unsubscribed" to the user), the contact's server MUST send a presence stanza of type "unavailable" from all of the contact's online resources to the user.
1847</p><div style='display: table; width: 0; margin-left: 3em; margin-right: auto'><pre>
1848CS: &lt;presence from='juliet@example.com/balcony'
1849 id='i8bsg3h3'
1850 type='unavailable'/&gt;
1851
1852CS: &lt;presence from='juliet@example.com/chamber'
1853 id='bvx2c9mk'
1854 type='unavailable'/&gt;
1855</pre></div>
1856<p>Then the contact's server MUST route or deliver the presence stanza of type "unsubscribed" to the user, making sure to stamp the outbound subscription cancellation with the bare JID &lt;contact@domainpart&gt; of the contact.
1857</p><div style='display: table; width: 0; margin-left: 3em; margin-right: auto'><pre>
1858CS: &lt;presence from='juliet@example.com'
1859 id='ij5b1v7g'
1860 to='romeo@example.net'
1861 type='unsubscribed'/&gt;
1862</pre></div>
1863<p>The contact's server then MUST send a roster push with the updated roster item to all of the contact's interested resources, where the subscription state is now either "none" or "to" (see <a class='info' href='#substates'>Appendix&nbsp;A<span> (</span><span class='info'>Subscription States</span><span>)</span></a>).
1864</p><div style='display: table; width: 0; margin-left: 3em; margin-right: auto'><pre>
1865CS: &lt;iq id='pw3f2v175b34'
1866 to='juliet@example.com/balcony'
1867 type='set'&gt;
1868 &lt;query xmlns='jabber:iq:roster'&gt;
1869 &lt;item jid='romeo@example.net'
1870 subscription='none'/&gt;
1871 &lt;/query&gt;
1872 &lt;/iq&gt;
1873
1874CS: &lt;iq id='zu2y3f571v35'
1875 to='juliet@example.com/chamber'
1876 type='set'&gt;
1877 &lt;query xmlns='jabber:iq:roster'&gt;
1878 &lt;item jid='romeo@example.net'
1879 subscription='none'/&gt;
1880 &lt;/query&gt;
1881 &lt;/iq&gt;
1882</pre></div>
1883<a name="sub-cancel-inbound"></a><br /><hr />
1884<table summary="layout" cellpadding="0" cellspacing="2" class="TOCbug" align="right"><tr><td class="TOCbug"><a href="#toc">&nbsp;TOC&nbsp;</a></td></tr></table>
1885<a name="rfc.section.3.2.3"></a><h3>3.2.3.&nbsp;
1886Server Processing of Inbound Subscription Cancellation</h3>
1887
1888<p>When the user's server receives the inbound subscription cancellation, it MUST first check if the contact is in the user's roster with subscription='to' or subscription='both' (see <a class='info' href='#substates'>Appendix&nbsp;A<span> (</span><span class='info'>Subscription States</span><span>)</span></a>). If this check is successful, then the user's server MUST:
1889</p>
1890<p>
1891 </p>
1892<ol class="text">
1893<li>Deliver the inbound subscription cancellation to all of the user's interested resources (this helps to give the user's client(s) proper context regarding the subscription cancellation so that they can differentiate between a roster push originated by another of the user's resources and a subscription cancellation received from the contact). This MUST occur before sending the roster push described in the next step.
1894 <div style='display: table; width: 0; margin-left: 3em; margin-right: auto'><pre>
1895US: &lt;presence from='juliet@example.com'
1896 id='ij5b1v7g'
1897 to='romeo@example.net'
1898 type='unsubscribed'/&gt;
1899</pre></div>
1900
1901</li>
1902<li>Initiate a roster push to all of the user's interested resources, containing an updated roster item for the contact with the 'subscription' attribute set to a value of "none" (if the subscription state was "To" or "To + Pending In") or "from" (if the subscription state was "Both").
1903 <div style='display: table; width: 0; margin-left: 3em; margin-right: auto'><pre>
1904US: &lt;iq id='h37h3u1bv400'
1905 to='romeo@example.net/foo'
1906 type='set'&gt;
1907 &lt;query xmlns='jabber:iq:roster'&gt;
1908 &lt;item jid='juliet@example.com'
1909 subscription='none'/&gt;
1910 &lt;/query&gt;
1911 &lt;/iq&gt;
1912
1913US: &lt;iq id='h37h3u1bv401'
1914 to='romeo@example.net/bar'
1915 type='set'&gt;
1916 &lt;query xmlns='jabber:iq:roster'&gt;
1917 &lt;item jid='juliet@example.com'
1918 subscription='none'/&gt;
1919 &lt;/query&gt;
1920 &lt;/iq&gt;
1921</pre></div>
1922
1923
1924</li>
1925</ol><p>
1926
1927</p>
1928<p>The user's server MUST also deliver the inbound presence stanzas of type "unavailable".
1929</p>
1930<p></p>
1931<blockquote class="text">
1932<p>Implementation Note: If the user's account has no available resources when the inbound unsubscribed notification is received, the user's server MAY keep a record of the notification (ideally the complete presence stanza) and then deliver the notification when the account next has an available resource. This behavior provides more complete signaling to the user regarding the reasons for the roster change that occurred while the user was offline.
1933</p>
1934</blockquote>
1935
1936<p>Otherwise -- that is, if the user does not exist, if the contact is not in the user's roster, or if the contact is in the user's roster with a subscription state other than those described in the foregoing check -- then the user's server MUST silently ignore the unsubscribed notification by not delivering it to the user, not modifying the user's roster, and not generating a roster push to the user's interested resources.
1937</p>
1938<a name="sub-unsub"></a><br /><hr />
1939<table summary="layout" cellpadding="0" cellspacing="2" class="TOCbug" align="right"><tr><td class="TOCbug"><a href="#toc">&nbsp;TOC&nbsp;</a></td></tr></table>
1940<a name="rfc.section.3.3"></a><h3>3.3.&nbsp;
1941Unsubscribing</h3>
1942
1943<a name="sub-unsub-gen"></a><br /><hr />
1944<table summary="layout" cellpadding="0" cellspacing="2" class="TOCbug" align="right"><tr><td class="TOCbug"><a href="#toc">&nbsp;TOC&nbsp;</a></td></tr></table>
1945<a name="rfc.section.3.3.1"></a><h3>3.3.1.&nbsp;
1946Client Generation of Unsubscribe</h3>
1947
1948<p>If a user would like to unsubscribe from a contact's presence, it sends a presence stanza of type "unsubscribe".
1949</p><div style='display: table; width: 0; margin-left: 3em; margin-right: auto'><pre>
1950UC: &lt;presence id='ul4bs71n'
1951 to='juliet@example.com'
1952 type='unsubscribe'/&gt;
1953</pre></div>
1954<a name="sub-unsub-outbound"></a><br /><hr />
1955<table summary="layout" cellpadding="0" cellspacing="2" class="TOCbug" align="right"><tr><td class="TOCbug"><a href="#toc">&nbsp;TOC&nbsp;</a></td></tr></table>
1956<a name="rfc.section.3.3.2"></a><h3>3.3.2.&nbsp;
1957Server Processing of Outbound Unsubscribe</h3>
1958
1959<p>Upon receiving the outbound unsubscribe, the user's server MUST proceed as follows.
1960</p>
1961<p>
1962 </p>
1963<ol class="text">
1964<li>If the contact is hosted on the same server as the user, then
1965the server MUST adhere to the rules specified under <a class='info' href='#sub-unsub-inbound'>Section&nbsp;3.3.3<span> (</span><span class='info'>Server Processing of Inbound Unsubscribe</span><span>)</span></a> when processing the subscription request.
1966</li>
1967<li>If the contact is hosted on a remote server, subject to local service policies the user's server MUST then route the stanza to that remote domain in accordance with core XMPP stanza processing rules. (This can result in returning an appropriate stanza error to the user, such as &lt;remote-server-timeout/&gt;.)
1968</li>
1969</ol><p>
1970
1971</p>
1972<p>As mentioned, before locally delivering or remotely routing the unsubscribe, the user's server MUST stamp the stanza with the bare JID &lt;user@domainpart&gt; of the user.
1973</p><div style='display: table; width: 0; margin-left: 3em; margin-right: auto'><pre>
1974US: &lt;presence from='romeo@example.net'
1975 id='ul4bs71n'
1976 to='juliet@example.com'
1977 type='unsubscribe'/&gt;
1978</pre></div>
1979<p>The user's server then MUST send a roster push with the updated roster item to all of the user's interested resources, where the subscription state is now either "none" or "from" (see <a class='info' href='#substates'>Appendix&nbsp;A<span> (</span><span class='info'>Subscription States</span><span>)</span></a>).
1980</p><div style='display: table; width: 0; margin-left: 3em; margin-right: auto'><pre>
1981US: &lt;iq id='h37h3u1bv402'
1982 to='romeo@example.net/foo'
1983 type='set'&gt;
1984 &lt;query xmlns='jabber:iq:roster'&gt;
1985 &lt;item jid='juliet@example.com'
1986 subscription='none'/&gt;
1987 &lt;/query&gt;
1988 &lt;/iq&gt;
1989
1990US: &lt;iq to='romeo@example.net/bar'
1991 type='set'
1992 id='h37h3u1bv403'&gt;
1993 &lt;query xmlns='jabber:iq:roster'&gt;
1994 &lt;item jid='juliet@example.com'
1995 subscription='none'/&gt;
1996 &lt;/query&gt;
1997 &lt;/iq&gt;
1998</pre></div>
1999<a name="sub-unsub-inbound"></a><br /><hr />
2000<table summary="layout" cellpadding="0" cellspacing="2" class="TOCbug" align="right"><tr><td class="TOCbug"><a href="#toc">&nbsp;TOC&nbsp;</a></td></tr></table>
2001<a name="rfc.section.3.3.3"></a><h3>3.3.3.&nbsp;
2002Server Processing of Inbound Unsubscribe</h3>
2003
2004<p>When the contact's server receives the unsubscribe notification, it MUST first check if the user's bare JID is in the contact's roster with subscription='from' or subscription='both' (i.e., a subscription state of "From", "From + Pending Out", or "Both"; see <a class='info' href='#substates'>Appendix&nbsp;A<span> (</span><span class='info'>Subscription States</span><span>)</span></a>). If this check is successful, then the contact's server MUST:
2005</p>
2006<p>
2007 </p>
2008<ol class="text">
2009<li>Deliver the inbound unsubscribe to all of the contact's interested resources (this helps to give the contact's client(s) proper context regarding the unsubscribe so that they can differentiate between a roster push originated by another of the contact's resources and an unsubscribe received from the user). This MUST occur before sending the roster push described in the next step.
2010 <div style='display: table; width: 0; margin-left: 3em; margin-right: auto'><pre>
2011CS: &lt;presence from='romeo@example.net'
2012 id='ul4bs71n'
2013 to='juliet@example.com'
2014 type='unsubscribe'/&gt;
2015</pre></div>
2016
2017</li>
2018<li>Initiate a roster push to all of the contact's interested resources, containing an updated roster item for the user with the 'subscription' attribute set to a value of "none" (if the subscription state was "From" or "From + Pending Out") or "to" (if the subscription state was "Both").
2019 <div style='display: table; width: 0; margin-left: 3em; margin-right: auto'><pre>
2020CS: &lt;iq id='tn2b5893g1s4'
2021 to='juliet@example.com/balcony'
2022 type='set'&gt;
2023 &lt;query xmlns='jabber:iq:roster'&gt;
2024 &lt;item jid='romeo@example.net'
2025 subscription='none'/&gt;
2026 &lt;/query&gt;
2027 &lt;/iq&gt;
2028
2029CS: &lt;iq id='sp3b56n27hrp'
2030 to='juliet@example.com/chamber'
2031 type='set'&gt;
2032 &lt;query xmlns='jabber:iq:roster'&gt;
2033 &lt;item jid='romeo@example.net'
2034 subscription='none'/&gt;
2035 &lt;/query&gt;
2036 &lt;/iq&gt;
2037</pre></div>
2038
2039</li>
2040<li>Generate an outbound presence stanza of type "unavailable" from each of the contact's available resources to the user.
2041 <div style='display: table; width: 0; margin-left: 3em; margin-right: auto'><pre>
2042CS: &lt;presence from='juliet@example.com/balcony'
2043 id='o5v91w49'
2044 to='romeo@example.net'
2045 type='unavailable'/&gt;
2046
2047CS: &lt;presence from='juliet@example.com/chamber'
2048 id='n6b1c37k'
2049 to='romeo@example.net'
2050 type='unavailable'/&gt;
2051</pre></div>
2052
2053</li>
2054</ol><p>
2055
2056</p>
2057<p></p>
2058<blockquote class="text">
2059<p>Implementation Note: If the contact's account has no available resources when the inbound unsubscribe notification is received, the contact's server MAY keep a record of the notification (ideally the complete presence stanza) and then deliver the notification when the account next has an available resource. This behavior provides more complete signaling to the user regarding the reasons for the roster change that occurred while the user was offline.
2060</p>
2061</blockquote>
2062
2063<p>Otherwise -- that is, if the contact does not exist, if the user is not in the contact's roster, or if the user's bare JID is in the contact's roster with a subscription state other than those described in the foregoing check -- then the contact's server MUST silently ignore the unsubscribe stanza by not delivering it to the contact, not modifying the contact's roster, and not generating a roster push to the contact's interested resources. However, if the contact's server is keeping track of an inbound presence subscription request from the user to the contact but the user is not yet in the contact's roster (functionally equivalent to a subscription state of "None + Pending In" where the contact never added the user to the contact's roster), then the contact's server MUST simply remove any record of the inbound presence subscription request (it cannot remove the user from the contact's roster because the user was never added to the contact's roster).
2064</p>
2065<p></p>
2066<blockquote class="text">
2067<p>Implementation Note: The user's client MUST NOT depend on receiving the unavailable presence notification from the contact, since it MUST consider its presence subscription to the contact, and its presence information about the contact, to be null and void when it sends the presence stanza of type "unsubscribe" or when it receives the roster push triggered by the unsubscribe request.
2068</p>
2069</blockquote>
2070
2071<a name="sub-preapproval"></a><br /><hr />
2072<table summary="layout" cellpadding="0" cellspacing="2" class="TOCbug" align="right"><tr><td class="TOCbug"><a href="#toc">&nbsp;TOC&nbsp;</a></td></tr></table>
2073<a name="rfc.section.3.4"></a><h3>3.4.&nbsp;
2074Pre-Approving a Subscription Request</h3>
2075
2076<p>If a user has not received a subscription request from a contact, the user can "pre-approve" such a request so that it will be automatically approved by the user's server.
2077</p>
2078<p>Support for subscription pre-approvals is OPTIONAL on the part of clients and servers. If a server supports subscription pre-approvals, then it MUST advertise the following stream feature during stream negotiation.
2079</p><div style='display: table; width: 0; margin-left: 3em; margin-right: auto'><pre>
2080&lt;sub xmlns='urn:xmpp:features:pre-approval'/&gt;
2081</pre></div>
2082<p>The subscription pre-approval stream feature is merely informative and therefore is never mandatory-to-negotiate.
2083</p>
2084<a name="sub-preapproval-gen"></a><br /><hr />
2085<table summary="layout" cellpadding="0" cellspacing="2" class="TOCbug" align="right"><tr><td class="TOCbug"><a href="#toc">&nbsp;TOC&nbsp;</a></td></tr></table>
2086<a name="rfc.section.3.4.1"></a><h3>3.4.1.&nbsp;
2087Client Generation of Subscription Pre-Approval</h3>
2088
2089<p>If the server to which a client connects has advertised support for subscription pre-approvals, the client MAY generate a subscription pre-approval by sending a presence stanza of type "subscribed" to the contact.
2090</p><div style='display: table; width: 0; margin-left: 3em; margin-right: auto'><pre>
2091UC: &lt;presence id='pg81vx64'
2092 to='juliet@example.com'
2093 type='subscribed'/&gt;
2094</pre></div>
2095<p>If the server does not advertise support for subscription pre-approvals, the client MUST NOT attempt to pre-approve subscription requests from potential or actual contacts.
2096</p>
2097<a name="sub-preapproval-proc"></a><br /><hr />
2098<table summary="layout" cellpadding="0" cellspacing="2" class="TOCbug" align="right"><tr><td class="TOCbug"><a href="#toc">&nbsp;TOC&nbsp;</a></td></tr></table>
2099<a name="rfc.section.3.4.2"></a><h3>3.4.2.&nbsp;
2100Server Processing of Subscription Pre-Approval</h3>
2101
2102<p>Upon receiving the presence stanza of type "subscribed", the user's server MUST proceed as follows if it supports subscription pre-approvals.
2103</p>
2104<p>
2105 </p>
2106<ol class="text">
2107<li>If the contact is in the user's roster with a state of "Both", "From", or "From + Pending Out", the user's server MUST silently ignore the stanza.
2108</li>
2109<li>If the contact is in the user's roster with a state of "To + Pending In", "None + Pending In", or "None + Pending Out+In", the user's server MUST handle the stanza as a normal subscription approval (see under <a class='info' href='#sub-request-approvalout'>Section&nbsp;3.1.5<span> (</span><span class='info'>Server Processing of Outbound Subscription Approval</span><span>)</span></a>) by updating the existing roster item to a state of "Both", "From", or "From + Pending Out" (respectively), pushing the modified roster item to all of the user's interested resources, and routing the presence stanza of type "subscribed" to the contact.
2110</li>
2111<li>If the contact is in the user's roster with a state of "To", "None", or "None + Pending Out", the user's server MUST note the subscription pre-approval by setting the 'approved' flag to a value of "true", then push the modified roster item to all of the user's interested resources. However, the user's server MUST NOT route the presence stanza of type "subscribed" to the contact.
2112</li>
2113<li>If the contact is not yet in the user's roster, the user's server MUST create a roster item for the contact with a state of "None" and set the 'approved' flag to a value of "true", then push the roster item to all of the user's interested resources. However, the user's server MUST NOT route the presence stanza of type "subscribed" to the contact.
2114</li>
2115</ol><p>
2116
2117</p>
2118<p>An example of the roster push follows.
2119</p><div style='display: table; width: 0; margin-left: 3em; margin-right: auto'><pre>
2120US: &lt;iq id='h3bs81vs763f'
2121 to='romeo@example.net/bar'
2122 type='set'&gt;
2123 &lt;query xmlns='jabber:iq:roster'&gt;
2124 &lt;item approved='true'
2125 jid='juliet@example.com'
2126 subscription='none'/&gt;
2127 &lt;/query&gt;
2128 &lt;/iq&gt;
2129</pre></div>
2130<p>When the 'approved' flag is set to "true", the user's server MUST NOT deliver a presence stanza of type "subscribe" from the contact to the user, but instead MUST automatically respond to such a stanza on behalf of the user by returning a presence stanza of type "subscribed" from the bare JID of the user to the bare JID of the contact.
2131</p>
2132<p></p>
2133<blockquote class="text">
2134<p>Implementation Note: It is a matter of implementation or local service policy whether the server maintains a record of the subscription approval after it has received a presence subscription request from the contact. If the server does not maintain such a record, upon receiving the subscription request it will not include the 'approved' attribute in the roster item for the contact (i.e., in subsequent roster pushes and roster results). If the server maintains such a record, it will always include the 'approved' attribute (set to "true") in the roster item for the contact, until and unless the user sends a presence stanza of type "unsubscribed" to the contact (or removes the contact from the roster entirely).
2135</p>
2136</blockquote>
2137
2138<p></p>
2139<blockquote class="text">
2140<p>Implementation Note: A client can cancel a pre-approval by sending a presence stanza of type "unsubscribed", as described more fully under <a class='info' href='#sub-cancel'>Section&nbsp;3.2<span> (</span><span class='info'>Canceling a Subscription</span><span>)</span></a>. In this case, the user's server would send a roster push to all of the user's interested resources with the 'approved' attribute removed. (Alternatively, the client can simply remove the roster item entirely.)
2141</p>
2142</blockquote>
2143
2144<a name="presence"></a><br /><hr />
2145<table summary="layout" cellpadding="0" cellspacing="2" class="TOCbug" align="right"><tr><td class="TOCbug"><a href="#toc">&nbsp;TOC&nbsp;</a></td></tr></table>
2146<a name="rfc.section.4"></a><h3>4.&nbsp;
2147Exchanging Presence Information</h3>
2148
2149<a name="presence-fundamentals"></a><br /><hr />
2150<table summary="layout" cellpadding="0" cellspacing="2" class="TOCbug" align="right"><tr><td class="TOCbug"><a href="#toc">&nbsp;TOC&nbsp;</a></td></tr></table>
2151<a name="rfc.section.4.1"></a><h3>4.1.&nbsp;
2152Presence Fundamentals</h3>
2153
2154<p>The concept of presence refers to an entity's availability for communication over a network. At the most basic level, presence is a boolean "on/off" variable that signals whether an entity is available or unavailable for communication (the terms "online" and "offline" are also used). In XMPP, an entity's availability is signaled when its client generates a &lt;presence/&gt; stanza with no 'type' attribute, and an entity's lack of availability is signaled when its client generates a &lt;presence/&gt; stanza whose 'type' attribute has a value of "unavailable".
2155</p>
2156<p>XMPP presence typically follows a "publish-subscribe" or "observer" pattern, wherein an entity sends presence to its server, and its server then broadcasts that information to all of the entity's contacts who have a subscription to the entity's presence (in the terminology of <a class='info' href='#IMP-MODEL'>[IMP&#8209;MODEL]<span> (</span><span class='info'>Day, M., Rosenberg, J., and H. Sugano, &ldquo;A Model for Presence and Instant Messaging,&rdquo; February&nbsp;2000.</span><span>)</span></a>, an entity that generates presence is a "presentity" and the entities that receive presence are "subscribers"). A client generates presence for broadcast to all subscribed entities by sending a presence stanza to its server with no 'to' address, where the presence stanza has either no 'type' attribute or a 'type' attribute whose value is "unavailable". This kind of presence is called "broadcast presence". (A client can also send "directed presence", i.e., a presence stanza with a 'to' address; this is less common but is sometimes used to send presence to entities that are not subscribed to the user's presence; see <a class='info' href='#presence-directed'>Section&nbsp;4.6<span> (</span><span class='info'>Directed Presence</span><span>)</span></a>.)
2157</p>
2158<p>After a client completes the preconditions specified in <a class='info' href='#XMPP-CORE'>[XMPP&#8209;CORE]<span> (</span><span class='info'>Saint-Andre, P., &ldquo;Extensible Messaging and Presence Protocol (XMPP): Core,&rdquo; March&nbsp;2011.</span><span>)</span></a>, it can establish a "presence session" at its server by sending <a class='info' href='#presence-initial'>initial presence<span> (</span><span class='info'>Initial Presence</span><span>)</span></a>, where the presence session is terminated by sending <a class='info' href='#presence-unavailable'>unavailable presence<span> (</span><span class='info'>Unavailable Presence</span><span>)</span></a>. For the duration of its presence session, a connected resource (in the terminology of <a class='info' href='#XMPP-CORE'>[XMPP&#8209;CORE]<span> (</span><span class='info'>Saint-Andre, P., &ldquo;Extensible Messaging and Presence Protocol (XMPP): Core,&rdquo; March&nbsp;2011.</span><span>)</span></a>) is said to be an "available resource".
2159</p>
2160<p>In XMPP, applications that combine messaging and presence functionality, the default type of communication for which presence signals availability is messaging; however, it is not necessary for XMPP applications to combine messaging and presence functionality, and they can provide standalone presence features without messaging (in addition, XMPP servers do not require information about network availability in order to successfully route message and IQ stanzas).
2161</p>
2162<p></p>
2163<blockquote class="text">
2164<p>Informational Note: In the examples that follow, the user is &lt;juliet@example.com&gt;, she has two available resources ("balcony" and "chamber"), and she has three contacts in her roster with a subscription state of "from" or "both": &lt;romeo@example.net&gt;, &lt;mercutio@example.com&gt;, and &lt;benvolio@example.net&gt;.
2165</p>
2166</blockquote>
2167
2168<a name="presence-initial"></a><br /><hr />
2169<table summary="layout" cellpadding="0" cellspacing="2" class="TOCbug" align="right"><tr><td class="TOCbug"><a href="#toc">&nbsp;TOC&nbsp;</a></td></tr></table>
2170<a name="rfc.section.4.2"></a><h3>4.2.&nbsp;
2171Initial Presence</h3>
2172
2173<a name="presence-initial-gen"></a><br /><hr />
2174<table summary="layout" cellpadding="0" cellspacing="2" class="TOCbug" align="right"><tr><td class="TOCbug"><a href="#toc">&nbsp;TOC&nbsp;</a></td></tr></table>
2175<a name="rfc.section.4.2.1"></a><h3>4.2.1.&nbsp;
2176Client Generation of Initial Presence</h3>
2177
2178<p>After completing the preconditions described in <a class='info' href='#XMPP-CORE'>[XMPP&#8209;CORE]<span> (</span><span class='info'>Saint-Andre, P., &ldquo;Extensible Messaging and Presence Protocol (XMPP): Core,&rdquo; March&nbsp;2011.</span><span>)</span></a> (REQUIRED) and requesting the roster (RECOMMENDED), a client signals its availability for communication by sending "initial presence" to its server, i.e., a presence stanza with no 'to' address (indicating that it is meant to be broadcast by the server on behalf of the client) and no 'type' attribute (indicating the user's availability).
2179</p><div style='display: table; width: 0; margin-left: 3em; margin-right: auto'><pre>
2180UC: &lt;presence/&gt;
2181</pre></div>
2182<p>The initial presence stanza MAY contain the &lt;priority/&gt; element, the &lt;show/&gt; element, and one or more instances of the &lt;status/&gt; element, as well as extended content; details are provided under <a class='info' href='#presence-syntax'>Section&nbsp;4.7<span> (</span><span class='info'>Presence Syntax</span><span>)</span></a>.
2183</p>
2184<a name="presence-initial-outbound"></a><br /><hr />
2185<table summary="layout" cellpadding="0" cellspacing="2" class="TOCbug" align="right"><tr><td class="TOCbug"><a href="#toc">&nbsp;TOC&nbsp;</a></td></tr></table>
2186<a name="rfc.section.4.2.2"></a><h3>4.2.2.&nbsp;
2187Server Processing of Outbound Initial Presence</h3>
2188
2189<p>Upon receiving initial presence from a client, the user's server MUST send the initial presence stanza from the full JID &lt;user@domainpart/resourcepart&gt; of the user to all contacts that are subscribed to the user's presence; such contacts are those for which a JID is present in the user's roster with the 'subscription' attribute set to a value of "from" or "both".
2190</p><div style='display: table; width: 0; margin-left: 3em; margin-right: auto'><pre>
2191US: &lt;presence from='juliet@example.com/balcony'
2192 to='romeo@example.net'/&gt;
2193
2194US: &lt;presence from='juliet@example.com/balcony'
2195 to='mercutio@example.com'/&gt;
2196
2197US: &lt;presence from='juliet@example.com/balcony'
2198 to='benvolio@example.net'/&gt;
2199</pre></div>
2200<p>The user's server MUST also broadcast initial presence from the user's newly available resource to all of the user's available resources, including the resource that generated the presence notification in the first place (i.e., an entity is implicitly subscribed to its own presence).
2201</p><div style='display: table; width: 0; margin-left: 3em; margin-right: auto'><pre>
2202[... to the "balcony" resource ...]
2203
2204US: &lt;presence from='juliet@example.com/balcony'
2205 to='juliet@example.com'/&gt;
2206
2207[... to the "chamber" resource ...]
2208
2209US: &lt;presence from='juliet@example.com/balcony'
2210 to='juliet@example.com'/&gt;
2211</pre></div>
2212<p>In the absence of presence information about the user's contacts, the user's server MUST also send presence probes to the user's contacts on behalf of the user as specified under <a class='info' href='#presence-probe'>Section&nbsp;4.3<span> (</span><span class='info'>Presence Probes</span><span>)</span></a>.
2213</p>
2214<a name="presence-initial-inbound"></a><br /><hr />
2215<table summary="layout" cellpadding="0" cellspacing="2" class="TOCbug" align="right"><tr><td class="TOCbug"><a href="#toc">&nbsp;TOC&nbsp;</a></td></tr></table>
2216<a name="rfc.section.4.2.3"></a><h3>4.2.3.&nbsp;
2217Server Processing of Inbound Initial Presence</h3>
2218
2219<p>Upon receiving presence from the user, the contact's server MUST deliver the user's presence stanza to all of the contact's available resources.
2220</p><div style='display: table; width: 0; margin-left: 3em; margin-right: auto'><pre>
2221[ ... to resource1 ... ]
2222
2223CS: &lt;presence from='juliet@example.com/balcony'
2224 to='romeo@example.net'/&gt;
2225
2226[ ... to resource2 ... ]
2227
2228CS: &lt;presence from='juliet@example.com/balcony'
2229 to='romeo@example.net'/&gt;
2230</pre></div>
2231<a name="presence-initial-client"></a><br /><hr />
2232<table summary="layout" cellpadding="0" cellspacing="2" class="TOCbug" align="right"><tr><td class="TOCbug"><a href="#toc">&nbsp;TOC&nbsp;</a></td></tr></table>
2233<a name="rfc.section.4.2.4"></a><h3>4.2.4.&nbsp;
2234Client Processing of Initial Presence</h3>
2235
2236<p>When the contact's client receives presence from the user, the following behavior is suggested for interactive clients:
2237</p>
2238<p>
2239 </p>
2240<ol class="text">
2241<li>If the user's bare JID is in the contact's roster, display the presence information in an appropriate roster interface.
2242</li>
2243<li>If the user is not in the contact's roster but the contact and the user are actively exchanging message or IQ stanzas, display the presence information in the user interface for that communication session (see also <a class='info' href='#presence-directed'>Section&nbsp;4.6<span> (</span><span class='info'>Directed Presence</span><span>)</span></a> and <a class='info' href='#message-chat'>Section&nbsp;5.1<span> (</span><span class='info'>One-to-One Chat Sessions</span><span>)</span></a>).
2244</li>
2245<li>Otherwise, ignore the presence information and do not display it to the contact.
2246</li>
2247</ol><p>
2248
2249</p>
2250<a name="presence-probe"></a><br /><hr />
2251<table summary="layout" cellpadding="0" cellspacing="2" class="TOCbug" align="right"><tr><td class="TOCbug"><a href="#toc">&nbsp;TOC&nbsp;</a></td></tr></table>
2252<a name="rfc.section.4.3"></a><h3>4.3.&nbsp;
2253Presence Probes</h3>
2254
2255<p>A "presence probe" is a request for a contact's current presence information, sent on behalf of a user by the user's server; syntactically it is a presence stanza whose 'type' attribute has a value of "probe". In the context of presence subscriptions, the value of the 'from' address MUST be the bare JID of the subscribed user and the value of the 'to' address MUST be the bare JID of the contact to which the user is subscribed, since presence subscriptions are based on the bare JID.
2256</p><div style='display: table; width: 0; margin-left: 3em; margin-right: auto'><pre>
2257US: &lt;presence from='juliet@example.com'
2258 id='ign291v5'
2259 to='romeo@example.net'
2260 type='probe'/&gt;
2261</pre></div>
2262<p></p>
2263<blockquote class="text">
2264<p>Interoperability Note: RFC 3921 specified that probes are sent from the full JID, not the bare JID (a rule that was changed because subscriptions are based on the bare JID). Some existing implementations send from the full JID instead of the bare JID.
2265</p>
2266</blockquote>
2267
2268<p>Probes can also be sent by an entity that has received presence outside the context of a presence subscription, typically when the contact has sent directed presence as described under <a class='info' href='#presence-directed'>Section&nbsp;4.6<span> (</span><span class='info'>Directed Presence</span><span>)</span></a>; in this case the value of the 'from' or 'to' address can be a full JID instead of a bare JID. See <a class='info' href='#presence-directed'>Section&nbsp;4.6<span> (</span><span class='info'>Directed Presence</span><span>)</span></a> for a complete discussion.
2269</p>
2270<p>Presence probes SHOULD NOT be sent by a client, because in general a client will not need to send them since the task of gathering presence from a user's contacts is managed by the user's server. However, if a user's client generates an outbound presence probe then the user's server SHOULD route the probe (if the contact is at another server) or process the probe (if the contact is at the same server) and MUST NOT use its receipt of the presence probe from a connected client as the sole cause for returning a stanza or stream error to the client.
2271</p>
2272<a name="presence-probe-outbound"></a><br /><hr />
2273<table summary="layout" cellpadding="0" cellspacing="2" class="TOCbug" align="right"><tr><td class="TOCbug"><a href="#toc">&nbsp;TOC&nbsp;</a></td></tr></table>
2274<a name="rfc.section.4.3.1"></a><h3>4.3.1.&nbsp;
2275Server Generation of Outbound Presence Probe</h3>
2276
2277<p>When a server needs to discover the availability of a user's contact, it sends a presence probe from the bare JID &lt;user@domainpart&gt; of the user to the bare JID &lt;contact@domainpart&gt; of the contact.
2278</p>
2279<p></p>
2280<blockquote class="text">
2281<p>Implementation Note: Although presence probes are intended for sending to contacts (i.e., entities to which a user is subscribed), a server MAY send a presence probe to the full JID of an entity from which the user has received presence information during the current session.
2282</p>
2283</blockquote>
2284
2285<p>The user's server SHOULD send a presence probe whenever the user starts a new presence session by sending initial presence; however, the server MAY choose not to send the probe at that point if it has what it deems to be reliable and up-to-date presence information about the user's contacts (e.g., because the user has another available resource or because the user briefly logged off and on before the new presence session began). In addition, a server MAY periodically send a presence probe to a contact if it has not received presence information or other traffic from the contact in some configurable amount of time; this can help to prevent "ghost" contacts who appear to be online but in fact are not.
2286</p><div style='display: table; width: 0; margin-left: 3em; margin-right: auto'><pre>
2287US: &lt;presence from='juliet@example.com'
2288 id='ign291v5'
2289 to='romeo@example.net'
2290 type='probe'/&gt;
2291
2292US: &lt;presence from='juliet@example.com'
2293 id='xv291f38'
2294 to='mercutio@example.com'
2295 type='probe'/&gt;
2296</pre></div>
2297<p>Naturally, the user's server does not need to send a presence probe to a contact if the contact's account resides on the same server as the user, since the server possesses the contact's information locally.
2298</p>
2299<a name="presence-probe-inbound"></a><br /><hr />
2300<table summary="layout" cellpadding="0" cellspacing="2" class="TOCbug" align="right"><tr><td class="TOCbug"><a href="#toc">&nbsp;TOC&nbsp;</a></td></tr></table>
2301<a name="rfc.section.4.3.2"></a><h3>4.3.2.&nbsp;
2302Server Processing of Inbound Presence Probe</h3>
2303
2304<p>Upon receiving a presence probe to the contact's bare JID from the user's server on behalf of the user, the contact's server MUST reply as follows:
2305</p>
2306<p>
2307 </p>
2308<ol class="text">
2309<li>If the contact account does not exist or the user's bare JID is in the contact's roster with a subscription state other than "From", "From + Pending Out", or "Both" (as explained under <a class='info' href='#substates'>Appendix&nbsp;A<span> (</span><span class='info'>Subscription States</span><span>)</span></a>), then the contact's server SHOULD return a presence stanza of type "unsubscribed" in response to the presence probe (this will trigger a protocol flow for canceling the user's subscription to the contact as described under <a class='info' href='#sub-cancel'>Section&nbsp;3.2<span> (</span><span class='info'>Canceling a Subscription</span><span>)</span></a>; however, this MUST NOT result in cancellation of a subscription pre-approval as described under <a class='info' href='#sub-preapproval'>Section&nbsp;3.4<span> (</span><span class='info'>Pre-Approving a Subscription Request</span><span>)</span></a>). Here the 'from' address MUST be the bare JID of the contact, since specifying a full JID would constitute a presence leak as described in <a class='info' href='#XMPP-CORE'>[XMPP&#8209;CORE]<span> (</span><span class='info'>Saint-Andre, P., &ldquo;Extensible Messaging and Presence Protocol (XMPP): Core,&rdquo; March&nbsp;2011.</span><span>)</span></a>.
2310 <div style='display: table; width: 0; margin-left: 3em; margin-right: auto'><pre>
2311CS: &lt;presence from='mercutio@example.com'
2312 id='xv291f38'
2313 to='juliet@example.com'
2314 type='unsubscribed'/&gt;
2315</pre></div>
2316 However, if a server receives a presence probe from a configured domain of the server itself or another such trusted service, it MAY provide presence information about the user to that entity.
2317
2318</li>
2319<li>Else, if the contact has moved temporarily or permanently to another address, then the server SHOULD return a presence stanza of type "error" with a stanza error condition of &lt;redirect/&gt; (temporary) or &lt;gone/&gt; (permanent) that includes the new address of the contact.
2320 <div style='display: table; width: 0; margin-left: 3em; margin-right: auto'><pre>
2321CS: &lt;presence from='mercutio@example.com'
2322 id='xv291f38'
2323 to='juliet@example.com'
2324 type='error'&gt;
2325 &lt;error type='modify'&gt;
2326 &lt;gone xmlns='urn:ietf:params:xml:ns:xmpp-stanzas'&gt;
2327 xmpp:la-mer@example.com
2328 &lt;/gone&gt;
2329 &lt;/error&gt;
2330 &lt;/presence&gt;
2331</pre></div>
2332
2333</li>
2334<li>Else, if the contact has no available resources, then the server SHOULD reply to the presence probe by sending to the user a presence stanza of type "unavailable" (although sending unavailable presence here is preferable because it results in a deterministic answer to the probe, it is not mandatory because it can greatly increase the number of presence notifications generated by the contact's server). Here the 'from' address is the bare JID because there is no available resource associated with the contact.
2335
2336 If appropriate in accordance with local security policies this presence notification MAY include the full XML of the last unavailable presence stanza that the server received from the contact (including the 'id' of the original stanza), but if not then the presence notification SHOULD simply indicate that the contact is unavailable without any of the details originally provided. In any case, the presence notification returned to the probing entity SHOULD include information about the time when the last unavailable presence stanza was generated (formatted using the XMPP delayed delivery extension <a class='info' href='#DELAY'>[DELAY]<span> (</span><span class='info'>Saint-Andre, P., &ldquo;Delayed Delivery,&rdquo; September&nbsp;2009.</span><span>)</span></a>).
2337 <div style='display: table; width: 0; margin-left: 3em; margin-right: auto'><pre>
2338CS: &lt;presence from='mercutio@example.com'
2339 id='xv291f38'
2340 to='juliet@example.com'
2341 type='unavailable'&gt;
2342 &lt;delay xmlns='urn:xmpp:delay'
2343 stamp='2002-09-10T23:41:07Z'/&gt;
2344 &lt;/presence&gt;
2345</pre></div>
2346
2347</li>
2348<li>Else, if the contact has at least one available resource, then the server MUST reply to the presence probe by sending to the user the full XML of the last presence stanza with no 'to' attribute received by the server from each of the contact's available resources. Here the 'from' addresses are the full JIDs of each available resource.
2349 <div style='display: table; width: 0; margin-left: 3em; margin-right: auto'><pre>
2350CS: &lt;presence from='romeo@example.net/foo'
2351 id='hzf1v27k'
2352 to='juliet@example.com'/&gt;
2353
2354CS: &lt;presence from='romeo@example.net/bar'
2355 id='ps6t1fu3'
2356 to='juliet@example.com'&gt;
2357 &lt;show&gt;away&lt;/show&gt;
2358 &lt;/presence&gt;
2359</pre></div>
2360
2361</li>
2362</ol><p>
2363
2364</p>
2365<p></p>
2366<blockquote class="text">
2367<p>Implementation Note: By "full XML" is meant the complete stanza from the opening &lt;presence&gt; tag to the closing &lt;/presence&gt; tag, including all elements and attributes whether qualified by the content namespace or extended namespaces; however, in accordance with <a class='info' href='#XMPP-CORE'>[XMPP&#8209;CORE]<span> (</span><span class='info'>Saint-Andre, P., &ldquo;Extensible Messaging and Presence Protocol (XMPP): Core,&rdquo; March&nbsp;2011.</span><span>)</span></a>, the contact's server will need to transform the content namespace from 'jabber:client' to 'jabber:server' if it sends the complete stanza over a server-to-server stream.
2368</p>
2369</blockquote>
2370
2371<p>If the contact's server receives a presence probe addressed to a full JID of the contact, the server MUST NOT return presence information about any resource except the resource specified by the 'to' address of the probe. Rules #1 and #2 for a bare JID probe apply equally to the case of a full JID probe. If there is a resource matching the full JID and the probing entity has authorization via a presence subscription to see the contact's presence, then the server MUST return an available presence notification, which SHOULD communicate only the fact that the resource is available (not detailed information such as the &lt;show/&gt;, &lt;status/&gt;, &lt;priority/&gt;, or presence extensions).
2372</p>
2373<p>
2374 </p>
2375<div style='display: table; width: 0; margin-left: 3em; margin-right: auto'><pre>
2376CS: &lt;presence from='romeo@example.net/bar'
2377 to='lobby@chat.example.com'/&gt;
2378</pre></div><p>
2379
2380
2381</p>
2382<p></p>
2383<blockquote class="text">
2384<p>Implementation Note: See <a class='info' href='#presence-directed'>Section&nbsp;4.6<span> (</span><span class='info'>Directed Presence</span><span>)</span></a> regarding rules that supplement the foregoing for handling of directed presence.
2385</p>
2386</blockquote>
2387
2388<a name="presence-probe-inbound-id"></a><br /><hr />
2389<table summary="layout" cellpadding="0" cellspacing="2" class="TOCbug" align="right"><tr><td class="TOCbug"><a href="#toc">&nbsp;TOC&nbsp;</a></td></tr></table>
2390<a name="rfc.section.4.3.2.1"></a><h3>4.3.2.1.&nbsp;
2391Handling of the 'id' Attribute</h3>
2392
2393<p>The handling of the 'id' attribute in relation to
2394 presence probes was unspecified in RFC 3921. Although the
2395 pattern of "send a probe and receive a reply" might seem
2396 like a request-response protocol similar to the XMPP
2397 &lt;iq/&gt; stanza, in fact it is not because the response
2398 to a probe might consist of multiple presence stanzas (one
2399 for each available resource currently active for the
2400 contact). For this reason, if the contact currently has
2401 available resources then the contact's server SHOULD
2402 preserve the 'id' attribute of the contact's original
2403 presence stanza (if any) when sending those presence
2404 notifications to the probing entity. By contrast, if the contact currently has no available resources, the probing entity is not authorized (via presence subscription) to see the contact's presence, or an error occurs in relation to the probe, then the contact's server SHOULD mirror the 'id' of the user's presence probe when replying to the probing entity.
2405</p>
2406<p>The following examples illustrate the difference.
2407</p>
2408<p>In the first scenario, Juliet sends presence from her "chamber" resource.
2409 </p>
2410<div style='display: table; width: 0; margin-left: 3em; margin-right: auto'><pre>
2411CC: &lt;presence from='juliet@example.com/chamber' id='pres1'&gt;
2412 &lt;show&gt;dnd&lt;/show&gt;
2413 &lt;status&gt;busy!&lt;/status&gt;
2414 &lt;/presence&gt;
2415</pre></div><p>
2416
2417
2418</p>
2419<p>She also sends presence from her "balcony" resource.
2420 </p>
2421<div style='display: table; width: 0; margin-left: 3em; margin-right: auto'><pre>
2422CC: &lt;presence from='juliet@example.com/balcony' id='pres2'&gt;
2423 &lt;show&gt;away&lt;/show&gt;
2424 &lt;status&gt;stepped away&lt;/status&gt;
2425 &lt;/presence&gt;
2426</pre></div><p>
2427
2428
2429</p>
2430<p>Romeo's server then sends a probe to Juliet.
2431 </p>
2432<div style='display: table; width: 0; margin-left: 3em; margin-right: auto'><pre>
2433US: &lt;presence from='romeo@example.net' id='probe1' type='probe'/&gt;
2434</pre></div><p>
2435
2436
2437</p>
2438<p>Juliet's server then sends both of her presence notifications to Romeo, preserving the 'id' attributes included in the stanzas that her client has sent.
2439 </p>
2440<div style='display: table; width: 0; margin-left: 3em; margin-right: auto'><pre>
2441CS: &lt;presence from='juliet@example.com/chamber' id='pres1'&gt;
2442 &lt;show&gt;dnd&lt;/show&gt;
2443 &lt;status&gt;busy!&lt;/status&gt;
2444 &lt;/presence&gt;
2445
2446CS: &lt;presence from='juliet@example.com/balcony' id='pres2'&gt;
2447 &lt;show&gt;away&lt;/show&gt;
2448 &lt;status&gt;stepped away&lt;/status&gt;
2449 &lt;/presence&gt;
2450</pre></div><p>
2451
2452
2453</p>
2454<p>In the second scenario, Juliet is offline when Romeo's server sends a probe.
2455 </p>
2456<div style='display: table; width: 0; margin-left: 3em; margin-right: auto'><pre>
2457US: &lt;presence from='romeo@example.net'
2458 id='probe2'
2459 type='probe'/&gt;
2460</pre></div><p>
2461
2462
2463</p>
2464<p>Juliet's server replies with an unavailable notification, mirroring the 'id' of Rome's presence probe because there is no 'id' to preserve from an available notification that her client has sent.
2465 </p>
2466<div style='display: table; width: 0; margin-left: 3em; margin-right: auto'><pre>
2467CS: &lt;presence from='juliet@example.com'
2468 id='probe2'
2469 type='unavailable'/&gt;
2470</pre></div><p>
2471
2472
2473</p>
2474<a name="presence-broadcast"></a><br /><hr />
2475<table summary="layout" cellpadding="0" cellspacing="2" class="TOCbug" align="right"><tr><td class="TOCbug"><a href="#toc">&nbsp;TOC&nbsp;</a></td></tr></table>
2476<a name="rfc.section.4.4"></a><h3>4.4.&nbsp;
2477Subsequent Presence Broadcast</h3>
2478
2479<a name="presence-broadcast-gen"></a><br /><hr />
2480<table summary="layout" cellpadding="0" cellspacing="2" class="TOCbug" align="right"><tr><td class="TOCbug"><a href="#toc">&nbsp;TOC&nbsp;</a></td></tr></table>
2481<a name="rfc.section.4.4.1"></a><h3>4.4.1.&nbsp;
2482Client Generation of Subsequent Presence Broadcast</h3>
2483
2484<p>After sending initial presence, at any time during its session the user's client can update its availability for broadcast by sending a presence stanza with no 'to' address and no 'type' attribute.
2485</p><div style='display: table; width: 0; margin-left: 3em; margin-right: auto'><pre>
2486UC: &lt;presence&gt;
2487 &lt;show&gt;away&lt;/show&gt;
2488 &lt;/presence&gt;
2489</pre></div>
2490<p>The presence broadcast MAY contain the &lt;priority/&gt; element, the &lt;show/&gt; element, and one or more instances of the &lt;status/&gt; element, as well as extended content; details are provided under <a class='info' href='#presence-syntax'>Section&nbsp;4.7<span> (</span><span class='info'>Presence Syntax</span><span>)</span></a>.
2491</p>
2492<p>However, a user SHOULD send a presence update only to broadcast information that is relevant to the user's availability for communication or the communication capabilities of the resource. Information that is not relevant in this way might be of interest to the user's contacts but SHOULD be sent via other means, such as the "publish-subscribe" method described in <a class='info' href='#XEP-0163'>[XEP&#8209;0163]<span> (</span><span class='info'>Saint-Andre, P. and K. Smith, &ldquo;Personal Eventing Protocol,&rdquo; July&nbsp;2010.</span><span>)</span></a>.
2493</p>
2494<a name="presence-broadcast-outbound"></a><br /><hr />
2495<table summary="layout" cellpadding="0" cellspacing="2" class="TOCbug" align="right"><tr><td class="TOCbug"><a href="#toc">&nbsp;TOC&nbsp;</a></td></tr></table>
2496<a name="rfc.section.4.4.2"></a><h3>4.4.2.&nbsp;
2497Server Processing of Subsequent Outbound Presence</h3>
2498
2499<p>Upon receiving a presence stanza expressing updated availability, the user's server MUST broadcast the full XML of that presence stanza to the contacts who are in the user's roster with a subscription type of "from" or "both".
2500</p>
2501<p></p>
2502<blockquote class="text">
2503<p>Interoperability Note: RFC 3921 specified that the user's server would check to make sure that it had not received a presence error from the contact before sending subsequent presence notifications. That rule has been removed because this specification uses presence stanzas of type "unsubscribe" (not "error") to solve subscription synchronization problems, in part because such stanzas change the contact's subscription state in the user's roster to either "none" or "to" (see <a class='info' href='#sub-unsub'>Section&nbsp;3.3<span> (</span><span class='info'>Unsubscribing</span><span>)</span></a> and <a class='info' href='#substates'>Appendix&nbsp;A<span> (</span><span class='info'>Subscription States</span><span>)</span></a>), thus obviating the need for the error check.
2504</p>
2505</blockquote>
2506
2507<p></p>
2508<blockquote class="text">
2509<p>Interoperability Note: If the subscription type is "both", some existing server implementations send subsequent presence notifications to a contact only if the contact is online according to the user's server (that is, if the user's server never received a positive indication that the contact is online in response to the presence probe it sent to the contact, the user's server does not send subsequent presence notifications from the user to the contact). This behavior is perceived to save bandwidth, since most presence subscriptions are bidirectional and many contacts will not be online at any given time.
2510</p>
2511</blockquote>
2512<div style='display: table; width: 0; margin-left: 3em; margin-right: auto'><pre>
2513US: &lt;presence from='juliet@example.com/balcony'
2514 to='romeo@example.net'&gt;
2515 &lt;show&gt;away&lt;/show&gt;
2516 &lt;/presence&gt;
2517
2518US: &lt;presence from='juliet@example.com/balcony'
2519 to='benvolio@example.net'&gt;
2520 &lt;show&gt;away&lt;/show&gt;
2521 &lt;/presence&gt;
2522
2523US: &lt;presence from='juliet@example.com/balcony'
2524 to='mercutio@example.com'&gt;
2525 &lt;show&gt;away&lt;/show&gt;
2526 &lt;/presence&gt;
2527</pre></div>
2528<p></p>
2529<blockquote class="text">
2530<p>Implementation Note: See <a class='info' href='#presence-directed'>Section&nbsp;4.6<span> (</span><span class='info'>Directed Presence</span><span>)</span></a> regarding rules that supplement the foregoing for handling of directed presence.
2531</p>
2532</blockquote>
2533
2534<p>The user's server MUST also send the presence stanza to all of the user's available resources (including the resource that generated the presence notification in the first place).
2535</p><div style='display: table; width: 0; margin-left: 3em; margin-right: auto'><pre>
2536US: &lt;presence from='juliet@example.com/balcony'
2537 to='juliet@example.com/chamber'&gt;
2538 &lt;show&gt;away&lt;/show&gt;
2539 &lt;/presence&gt;
2540
2541US: &lt;presence from='juliet@example.com/balcony'
2542 to='juliet@example.com/balcony'&gt;
2543 &lt;show&gt;away&lt;/show&gt;
2544 &lt;/presence&gt;
2545</pre></div>
2546<a name="presence-broadcast-inbound"></a><br /><hr />
2547<table summary="layout" cellpadding="0" cellspacing="2" class="TOCbug" align="right"><tr><td class="TOCbug"><a href="#toc">&nbsp;TOC&nbsp;</a></td></tr></table>
2548<a name="rfc.section.4.4.3"></a><h3>4.4.3.&nbsp;
2549Server Processing of Subsequent Inbound Presence</h3>
2550
2551<p>Upon receiving presence from the user, the contact's server MUST deliver the user's presence stanza to all of the contact's available resources.
2552</p><div style='display: table; width: 0; margin-left: 3em; margin-right: auto'><pre>
2553[ ... to resource1 ... ]
2554
2555CS: &lt;presence from='juliet@example.com/balcony'
2556 to='romeo@example.net'&gt;
2557 &lt;show&gt;away&lt;/show&gt;
2558 &lt;/presence&gt;
2559
2560[ ... to resource2 ... ]
2561
2562CS: &lt;presence from='juliet@example.com/balcony'
2563 to='romeo@example.net'&gt;
2564 &lt;show&gt;away&lt;/show&gt;
2565 &lt;/presence&gt;
2566</pre></div>
2567<a name="presence-broadcast-client"></a><br /><hr />
2568<table summary="layout" cellpadding="0" cellspacing="2" class="TOCbug" align="right"><tr><td class="TOCbug"><a href="#toc">&nbsp;TOC&nbsp;</a></td></tr></table>
2569<a name="rfc.section.4.4.4"></a><h3>4.4.4.&nbsp;
2570Client Processing of Subsequent Presence</h3>
2571
2572<p>From the perspective of the contact's client, there is no significant difference between initial presence broadcast and subsequent presence, so the contact's client follows the rules for processing of inbound presence defined under <a class='info' href='#presence-broadcast-inbound'>Section&nbsp;4.4.3<span> (</span><span class='info'>Server Processing of Subsequent Inbound Presence</span><span>)</span></a>.
2573</p>
2574<a name="presence-unavailable"></a><br /><hr />
2575<table summary="layout" cellpadding="0" cellspacing="2" class="TOCbug" align="right"><tr><td class="TOCbug"><a href="#toc">&nbsp;TOC&nbsp;</a></td></tr></table>
2576<a name="rfc.section.4.5"></a><h3>4.5.&nbsp;
2577Unavailable Presence</h3>
2578
2579<a name="presence-unavailable-gen"></a><br /><hr />
2580<table summary="layout" cellpadding="0" cellspacing="2" class="TOCbug" align="right"><tr><td class="TOCbug"><a href="#toc">&nbsp;TOC&nbsp;</a></td></tr></table>
2581<a name="rfc.section.4.5.1"></a><h3>4.5.1.&nbsp;
2582Client Generation of Unavailable Presence</h3>
2583
2584<p>Before ending its presence session with a server, the user's client SHOULD gracefully become unavailable by sending "unavailable presence", i.e., a presence stanza that possesses no 'to' attribute and that possesses a 'type' attribute whose value is "unavailable".
2585</p><div style='display: table; width: 0; margin-left: 3em; margin-right: auto'><pre>
2586UC: &lt;presence type='unavailable'/&gt;
2587</pre></div>
2588<p>Optionally, the unavailable presence stanza MAY contain one or more &lt;status/&gt; elements specifying the reason why the user is no longer available.
2589</p><div style='display: table; width: 0; margin-left: 3em; margin-right: auto'><pre>
2590UC: &lt;presence type='unavailable'&gt;
2591 &lt;status&gt;going on vacation&lt;/status&gt;
2592 &lt;/presence&gt;
2593</pre></div>
2594<p>However, the unavailable presence stanza MUST NOT contain the &lt;priority/&gt; element or the &lt;show/&gt; element, since these elements apply only to available resources.
2595</p>
2596<a name="presence-unavailable-outbound"></a><br /><hr />
2597<table summary="layout" cellpadding="0" cellspacing="2" class="TOCbug" align="right"><tr><td class="TOCbug"><a href="#toc">&nbsp;TOC&nbsp;</a></td></tr></table>
2598<a name="rfc.section.4.5.2"></a><h3>4.5.2.&nbsp;
2599Server Processing of Outbound Unavailable Presence</h3>
2600
2601<p>The user's server MUST NOT depend on receiving unavailable presence from an available resource, since the resource might become unavailable ungracefully (e.g., the resource's XML stream might be closed with or without a stream error for any of the reasons described in <a class='info' href='#XMPP-CORE'>[XMPP&#8209;CORE]<span> (</span><span class='info'>Saint-Andre, P., &ldquo;Extensible Messaging and Presence Protocol (XMPP): Core,&rdquo; March&nbsp;2011.</span><span>)</span></a>).
2602</p>
2603<p>If an available resource becomes unavailable for any reason (either gracefully or ungracefully), the user's server MUST broadcast unavailable presence to all contacts that are in the user's roster with a subscription type of "from" or "both".
2604</p>
2605<p></p>
2606<blockquote class="text">
2607<p>Interoperability Note: RFC 3921 specified that the user's server would check to make sure that it had not received a presence error from the contact before sending unavailable presence notifications. That rule has been removed because this specification uses presence stanzas of type "unsubscribe" (not "error") to solve subscription synchronization problems, in part because such stanzas change the contact's subscription state in the user's roster to either "none" or "to" (see <a class='info' href='#sub-unsub'>Section&nbsp;3.3<span> (</span><span class='info'>Unsubscribing</span><span>)</span></a> and <a class='info' href='#substates'>Appendix&nbsp;A<span> (</span><span class='info'>Subscription States</span><span>)</span></a>), thus obviating the need for the error check.
2608</p>
2609</blockquote>
2610
2611<p></p>
2612<blockquote class="text">
2613<p>Implementation Note: Even if the user's server does not broadcast the user's subsequent presence notifications to contacts who are offline (as described under <a class='info' href='#presence-broadcast-outbound'>Section&nbsp;4.4.2<span> (</span><span class='info'>Server Processing of Subsequent Outbound Presence</span><span>)</span></a>), it MUST broadcast the user's unavailable presence notification; if it did not do so, the last presence received by the contact's server would be the user's initial presence for the presence session, with the result that the contact would consider the user to be online.
2614</p>
2615</blockquote>
2616
2617<p></p>
2618<blockquote class="text">
2619<p>Implementation Note: See <a class='info' href='#presence-directed'>Section&nbsp;4.6<span> (</span><span class='info'>Directed Presence</span><span>)</span></a> regarding rules that supplement the foregoing for handling of directed presence.
2620</p>
2621</blockquote>
2622
2623<p>If the unavailable notification was gracefully received from the client, then the server MUST broadcast the full XML of the presence stanza.
2624</p><div style='display: table; width: 0; margin-left: 3em; margin-right: auto'><pre>
2625US: &lt;presence from='juliet@example.com/balcony'
2626 to='romeo@example.net'
2627 type='unavailable'&gt;
2628 &lt;status&gt;going on vacation&lt;/status&gt;
2629 &lt;/presence&gt;
2630
2631US: &lt;presence from='juliet@example.com/balcony'
2632 to='benvolio@example.net'
2633 type='unavailable'&gt;
2634 &lt;status&gt;going on vacation&lt;/status&gt;
2635 &lt;/presence&gt;
2636
2637US: &lt;presence from='juliet@example.com/balcony'
2638 to='mercutio@example.com'
2639 type='unavailable'&gt;
2640 &lt;status&gt;going on vacation&lt;/status&gt;
2641 &lt;/presence&gt;
2642</pre></div>
2643<p>The user's server MUST also send the unavailable notification to all of the user's available resources (as well as to the resource that generated the unavailable presence in the first place).
2644</p><div style='display: table; width: 0; margin-left: 3em; margin-right: auto'><pre>
2645US: &lt;presence from='juliet@example.com/balcony'
2646 to='juliet@example.com/chamber'
2647 type='unavailable'&gt;
2648 &lt;status&gt;going on vacation&lt;/status&gt;
2649 &lt;/presence&gt;
2650</pre></div>
2651<p>If the server detects that the user has gone offline ungracefully, then the server MUST generate the unavailable presence broadcast on the user's behalf.
2652</p>
2653<p></p>
2654<blockquote class="text">
2655<p>Implementation Note: Any presence stanza with no 'type' attribute and no 'to' attribute that the client sends after the server broadcasts or generates an unavailable presence notification MUST be routed or delivered by the user's server to all subscribers (i.e., MUST be treated as equivalent to initial presence for a new presence session).
2656</p>
2657</blockquote>
2658
2659<a name="presence-unavailable-inbound"></a><br /><hr />
2660<table summary="layout" cellpadding="0" cellspacing="2" class="TOCbug" align="right"><tr><td class="TOCbug"><a href="#toc">&nbsp;TOC&nbsp;</a></td></tr></table>
2661<a name="rfc.section.4.5.3"></a><h3>4.5.3.&nbsp;
2662Server Processing of Inbound Unavailable Presence</h3>
2663
2664<p>Upon receiving an unavailable notification from the user, the contact's server MUST deliver the user's presence stanza to all of the contact's available resources.
2665</p><div style='display: table; width: 0; margin-left: 3em; margin-right: auto'><pre>
2666[ ... to resource1 ... ]
2667
2668CS: &lt;presence from='juliet@example.com/balcony'
2669 to='romeo@example.net'
2670 type='unavailable'&gt;
2671 &lt;status&gt;going on vacation&lt;/status&gt;
2672 &lt;/presence&gt;
2673
2674[ ... to resource2 ... ]
2675
2676CS: &lt;presence from='juliet@example.com/balcony'
2677 to='romeo@example.net'
2678 type='unavailable'&gt;
2679 &lt;status&gt;going on vacation&lt;/status&gt;
2680 &lt;/presence&gt;
2681</pre></div>
2682<p></p>
2683<blockquote class="text">
2684<p>Implementation Note: If the contact's server does not broadcast subsequent presence notifications to users who are offline (as described under <a class='info' href='#presence-broadcast-outbound'>Section&nbsp;4.4.2<span> (</span><span class='info'>Server Processing of Subsequent Outbound Presence</span><span>)</span></a>), it MUST also update its internal representation of which entities are online by noting that the user is unavailable.
2685</p>
2686</blockquote>
2687
2688<a name="presence-unavailable-client"></a><br /><hr />
2689<table summary="layout" cellpadding="0" cellspacing="2" class="TOCbug" align="right"><tr><td class="TOCbug"><a href="#toc">&nbsp;TOC&nbsp;</a></td></tr></table>
2690<a name="rfc.section.4.5.4"></a><h3>4.5.4.&nbsp;
2691Client Processing of Unavailable Presence</h3>
2692
2693<p>From the perspective of the contact's client, there is no significant difference between available presence broadcast and unavailable presence broadcast, so in general the contact's client follows the rules for processing of inbound presence defined under <a class='info' href='#presence-broadcast-inbound'>Section&nbsp;4.4.3<span> (</span><span class='info'>Server Processing of Subsequent Inbound Presence</span><span>)</span></a>.
2694</p>
2695<p>However, if the contact receives an unavailable notification from the bare JID of the user (rather than the full JID of a particular available resource), the contact's client SHOULD treat the unavailable notification as applying to all resources.
2696</p>
2697<a name="presence-directed"></a><br /><hr />
2698<table summary="layout" cellpadding="0" cellspacing="2" class="TOCbug" align="right"><tr><td class="TOCbug"><a href="#toc">&nbsp;TOC&nbsp;</a></td></tr></table>
2699<a name="rfc.section.4.6"></a><h3>4.6.&nbsp;
2700Directed Presence</h3>
2701
2702<p>This section supplements the rules for client and server processing of presence notifications and presence probes, but only for the special case of directed presence.
2703</p>
2704<a name="presence-directed-considerations"></a><br /><hr />
2705<table summary="layout" cellpadding="0" cellspacing="2" class="TOCbug" align="right"><tr><td class="TOCbug"><a href="#toc">&nbsp;TOC&nbsp;</a></td></tr></table>
2706<a name="rfc.section.4.6.1"></a><h3>4.6.1.&nbsp;
2707General Considerations</h3>
2708
2709<p>In general, a client sends directed presence when it wishes to share availability information with an entity that is not subscribed to its presence, typically on a temporary basis. Common uses of directed presence include casual one-to-one chat sessions as described under <a class='info' href='#message-chat'>Section&nbsp;5.1<span> (</span><span class='info'>One-to-One Chat Sessions</span><span>)</span></a> and multi-user chat rooms as described in <a class='info' href='#XEP-0045'>[XEP&#8209;0045]<span> (</span><span class='info'>Saint-Andre, P., &ldquo;Multi-User Chat,&rdquo; July&nbsp;2008.</span><span>)</span></a>.
2710</p>
2711<p>The temporary relationship established by sharing directed presence with another entity is secondary to the permanent relationship established through a presence subscription. Therefore, the acts of creating, modifying, or canceling a presence subscription MUST take precedence over the rules specified in the following subsections. For example, if a user shares directed presence with a contact but then adds the contact to the user's roster by completing the presence subscription "handshake", the user's server MUST treat the contact just as it would any normal subscriber as described under <a class='info' href='#sub'>Section&nbsp;3<span> (</span><span class='info'>Managing Presence Subscriptions</span><span>)</span></a>, for example, by sending subsequent presence broadcasts to the contact. As another example, if the user then cancels the contact's subscription to the user's presence, the user's server MUST handle the cancellation just as it normally would as described under <a class='info' href='#sub-cancel'>Section&nbsp;3.2<span> (</span><span class='info'>Canceling a Subscription</span><span>)</span></a>, which includes sending unavailable presence to the contact even if the user has sent directed presence to the contact.
2712</p>
2713<p>XMPP servers typically implement directed presence by keeping a list of the entities (bare JIDs or full JIDs) to which a user has sent directed presence during the user's current session for a given resource (full JID), then clearing the list when the user goes offline (e.g., by sending a broadcast presence stanza of type "unavailable"). The server MUST remove from the directed presence list (or its functional equivalent) any entity to which the user sends directed unavailable presence and SHOULD remove any entity that sends unavailable presence to the user.
2714</p>
2715<a name="presence-directed-gen"></a><br /><hr />
2716<table summary="layout" cellpadding="0" cellspacing="2" class="TOCbug" align="right"><tr><td class="TOCbug"><a href="#toc">&nbsp;TOC&nbsp;</a></td></tr></table>
2717<a name="rfc.section.4.6.2"></a><h3>4.6.2.&nbsp;
2718Client Generation of Directed Presence</h3>
2719
2720<p>As noted, directed presence is a client-generated presence stanza with a 'to' attribute whose value is the bare JID or full JID of the other entity and with either no 'type' attribute (indicating availability) or a 'type' attribute whose value is "unavailable".
2721</p>
2722<a name="presence-directed-outbound"></a><br /><hr />
2723<table summary="layout" cellpadding="0" cellspacing="2" class="TOCbug" align="right"><tr><td class="TOCbug"><a href="#toc">&nbsp;TOC&nbsp;</a></td></tr></table>
2724<a name="rfc.section.4.6.3"></a><h3>4.6.3.&nbsp;
2725Server Processing of Outbound Directed Presence</h3>
2726
2727<p>When the user's server receives a directed presence stanza, it SHOULD process it according to the following rules.
2728</p>
2729<p>
2730 </p>
2731<ol class="text">
2732<li>If the user sends directed available or unavailable presence to a contact that is in the user's roster with a subscription type of "from" or "both" after having sent initial presence and before sending unavailable presence broadcast (i.e., during the user's presence session), the user's server MUST locally deliver or remotely route the full XML of that presence stanza but SHOULD NOT otherwise modify the contact's status regarding presence broadcast (i.e., it SHOULD include the contact's JID in any subsequent presence broadcasts initiated by the user).
2733</li>
2734<li>If the user sends directed presence to an entity that is not in the user's roster with a subscription type of "from" or "both" after having sent initial presence and before sending unavailable presence broadcast (i.e., during the user's presence session), the user's server MUST locally deliver or remotely route the full XML of that presence stanza to the entity but MUST NOT modify the contact's status regarding available presence broadcast (i.e., it MUST NOT include the entity's JID in any subsequent broadcasts of available presence initiated by the user); however, if the available resource from which the user sent the directed presence becomes unavailable, the user's server MUST route that unavailable presence to the entity (if the user has not yet sent directed unavailable presence to that entity).
2735</li>
2736<li>If the user sends directed presence without first sending initial presence or after having sent unavailable presence broadcast (i.e., the resource is connected but not available), the user's server MUST treat the entity to which the user sends directed presence as in case #2 above.
2737</li>
2738</ol><p>
2739
2740</p>
2741<a name="presence-directed-inbound"></a><br /><hr />
2742<table summary="layout" cellpadding="0" cellspacing="2" class="TOCbug" align="right"><tr><td class="TOCbug"><a href="#toc">&nbsp;TOC&nbsp;</a></td></tr></table>
2743<a name="rfc.section.4.6.4"></a><h3>4.6.4.&nbsp;
2744Server Processing of Inbound Directed Presence</h3>
2745
2746<p>From the perspective of the contact's server, there is no
2747significant difference between presence broadcast and directed presence, so the
2748contact's server follows the rules for processing of inbound presence defined
2749under Sections <a class='info' href='#presence-probe-inbound'>4.3.2<span> (</span><span class='info'>Server Processing of Inbound Presence Probe</span><span>)</span></a>, <a class='info' href='#presence-broadcast-inbound'>4.4.3<span> (</span><span class='info'>Server Processing of Subsequent Inbound Presence</span><span>)</span></a>, and <a class='info' href='#presence-unavailable-inbound'>4.5.3<span> (</span><span class='info'>Server Processing of Inbound Unavailable Presence</span><span>)</span></a>.
2750</p>
2751<a name="presence-directed-client"></a><br /><hr />
2752<table summary="layout" cellpadding="0" cellspacing="2" class="TOCbug" align="right"><tr><td class="TOCbug"><a href="#toc">&nbsp;TOC&nbsp;</a></td></tr></table>
2753<a name="rfc.section.4.6.5"></a><h3>4.6.5.&nbsp;
2754Client Processing of Inbound Directed Presence</h3>
2755
2756<p>From the perspective of the contact's client, there is no significant difference between presence broadcast and directed presence, so the contact's client follows the rules for processing of inbound presence defined under <a class='info' href='#presence-broadcast-inbound'>Section&nbsp;4.4.3<span> (</span><span class='info'>Server Processing of Subsequent Inbound Presence</span><span>)</span></a>.
2757</p>
2758<a name="presence-directed-probe"></a><br /><hr />
2759<table summary="layout" cellpadding="0" cellspacing="2" class="TOCbug" align="right"><tr><td class="TOCbug"><a href="#toc">&nbsp;TOC&nbsp;</a></td></tr></table>
2760<a name="rfc.section.4.6.6"></a><h3>4.6.6.&nbsp;
2761Server Processing of Presence Probes</h3>
2762
2763<p>If a user's client has sent directed presence to another entity (e.g., a one-to-one chat partner or a multi-user chat room), after some time the entity or its server might want to know if the client is still online. This scenario is especially common in the case of multi-user chat rooms, in which the user might be a participant for a long period of time. If the user's client goes offline without the chat room being informed (either by the client or the client's server), the user's representation in the room might become a "ghost" that appears to be participating but that in fact is no longer present in the room. To detect such "ghosts", some multi-user chat room implementations send presence probes to users that have joined the room.
2764</p>
2765<p>In the case of directed presence, the probing entity SHOULD send the probe from the JID that received directed presence (whether a full JID or a bare JID). The probe SHOULD be sent to the user's full JID, not the user's bare JID without a resourcepart, because the temporary "authorization" involved with directed presence is based on the full JID from which the user sent directed presence to the probing entity. When the user's server receives a probe, it MUST first apply any logic associated with presence subscriptions as described under <a class='info' href='#presence-probe-inbound'>Section&nbsp;4.3.2<span> (</span><span class='info'>Server Processing of Inbound Presence Probe</span><span>)</span></a>. If the probing entity does not have a subscription to the user's presence, then the server MUST check if the user has sent directed presence to the entity during its current session; if so, the server SHOULD answer the probe with only mere presence of type "available" or "unavailable" (i.e., not including child elements) and only for that full JID (i.e., not for any other resources that might be currently associated with the user's bare JID).
2766</p>
2767<a name="presence-syntax"></a><br /><hr />
2768<table summary="layout" cellpadding="0" cellspacing="2" class="TOCbug" align="right"><tr><td class="TOCbug"><a href="#toc">&nbsp;TOC&nbsp;</a></td></tr></table>
2769<a name="rfc.section.4.7"></a><h3>4.7.&nbsp;
2770Presence Syntax</h3>
2771
2772<a name="presence-syntax-type"></a><br /><hr />
2773<table summary="layout" cellpadding="0" cellspacing="2" class="TOCbug" align="right"><tr><td class="TOCbug"><a href="#toc">&nbsp;TOC&nbsp;</a></td></tr></table>
2774<a name="rfc.section.4.7.1"></a><h3>4.7.1.&nbsp;
2775Type Attribute</h3>
2776
2777<p>The absence of a 'type' attribute signals that the relevant entity is available for communication (see <a class='info' href='#presence-initial'>Section&nbsp;4.2<span> (</span><span class='info'>Initial Presence</span><span>)</span></a> and <a class='info' href='#presence-broadcast'>Section&nbsp;4.4<span> (</span><span class='info'>Subsequent Presence Broadcast</span><span>)</span></a>).
2778</p>
2779<p>A 'type' attribute with a value of "unavailable" signals that the relevant entity is not available for communication (see <a class='info' href='#presence-unavailable'>Section&nbsp;4.5<span> (</span><span class='info'>Unavailable Presence</span><span>)</span></a>).
2780</p>
2781<p>The XMPP presence stanza is also used to negotiate and manage subscriptions to the presence of other entities. These tasks are completed via presence stanzas of type "subscribe", "unsubscribe", "subscribed", and "unsubscribed" as described under <a class='info' href='#sub'>Section&nbsp;3<span> (</span><span class='info'>Managing Presence Subscriptions</span><span>)</span></a>.
2782</p>
2783<p>If a user and contact are associated with different XMPP servers, those servers also use a special presence stanza of type "probe" in order to determine the availability of the entity on the peer server; details are provided under <a class='info' href='#presence-probe'>Section&nbsp;4.3<span> (</span><span class='info'>Presence Probes</span><span>)</span></a>. Clients SHOULD NOT send presence stanzas of type "probe".
2784</p>
2785<p>The values of the 'type' attribute can be summarized as follows:
2786</p>
2787<p>
2788 </p>
2789<ul class="text">
2790<li>error -- An error has occurred regarding processing of a previously sent presence stanza; if the presence stanza is of type "error", it MUST include an &lt;error/&gt; child element (refer to <a class='info' href='#XMPP-CORE'>[XMPP&#8209;CORE]<span> (</span><span class='info'>Saint-Andre, P., &ldquo;Extensible Messaging and Presence Protocol (XMPP): Core,&rdquo; March&nbsp;2011.</span><span>)</span></a>).
2791</li>
2792<li>probe -- A request for an entity's current presence; SHOULD be generated only by a server on behalf of a user.
2793</li>
2794<li>subscribe -- The sender wishes to subscribe to the recipient's presence.
2795</li>
2796<li>subscribed -- The sender has allowed the recipient to receive their presence.
2797</li>
2798<li>unavailable -- The sender is no longer available for communication.
2799</li>
2800<li>unsubscribe -- The sender is unsubscribing from the receiver's presence.
2801</li>
2802<li>unsubscribed -- The subscription request has been denied or a previously granted subscription has been canceled.
2803</li>
2804</ul><p>
2805
2806</p>
2807<p>If the value of the 'type' attribute is not one of the foregoing values, the recipient or an intermediate router SHOULD return a stanza error of &lt;bad-request/&gt;.
2808</p>
2809<p></p>
2810<blockquote class="text">
2811<p>Implementation Note: There is no default value for the 'type' attribute of the &lt;presence/&gt; element.
2812</p>
2813</blockquote>
2814
2815<p></p>
2816<blockquote class="text">
2817<p>Implementation Note: There is no value of "available" for the 'type' attribute of the &lt;presence/&gt; element.
2818</p>
2819</blockquote>
2820
2821<a name="presence-syntax-children"></a><br /><hr />
2822<table summary="layout" cellpadding="0" cellspacing="2" class="TOCbug" align="right"><tr><td class="TOCbug"><a href="#toc">&nbsp;TOC&nbsp;</a></td></tr></table>
2823<a name="rfc.section.4.7.2"></a><h3>4.7.2.&nbsp;
2824Child Elements</h3>
2825
2826<p>In accordance with the default namespace declaration, a presence stanza is qualified by the 'jabber:client' or 'jabber:server' namespace, which defines certain child elements of presence stanzas, in particular the &lt;show/&gt;, &lt;status/&gt;, and &lt;priority/&gt; elements. These child elements are used to provide more detailed information about an entity's availability. Typically these child elements are included only if the presence stanza possesses no 'type' attribute, although exceptions are noted in the text that follows.
2827</p>
2828<a name="presence-syntax-children-show"></a><br /><hr />
2829<table summary="layout" cellpadding="0" cellspacing="2" class="TOCbug" align="right"><tr><td class="TOCbug"><a href="#toc">&nbsp;TOC&nbsp;</a></td></tr></table>
2830<a name="rfc.section.4.7.2.1"></a><h3>4.7.2.1.&nbsp;
2831Show Element</h3>
2832
2833<p>The OPTIONAL &lt;show/&gt; element specifies the particular availability sub-state of an entity or a specific resource thereof. A presence stanza MUST NOT contain more than one &lt;show/&gt; element. There are no attributes defined for the &lt;show/&gt; element. The &lt;show/&gt; element MUST NOT contain mixed content (as defined in Section 3.2.2 of <a class='info' href='#XML'>[XML]<span> (</span><span class='info'>Maler, E., Yergeau, F., Sperberg-McQueen, C., Paoli, J., and T. Bray, &ldquo;Extensible Markup Language (XML) 1.0 (Fifth Edition),&rdquo; November&nbsp;2008.</span><span>)</span></a>). The XML character data of the &lt;show/&gt; element is not meant for presentation to a human user. The XML character data MUST be one of the following (additional availability states could be defined through extended content elements):
2834</p>
2835<p>
2836 </p>
2837<ul class="text">
2838<li>away -- The entity or resource is temporarily away.
2839</li>
2840<li>chat -- The entity or resource is actively interested in chatting.
2841</li>
2842<li>dnd -- The entity or resource is busy (dnd = "Do Not Disturb").
2843</li>
2844<li>xa -- The entity or resource is away for an extended period (xa = "eXtended Away").
2845</li>
2846</ul><p>
2847
2848</p>
2849<p>If no &lt;show/&gt; element is provided, the entity is assumed to be online and available.
2850</p>
2851<p>Any specialized processing of availability states by recipients and intermediate routers is up to the implementation (e.g., incorporation of availability states into stanza routing and delivery logic).
2852</p>
2853<a name="presence-syntax-children-status"></a><br /><hr />
2854<table summary="layout" cellpadding="0" cellspacing="2" class="TOCbug" align="right"><tr><td class="TOCbug"><a href="#toc">&nbsp;TOC&nbsp;</a></td></tr></table>
2855<a name="rfc.section.4.7.2.2"></a><h3>4.7.2.2.&nbsp;
2856Status Element</h3>
2857
2858<p>The OPTIONAL &lt;status/&gt; element contains human-readable XML character data specifying a natural-language description of an entity's availability. It is normally used in conjunction with the show element to provide a detailed description of an availability state (e.g., "In a meeting") when the presence stanza has no 'type' attribute.
2859</p><div style='display: table; width: 0; margin-left: 3em; margin-right: auto'><pre>
2860&lt;presence from='romeo@example.net/orchard'
2861 xml:lang='en'&gt;
2862 &lt;show&gt;dnd&lt;/show&gt;
2863 &lt;status&gt;Wooing Juliet&lt;/status&gt;
2864&lt;/presence&gt;
2865</pre></div>
2866<p>There are no attributes defined for the &lt;status/&gt; element, with the exception of the 'xml:lang' attribute inherited from <a class='info' href='#XML'>[XML]<span> (</span><span class='info'>Maler, E., Yergeau, F., Sperberg-McQueen, C., Paoli, J., and T. Bray, &ldquo;Extensible Markup Language (XML) 1.0 (Fifth Edition),&rdquo; November&nbsp;2008.</span><span>)</span></a>. The &lt;status/&gt; element MUST NOT contain mixed content (as defined in Section 3.2.2 of <a class='info' href='#XML'>[XML]<span> (</span><span class='info'>Maler, E., Yergeau, F., Sperberg-McQueen, C., Paoli, J., and T. Bray, &ldquo;Extensible Markup Language (XML) 1.0 (Fifth Edition),&rdquo; November&nbsp;2008.</span><span>)</span></a>). Multiple instances of the &lt;status/&gt; element MAY be included, but only if each instance possesses an 'xml:lang' attribute with a distinct language value (either explicitly or by inheritance from the 'xml:lang' value of an element farther up in the XML hierarchy, which from the sender's perspective can include the XML stream header as described in <a class='info' href='#XMPP-CORE'>[XMPP&#8209;CORE]<span> (</span><span class='info'>Saint-Andre, P., &ldquo;Extensible Messaging and Presence Protocol (XMPP): Core,&rdquo; March&nbsp;2011.</span><span>)</span></a>).
2867</p><div style='display: table; width: 0; margin-left: 3em; margin-right: auto'><pre>
2868&lt;presence from='romeo@example.net/orchard'
2869 id='jx62vs97'
2870 xml:lang='en'&gt;
2871 &lt;show&gt;dnd&lt;/show&gt;
2872 &lt;status&gt;Wooing Juliet&lt;/status&gt;
2873 &lt;status xml:lang='cs'&gt;Dvo&amp;#x0159;&amp;#x00ED;m se Julii&lt;/status&gt;
2874&lt;/presence&gt;
2875</pre></div>
2876<p>A presence stanza of type "unavailable" MAY also include a &lt;status/&gt; element to provide detailed information about why the entity is going offline.
2877</p><div style='display: table; width: 0; margin-left: 3em; margin-right: auto'><pre>
2878&lt;presence from='romeo@example.net/orchard'
2879 id='oy6sb241'
2880 type='unavailable'
2881 xml:lang='en'&gt;
2882 &lt;status&gt;Busy IRL&lt;/status&gt;
2883&lt;/presence&gt;
2884</pre></div>
2885<p>The &lt;status/&gt; child MAY also be sent in a subscription-related presence stanza (i.e., type "subscribe", "subscribed", "unsubscribe", or "unsubscribed") to provide a description of the action. An interactive client MAY present this &lt;status/&gt; information to a human user (see <a class='info' href='#security'>Section&nbsp;11<span> (</span><span class='info'>Security Considerations</span><span>)</span></a>).
2886</p><div style='display: table; width: 0; margin-left: 3em; margin-right: auto'><pre>
2887&lt;presence from='romeo@example.net'
2888 id='uc51xs63'
2889 to='nurse@example.com'
2890 type='subscribe'&gt;
2891 &lt;status&gt;Hi, Juliet told me to add you to my buddy list.&lt;/status&gt;
2892&lt;/presence&gt;
2893</pre></div>
2894<a name="presence-syntax-children-priority"></a><br /><hr />
2895<table summary="layout" cellpadding="0" cellspacing="2" class="TOCbug" align="right"><tr><td class="TOCbug"><a href="#toc">&nbsp;TOC&nbsp;</a></td></tr></table>
2896<a name="rfc.section.4.7.2.3"></a><h3>4.7.2.3.&nbsp;
2897Priority Element</h3>
2898
2899<p>The OPTIONAL &lt;priority/&gt; element contains non-human-readable XML character data that specifies the priority level of the resource. The value MUST be an integer between -128 and +127. A presence stanza MUST NOT contain more than one &lt;priority/&gt; element. There are no attributes defined for the &lt;priority/&gt; element. The &lt;priority/&gt; element MUST NOT contain mixed content (as defined in Section 3.2.2 of <a class='info' href='#XML'>[XML]<span> (</span><span class='info'>Maler, E., Yergeau, F., Sperberg-McQueen, C., Paoli, J., and T. Bray, &ldquo;Extensible Markup Language (XML) 1.0 (Fifth Edition),&rdquo; November&nbsp;2008.</span><span>)</span></a>).
2900</p><div style='display: table; width: 0; margin-left: 3em; margin-right: auto'><pre>
2901&lt;presence xml:lang='en'&gt;
2902 &lt;show&gt;dnd&lt;/show&gt;
2903 &lt;status&gt;Wooing Juliet&lt;/status&gt;
2904 &lt;status xml:lang='cs'&gt;Dvo&amp;#x0159;&amp;#x00ED;m se Julii&lt;/status&gt;
2905 &lt;priority&gt;1&lt;/priority&gt;
2906&lt;/presence&gt;
2907</pre></div>
2908<p>If no priority is provided, the processing server or client MUST consider the priority to be zero ("0").
2909</p>
2910<p>The client's server MAY override the priority value
2911 provided by the client (e.g., in order to impose a message
2912 handling rule of delivering a message intended for the
2913 account's bare JID to all of the account's available
2914 resources). If the server does so, it MUST communicate the modified priority value when it echoes the client's presence back to itself and sends the presence notification to the user's contacts (because this modified priority value is typically the default value of zero, communicating the modified priority value can be done by not including the &lt;priority/&gt; child element).
2915</p>
2916<p>For information regarding the semantics of priority values in stanza processing within instant messaging and presence applications, refer to <a class='info' href='#rules'>Section&nbsp;8<span> (</span><span class='info'>Server Rules for Processing XML Stanzas</span><span>)</span></a>.
2917</p>
2918<a name="presence-extended"></a><br /><hr />
2919<table summary="layout" cellpadding="0" cellspacing="2" class="TOCbug" align="right"><tr><td class="TOCbug"><a href="#toc">&nbsp;TOC&nbsp;</a></td></tr></table>
2920<a name="rfc.section.4.7.3"></a><h3>4.7.3.&nbsp;
2921Extended Content</h3>
2922
2923<p>As described in <a class='info' href='#XMPP-CORE'>[XMPP&#8209;CORE]<span> (</span><span class='info'>Saint-Andre, P., &ldquo;Extensible Messaging and Presence Protocol (XMPP): Core,&rdquo; March&nbsp;2011.</span><span>)</span></a>, an XML stanza MAY contain any child element that is qualified by a namespace other than the default namespace; this applies to the presence stanza as well.
2924</p>
2925<p>(In the following example, the presence stanza includes entity capabilities information as defined in <a class='info' href='#XEP-0115'>[XEP&#8209;0115]<span> (</span><span class='info'>Hildebrand, J., Saint-Andre, P., and R. Tron&#xE7;on, &ldquo;Entity Capabilities,&rdquo; February&nbsp;2008.</span><span>)</span></a>.)
2926</p><div style='display: table; width: 0; margin-left: 3em; margin-right: auto'><pre>
2927&lt;presence from='romeo@example.net'&gt;
2928 &lt;c xmlns='http://jabber.org/protocol/caps'
2929 hash='sha-1'
2930 node='http://psi-im.org'
2931 ver='q07IKJEyjvHSyhy//CH0CxmKi8w='/&gt;
2932&lt;/presence&gt;
2933</pre></div>
2934<p>Any extended content included in a presence stanza SHOULD represent aspects of an entity's availability for communication or provide information about communication-related capabilities.
2935</p>
2936<a name="message"></a><br /><hr />
2937<table summary="layout" cellpadding="0" cellspacing="2" class="TOCbug" align="right"><tr><td class="TOCbug"><a href="#toc">&nbsp;TOC&nbsp;</a></td></tr></table>
2938<a name="rfc.section.5"></a><h3>5.&nbsp;
2939Exchanging Messages</h3>
2940
2941<p>Once a client has authenticated with a server and bound a resource to an XML stream as described in <a class='info' href='#XMPP-CORE'>[XMPP&#8209;CORE]<span> (</span><span class='info'>Saint-Andre, P., &ldquo;Extensible Messaging and Presence Protocol (XMPP): Core,&rdquo; March&nbsp;2011.</span><span>)</span></a>, an XMPP server will route XML stanzas to and from that client. One kind of stanza that can be exchanged is &lt;message/&gt; (if, that is, messaging functionality is enabled on the server). Exchanging messages is a basic use of XMPP and occurs when a user generates a message stanza that is addressed to another entity. As defined under <a class='info' href='#rules'>Section&nbsp;8<span> (</span><span class='info'>Server Rules for Processing XML Stanzas</span><span>)</span></a>, the sender's server is responsible for delivering the message to the intended recipient (if the recipient is on the same local server) or for routing the message to the recipient's server (if the recipient is on a remote server). Thus a message stanza is used to "push" information to another entity.
2942</p>
2943<a name="message-chat"></a><br /><hr />
2944<table summary="layout" cellpadding="0" cellspacing="2" class="TOCbug" align="right"><tr><td class="TOCbug"><a href="#toc">&nbsp;TOC&nbsp;</a></td></tr></table>
2945<a name="rfc.section.5.1"></a><h3>5.1.&nbsp;
2946One-to-One Chat Sessions</h3>
2947
2948<p>In practice, instant messaging activity between human users tends to occur in the form of a conversational burst that we call a "chat session": the exchange of multiple messages between two parties in relatively rapid succession within a relatively brief period of time.
2949</p>
2950<p>When a human user intends to engage in such a chat session with a contact (rather than sending a single message to which no reply is expected), the message type generated by the user's client SHOULD be "chat" and the contact's client SHOULD preserve that message type in subsequent replies. The user's client also SHOULD include a &lt;thread/&gt; element with its initial message, which the contact's client SHOULD also preserve during the life of the chat session (see <a class='info' href='#message-syntax-thread'>Section&nbsp;5.2.5<span> (</span><span class='info'>Thread Element</span><span>)</span></a>).
2951</p>
2952<p>The user's client SHOULD address the initial message in a chat session to the bare JID &lt;contact@domainpart&gt; of the contact (rather than attempting to guess an appropriate full JID &lt;contact@domainpart/resourcepart&gt; based on the &lt;show/&gt;, &lt;status/&gt;, or &lt;priority/&gt; value of any presence notifications it might have received from the contact). Until and unless the user's client receives a reply from the contact, it SHOULD send any further messages to the contact's bare JID. The contact's client SHOULD address its replies to the user's full JID &lt;user@domainpart/resourcepart&gt; as provided in the 'from' address of the initial message. Once the user's client receives a reply from the contact's full JID, it SHOULD address its subsequent messages to the contact's full JID as provided in the 'from' address of the contact's replies, thus "locking in" on that full JID. A client SHOULD "unlock" after having received a &lt;message/&gt; or &lt;presence/&gt; stanza from any other resource controlled by the peer (or a presence stanza from the locked resource); as a result, it SHOULD address its next message(s) in the chat session to the bare JID of the peer (thus "unlocking" the previous "lock") until it receives a message from one of the peer's full JIDs.
2953</p>
2954<p>When two parties engage in a chat session but do not share presence with each other based on a presence subscription, they SHOULD send directed presence to each other so that either party can easily discover if the peer goes offline during the course of the chat session. However, a client MUST provide a way for a user to disable such presence sharing globally or to enable it only with particular entities. Furthermore, a party SHOULD send directed unavailable presence to the peer when it has reason to believe that the chat session is over (e.g., if, after some reasonable amount of time, no subsequent messages have been exchanged between the parties).
2955</p>
2956<p>An example of a chat session is provided under <a class='info' href='#session'>Section&nbsp;7<span> (</span><span class='info'>A Sample Session</span><span>)</span></a>.
2957</p>
2958<a name="message-syntax"></a><br /><hr />
2959<table summary="layout" cellpadding="0" cellspacing="2" class="TOCbug" align="right"><tr><td class="TOCbug"><a href="#toc">&nbsp;TOC&nbsp;</a></td></tr></table>
2960<a name="rfc.section.5.2"></a><h3>5.2.&nbsp;
2961Message Syntax</h3>
2962
2963<p>The following sections describe the syntax of the &lt;message/&gt; stanza.
2964</p>
2965<a name="message-syntax-to"></a><br /><hr />
2966<table summary="layout" cellpadding="0" cellspacing="2" class="TOCbug" align="right"><tr><td class="TOCbug"><a href="#toc">&nbsp;TOC&nbsp;</a></td></tr></table>
2967<a name="rfc.section.5.2.1"></a><h3>5.2.1.&nbsp;
2968To Attribute</h3>
2969
2970<p>An instant messaging client specifies an intended recipient for a message by providing the JID of the intended recipient in the 'to' attribute of the &lt;message/&gt; stanza.
2971</p>
2972<p>If the message is being sent outside the context of any existing chat session or received message, the value of the 'to' address SHOULD be of the form &lt;localpart@domainpart&gt; rather than of the form &lt;localpart@domainpart/resourcepart&gt; (see <a class='info' href='#message-chat'>Section&nbsp;5.1<span> (</span><span class='info'>One-to-One Chat Sessions</span><span>)</span></a>).
2973</p><div style='display: table; width: 0; margin-left: 3em; margin-right: auto'><pre>
2974&lt;message
2975 from='juliet@example.com/balcony'
2976 id='ktx72v49'
2977 to='romeo@example.net'
2978 type='chat'
2979 xml:lang='en'&gt;
2980 &lt;body&gt;Art thou not Romeo, and a Montague?&lt;/body&gt;
2981&lt;/message&gt;
2982</pre></div>
2983<p>If the message is being sent in reply to a message previously received from an address of the form &lt;localpart@domainpart/resourcepart&gt; (e.g., within the context of a one-to-one chat session as described under <a class='info' href='#message-chat'>Section&nbsp;5.1<span> (</span><span class='info'>One-to-One Chat Sessions</span><span>)</span></a>), the value of the 'to' address SHOULD be of the form &lt;localpart@domainpart/resourcepart&gt; rather than of the form &lt;localpart@domainpart&gt; unless the sender has knowledge (e.g., via presence) that the intended recipient's resource is no longer available.
2984</p><div style='display: table; width: 0; margin-left: 3em; margin-right: auto'><pre>
2985&lt;message
2986 from='romeo@example.net/orchard'
2987 id='sl3nx51f'
2988 to='juliet@example.com/balcony'
2989 type='chat'
2990 xml:lang='en'&gt;
2991 &lt;body&gt;Neither, fair saint, if either thee dislike.&lt;/body&gt;
2992&lt;/message&gt;
2993</pre></div>
2994<a name="message-syntax-type"></a><br /><hr />
2995<table summary="layout" cellpadding="0" cellspacing="2" class="TOCbug" align="right"><tr><td class="TOCbug"><a href="#toc">&nbsp;TOC&nbsp;</a></td></tr></table>
2996<a name="rfc.section.5.2.2"></a><h3>5.2.2.&nbsp;
2997Type Attribute</h3>
2998
2999<p>Common uses of the message stanza in instant messaging applications include: single messages; messages sent in the context of a one-to-one chat session; messages sent in the context of a multi-user chat room; alerts, notifications, or other information to which no reply is expected; and errors. These uses are differentiated via the 'type' attribute. Inclusion of the 'type' attribute is RECOMMENDED. If included, the 'type' attribute MUST have one of the following values:
3000</p>
3001<p>
3002 </p>
3003<ul class="text">
3004<li>chat -- The message is sent in the context of a one-to-one chat session. Typically an interactive client will present a message of type "chat" in an interface that enables one-to-one chat between the two parties, including an appropriate conversation history. Detailed recommendations regarding one-to-one chat sessions are provided under <a class='info' href='#message-chat'>Section&nbsp;5.1<span> (</span><span class='info'>One-to-One Chat Sessions</span><span>)</span></a>.
3005</li>
3006<li>error -- The message is generated by an entity that experiences an error when processing a message received from another entity (for details regarding stanza error syntax, refer to <a class='info' href='#XMPP-CORE'>[XMPP&#8209;CORE]<span> (</span><span class='info'>Saint-Andre, P., &ldquo;Extensible Messaging and Presence Protocol (XMPP): Core,&rdquo; March&nbsp;2011.</span><span>)</span></a>). A client that receives a message of type "error" SHOULD present an appropriate interface informing the original sender regarding the nature of the error.
3007</li>
3008<li>groupchat -- The message is sent in the context of a multi-user chat environment (similar to that of <a class='info' href='#IRC'>[IRC]<span> (</span><span class='info'>Kalt, C., &ldquo;Internet Relay Chat: Architecture,&rdquo; April&nbsp;2000.</span><span>)</span></a>). Typically a receiving client will present a message of type "groupchat" in an interface that enables many-to-many chat between the parties, including a roster of parties in the chatroom and an appropriate conversation history. For detailed information about XMPP-based groupchat, refer to <a class='info' href='#XEP-0045'>[XEP&#8209;0045]<span> (</span><span class='info'>Saint-Andre, P., &ldquo;Multi-User Chat,&rdquo; July&nbsp;2008.</span><span>)</span></a>.
3009</li>
3010<li>headline -- The message provides an alert, a notification, or other transient information to which no reply is expected (e.g., news headlines, sports updates, near-real-time market data, or syndicated content). Because no reply to the message is expected, typically a receiving client will present a message of type "headline" in an interface that appropriately differentiates the message from standalone messages, chat messages, and groupchat messages (e.g., by not providing the recipient with the ability to reply). If the 'to' address is the bare JID, the receiving server SHOULD deliver the message to all of the recipient's available resources with non-negative presence priority and MUST deliver the message to at least one of those resources; if the 'to' address is a full JID and there is a matching resource, the server MUST deliver the message to that resource; otherwise the server MUST either silently ignore the message or return an error (see <a class='info' href='#rules'>Section&nbsp;8<span> (</span><span class='info'>Server Rules for Processing XML Stanzas</span><span>)</span></a>).
3011</li>
3012<li>normal -- The message is a standalone message that is sent outside the context of a one-to-one conversation or groupchat, and to which it is expected that the recipient will reply. Typically a receiving client will present a message of type "normal" in an interface that enables the recipient to reply, but without a conversation history. The default value of the 'type' attribute is "normal".
3013</li>
3014</ul><p>
3015
3016</p>
3017<p>An IM application SHOULD support all of the foregoing message types. If an application receives a message with no 'type' attribute or the application does not understand the value of the 'type' attribute provided, it MUST consider the message to be of type "normal" (i.e., "normal" is the default).
3018</p>
3019<p>Guidelines for server handling of different message types is provided under <a class='info' href='#rules'>Section&nbsp;8<span> (</span><span class='info'>Server Rules for Processing XML Stanzas</span><span>)</span></a>.
3020</p>
3021<p>Although the 'type' attribute is OPTIONAL, it is considered polite to mirror the type in any replies to a message; furthermore, some specialized applications (e.g., a multi-user chat service) MAY at their discretion enforce the use of a particular message type (e.g., type='groupchat').
3022</p>
3023<a name="message-syntax-body"></a><br /><hr />
3024<table summary="layout" cellpadding="0" cellspacing="2" class="TOCbug" align="right"><tr><td class="TOCbug"><a href="#toc">&nbsp;TOC&nbsp;</a></td></tr></table>
3025<a name="rfc.section.5.2.3"></a><h3>5.2.3.&nbsp;
3026Body Element</h3>
3027
3028<p>The &lt;body/&gt; element contains human-readable XML character data that specifies the textual contents of the message; this child element is normally included but is OPTIONAL.
3029</p><div style='display: table; width: 0; margin-left: 3em; margin-right: auto'><pre>
3030&lt;message
3031 from='juliet@example.com/balcony'
3032 id='b4vs9km4'
3033 to='romeo@example.net'
3034 type='chat'
3035 xml:lang='en'&gt;
3036 &lt;body&gt;Wherefore art thou, Romeo?&lt;/body&gt;
3037&lt;/message&gt;
3038</pre></div>
3039<p>There are no attributes defined for the &lt;body/&gt; element, with the exception of the 'xml:lang' attribute. Multiple instances of the &lt;body/&gt; element MAY be included in a message stanza for the purpose of providing alternate versions of the same body, but only if each instance possesses an 'xml:lang' attribute with a distinct language value (either explicitly or by inheritance from the 'xml:lang' value of an element farther up in the XML hierarchy, which from the sender's perspective can include the XML stream header as described in <a class='info' href='#XMPP-CORE'>[XMPP&#8209;CORE]<span> (</span><span class='info'>Saint-Andre, P., &ldquo;Extensible Messaging and Presence Protocol (XMPP): Core,&rdquo; March&nbsp;2011.</span><span>)</span></a>).
3040</p><div style='display: table; width: 0; margin-left: 3em; margin-right: auto'><pre>
3041&lt;message
3042 from='juliet@example.com/balcony'
3043 id='z94nb37h'
3044 to='romeo@example.net'
3045 type='chat'
3046 xml:lang='en'&gt;
3047 &lt;body&gt;Wherefore art thou, Romeo?&lt;/body&gt;
3048 &lt;body xml:lang='cs'&gt;
3049 Pro&amp;#x010D;e&amp;#x017D; jsi ty, Romeo?
3050 &lt;/body&gt;
3051&lt;/message&gt;
3052</pre></div>
3053<p>The &lt;body/&gt; element MUST NOT contain mixed content (as defined in Section 3.2.2 of <a class='info' href='#XML'>[XML]<span> (</span><span class='info'>Maler, E., Yergeau, F., Sperberg-McQueen, C., Paoli, J., and T. Bray, &ldquo;Extensible Markup Language (XML) 1.0 (Fifth Edition),&rdquo; November&nbsp;2008.</span><span>)</span></a>).
3054</p>
3055<a name="message-syntax-subject"></a><br /><hr />
3056<table summary="layout" cellpadding="0" cellspacing="2" class="TOCbug" align="right"><tr><td class="TOCbug"><a href="#toc">&nbsp;TOC&nbsp;</a></td></tr></table>
3057<a name="rfc.section.5.2.4"></a><h3>5.2.4.&nbsp;
3058Subject Element</h3>
3059
3060<p>The &lt;subject/&gt; element contains human-readable XML character data that specifies the topic of the message.
3061</p><div style='display: table; width: 0; margin-left: 3em; margin-right: auto'><pre>
3062&lt;message
3063 from='juliet@example.com/balcony'
3064 id='c8xg3nf8'
3065 to='romeo@example.net'
3066 type='chat'
3067 xml:lang='en'&gt;
3068 &lt;subject&gt;I implore you!&lt;/subject&gt;
3069 &lt;body&gt;Wherefore art thou, Romeo?&lt;/body&gt;
3070&lt;/message&gt;
3071</pre></div>
3072<p>There are no attributes defined for the &lt;subject/&gt; element, with the exception of the 'xml:lang' attribute inherited from <a class='info' href='#XML'>[XML]<span> (</span><span class='info'>Maler, E., Yergeau, F., Sperberg-McQueen, C., Paoli, J., and T. Bray, &ldquo;Extensible Markup Language (XML) 1.0 (Fifth Edition),&rdquo; November&nbsp;2008.</span><span>)</span></a>. Multiple instances of the &lt;subject/&gt; element MAY be included for the purpose of providing alternate versions of the same subject, but only if each instance possesses an 'xml:lang' attribute with a distinct language value (either explicitly or by inheritance from the 'xml:lang' value of an element farther up in the XML hierarchy, which from the sender's perspective can include the XML stream header as described in <a class='info' href='#XMPP-CORE'>[XMPP&#8209;CORE]<span> (</span><span class='info'>Saint-Andre, P., &ldquo;Extensible Messaging and Presence Protocol (XMPP): Core,&rdquo; March&nbsp;2011.</span><span>)</span></a>).
3073</p><div style='display: table; width: 0; margin-left: 3em; margin-right: auto'><pre>
3074&lt;message
3075 from='juliet@example.com/balcony'
3076 id='jk3v47gw'
3077 to='romeo@example.net'
3078 type='chat'
3079 xml:lang='en'&gt;
3080 &lt;subject&gt;I implore you!&lt;/subject&gt;
3081 &lt;subject xml:lang='cs'&gt;
3082 &amp;#x00DA;p&amp;#x011B;nliv&amp;#x011B; pros&amp;#x00ED;m!
3083 &lt;/subject&gt;
3084 &lt;body&gt;Wherefore art thou, Romeo?&lt;/body&gt;
3085 &lt;body xml:lang='cs'&gt;
3086 Pro&amp;#x010D;e&amp;#x017E; jsi ty, Romeo?
3087 &lt;/body&gt;
3088&lt;/message&gt;
3089</pre></div>
3090<p>The &lt;subject/&gt; element MUST NOT contain mixed content (as defined in Section 3.2.2 of <a class='info' href='#XML'>[XML]<span> (</span><span class='info'>Maler, E., Yergeau, F., Sperberg-McQueen, C., Paoli, J., and T. Bray, &ldquo;Extensible Markup Language (XML) 1.0 (Fifth Edition),&rdquo; November&nbsp;2008.</span><span>)</span></a>).
3091</p>
3092<a name="message-syntax-thread"></a><br /><hr />
3093<table summary="layout" cellpadding="0" cellspacing="2" class="TOCbug" align="right"><tr><td class="TOCbug"><a href="#toc">&nbsp;TOC&nbsp;</a></td></tr></table>
3094<a name="rfc.section.5.2.5"></a><h3>5.2.5.&nbsp;
3095Thread Element</h3>
3096
3097<p>The primary use of the XMPP &lt;thread/&gt; element is to uniquely identify a conversation thread or "chat session" between two entities instantiated by &lt;message/&gt; stanzas of type 'chat'. However, the XMPP &lt;thread/&gt; element MAY also be used to uniquely identify an analogous thread between two entities instantiated by &lt;message/&gt; stanzas of type 'headline' or 'normal', or among multiple entities in the context of a multi-user chat room instantiated by &lt;message/&gt; stanzas of type 'groupchat'. It MAY also be used for &lt;message/&gt; stanzas not related to a human conversation, such as a game session or an interaction between plugins. The &lt;thread/&gt; element is not used to identify individual messages, only conversations or messaging sessions.
3098</p>
3099<p>The inclusion of the &lt;thread/&gt; element is OPTIONAL. Because the &lt;thread/&gt; element identifies the particular conversation thread to which a message belongs, a message stanza MUST NOT contain more than one &lt;thread/&gt; element.
3100</p>
3101<p>The &lt;thread/&gt; element MAY possess a 'parent' attribute that identifies another thread of which the current thread is an offshoot or child. The 'parent' attribute MUST conform to the syntax of the &lt;thread/&gt; element itself and its value MUST be different from the XML character data of the &lt;thread/&gt; element on which the 'parent' attribute is included.
3102</p>
3103<p></p>
3104<blockquote class="text">
3105<p>Implementation Note: The ability to specify both a parent thread and a child thread introduces the possibility of conflicts between thread identifiers for overlapping threads. For example, one &lt;thread/&gt; element might contain XML character data of "foo" and a 'parent' attribute whose value is "bar", a second &lt;thread/&gt; element might contain XML character data of "bar" and a 'parent' attribute whose value is "baz", and a third &lt;thread/&gt; element might contain XML character data of "baz" and a 'parent' attribute whose value is once again "foo". It is up to the implementation how it will treat conflicts between such overlapping thread identifiers (e.g., whether it will "chain together" thread identifiers by showing "foo" as both a parent and grandchild of "baz" in a multi-level user interface, or whether it will show only one level of dependency at a time).
3106</p>
3107</blockquote>
3108
3109<p>The value of the &lt;thread/&gt; element is not human-readable and MUST be treated as opaque by entities; no semantic meaning can be derived from it, and only exact comparisons can be made against it. The value of the &lt;thread/&gt; element MUST uniquely identify the conversation thread either between the conversation partners or more generally (one way to ensure uniqueness is by generating a universally unique identifier (UUID) as described in <a class='info' href='#UUID'>[UUID]<span> (</span><span class='info'>Leach, P., Mealling, M., and R. Salz, &ldquo;A Universally Unique IDentifier (UUID) URN Namespace,&rdquo; July&nbsp;2005.</span><span>)</span></a>).
3110</p>
3111<p></p>
3112<blockquote class="text">
3113<p>Security Warning: An application that generates a ThreadID MUST ensure that it does not reveal identifying information about the entity (e.g., the MAC address of the device on which the XMPP application is running).
3114</p>
3115</blockquote>
3116
3117<p>The &lt;thread/&gt; element MUST NOT contain mixed content (as defined in Section 3.2.2 of <a class='info' href='#XML'>[XML]<span> (</span><span class='info'>Maler, E., Yergeau, F., Sperberg-McQueen, C., Paoli, J., and T. Bray, &ldquo;Extensible Markup Language (XML) 1.0 (Fifth Edition),&rdquo; November&nbsp;2008.</span><span>)</span></a>).
3118</p><div style='display: table; width: 0; margin-left: 3em; margin-right: auto'><pre>
3119&lt;message
3120 from='juliet@example.com/balcony'
3121 to='romeo@example.net'
3122 type='chat'
3123 xml:lang='en'&gt;
3124 &lt;subject&gt;I implore you!&lt;/subject&gt;
3125 &lt;subject xml:lang='cs'&gt;
3126 &amp;#x00DA;p&amp;#x011B;nliv&amp;#x011B; pros&amp;#x00ED;m!
3127 &lt;/subject&gt;
3128 &lt;body&gt;Wherefore art thou, Romeo?&lt;/body&gt;
3129 &lt;body xml:lang='cs'&gt;
3130 Pro&amp;#x010D;e&amp;#x017E; jsi ty, Romeo?
3131 &lt;/body&gt;
3132 &lt;thread parent='e0ffe42b28561960c6b12b944a092794b9683a38'&gt;
3133 0e3141cd80894871a68e6fe6b1ec56fa
3134 &lt;/thread&gt;
3135&lt;/message&gt;
3136</pre></div>
3137<p>For detailed recommendations regarding use of the &lt;thread/&gt; element, refer to <a class='info' href='#XEP-0201'>[XEP&#8209;0201]<span> (</span><span class='info'>Saint-Andre, P., Paterson, I., and K. Smith, &ldquo;Best Practices for Message Threads,&rdquo; November&nbsp;2010.</span><span>)</span></a>.
3138</p>
3139<a name="message-syntax-extended"></a><br /><hr />
3140<table summary="layout" cellpadding="0" cellspacing="2" class="TOCbug" align="right"><tr><td class="TOCbug"><a href="#toc">&nbsp;TOC&nbsp;</a></td></tr></table>
3141<a name="rfc.section.5.3"></a><h3>5.3.&nbsp;
3142Extended Content</h3>
3143
3144<p>As described in <a class='info' href='#XMPP-CORE'>[XMPP&#8209;CORE]<span> (</span><span class='info'>Saint-Andre, P., &ldquo;Extensible Messaging and Presence Protocol (XMPP): Core,&rdquo; March&nbsp;2011.</span><span>)</span></a>, an XML stanza MAY contain any child element that is qualified by a namespace other than the default namespace; this applies to the message stanza as well. Guidelines for handling extended content on the part of both routing servers and end recipients are provided in Section 8.4 of <a class='info' href='#XMPP-CORE'>[XMPP&#8209;CORE]<span> (</span><span class='info'>Saint-Andre, P., &ldquo;Extensible Messaging and Presence Protocol (XMPP): Core,&rdquo; March&nbsp;2011.</span><span>)</span></a>.
3145</p>
3146<p>(In the following example, the message stanza includes an XHTML-formatted version of the message as defined in <a class='info' href='#XEP-0071'>[XEP&#8209;0071]<span> (</span><span class='info'>Saint-Andre, P., &ldquo;XHTML-IM,&rdquo; September&nbsp;2008.</span><span>)</span></a>).)
3147</p><div style='display: table; width: 0; margin-left: 3em; margin-right: auto'><pre>
3148&lt;message
3149 from='juliet@example.com/balcony'
3150 to='romeo@example.net'
3151 type='chat'
3152 xml:lang='en'&gt;
3153 &lt;body&gt;Wherefore art thou, Romeo?&lt;/body&gt;
3154 &lt;html xmlns='http://jabber.org/protocol/xhtml-im'&gt;
3155 &lt;body xmlns='http://www.w3.org/1999/xhtml'&gt;
3156 &lt;p&gt;Wherefore &lt;span style='font-style: italic'&gt;art&lt;/span&gt;
3157 thou, &lt;span style='color:red'&gt;Romeo&lt;/span&gt;?&lt;/p&gt;
3158 &lt;/body&gt;
3159 &lt;/html&gt;
3160&lt;/message&gt;
3161</pre></div>
3162<a name="iq"></a><br /><hr />
3163<table summary="layout" cellpadding="0" cellspacing="2" class="TOCbug" align="right"><tr><td class="TOCbug"><a href="#toc">&nbsp;TOC&nbsp;</a></td></tr></table>
3164<a name="rfc.section.6"></a><h3>6.&nbsp;
3165Exchanging IQ Stanzas</h3>
3166
3167<p>As described in <a class='info' href='#XMPP-CORE'>[XMPP&#8209;CORE]<span> (</span><span class='info'>Saint-Andre, P., &ldquo;Extensible Messaging and Presence Protocol (XMPP): Core,&rdquo; March&nbsp;2011.</span><span>)</span></a>, IQ stanzas provide a structured request-response mechanism. The basic semantics of that mechanism (e.g., that the 'id' attribute is mandatory) are defined in <a class='info' href='#XMPP-CORE'>[XMPP&#8209;CORE]<span> (</span><span class='info'>Saint-Andre, P., &ldquo;Extensible Messaging and Presence Protocol (XMPP): Core,&rdquo; March&nbsp;2011.</span><span>)</span></a>, whereas the specific semantics needed to complete particular use cases are defined in all instances by the extended namespace that qualifies the direct child element of an IQ stanza of type "get" or "set". The 'jabber:client' and 'jabber:server' namespaces do not define any children of IQ stanzas other than the &lt;error/&gt; element common to all stanza types. This document defines one such extended namespace, for <a class='info' href='#roster'>Managing the Roster<span> (</span><span class='info'>Managing the Roster</span><span>)</span></a>. However, an IQ stanza MAY contain structured information qualified by any extended namespace.
3168</p>
3169<a name="session"></a><br /><hr />
3170<table summary="layout" cellpadding="0" cellspacing="2" class="TOCbug" align="right"><tr><td class="TOCbug"><a href="#toc">&nbsp;TOC&nbsp;</a></td></tr></table>
3171<a name="rfc.section.7"></a><h3>7.&nbsp;
3172A Sample Session</h3>
3173
3174<p>The examples in this section illustrate a possible instant messaging and presence session. The user is &lt;romeo@example.net&gt;, he has an available resource whose resourcepart is "orchard", and he has the following individuals in his roster:
3175</p>
3176<p>
3177 </p>
3178<ul class="text">
3179<li>&lt;juliet@example.com&gt; (subscription="both" and she has two available resources, "chamber" and "balcony")
3180</li>
3181<li>&lt;benvolio@example.net&gt; (subscription="to")
3182</li>
3183<li>&lt;mercutio@example.org&gt; (subscription="from")
3184</li>
3185</ul><p>
3186
3187</p>
3188<p>First, the user completes the preconditions (stream establishment, TLS and SASL negotiation, and resource binding) described in <a class='info' href='#XMPP-CORE'>[XMPP&#8209;CORE]<span> (</span><span class='info'>Saint-Andre, P., &ldquo;Extensible Messaging and Presence Protocol (XMPP): Core,&rdquo; March&nbsp;2011.</span><span>)</span></a>; those protocol flows are not reproduced here.
3189</p>
3190<p>Next, the user requests his roster.
3191</p>
3192<p>Example 1: User requests current roster from server
3193</p><div style='display: table; width: 0; margin-left: 3em; margin-right: auto'><pre>
3194UC: &lt;iq from='romeo@example.net/orchard'
3195 id='hf61v3n7'
3196 type='get'&gt;
3197 &lt;query xmlns='jabber:iq:roster'/&gt;
3198 &lt;/iq&gt;
3199</pre></div>
3200<p>Example 2: User receives roster from server
3201</p><div style='display: table; width: 0; margin-left: 3em; margin-right: auto'><pre>
3202US: &lt;iq id='hf61v3n7'
3203 to='romeo@example.net/orchard'
3204 type='result'&gt;
3205 &lt;query xmlns='jabber:iq:roster'&gt;
3206 &lt;item jid='juliet@example.com'
3207 name='Juliet'
3208 subscription='both'&gt;
3209 &lt;group&gt;Friends&lt;/group&gt;
3210 &lt;/item&gt;
3211 &lt;item jid='benvolio@example.org'
3212 name='Benvolio'
3213 subscription='to'/&gt;
3214 &lt;item jid='mercutio@example.org'
3215 name='Mercutio'
3216 subscription='from'/&gt;
3217 &lt;/query&gt;
3218 &lt;/iq&gt;
3219</pre></div>
3220<p>Now the user begins a presence session.
3221</p>
3222<p>Example 3: User sends initial presence
3223</p><div style='display: table; width: 0; margin-left: 3em; margin-right: auto'><pre>
3224UC: &lt;presence/&gt;
3225</pre></div>
3226<p>Example 4: User's server sends presence probes to contacts with subscription="to" and subscription="both" on behalf of the user
3227</p><div style='display: table; width: 0; margin-left: 3em; margin-right: auto'><pre>
3228US: &lt;presence
3229 from='romeo@example.net'
3230 to='juliet@example.com'
3231 type='probe'/&gt;
3232
3233US: &lt;presence
3234 from='romeo@example.net'
3235 to='benvolio@example.org'
3236 type='probe'/&gt;
3237</pre></div>
3238<p>Example 5: User's server sends initial presence to contacts with subscription="from" and subscription="both" on behalf of the user's available resource, as well as to user
3239</p><div style='display: table; width: 0; margin-left: 3em; margin-right: auto'><pre>
3240US: &lt;presence
3241 from='romeo@example.net/orchard'
3242 to='juliet@example.com'/&gt;
3243
3244US: &lt;presence
3245 from='romeo@example.net/orchard'
3246 to='mercutio@example.org'/&gt;
3247
3248US: &lt;presence
3249 from='romeo@example.net/orchard'
3250 to='romeo@example.net'/&gt;
3251</pre></div>
3252<p>Example 6: Contacts' servers reply to presence probe on behalf of all available resources
3253</p><div style='display: table; width: 0; margin-left: 3em; margin-right: auto'><pre>
3254CS: &lt;presence
3255 from='juliet@example.com/balcony'
3256 to='romeo@example.net'
3257 xml:lang='en'&gt;
3258 &lt;show&gt;away&lt;/show&gt;
3259 &lt;status&gt;be right back&lt;/status&gt;
3260 &lt;priority&gt;0&lt;/priority&gt;
3261 &lt;/presence&gt;
3262
3263CS: &lt;presence
3264 from='juliet@example.com/chamber'
3265 to='romeo@example.net'&gt;
3266 &lt;priority&gt;1&lt;/priority&gt;
3267 &lt;/presence&gt;
3268
3269CS: &lt;presence
3270 from='benvolio@example.org/pda'
3271 to='romeo@example.net'
3272 xml:lang='en'&gt;
3273 &lt;show&gt;dnd&lt;/show&gt;
3274 &lt;status&gt;gallivanting&lt;/status&gt;
3275 &lt;/presence&gt;
3276</pre></div>
3277<p>Example 7: Contacts' servers deliver user's initial presence to all available resources
3278</p><div style='display: table; width: 0; margin-left: 3em; margin-right: auto'><pre>
3279CS: &lt;presence
3280 from='romeo@example.net/orchard'
3281 to='juliet@example.com'/&gt;
3282
3283CS: &lt;presence
3284 from='romeo@example.net/orchard'
3285 to='juliet@example.com'/&gt;
3286
3287CS: &lt;presence
3288 from='romeo@example.net/orchard'
3289 to='mercutio@example.org'/&gt;
3290</pre></div>
3291<p>Example 8: User sends directed presence to another user not in his roster
3292</p><div style='display: table; width: 0; margin-left: 3em; margin-right: auto'><pre>
3293UC: &lt;presence
3294 from='romeo@example.net/orchard'
3295 to='nurse@example.com'
3296 xml:lang='en'&gt;
3297 &lt;show&gt;dnd&lt;/show&gt;
3298 &lt;status&gt;courting Juliet&lt;/status&gt;
3299 &lt;priority&gt;0&lt;/priority&gt;
3300 &lt;/presence&gt;
3301</pre></div>
3302<p>Now the user engages in a chat session with one of his contacts.
3303</p>
3304<p>Example 9: A threaded conversation
3305</p><div style='display: table; width: 0; margin-left: 3em; margin-right: auto'><pre>
3306CC: &lt;message
3307 from='juliet@example.com/balcony'
3308 to='romeo@example.net'
3309 type='chat'
3310 xml:lang='en'&gt;
3311 &lt;body&gt;My ears have not yet drunk a hundred words&lt;/body&gt;
3312 &lt;thread&gt;e0ffe42b28561960c6b12b944a092794b9683a38&lt;/thread&gt;
3313 &lt;/message&gt;
3314
3315CC: &lt;message
3316 from='juliet@example.com/balcony'
3317 to='romeo@example.net'
3318 type='chat'
3319 xml:lang='en'&gt;
3320 &lt;body&gt;Of that tongue's utterance, yet I know the sound:&lt;/body&gt;
3321 &lt;thread&gt;e0ffe42b28561960c6b12b944a092794b9683a38&lt;/thread&gt;
3322 &lt;/message&gt;
3323
3324CC: &lt;message
3325 from='juliet@example.com/balcony'
3326 to='romeo@example.net'
3327 type='chat'
3328 xml:lang='en'&gt;
3329 &lt;body&gt;Art thou not Romeo, and a Montague?&lt;/body&gt;
3330 &lt;thread&gt;e0ffe42b28561960c6b12b944a092794b9683a38&lt;/thread&gt;
3331 &lt;/message&gt;
3332
3333UC: &lt;message
3334 from='romeo@example.net/orchard'
3335 to='juliet@example.com/balcony'
3336 type='chat'
3337 xml:lang='en'&gt;
3338 &lt;body&gt;Neither, fair saint, if either thee dislike.&lt;/body&gt;
3339 &lt;thread&gt;e0ffe42b28561960c6b12b944a092794b9683a38&lt;/thread&gt;
3340 &lt;/message&gt;
3341
3342CC: &lt;message
3343 from='juliet@example.com/balcony'
3344 to='romeo@example.net/orchard'
3345 type='chat'
3346 xml:lang='en'&gt;
3347 &lt;body&gt;How cam'st thou hither, tell me, and wherefore?&lt;/body&gt;
3348 &lt;thread&gt;e0ffe42b28561960c6b12b944a092794b9683a38&lt;/thread&gt;
3349 &lt;/message&gt;
3350</pre></div>
3351<p>And so on.
3352</p>
3353<p>The user can also send subsequent presence broadcast.
3354</p>
3355<p>Example 10: User sends updated available presence for broadcast
3356</p><div style='display: table; width: 0; margin-left: 3em; margin-right: auto'><pre>
3357UC: &lt;presence xml:lang='en'&gt;
3358 &lt;show&gt;away&lt;/show&gt;
3359 &lt;status&gt;I shall return!&lt;/status&gt;
3360 &lt;priority&gt;1&lt;/priority&gt;
3361 &lt;/presence&gt;
3362</pre></div>
3363<p>Example 11: User's server broadcasts updated presence to the contacts who have a subscription of type "both" or "from" (but not to the entity to which the user sent directed presence)
3364</p><div style='display: table; width: 0; margin-left: 3em; margin-right: auto'><pre>
3365US: &lt;presence
3366 from='romeo@example.net/orchard'
3367 to='juliet@example.com'
3368 xml:lang='en'&gt;
3369 &lt;show&gt;away&lt;/show&gt;
3370 &lt;status&gt;I shall return!&lt;/status&gt;
3371 &lt;priority&gt;1&lt;/priority&gt;
3372 &lt;/presence&gt;
3373
3374US: &lt;presence
3375 from='romeo@example.net/orchard'
3376 to='mercutio@example.org'
3377 xml:lang='en'&gt;
3378 &lt;show&gt;away&lt;/show&gt;
3379 &lt;status&gt;I shall return!&lt;/status&gt;
3380 &lt;priority&gt;1&lt;/priority&gt;
3381 &lt;/presence&gt;
3382</pre></div>
3383<p>Example 12: Contacts' servers deliver updated presence
3384</p><div style='display: table; width: 0; margin-left: 3em; margin-right: auto'><pre>
3385CS: &lt;presence
3386 from='romeo@example.net/orchard'
3387 to='juliet@example.com'
3388 xml:lang='en'&gt;
3389 &lt;show&gt;away&lt;/show&gt;
3390 &lt;status&gt;I shall return!&lt;/status&gt;
3391 &lt;priority&gt;1&lt;/priority&gt;
3392 &lt;/presence&gt;
3393
3394CS: &lt;presence
3395 from='romeo@example.net/orchard'
3396 to='juliet@example.com'
3397 xml:lang='en'&gt;
3398 &lt;show&gt;away&lt;/show&gt;
3399 &lt;status&gt;I shall return!&lt;/status&gt;
3400 &lt;priority&gt;1&lt;/priority&gt;
3401 &lt;/presence&gt;
3402
3403CS: &lt;presence
3404 from='romeo@example.net/orchard'
3405 to='mercutio@example.org'
3406 xml:lang='en'&gt;
3407 &lt;show&gt;away&lt;/show&gt;
3408 &lt;status&gt;I shall return!&lt;/status&gt;
3409 &lt;priority&gt;1&lt;/priority&gt;
3410 &lt;/presence&gt;
3411</pre></div>
3412<p>Example 13: One of the contact's resources broadcasts unavailable notification
3413</p><div style='display: table; width: 0; margin-left: 3em; margin-right: auto'><pre>
3414CC: &lt;presence from='juliet@example.com/chamber' type='unavailable'/&gt;
3415</pre></div>
3416<p>Example 14: Contact's server sends unavailable notification to user
3417</p><div style='display: table; width: 0; margin-left: 3em; margin-right: auto'><pre>
3418CS: &lt;presence
3419 from='juliet@example.com/chamber'
3420 to='romeo@example.net'
3421 type='unavailable'/&gt;
3422</pre></div>
3423<p>Now the user ends his presence session.
3424</p>
3425<p>Example 15: User sends unavailable notification
3426</p><div style='display: table; width: 0; margin-left: 3em; margin-right: auto'><pre>
3427UC: &lt;presence type='unavailable' xml:lang='en'&gt;
3428 &lt;status&gt;gone home&lt;/status&gt;
3429 &lt;/presence&gt;
3430</pre></div>
3431<p>Example 16: User's server broadcasts unavailable notification to contacts as well as to the entity to whom the user sent directed presence
3432</p><div style='display: table; width: 0; margin-left: 3em; margin-right: auto'><pre>
3433US: &lt;presence
3434 from='romeo@example.net/orchard'
3435 to='juliet@example.com'
3436 type='unavailable'
3437 xml:lang='en'&gt;
3438 &lt;status&gt;gone home&lt;/status&gt;
3439 &lt;/presence&gt;
3440
3441US: &lt;presence
3442 from='romeo@example.net/orchard'
3443 to='mercutio@example.org'
3444 type='unavailable'
3445 xml:lang='en'&gt;
3446 &lt;status&gt;gone home&lt;/status&gt;
3447 &lt;/presence&gt;
3448
3449US: &lt;presence
3450 from='romeo@example.net/orchard'
3451 to='nurse@example.com'
3452 type='unavailable'
3453 xml:lang='en'&gt;
3454 &lt;status&gt;gone home&lt;/status&gt;
3455 &lt;/presence&gt;
3456</pre></div>
3457<p>Finally the user closes his stream and the server responds in kind.
3458</p>
3459<p>Example 17: User closes stream
3460</p><div style='display: table; width: 0; margin-left: 3em; margin-right: auto'><pre>
3461UC: &lt;/stream:stream&gt;
3462</pre></div>
3463<p>Example 18: User's server closes stream
3464</p><div style='display: table; width: 0; margin-left: 3em; margin-right: auto'><pre>
3465US: &lt;/stream:stream&gt;
3466</pre></div>
3467<p>THE END
3468</p>
3469<a name="rules"></a><br /><hr />
3470<table summary="layout" cellpadding="0" cellspacing="2" class="TOCbug" align="right"><tr><td class="TOCbug"><a href="#toc">&nbsp;TOC&nbsp;</a></td></tr></table>
3471<a name="rfc.section.8"></a><h3>8.&nbsp;
3472Server Rules for Processing XML Stanzas</h3>
3473
3474<p>Basic server rules for processing XML stanzas are defined in
3475 <a class='info' href='#XMPP-CORE'>[XMPP&#8209;CORE]<span> (</span><span class='info'>Saint-Andre, P., &ldquo;Extensible Messaging and Presence Protocol (XMPP): Core,&rdquo; March&nbsp;2011.</span><span>)</span></a>, and the reader is referred to that specification for underlying rules and security implications. This section defines supplementary rules for XMPP instant messaging and presence servers.
3476</p>
3477<p>Some delivery rules defined in this section specify the use of "offline storage", i.e., the server's act of storing a message stanza on behalf of the user and then delivering it when the user next becomes available. For recommendations regarding offline message storage, refer to <a class='info' href='#XEP-0160'>[XEP&#8209;0160]<span> (</span><span class='info'>Saint-Andre, P., &ldquo;Best Practices for Handling Offline Messages,&rdquo; January&nbsp;2006.</span><span>)</span></a>.
3478</p>
3479<a name="rules-general"></a><br /><hr />
3480<table summary="layout" cellpadding="0" cellspacing="2" class="TOCbug" align="right"><tr><td class="TOCbug"><a href="#toc">&nbsp;TOC&nbsp;</a></td></tr></table>
3481<a name="rfc.section.8.1"></a><h3>8.1.&nbsp;
3482General Considerations</h3>
3483
3484<p><a class='info' href='#XMPP-CORE'>[XMPP&#8209;CORE]<span> (</span><span class='info'>Saint-Andre, P., &ldquo;Extensible Messaging and Presence Protocol (XMPP): Core,&rdquo; March&nbsp;2011.</span><span>)</span></a> discusses general considerations for stanza delivery, in particular the tradeoffs between (i) providing an acceptable level of service regarding stanza delivery and (ii) preventing directory harvesting attacks and presence leaks. However, the concept of a directory harvesting attack does not apply if a contact is known to and trusted by a user (because the contact is in the user's roster as described under <a class='info' href='#roster'>Section&nbsp;2<span> (</span><span class='info'>Managing the Roster</span><span>)</span></a>). Similarly, the concept of a presence leak does not apply if a contact is authorized to know a user's presence (by means of a presence subscription as described under <a class='info' href='#sub'>Section&nbsp;3<span> (</span><span class='info'>Managing Presence Subscriptions</span><span>)</span></a>) or if the user has voluntarily sent presence to an entity (by means of directed presence as described under <a class='info' href='#presence-directed'>Section&nbsp;4.6<span> (</span><span class='info'>Directed Presence</span><span>)</span></a>). Therefore, in cases where the following sections guard against directory harvesting attacks and presence leaks by providing an alternative of (a) silently ignoring a stanza or (b) returning an error, a server SHOULD return an error if the originating entity is in the user's roster (when the error would reveal whether the user's account exists) or is authorized to receive presence from the user or has received directed presence from the user (when the error would reveal the presence of a user's resource).
3485</p>
3486<p></p>
3487<blockquote class="text">
3488<p>Security Warning: All of the stanza processing rules described below are defined with the understanding that they will be applied subject to enforcement of relevant privacy and security policies, such as those deployed by means of <a class='info' href='#XEP-0016'>[XEP&#8209;0016]<span> (</span><span class='info'>Millard, P. and P. Saint-Andre, &ldquo;Privacy Lists,&rdquo; February&nbsp;2007.</span><span>)</span></a> or <a class='info' href='#XEP-0191'>[XEP&#8209;0191]<span> (</span><span class='info'>Saint-Andre, P., &ldquo;Simple Communications Blocking,&rdquo; February&nbsp;2007.</span><span>)</span></a>. The conformance language (MUST, SHOULD, etc.) in the following sections is not meant to override any such local service policies.
3489</p>
3490</blockquote>
3491
3492<a name="rules-noto"></a><br /><hr />
3493<table summary="layout" cellpadding="0" cellspacing="2" class="TOCbug" align="right"><tr><td class="TOCbug"><a href="#toc">&nbsp;TOC&nbsp;</a></td></tr></table>
3494<a name="rfc.section.8.2"></a><h3>8.2.&nbsp;
3495No 'to' Address</h3>
3496
3497<p>If the stanza possesses no 'to' attribute, the rules defined in <a class='info' href='#XMPP-CORE'>[XMPP&#8209;CORE]<span> (</span><span class='info'>Saint-Andre, P., &ldquo;Extensible Messaging and Presence Protocol (XMPP): Core,&rdquo; March&nbsp;2011.</span><span>)</span></a> apply.
3498</p>
3499<a name="rules-remote"></a><br /><hr />
3500<table summary="layout" cellpadding="0" cellspacing="2" class="TOCbug" align="right"><tr><td class="TOCbug"><a href="#toc">&nbsp;TOC&nbsp;</a></td></tr></table>
3501<a name="rfc.section.8.3"></a><h3>8.3.&nbsp;
3502Remote Domain</h3>
3503
3504<p>If the domainpart of the address contained in the 'to' attribute of an outbound stanza does not match a configured domain of the server itself, then the rules provided in Section 10.4 of <a class='info' href='#XMPP-CORE'>[XMPP&#8209;CORE]<span> (</span><span class='info'>Saint-Andre, P., &ldquo;Extensible Messaging and Presence Protocol (XMPP): Core,&rdquo; March&nbsp;2011.</span><span>)</span></a> apply.
3505</p>
3506<p></p>
3507<blockquote class="text">
3508<p>Interoperability Note: RFC 3921 specified how to use the _im._xmpp and _pres._xmpp SRV records <a class='info' href='#IMP-SRV'>[IMP&#8209;SRV]<span> (</span><span class='info'>Peterson, J., &ldquo;Address Resolution for Instant Messaging and Presence,&rdquo; August&nbsp;2004.</span><span>)</span></a> as a fallback method for discovering whether a remote instant messaging and presence service communicates via XMPP. Because those SRV records have not been widely deployed, this document no longer specifies their use, and new implementations are not encouraged.
3509</p>
3510</blockquote>
3511
3512<a name="rules-local"></a><br /><hr />
3513<table summary="layout" cellpadding="0" cellspacing="2" class="TOCbug" align="right"><tr><td class="TOCbug"><a href="#toc">&nbsp;TOC&nbsp;</a></td></tr></table>
3514<a name="rfc.section.8.4"></a><h3>8.4.&nbsp;
3515Local Domain</h3>
3516
3517<p>If the domainpart of the JID contained in the 'to' attribute matches one of the configured domains of the server, the domain is serviced by the server itself (not by a specialized local service), and the JID is of the form &lt;domainpart&gt; or &lt;domainpart/resourcepart&gt;, the rules defined in <a class='info' href='#XMPP-CORE'>[XMPP&#8209;CORE]<span> (</span><span class='info'>Saint-Andre, P., &ldquo;Extensible Messaging and Presence Protocol (XMPP): Core,&rdquo; March&nbsp;2011.</span><span>)</span></a> apply.
3518</p>
3519<a name="rules-localpart"></a><br /><hr />
3520<table summary="layout" cellpadding="0" cellspacing="2" class="TOCbug" align="right"><tr><td class="TOCbug"><a href="#toc">&nbsp;TOC&nbsp;</a></td></tr></table>
3521<a name="rfc.section.8.5"></a><h3>8.5.&nbsp;
3522Local User</h3>
3523
3524<p>If the 'to' address specifies a bare JID &lt;localpart@domainpart&gt; or full JID &lt;localpart@domainpart/resourcepart&gt; where the domainpart of the JID matches a configured domain that is serviced by the server itself, the server MUST proceed as follows.
3525</p>
3526<a name="rules-localpart-nosuchuser"></a><br /><hr />
3527<table summary="layout" cellpadding="0" cellspacing="2" class="TOCbug" align="right"><tr><td class="TOCbug"><a href="#toc">&nbsp;TOC&nbsp;</a></td></tr></table>
3528<a name="rfc.section.8.5.1"></a><h3>8.5.1.&nbsp;
3529No Such User</h3>
3530
3531<p>If the user account identified by the 'to' attribute does not exist, how the stanza is processed depends on the stanza type.
3532</p>
3533<p>
3534 </p>
3535<ul class="text">
3536<li>For an IQ stanza, the server MUST return a &lt;service-unavailable/&gt; stanza error to the sender.
3537</li>
3538<li>For a message stanza, the server MUST either (a) silently ignore the message or (b) return a &lt;service-unavailable/&gt; stanza error to the sender.
3539</li>
3540<li>For a presence stanza with no 'type' attribute or a 'type' attribute of "unavailable", the server MUST silently ignore the stanza.
3541</li>
3542<li>For a presence stanza of type "subscribe", "subscribed", "unsubscribe", or "unsubscribed", the server MUST silently ignore the stanza.
3543</li>
3544<li>For a presence stanza of type "probe", the server MUST either (a) silently ignore the stanza or (b) return a presence stanza of type "unsubscribed".
3545</li>
3546</ul><p>
3547
3548</p>
3549<a name="rules-localpart-barejid"></a><br /><hr />
3550<table summary="layout" cellpadding="0" cellspacing="2" class="TOCbug" align="right"><tr><td class="TOCbug"><a href="#toc">&nbsp;TOC&nbsp;</a></td></tr></table>
3551<a name="rfc.section.8.5.2"></a><h3>8.5.2.&nbsp;
3552localpart@domainpart</h3>
3553
3554<p>If the JID contained in the 'to' attribute is of the form &lt;localpart@domainpart&gt;, then the server MUST adhere to the following rules.
3555</p>
3556<a name="rules-localpart-barejid-resource"></a><br /><hr />
3557<table summary="layout" cellpadding="0" cellspacing="2" class="TOCbug" align="right"><tr><td class="TOCbug"><a href="#toc">&nbsp;TOC&nbsp;</a></td></tr></table>
3558<a name="rfc.section.8.5.2.1"></a><h3>8.5.2.1.&nbsp;
3559Available or Connected Resources</h3>
3560
3561<p>If there is at least one available resource or connected resource, how the stanza is processed depends on the stanza type.
3562</p>
3563<a name="rules-localpart-barejid-resource-message"></a><br /><hr />
3564<table summary="layout" cellpadding="0" cellspacing="2" class="TOCbug" align="right"><tr><td class="TOCbug"><a href="#toc">&nbsp;TOC&nbsp;</a></td></tr></table>
3565<a name="rfc.section.8.5.2.1.1"></a><h3>8.5.2.1.1.&nbsp;
3566Message</h3>
3567
3568<p>For a message stanza of type "normal":
3569</p>
3570<p>
3571 </p>
3572<ul class="text">
3573<li>If all of the available resources have a negative presence priority then the server SHOULD either (a) store the message offline for later delivery or (b) return a stanza error to the sender, which SHOULD be &lt;service-unavailable/&gt;.
3574</li>
3575<li>If there is one available resource with a non-negative presence priority then the server MUST deliver the message to that resource.
3576</li>
3577<li>If there is more than one resource with a non-negative presence priority then the server MUST either (a) deliver the message to the "most available" resource or resources (according to the server's implementation-specific algorithm, e.g., treating the resource or resources with the highest presence priority as "most available") or (b) deliver the message to all of the non-negative resources.
3578</li>
3579</ul><p>
3580
3581</p>
3582<p>For a message stanza of type "chat":
3583</p>
3584<p>
3585 </p>
3586<ul class="text">
3587<li>If the only available resource has a negative presence priority then the server SHOULD either (a) store the message offline for later delivery or (b) return a stanza error to the sender, which SHOULD be &lt;service-unavailable/&gt;.
3588</li>
3589<li>If the only available resource has a non-negative presence priority then the server MUST deliver the message to that resource.
3590</li>
3591<li>If there is more than one resource with a non-negative presence priority then the server MUST either (a) deliver the message to the "most available" resource or resources (according to the server's implementation-specific algorithm, e.g., treating the resource or resources with the highest presence priority as "most available") or (b) deliver the message to all of the non-negative resources that have opted in to receive chat messages.
3592</li>
3593</ul><p>
3594
3595</p>
3596<p>For a message stanza of type "groupchat", the server MUST NOT deliver the stanza to any of the available resources but instead MUST return a stanza error to the sender, which SHOULD be &lt;service-unavailable/&gt;.
3597</p>
3598<p>For a message stanza of type "headline":
3599</p>
3600<p>
3601 </p>
3602<ul class="text">
3603<li>If the only available resource has a negative presence priority then the server MUST silently ignore the stanza.
3604</li>
3605<li>If the only available resource has a non-negative presence priority then the server MUST deliver the message to that resource.
3606</li>
3607<li>If there is more than one resource with a non-negative presence priority then the server MUST deliver the message to all of the non-negative resources.
3608</li>
3609</ul><p>
3610
3611</p>
3612<p>For a message stanza of type "error", the server MUST silently ignore the message.
3613</p>
3614<p>However, for any message type the server MUST NOT deliver the stanza to any available resource with a negative priority; if the only available resource has a negative priority, the server SHOULD handle the message as if there were no available resources or connected resources as described under <a class='info' href='#rules-localpart-barejid-noresource'>Section&nbsp;8.5.2.2<span> (</span><span class='info'>No Available or Connected Resources</span><span>)</span></a>.
3615</p>
3616<p>In all cases, the server MUST NOT rewrite the 'to' attribute (i.e., it MUST leave it as &lt;localpart@domainpart&gt; rather than change it to &lt;localpart@domainpart/resourcepart&gt;).
3617</p>
3618<a name="rules-localpart-barejid-resource-pres"></a><br /><hr />
3619<table summary="layout" cellpadding="0" cellspacing="2" class="TOCbug" align="right"><tr><td class="TOCbug"><a href="#toc">&nbsp;TOC&nbsp;</a></td></tr></table>
3620<a name="rfc.section.8.5.2.1.2"></a><h3>8.5.2.1.2.&nbsp;
3621Presence</h3>
3622
3623<p>For a presence stanza with no type or of type "unavailable", the server MUST deliver it to all available resources.
3624</p>
3625<p>For a presence stanza of type "subscribe", "subscribed", "unsubscribe", or "unsubscribed", the server MUST adhere to the rules defined under <a class='info' href='#sub'>Section&nbsp;3<span> (</span><span class='info'>Managing Presence Subscriptions</span><span>)</span></a> and summarized under <a class='info' href='#substates'>Appendix&nbsp;A<span> (</span><span class='info'>Subscription States</span><span>)</span></a>.
3626</p>
3627<p>For a presence stanza of type "probe", the server MUST handle it directly as described under <a class='info' href='#presence-probe'>Section&nbsp;4.3<span> (</span><span class='info'>Presence Probes</span><span>)</span></a>.
3628</p>
3629<p>In all cases, the server MUST NOT rewrite the 'to' attribute (i.e., it MUST leave it as &lt;localpart@domainpart&gt; rather than change it to &lt;localpart@domainpart/resourcepart&gt;).
3630</p>
3631<a name="rules-localpart-barejid-resource-iq"></a><br /><hr />
3632<table summary="layout" cellpadding="0" cellspacing="2" class="TOCbug" align="right"><tr><td class="TOCbug"><a href="#toc">&nbsp;TOC&nbsp;</a></td></tr></table>
3633<a name="rfc.section.8.5.2.1.3"></a><h3>8.5.2.1.3.&nbsp;
3634IQ</h3>
3635
3636<p>For an IQ stanza, the server itself MUST reply on behalf of the user with either an IQ result or an IQ error, and MUST NOT deliver the IQ stanza to any of the user's available resources. Specifically, if the semantics of the qualifying namespace define a reply that the server can provide on behalf of the user, then the server MUST reply to the stanza on behalf of the user by returning either an IQ stanza of type "result" or an IQ stanza of type "error" that is appropriate to the original payload; if not, then the server MUST reply with a &lt;service-unavailable/&gt; stanza error.
3637</p>
3638<a name="rules-localpart-barejid-noresource"></a><br /><hr />
3639<table summary="layout" cellpadding="0" cellspacing="2" class="TOCbug" align="right"><tr><td class="TOCbug"><a href="#toc">&nbsp;TOC&nbsp;</a></td></tr></table>
3640<a name="rfc.section.8.5.2.2"></a><h3>8.5.2.2.&nbsp;
3641No Available or Connected Resources</h3>
3642
3643<p>If there are no available resources or connected resources associated with the user, how the stanza is processed depends on the stanza type.
3644</p>
3645<a name="rules-localpart-barejid-noresource-message"></a><br /><hr />
3646<table summary="layout" cellpadding="0" cellspacing="2" class="TOCbug" align="right"><tr><td class="TOCbug"><a href="#toc">&nbsp;TOC&nbsp;</a></td></tr></table>
3647<a name="rfc.section.8.5.2.2.1"></a><h3>8.5.2.2.1.&nbsp;
3648Message</h3>
3649
3650<p>For a message stanza of type "normal" or "chat", the server SHOULD either (a) add the message to offline storage or (b) return a stanza error to the sender, which SHOULD be &lt;service-unavailable/&gt;.
3651</p>
3652<p>For a message stanza of type "groupchat", the server MUST return an error to the sender, which SHOULD be &lt;service-unavailable/&gt;.
3653</p>
3654<p>For a message stanza of type "headline" or "error", the server MUST silently ignore the message.
3655</p>
3656<a name="rules-localpart-barejid-noresource-pres"></a><br /><hr />
3657<table summary="layout" cellpadding="0" cellspacing="2" class="TOCbug" align="right"><tr><td class="TOCbug"><a href="#toc">&nbsp;TOC&nbsp;</a></td></tr></table>
3658<a name="rfc.section.8.5.2.2.2"></a><h3>8.5.2.2.2.&nbsp;
3659Presence</h3>
3660
3661<p>For a presence stanza with no type or of type "unavailable", the server SHOULD silently ignore the stanza by not storing it for later delivery and not replying to it on behalf of the user.
3662</p>
3663<p>For a presence stanza of type "subscribe", "subscribed", "unsubscribe", or "unsubscribed", the server MUST adhere to the rules defined under <a class='info' href='#sub'>Section&nbsp;3<span> (</span><span class='info'>Managing Presence Subscriptions</span><span>)</span></a> and summarized under <a class='info' href='#substates'>Appendix&nbsp;A<span> (</span><span class='info'>Subscription States</span><span>)</span></a>.
3664</p>
3665<p>For a presence stanza of type "probe", the server MUST handle it directly as described under <a class='info' href='#presence-probe'>Section&nbsp;4.3<span> (</span><span class='info'>Presence Probes</span><span>)</span></a>.
3666</p>
3667<a name="rules-localpart-barejid-noresource-iq"></a><br /><hr />
3668<table summary="layout" cellpadding="0" cellspacing="2" class="TOCbug" align="right"><tr><td class="TOCbug"><a href="#toc">&nbsp;TOC&nbsp;</a></td></tr></table>
3669<a name="rfc.section.8.5.2.2.3"></a><h3>8.5.2.2.3.&nbsp;
3670IQ</h3>
3671
3672<p>For an IQ stanza, the server itself MUST reply on behalf of the user with either an IQ result or an IQ error. Specifically, if the semantics of the qualifying namespace define a reply that the server can provide on behalf of the user, then the server MUST reply to the stanza on behalf of the user by returning either an IQ stanza of type "result" or an IQ stanza of type "error" that is appropriate to the original payload; if not, then the server MUST reply with a &lt;service-unavailable/&gt; stanza error.
3673</p>
3674<a name="rules-localpart-fulljid"></a><br /><hr />
3675<table summary="layout" cellpadding="0" cellspacing="2" class="TOCbug" align="right"><tr><td class="TOCbug"><a href="#toc">&nbsp;TOC&nbsp;</a></td></tr></table>
3676<a name="rfc.section.8.5.3"></a><h3>8.5.3.&nbsp;
3677localpart@domainpart/resourcepart</h3>
3678
3679<p>If the domainpart of the JID contained in the 'to' attribute of an inbound stanza matches one of the configured domains of the server itself and the JID contained in the 'to' attribute is of the form &lt;localpart@domainpart/resourcepart&gt;, then the server MUST adhere to the following rules.
3680</p>
3681<a name="rules-localpart-fulljid-match"></a><br /><hr />
3682<table summary="layout" cellpadding="0" cellspacing="2" class="TOCbug" align="right"><tr><td class="TOCbug"><a href="#toc">&nbsp;TOC&nbsp;</a></td></tr></table>
3683<a name="rfc.section.8.5.3.1"></a><h3>8.5.3.1.&nbsp;
3684Resource Matches</h3>
3685
3686<p>If an available resource or connected resource exactly matches the full JID, how the stanza is processed depends on the stanza type.
3687</p>
3688<p>
3689 </p>
3690<ul class="text">
3691<li>For an IQ stanza of type "get" or "set", if the intended recipient does not share presence with the requesting entity either by means of a presence subscription of type "both" or "from" or by means of directed presence, then the server SHOULD NOT deliver the IQ stanza but instead SHOULD return a &lt;service-unavailable/&gt; stanza error to the requesting entity. This policy helps to prevent presence leaks (see <a class='info' href='#security'>Section&nbsp;11<span> (</span><span class='info'>Security Considerations</span><span>)</span></a>).
3692</li>
3693<li>For an IQ stanza of type "result" or "error", the server MUST deliver the stanza to the resource.
3694</li>
3695<li>For a message stanza, the server MUST deliver the stanza to the resource.
3696</li>
3697<li>For a presence stanza with no 'type' attribute or a 'type' attribute of "unavailable", the server MUST deliver the stanza to the resource.
3698</li>
3699<li>For a presence stanza of type "subscribe", "subscribed", "unsubscribe", or "unsubscribed", the server MUST follow the guidelines provided under <a class='info' href='#sub'>Section&nbsp;3<span> (</span><span class='info'>Managing Presence Subscriptions</span><span>)</span></a>.
3700</li>
3701<li>For a presence stanza of type "probe", the server MUST follow the guidelines provided under <a class='info' href='#presence-probe'>Section&nbsp;4.3<span> (</span><span class='info'>Presence Probes</span><span>)</span></a>.
3702</li>
3703</ul><p>
3704
3705</p>
3706<a name="rules-localpart-fulljid-nomatch"></a><br /><hr />
3707<table summary="layout" cellpadding="0" cellspacing="2" class="TOCbug" align="right"><tr><td class="TOCbug"><a href="#toc">&nbsp;TOC&nbsp;</a></td></tr></table>
3708<a name="rfc.section.8.5.3.2"></a><h3>8.5.3.2.&nbsp;
3709No Resource Matches</h3>
3710
3711<p>If no available resource or connected resource exactly matches the full JID, how the stanza is processed depends on the stanza type.
3712</p>
3713<a name="rules-local-fulljid-nomatch-message"></a><br /><hr />
3714<table summary="layout" cellpadding="0" cellspacing="2" class="TOCbug" align="right"><tr><td class="TOCbug"><a href="#toc">&nbsp;TOC&nbsp;</a></td></tr></table>
3715<a name="rfc.section.8.5.3.2.1"></a><h3>8.5.3.2.1.&nbsp;
3716Message</h3>
3717
3718<p>For a message stanza of type "normal", "groupchat", or "headline", the server MUST either (a) silently ignore the stanza or (b) return an error stanza to the sender, which SHOULD be &lt;service-unavailable/&gt;.
3719</p>
3720<p>For a message stanza of type "chat":
3721</p>
3722<p>
3723 </p>
3724<ul class="text">
3725<li>If there is no available or connected resource, the server MUST either (a) store the message offline for later delivery or (b) return an error stanza to the sender, which SHOULD be &lt;service-unavailable/&gt;.
3726</li>
3727<li>If all of the available resources have a negative presence priority then the server SHOULD (a) store the message offline for later delivery or (b) return a stanza error to the sender, which SHOULD be &lt;service-unavailable/&gt;.
3728</li>
3729<li>If there is one available resource with a non-negative presence priority then the server MUST deliver the message to that resource.
3730</li>
3731<li>If there is more than one resource with a non-negative presence priority then the server MUST either (a) deliver the message to the "most available" resource or resources (according to the server's implementation-specific algorithm, e.g., treating the resource or resources with the highest presence priority as "most available") or (b) deliver the message to all of the non-negative resources that have opted in to receive chat messages.
3732</li>
3733</ul><p>
3734
3735</p>
3736<p>For a message stanza of type "error", the server MUST silently ignore the stanza.
3737</p>
3738<a name="rules-localpart-fulljid-nomatch-presence"></a><br /><hr />
3739<table summary="layout" cellpadding="0" cellspacing="2" class="TOCbug" align="right"><tr><td class="TOCbug"><a href="#toc">&nbsp;TOC&nbsp;</a></td></tr></table>
3740<a name="rfc.section.8.5.3.2.2"></a><h3>8.5.3.2.2.&nbsp;
3741Presence</h3>
3742
3743<p>For a presence stanza with no 'type' attribute or a 'type' attribute of "unavailable", the server MUST silently ignore the stanza.
3744</p>
3745<p>For a presence stanza of type "subscribe", the server MUST follow the guidelines provided under <a class='info' href='#sub-request-inbound'>Section&nbsp;3.1.3<span> (</span><span class='info'>Server Processing of Inbound Subscription Request</span><span>)</span></a>.
3746</p>
3747<p>For a presence stanza of type "subscribed", "unsubscribe", or "unsubscribed", the server MUST ignore the stanza.
3748</p>
3749<p>For a presence stanza of type "probe", the server MUST follow the guidelines provided under <a class='info' href='#presence-probe'>Section&nbsp;4.3<span> (</span><span class='info'>Presence Probes</span><span>)</span></a>.
3750</p>
3751<a name="rules-localpart-fulljid-nomatch-iq"></a><br /><hr />
3752<table summary="layout" cellpadding="0" cellspacing="2" class="TOCbug" align="right"><tr><td class="TOCbug"><a href="#toc">&nbsp;TOC&nbsp;</a></td></tr></table>
3753<a name="rfc.section.8.5.3.2.3"></a><h3>8.5.3.2.3.&nbsp;
3754IQ</h3>
3755
3756<p>For an IQ stanza, the server MUST return a &lt;service-unavailable/&gt; stanza error to the sender.
3757</p>
3758<a name="rules-local-message"></a><br /><hr />
3759<table summary="layout" cellpadding="0" cellspacing="2" class="TOCbug" align="right"><tr><td class="TOCbug"><a href="#toc">&nbsp;TOC&nbsp;</a></td></tr></table>
3760<a name="rfc.section.8.5.4"></a><h3>8.5.4.&nbsp;
3761Summary of Message Delivery Rules</h3>
3762
3763<p>The following table summarizes the message (not stanza) delivery rules described earlier in this section. The left column shows various combinations of conditions (non-existent account, no active resources, only one resource and it has a negative presence priority, only one resource and it has a non-negative presence priority, or more than one resource and each one has a non-negative presence priority) and 'to' addresses (bare JID, full JID matching an available resource, or full JID matching no available resource). The subsequent columns list the four primary message types (normal, chat, groupchat, or headline) along with six possible delivery options: storing the message offline (O), bouncing the message with a stanza error (E), silently ignoring the message (S), delivering the message to the resource specified in the 'to' address (D), delivering the message to the "most available" resource or resources according to the server's implementation-specific algorithm, e.g., treating the resource or resources with the highest presence priority as "most available" (M), or delivering the message to all resources with non-negative presence priority (A -- where for chat messages "all resources" can mean the set of resources that have explicitly opted in to receiving every chat message). The '/' character stands for "exclusive or". The server SHOULD observe the rules given in section 8.1 when choosing which action to take for a particular message.
3764</p>
3765<p>Table 1: Message Delivery Rules
3766</p><div style='display: table; width: 0; margin-left: 3em; margin-right: auto'><pre>
3767+----------------------------------------------------------+
3768| Condition | Normal | Chat | Groupchat | Headline |
3769+----------------------------------------------------------+
3770| ACCOUNT DOES NOT EXIST |
3771| bare | S/E | S/E | E | S |
3772| full | S/E | S/E | S/E | S/E |
3773+----------------------------------------------------------+
3774| ACCOUNT EXISTS, BUT NO ACTIVE RESOURCES |
3775| bare | O/E | O/E | E | S |
3776| full (no match) | S/E | O/E | S/E | S/E |
3777+----------------------------------------------------------+
3778| 1+ NEGATIVE RESOURCES BUT ZERO NON-NEGATIVE RESOURCES |
3779| bare | O/E | O/E | E | S |
3780| full match | D | D | D | D |
3781| full no match | S/E | O/E | S/E | S/E |
3782+----------------------------------------------------------+
3783| 1 NON-NEGATIVE RESOURCE |
3784| bare | D | D | E | D |
3785| full match | D | D | D | D |
3786| full no match | S/E | D | S/E | S/E |
3787+----------------------------------------------------------+
3788| 1+ NON-NEGATIVE RESOURCES |
3789| bare | M/A | M/A* | E | A |
3790| full match | D | D/A* | D | D |
3791| full no match | S/E | M/A* | S/E | S/E |
3792+----------------------------------------------------------+
3793</pre></div>
3794<p></p>
3795<blockquote class="text">
3796<p>* For messages of type "chat", a server SHOULD NOT act in accordance with option (A) unless clients can explicitly opt in to receiving all chat messages; however, methods for opting in are outside the scope of this specification.
3797</p>
3798</blockquote>
3799
3800<a name="uri"></a><br /><hr />
3801<table summary="layout" cellpadding="0" cellspacing="2" class="TOCbug" align="right"><tr><td class="TOCbug"><a href="#toc">&nbsp;TOC&nbsp;</a></td></tr></table>
3802<a name="rfc.section.9"></a><h3>9.&nbsp;
3803Handling of URIs</h3>
3804
3805<p>The addresses of XMPP entities as used in communication over an XMPP network (e.g., in the 'from' and 'to' addresses of an XML stanza) MUST NOT be prepended with a Uniform Resource Identifier <a class='info' href='#URI'>[URI]<span> (</span><span class='info'>Berners-Lee, T., Fielding, R., and L. Masinter, &ldquo;Uniform Resource Identifier (URI): Generic Syntax,&rdquo; January&nbsp;2005.</span><span>)</span></a> scheme.
3806</p>
3807<p>However, an application that is external to XMPP itself (e.g., a page on the World Wide Web) might need to identify an XMPP entity either as a URI or as an Internationalized Resource Identifier <a class='info' href='#IRI'>[IRI]<span> (</span><span class='info'>Duerst, M. and M. Suignard, &ldquo;Internationalized Resource Identifiers (IRIs),&rdquo; January&nbsp;2005.</span><span>)</span></a>, and an XMPP client might need to interact with such an external application (for example, an XMPP client might be invoked by clicking a link provided on a web page). In the context of such interactions, XMPP clients are encouraged to handle addresses that are encoded as "xmpp:" URIs and IRIs as specified in <a class='info' href='#XMPP-URI'>[XMPP&#8209;URI]<span> (</span><span class='info'>Saint-Andre, P., &ldquo;Internationalized Resource Identifiers (IRIs) and Uniform Resource Identifiers (URIs) for the Extensible Messaging and Presence Protocol (XMPP),&rdquo; February&nbsp;2008.</span><span>)</span></a> and further described in <a class='info' href='#XEP-0147'>[XEP&#8209;0147]<span> (</span><span class='info'>Saint-Andre, P., &ldquo;XMPP URI Scheme Query Components,&rdquo; September&nbsp;2006.</span><span>)</span></a>. Although XMPP clients are also encouraged to handle addresses that are encoded as "im:" URIs as specified in <a class='info' href='#CPIM'>[CPIM]<span> (</span><span class='info'>Peterson, J., &ldquo;Common Profile for Instant Messaging (CPIM),&rdquo; August&nbsp;2004.</span><span>)</span></a> and "pres:" URIs as specified in <a class='info' href='#CPP'>[CPP]<span> (</span><span class='info'>Peterson, J., &ldquo;Common Profile for Presence (CPP),&rdquo; August&nbsp;2004.</span><span>)</span></a>, they can do so by removing the "im:" or "pres:" scheme and entrusting address resolution to the server as specified under <a class='info' href='#rules-remote'>Section&nbsp;8.3<span> (</span><span class='info'>Remote Domain</span><span>)</span></a>.
3808</p>
3809<a name="i18n"></a><br /><hr />
3810<table summary="layout" cellpadding="0" cellspacing="2" class="TOCbug" align="right"><tr><td class="TOCbug"><a href="#toc">&nbsp;TOC&nbsp;</a></td></tr></table>
3811<a name="rfc.section.10"></a><h3>10.&nbsp;
3812Internationalization Considerations</h3>
3813
3814<p>For internationalization considerations, refer to the relevant section of <a class='info' href='#XMPP-CORE'>[XMPP&#8209;CORE]<span> (</span><span class='info'>Saint-Andre, P., &ldquo;Extensible Messaging and Presence Protocol (XMPP): Core,&rdquo; March&nbsp;2011.</span><span>)</span></a>.
3815</p>
3816<a name="security"></a><br /><hr />
3817<table summary="layout" cellpadding="0" cellspacing="2" class="TOCbug" align="right"><tr><td class="TOCbug"><a href="#toc">&nbsp;TOC&nbsp;</a></td></tr></table>
3818<a name="rfc.section.11"></a><h3>11.&nbsp;
3819Security Considerations</h3>
3820
3821<p>Core security considerations for XMPP are provided in Section 13 of <a class='info' href='#XMPP-CORE'>[XMPP&#8209;CORE]<span> (</span><span class='info'>Saint-Andre, P., &ldquo;Extensible Messaging and Presence Protocol (XMPP): Core,&rdquo; March&nbsp;2011.</span><span>)</span></a>, including discussion of channel encryption, authentication, information leaks, denial-of-service attacks, and interdomain federation.
3822</p>
3823<p>Section 13.1 of <a class='info' href='#XMPP-CORE'>[XMPP&#8209;CORE]<span> (</span><span class='info'>Saint-Andre, P., &ldquo;Extensible Messaging and Presence Protocol (XMPP): Core,&rdquo; March&nbsp;2011.</span><span>)</span></a> outlines the architectural roles of clients and servers in typical deployments of XMPP, and discusses the security properties associated with those roles. These roles have an impact on the security of instant messages, presence subscriptions, and presence notifications as described in this document. In essence, an XMPP user registers (or has provisioned) an account on an XMPP server and therefore places some level of trust in the server to complete various tasks on the user's behalf, enforce security policies, etc. Thus it is the server's responsibility to:
3824</p>
3825<p>
3826 </p>
3827<ol class="text">
3828<li>Preferably mandate the use of channel encryption for communication with local clients and remote servers.
3829</li>
3830<li>Authenticate any client that wishes to access the user's account.
3831</li>
3832<li>Process XML stanzas to and from clients that have authenticated as the user (specifically with regard to instant messaging and presence functionality, store the user's roster, process inbound and outbound subscription requests and responses, generate and handle presence probes, broadcast outbound presence notifications, route outbound messages, and deliver inbound messages and presence notifications).
3833</li>
3834</ol><p>
3835
3836</p>
3837<p>As discussed in Sections 13.1 and 13.4 of <a class='info' href='#XMPP-CORE'>[XMPP&#8209;CORE]<span> (</span><span class='info'>Saint-Andre, P., &ldquo;Extensible Messaging and Presence Protocol (XMPP): Core,&rdquo; March&nbsp;2011.</span><span>)</span></a>, even if the server fulfills the foregoing responsibilities, the client does not have any assurance that stanzas it might exchange with other clients (whether on the same server or a remote server) are protected for all hops along the XMPP communication path, or within the server itself. It is the responsibility of the client to use an appropriate technology for encryption and signing of XML stanzas if it wishes to ensure end-to-end confidentiality and integrity of its communications.
3838</p>
3839<p>Additional considerations that apply only to instant messaging and presence applications of XMPP are defined in several places within this document; specifically:
3840</p>
3841<p>
3842 </p>
3843<ul class="text">
3844<li>When a server processes an inbound presence stanza of type "probe" whose intended recipient is a user associated with one of the server's configured domains, the server MUST NOT reveal the user's presence if the sender is an entity that is not authorized to receive that information as determined by presence subscriptions (see <a class='info' href='#presence'>Section&nbsp;4<span> (</span><span class='info'>Exchanging Presence Information</span><span>)</span></a>).
3845</li>
3846<li>A user's server MUST NOT leak the user's network availability to entities who are not authorized to know the user's presence. In XMPP itself, authorization takes the form of an explicit subscription from a contact to the user (as described under <a class='info' href='#sub'>Section&nbsp;3<span> (</span><span class='info'>Managing Presence Subscriptions</span><span>)</span></a>). However, some XMPP deployments might consider an entity to be authorized if there is an existing trust relationship between the entity and the user who is generating presence information (as an example, a corporate deployment of XMPP might automatically add the user's presence information to a private directory of employees if the organization mandates the sharing of presence information as part of an employment agreement).
3847</li>
3848<li>When a server processes an outbound presence stanza with no type or of type "unavailable", it MUST follow the rules defined under <a class='info' href='#presence'>Section&nbsp;4<span> (</span><span class='info'>Exchanging Presence Information</span><span>)</span></a> in order to ensure that such presence information is not sent to entities that are not authorized to know such information.
3849</li>
3850<li>A client MAY ignore the &lt;status/&gt; element when contained in a presence stanza of type "subscribe", "unsubscribe", "subscribed", or "unsubscribed"; this can help prevent "presence subscription spam".
3851</li>
3852</ul><p>
3853
3854</p>
3855<a name="conformance"></a><br /><hr />
3856<table summary="layout" cellpadding="0" cellspacing="2" class="TOCbug" align="right"><tr><td class="TOCbug"><a href="#toc">&nbsp;TOC&nbsp;</a></td></tr></table>
3857<a name="rfc.section.12"></a><h3>12.&nbsp;
3858Conformance Requirements</h3>
3859
3860<p>This section describes a protocol feature set that summarizes the conformance requirements of this specification. This feature set is appropriate for use in software certification, interoperability testing, and implementation reports. For each feature, this section provides the following information:
3861</p>
3862<p>
3863 </p>
3864<ul class="text">
3865<li>A human-readable name
3866</li>
3867<li>An informational description
3868</li>
3869<li>A reference to the particular section of this document that normatively defines the feature
3870</li>
3871<li>Whether the feature applies to the Client role, the Server role, or both (where "N/A" signifies that the feature is not applicable to the specified role)
3872</li>
3873<li>Whether the feature MUST or SHOULD be implemented, where the capitalized terms are to be understood as described in <a class='info' href='#KEYWORDS'>[KEYWORDS]<span> (</span><span class='info'>Bradner, S., &ldquo;Key words for use in RFCs to Indicate Requirement Levels,&rdquo; March&nbsp;1997.</span><span>)</span></a>
3874</li>
3875</ul><p>
3876
3877</p>
3878<p>The feature set specified here attempts to adhere to the concepts and formats proposed by Larry Masinter within the IETF's NEWTRK Working Group in 2005, as captured in <a class='info' href='#INTEROP'>[INTEROP]<span> (</span><span class='info'>Masinter, L., &ldquo;Formalizing IETF Interoperability Reporting,&rdquo; October&nbsp;2005.</span><span>)</span></a>. Although this feature set is more detailed than called for by <a class='info' href='#REPORTS'>[REPORTS]<span> (</span><span class='info'>Dusseault, L. and R. Sparks, &ldquo;Guidance on Interoperation and Implementation Reports for Advancement to Draft Standard,&rdquo; September&nbsp;2009.</span><span>)</span></a>, it provides a suitable basis for the generation of implementation reports to be submitted in support of advancing this specification from Proposed Standard to Draft Standard in accordance with <a class='info' href='#PROCESS'>[PROCESS]<span> (</span><span class='info'>Bradner, S., &ldquo;The Internet Standards Process -- Revision 3,&rdquo; October&nbsp;1996.</span><span>)</span></a>.
3879</p>
3880<p>
3881 </p>
3882<blockquote class="text"><dl>
3883<dt>Feature:</dt>
3884<dd>message-body
3885</dd>
3886<dt>Description:</dt>
3887<dd>Support the &lt;body/&gt; child element of the &lt;message/&gt; stanza.
3888</dd>
3889<dt>Section:</dt>
3890<dd><a class='info' href='#message-syntax-body'>Section&nbsp;5.2.3<span> (</span><span class='info'>Body Element</span><span>)</span></a>
3891</dd>
3892<dt>Roles:</dt>
3893<dd>Client MUST, Server N/A.
3894</dd>
3895</dl></blockquote><p>
3896
3897</p>
3898<p>
3899 </p>
3900<blockquote class="text"><dl>
3901<dt>Feature:</dt>
3902<dd>message-subject
3903</dd>
3904<dt>Description:</dt>
3905<dd>Support the &lt;subject/&gt; child element of the &lt;message/&gt; stanza.
3906</dd>
3907<dt>Section:</dt>
3908<dd><a class='info' href='#message-syntax-subject'>Section&nbsp;5.2.4<span> (</span><span class='info'>Subject Element</span><span>)</span></a>
3909</dd>
3910<dt>Roles:</dt>
3911<dd>Client SHOULD, Server N/A.
3912</dd>
3913</dl></blockquote><p>
3914
3915</p>
3916<p>
3917 </p>
3918<blockquote class="text"><dl>
3919<dt>Feature:</dt>
3920<dd>message-thread
3921</dd>
3922<dt>Description:</dt>
3923<dd>Support the &lt;thread/&gt; child element of the &lt;message/&gt; stanza.
3924</dd>
3925<dt>Section:</dt>
3926<dd><a class='info' href='#message-syntax-thread'>Section&nbsp;5.2.5<span> (</span><span class='info'>Thread Element</span><span>)</span></a>
3927</dd>
3928<dt>Roles:</dt>
3929<dd>Client SHOULD, Server N/A.
3930</dd>
3931</dl></blockquote><p>
3932
3933</p>
3934<p>
3935 </p>
3936<blockquote class="text"><dl>
3937<dt>Feature:</dt>
3938<dd>message-type-support
3939</dd>
3940<dt>Description:</dt>
3941<dd>Support reception of messages of type "normal", "chat", "groupchat", "headline", and "error".
3942</dd>
3943<dt>Section:</dt>
3944<dd><a class='info' href='#message-syntax-type'>Section&nbsp;5.2.2<span> (</span><span class='info'>Type Attribute</span><span>)</span></a>
3945</dd>
3946<dt>Roles:</dt>
3947<dd>Client SHOULD, Server N/A.
3948</dd>
3949</dl></blockquote><p>
3950
3951</p>
3952<p>
3953 </p>
3954<blockquote class="text"><dl>
3955<dt>Feature:</dt>
3956<dd>message-type-deliver
3957</dd>
3958<dt>Description:</dt>
3959<dd>Appropriately deliver messages of type "normal", "chat", "groupchat", "headline", and "error".
3960</dd>
3961<dt>Section:</dt>
3962<dd><a class='info' href='#rules'>Section&nbsp;8<span> (</span><span class='info'>Server Rules for Processing XML Stanzas</span><span>)</span></a>
3963</dd>
3964<dt>Roles:</dt>
3965<dd>Client N/A, Server SHOULD.
3966</dd>
3967</dl></blockquote><p>
3968
3969</p>
3970<p>
3971 </p>
3972<blockquote class="text"><dl>
3973<dt>Feature:</dt>
3974<dd>presence-notype
3975</dd>
3976<dt>Description:</dt>
3977<dd>Treat a presence stanza with no 'type' attribute as indicating availability.
3978</dd>
3979<dt>Section:</dt>
3980<dd><a class='info' href='#presence-syntax-type'>Section&nbsp;4.7.1<span> (</span><span class='info'>Type Attribute</span><span>)</span></a>
3981</dd>
3982<dt>Roles:</dt>
3983<dd>Client MUST, Server MUST.
3984</dd>
3985</dl></blockquote><p>
3986
3987</p>
3988<p>
3989 </p>
3990<blockquote class="text"><dl>
3991<dt>Feature:</dt>
3992<dd>presence-probe
3993</dd>
3994<dt>Description:</dt>
3995<dd>Send and receive presence stanzas with a 'type' attribute of "probe" for the discovery of presence information.
3996</dd>
3997<dt>Section:</dt>
3998<dd><a class='info' href='#presence-syntax-type'>Section&nbsp;4.7.1<span> (</span><span class='info'>Type Attribute</span><span>)</span></a>
3999</dd>
4000<dt>Roles:</dt>
4001<dd>Client N/A, Server MUST.
4002</dd>
4003</dl></blockquote><p>
4004
4005</p>
4006<p>
4007 </p>
4008<blockquote class="text"><dl>
4009<dt>Feature:</dt>
4010<dd>presence-sub-approval
4011</dd>
4012<dt>Description:</dt>
4013<dd>Treat an outbound presence stanza of type "subscribed" as the act of approving a presence subscription request previously received from another entity, and treat an inbound presence stanza of type "subscribed" as a subscription approval from another entity.
4014</dd>
4015<dt>Section:</dt>
4016<dd><a class='info' href='#sub-request'>Section&nbsp;3.1<span> (</span><span class='info'>Requesting a Subscription</span><span>)</span></a>
4017</dd>
4018<dt>Roles:</dt>
4019<dd>Client MUST, Server MUST.
4020</dd>
4021</dl></blockquote><p>
4022
4023</p>
4024<p>
4025 </p>
4026<blockquote class="text"><dl>
4027<dt>Feature:</dt>
4028<dd>presence-sub-cancel
4029</dd>
4030<dt>Description:</dt>
4031<dd>Treat an outbound presence stanza of type "unsubscribed" as the act of denying a subscription request received from another entity or canceling a subscription approval previously granted to another entity, and treat an inbound presence stanza of type "unsubscribed" as an subscription denial or cancellation from another entity.
4032</dd>
4033<dt>Section:</dt>
4034<dd><a class='info' href='#sub-cancel'>Section&nbsp;3.2<span> (</span><span class='info'>Canceling a Subscription</span><span>)</span></a>
4035</dd>
4036<dt>Roles:</dt>
4037<dd>Client MUST, Server MUST.
4038</dd>
4039</dl></blockquote><p>
4040
4041</p>
4042<p>
4043 </p>
4044<blockquote class="text"><dl>
4045<dt>Feature:</dt>
4046<dd>presence-sub-preapproval
4047</dd>
4048<dt>Description:</dt>
4049<dd>Treat an outbound presence stanza of type "subscribed" in certain circumstances as the act of pre-approving a subscription request received from another entity; this includes support for the 'approved' attribute of the &lt;item/&gt; element within the 'jabber:iq:roster' namespace.
4050</dd>
4051<dt>Section:</dt>
4052<dd><a class='info' href='#sub-preapproval'>Section&nbsp;3.4<span> (</span><span class='info'>Pre-Approving a Subscription Request</span><span>)</span></a>
4053</dd>
4054<dt>Roles:</dt>
4055<dd>Client MAY, Server MAY.
4056</dd>
4057</dl></blockquote><p>
4058
4059</p>
4060<p>
4061 </p>
4062<blockquote class="text"><dl>
4063<dt>Feature:</dt>
4064<dd>presence-sub-request
4065</dd>
4066<dt>Description:</dt>
4067<dd>Treat an outbound presence stanza of type "subscribe" as the act of requesting a subscription to the presence information of another entity, and treat an inbound presence stanza of type "subscribe" as a presence subscription request from another entity.
4068</dd>
4069<dt>Section:</dt>
4070<dd><a class='info' href='#sub-request'>Section&nbsp;3.1<span> (</span><span class='info'>Requesting a Subscription</span><span>)</span></a>
4071</dd>
4072<dt>Roles:</dt>
4073<dd>Client MUST, Server MUST.
4074</dd>
4075</dl></blockquote><p>
4076
4077</p>
4078<p>
4079 </p>
4080<blockquote class="text"><dl>
4081<dt>Feature:</dt>
4082<dd>presence-sub-unsubscribe
4083</dd>
4084<dt>Description:</dt>
4085<dd>Treat an outbound presence stanza of type "unsubscribe" as the act of unsubscribing from another entity, and treat an inbound presence stanza of type "unsubscribe" as an unsubscribe notification from another entity.
4086</dd>
4087<dt>Section:</dt>
4088<dd><a class='info' href='#sub-unsub'>Section&nbsp;3.3<span> (</span><span class='info'>Unsubscribing</span><span>)</span></a>
4089</dd>
4090<dt>Roles:</dt>
4091<dd>Client MUST, Server MUST.
4092</dd>
4093</dl></blockquote><p>
4094
4095</p>
4096<p>
4097 </p>
4098<blockquote class="text"><dl>
4099<dt>Feature:</dt>
4100<dd>presence-unavailable
4101</dd>
4102<dt>Description:</dt>
4103<dd>Treat a presence stanza with a 'type' attribute of "unavailable" as indicating lack of availability.
4104</dd>
4105<dt>Section:</dt>
4106<dd><a class='info' href='#presence-syntax-type'>Section&nbsp;4.7.1<span> (</span><span class='info'>Type Attribute</span><span>)</span></a>
4107</dd>
4108<dt>Roles:</dt>
4109<dd>Client MUST, Server MUST.
4110</dd>
4111</dl></blockquote><p>
4112
4113</p>
4114<p>
4115 </p>
4116<blockquote class="text"><dl>
4117<dt>Feature:</dt>
4118<dd>roster-get
4119</dd>
4120<dt>Description:</dt>
4121<dd>Treat an IQ stanza of type "get" containing an empty &lt;query/&gt; element qualified by the 'jabber:iq:roster' namespace as a request to retrieve the roster information associated with an account on a server.
4122</dd>
4123<dt>Section:</dt>
4124<dd><a class='info' href='#roster-syntax-actions-get'>Section&nbsp;2.1.3<span> (</span><span class='info'>Roster Get</span><span>)</span></a>
4125</dd>
4126<dt>Roles:</dt>
4127<dd>Client MUST, Server MUST.
4128</dd>
4129</dl></blockquote><p>
4130
4131</p>
4132<p>
4133 </p>
4134<blockquote class="text"><dl>
4135<dt>Feature:</dt>
4136<dd>roster-set
4137</dd>
4138<dt>Description:</dt>
4139<dd>Treat an IQ stanza of type "set" containing a &lt;query/&gt; element qualified by the 'jabber:iq:roster' namespace as a request to add or update the item contained in the &lt;query/&gt; element.
4140</dd>
4141<dt>Section:</dt>
4142<dd><a class='info' href='#roster-syntax-actions-set'>Section&nbsp;2.1.5<span> (</span><span class='info'>Roster Set</span><span>)</span></a>
4143</dd>
4144<dt>Roles:</dt>
4145<dd>Client MUST, Server MUST.
4146</dd>
4147</dl></blockquote><p>
4148
4149</p>
4150<p>
4151 </p>
4152<blockquote class="text"><dl>
4153<dt>Feature:</dt>
4154<dd>roster-push
4155</dd>
4156<dt>Description:</dt>
4157<dd>Send a roster push to each interested resource whenever the server-side representation of the roster information materially changes, or handle such a push when received from the server.
4158</dd>
4159<dt>Section:</dt>
4160<dd><a class='info' href='#roster-syntax-actions-push'>Section&nbsp;2.1.6<span> (</span><span class='info'>Roster Push</span><span>)</span></a>
4161</dd>
4162<dt>Roles:</dt>
4163<dd>Client MUST, Server MUST.
4164</dd>
4165</dl></blockquote><p>
4166
4167</p>
4168<p>
4169 </p>
4170<blockquote class="text"><dl>
4171<dt>Feature:</dt>
4172<dd>roster-version
4173</dd>
4174<dt>Description:</dt>
4175<dd>Treat the 'ver' attribute of the &lt;query/&gt; element qualified by the 'jabber:iq:roster' namespace as an identifier of the particular version of roster information being sent or received.
4176</dd>
4177<dt>Section:</dt>
4178<dd><a class='info' href='#roster-syntax-ver'>Section&nbsp;2.1.1<span> (</span><span class='info'>Ver Attribute</span><span>)</span></a>
4179</dd>
4180<dt>Roles:</dt>
4181<dd>Client SHOULD, Server MUST.
4182</dd>
4183</dl></blockquote><p>
4184
4185</p>
4186<a name="rfc.references"></a><br /><hr />
4187<table summary="layout" cellpadding="0" cellspacing="2" class="TOCbug" align="right"><tr><td class="TOCbug"><a href="#toc">&nbsp;TOC&nbsp;</a></td></tr></table>
4188<a name="rfc.section.13"></a><h3>13.&nbsp;
4189References</h3>
4190
4191<a name="rfc.references1"></a><br /><hr />
4192<table summary="layout" cellpadding="0" cellspacing="2" class="TOCbug" align="right"><tr><td class="TOCbug"><a href="#toc">&nbsp;TOC&nbsp;</a></td></tr></table>
4193<h3>13.1.&nbsp;Normative References</h3>
4194<table width="99%" border="0">
4195<tr><td class="author-text" valign="top"><a name="DELAY">[DELAY]</a></td>
4196<td class="author-text"><a href="mailto:stpeter@jabber.org">Saint-Andre, P.</a>, &ldquo;<a href="http://xmpp.org/extensions/xep-0203.html">Delayed Delivery</a>,&rdquo; XSF XEP&nbsp;0203, September&nbsp;2009.</td></tr>
4197<tr><td class="author-text" valign="top"><a name="KEYWORDS">[KEYWORDS]</a></td>
4198<td class="author-text"><a href="mailto:sob@harvard.edu">Bradner, S.</a>, &ldquo;<a href="http://tools.ietf.org/html/rfc2119">Key words for use in RFCs to Indicate Requirement Levels</a>,&rdquo; BCP&nbsp;14, RFC&nbsp;2119, March&nbsp;1997 (<a href="http://www.rfc-editor.org/rfc/rfc2119.txt">TXT</a>, <a href="http://xml.resource.org/public/rfc/html/rfc2119.html">HTML</a>, <a href="http://xml.resource.org/public/rfc/xml/rfc2119.xml">XML</a>).</td></tr>
4199<tr><td class="author-text" valign="top"><a name="XML">[XML]</a></td>
4200<td class="author-text">Maler, E., Yergeau, F., Sperberg-McQueen, C., Paoli, J., and T. Bray, &ldquo;<a href="http://www.w3.org/TR/2008/REC-xml-20081126">Extensible Markup Language (XML) 1.0 (Fifth Edition)</a>,&rdquo; World Wide Web Consortium Recommendation&nbsp;REC&#8209;xml&#8209;20081126, November&nbsp;2008 (<a href="http://www.w3.org/TR/2008/REC-xml-20081126">HTML</a>).</td></tr>
4201<tr><td class="author-text" valign="top"><a name="XML-NAMES">[XML-NAMES]</a></td>
4202<td class="author-text"><a href="mailto:tbray@textuality.com">Bray, T.</a>, <a href="mailto:dmh@corp.hp.com">Hollander, D.</a>, and <a href="mailto:andrewl@microsoft.com">A. Layman</a>, &ldquo;<a href="http://www.w3.org/TR/REC-xml-names">Namespaces in XML</a>,&rdquo; W3C&nbsp;REC-xml-names, January&nbsp;1999.</td></tr>
4203<tr><td class="author-text" valign="top"><a name="XMPP-CORE">[XMPP-CORE]</a></td>
4204<td class="author-text">Saint-Andre, P., &ldquo;<a href="http://tools.ietf.org/html/rfc6120">Extensible Messaging and Presence Protocol (XMPP): Core</a>,&rdquo; RFC&nbsp;6120, March&nbsp;2011.</td></tr>
4205</table>
4206
4207<a name="rfc.references2"></a><br /><hr />
4208<table summary="layout" cellpadding="0" cellspacing="2" class="TOCbug" align="right"><tr><td class="TOCbug"><a href="#toc">&nbsp;TOC&nbsp;</a></td></tr></table>
4209<h3>13.2.&nbsp;Informative References</h3>
4210<table width="99%" border="0">
4211<tr><td class="author-text" valign="top"><a name="CPIM">[CPIM]</a></td>
4212<td class="author-text">Peterson, J., &ldquo;<a href="http://tools.ietf.org/html/rfc3860">Common Profile for Instant Messaging (CPIM)</a>,&rdquo; RFC&nbsp;3860, August&nbsp;2004 (<a href="http://www.rfc-editor.org/rfc/rfc3860.txt">TXT</a>).</td></tr>
4213<tr><td class="author-text" valign="top"><a name="CPP">[CPP]</a></td>
4214<td class="author-text">Peterson, J., &ldquo;<a href="http://tools.ietf.org/html/rfc3859">Common Profile for Presence (CPP)</a>,&rdquo; RFC&nbsp;3859, August&nbsp;2004 (<a href="http://www.rfc-editor.org/rfc/rfc3859.txt">TXT</a>).</td></tr>
4215<tr><td class="author-text" valign="top"><a name="DOS">[DOS]</a></td>
4216<td class="author-text">Handley, M., Rescorla, E., and IAB, &ldquo;<a href="http://tools.ietf.org/html/rfc4732">Internet Denial-of-Service Considerations</a>,&rdquo; RFC&nbsp;4732, December&nbsp;2006 (<a href="http://www.rfc-editor.org/rfc/rfc4732.txt">TXT</a>).</td></tr>
4217<tr><td class="author-text" valign="top"><a name="IMP-MODEL">[IMP-MODEL]</a></td>
4218<td class="author-text"><a href="mailto:mday@alum.mit.edu">Day, M.</a>, <a href="mailto:jdrosen@dynamicsoft.com">Rosenberg, J.</a>, and <a href="mailto:suga@flab.fujitsu.co.jp">H. Sugano</a>, &ldquo;<a href="http://tools.ietf.org/html/rfc2778">A Model for Presence and Instant Messaging</a>,&rdquo; RFC&nbsp;2778, February&nbsp;2000.</td></tr>
4219<tr><td class="author-text" valign="top"><a name="IMP-REQS">[IMP-REQS]</a></td>
4220<td class="author-text"><a href="mailto:mday@alum.mit.edu">Day, M.</a>, <a href="mailto:sonuag@microsoft.com">Aggarwal, S.</a>, and <a href="mailto:jesse@intonet.com">J. Vincent</a>, &ldquo;<a href="http://tools.ietf.org/html/rfc2779">Instant Messaging / Presence Protocol Requirements</a>,&rdquo; RFC&nbsp;2779, February&nbsp;2000 (<a href="http://www.rfc-editor.org/rfc/rfc2779.txt">TXT</a>).</td></tr>
4221<tr><td class="author-text" valign="top"><a name="IMP-SRV">[IMP-SRV]</a></td>
4222<td class="author-text">Peterson, J., &ldquo;<a href="http://tools.ietf.org/html/rfc3861">Address Resolution for Instant Messaging and Presence</a>,&rdquo; RFC&nbsp;3861, August&nbsp;2004 (<a href="http://www.rfc-editor.org/rfc/rfc3861.txt">TXT</a>).</td></tr>
4223<tr><td class="author-text" valign="top"><a name="INTEROP">[INTEROP]</a></td>
4224<td class="author-text">Masinter, L., &ldquo;Formalizing IETF Interoperability Reporting,&rdquo; Work in&nbsp;Progress, October&nbsp;2005.</td></tr>
4225<tr><td class="author-text" valign="top"><a name="IRC">[IRC]</a></td>
4226<td class="author-text">Kalt, C., &ldquo;<a href="http://tools.ietf.org/html/rfc2810">Internet Relay Chat: Architecture</a>,&rdquo; RFC&nbsp;2810, April&nbsp;2000 (<a href="http://www.rfc-editor.org/rfc/rfc2810.txt">TXT</a>).</td></tr>
4227<tr><td class="author-text" valign="top"><a name="IRI">[IRI]</a></td>
4228<td class="author-text">Duerst, M. and M. Suignard, &ldquo;<a href="http://tools.ietf.org/html/rfc3987">Internationalized Resource Identifiers (IRIs)</a>,&rdquo; RFC&nbsp;3987, January&nbsp;2005 (<a href="http://www.rfc-editor.org/rfc/rfc3987.txt">TXT</a>).</td></tr>
4229<tr><td class="author-text" valign="top"><a name="PROCESS">[PROCESS]</a></td>
4230<td class="author-text"><a href="mailto:sob@harvard.edu">Bradner, S.</a>, &ldquo;<a href="http://tools.ietf.org/html/rfc2026">The Internet Standards Process -- Revision 3</a>,&rdquo; BCP&nbsp;9, RFC&nbsp;2026, October&nbsp;1996 (<a href="http://www.rfc-editor.org/rfc/rfc2026.txt">TXT</a>).</td></tr>
4231<tr><td class="author-text" valign="top"><a name="REPORTS">[REPORTS]</a></td>
4232<td class="author-text">Dusseault, L. and R. Sparks, &ldquo;<a href="http://tools.ietf.org/html/rfc5657">Guidance on Interoperation and Implementation Reports for Advancement to Draft Standard</a>,&rdquo; BCP&nbsp;9, RFC&nbsp;5657, September&nbsp;2009 (<a href="http://www.rfc-editor.org/rfc/rfc5657.txt">TXT</a>).</td></tr>
4233<tr><td class="author-text" valign="top"><a name="RFC3920">[RFC3920]</a></td>
4234<td class="author-text"><a href="mailto:stpeter@jabber.org">Saint-Andre, P., Ed.</a>, &ldquo;<a href="http://tools.ietf.org/html/rfc3920">Extensible Messaging and Presence Protocol (XMPP): Core</a>,&rdquo; RFC&nbsp;3920, October&nbsp;2004 (<a href="http://www.rfc-editor.org/rfc/rfc3920.txt">TXT</a>, <a href="http://xml.resource.org/public/rfc/html/rfc3920.html">HTML</a>, <a href="http://xml.resource.org/public/rfc/xml/rfc3920.xml">XML</a>).</td></tr>
4235<tr><td class="author-text" valign="top"><a name="RFC3921">[RFC3921]</a></td>
4236<td class="author-text"><a href="mailto:stpeter@jabber.org">Saint-Andre, P., Ed.</a>, &ldquo;<a href="http://tools.ietf.org/html/rfc3921">Extensible Messaging and Presence Protocol (XMPP): Instant Messaging and Presence</a>,&rdquo; RFC&nbsp;3921, October&nbsp;2004 (<a href="http://www.rfc-editor.org/rfc/rfc3921.txt">TXT</a>, <a href="http://xml.resource.org/public/rfc/html/rfc3921.html">HTML</a>, <a href="http://xml.resource.org/public/rfc/xml/rfc3921.xml">XML</a>).</td></tr>
4237<tr><td class="author-text" valign="top"><a name="SASL">[SASL]</a></td>
4238<td class="author-text">Melnikov, A. and K. Zeilenga, &ldquo;<a href="http://tools.ietf.org/html/rfc4422">Simple Authentication and Security Layer (SASL)</a>,&rdquo; RFC&nbsp;4422, June&nbsp;2006 (<a href="http://www.rfc-editor.org/rfc/rfc4422.txt">TXT</a>).</td></tr>
4239<tr><td class="author-text" valign="top"><a name="SIP-PRES">[SIP-PRES]</a></td>
4240<td class="author-text">Rosenberg, J., &ldquo;<a href="http://tools.ietf.org/html/rfc3856">A Presence Event Package for the Session Initiation Protocol (SIP)</a>,&rdquo; RFC&nbsp;3856, August&nbsp;2004 (<a href="http://www.rfc-editor.org/rfc/rfc3856.txt">TXT</a>).</td></tr>
4241<tr><td class="author-text" valign="top"><a name="TLS">[TLS]</a></td>
4242<td class="author-text">Dierks, T. and E. Rescorla, &ldquo;<a href="http://tools.ietf.org/html/rfc5246">The Transport Layer Security (TLS) Protocol Version 1.2</a>,&rdquo; RFC&nbsp;5246, August&nbsp;2008 (<a href="http://www.rfc-editor.org/rfc/rfc5246.txt">TXT</a>).</td></tr>
4243<tr><td class="author-text" valign="top"><a name="TLS-CERTS">[TLS-CERTS]</a></td>
4244<td class="author-text">Saint-Andre, P. and J. Hodges, &ldquo;<a href="http://tools.ietf.org/html/rfc6125">Representation and Verification of Domain-Based Application Service Identity within Internet Public Key Infrastructure Using X.509 (PKIX) Certificates in the Context of Transport Layer Security (TLS)</a>,&rdquo; RFC&nbsp;6125, March&nbsp;2011.</td></tr>
4245<tr><td class="author-text" valign="top"><a name="UNICODE">[UNICODE]</a></td>
4246<td class="author-text">The Unicode Consortium, &ldquo;<a href="http://www.unicode.org/versions/Unicode6.0.0/">The Unicode Standard, Version 6.0</a>,&rdquo; 2010.</td></tr>
4247<tr><td class="author-text" valign="top"><a name="URI">[URI]</a></td>
4248<td class="author-text">Berners-Lee, T., Fielding, R., and L. Masinter, &ldquo;<a href="http://tools.ietf.org/html/rfc3986">Uniform Resource Identifier (URI): Generic Syntax</a>,&rdquo; STD&nbsp;66, RFC&nbsp;3986, January&nbsp;2005 (<a href="http://www.rfc-editor.org/rfc/rfc3986.txt">TXT</a>).</td></tr>
4249<tr><td class="author-text" valign="top"><a name="UUID">[UUID]</a></td>
4250<td class="author-text"><a href="mailto:paulle@microsoft.com">Leach, P.</a>, <a href="mailto:michael@refactored-networks.com">Mealling, M.</a>, and <a href="mailto:rsalz@datapower.com">R. Salz</a>, &ldquo;<a href="http://tools.ietf.org/html/rfc4122">A Universally Unique IDentifier (UUID) URN Namespace</a>,&rdquo; RFC&nbsp;4122, July&nbsp;2005 (<a href="http://www.rfc-editor.org/rfc/rfc4122.txt">TXT</a>, <a href="http://xml.resource.org/public/rfc/html/rfc4122.html">HTML</a>, <a href="http://xml.resource.org/public/rfc/xml/rfc4122.xml">XML</a>).</td></tr>
4251<tr><td class="author-text" valign="top"><a name="XEP-0016">[XEP-0016]</a></td>
4252<td class="author-text">Millard, P. and <a href="mailto:stpeter@jabber.org">P. Saint-Andre</a>, &ldquo;<a href="http://www.xmpp.org/extensions/xep-0016.html">Privacy Lists</a>,&rdquo; XSF XEP&nbsp;0016, February&nbsp;2007.</td></tr>
4253<tr><td class="author-text" valign="top"><a name="XEP-0045">[XEP-0045]</a></td>
4254<td class="author-text"><a href="mailto:stpeter@jabber.org">Saint-Andre, P.</a>, &ldquo;<a href="http://www.xmpp.org/extensions/xep-0045.html">Multi-User Chat</a>,&rdquo; XSF XEP&nbsp;0045, July&nbsp;2008.</td></tr>
4255<tr><td class="author-text" valign="top"><a name="XEP-0054">[XEP-0054]</a></td>
4256<td class="author-text"><a href="mailto:stpeter@jabber.org">Saint-Andre, P.</a>, &ldquo;<a href="http://www.xmpp.org/extensions/xep-0054.html">vcard-temp</a>,&rdquo; XSF XEP&nbsp;0054, July&nbsp;2008.</td></tr>
4257<tr><td class="author-text" valign="top"><a name="XEP-0071">[XEP-0071]</a></td>
4258<td class="author-text"><a href="mailto:stpeter@jabber.org">Saint-Andre, P.</a>, &ldquo;<a href="http://www.xmpp.org/extensions/xep-0071.html">XHTML-IM</a>,&rdquo; XSF XEP&nbsp;0071, September&nbsp;2008.</td></tr>
4259<tr><td class="author-text" valign="top"><a name="XEP-0115">[XEP-0115]</a></td>
4260<td class="author-text"><a href="mailto:jhildebrand@jabber.com">Hildebrand, J.</a>, <a href="mailto:stpeter@jabber.org">Saint-Andre, P.</a>, and <a href="mailto:public@el-tramo.be">R. Tron&#xE7;on</a>, &ldquo;<a href="http://www.xmpp.org/extensions/xep-0115.html">Entity Capabilities</a>,&rdquo; XSF XEP&nbsp;0115, February&nbsp;2008.</td></tr>
4261<tr><td class="author-text" valign="top"><a name="XEP-0147">[XEP-0147]</a></td>
4262<td class="author-text"><a href="mailto:">Saint-Andre, P.</a>, &ldquo;<a href="http://www.xmpp.org/extensions/xep-0147.html">XMPP URI Scheme Query Components</a>,&rdquo; XSF XEP&nbsp;0147, September&nbsp;2006.</td></tr>
4263<tr><td class="author-text" valign="top"><a name="XEP-0160">[XEP-0160]</a></td>
4264<td class="author-text"><a href="mailto:stpeter@jabber.org">Saint-Andre, P.</a>, &ldquo;<a href="http://www.xmpp.org/extensions/xep-0160.html">Best Practices for Handling Offline Messages</a>,&rdquo; XSF XEP&nbsp;0160, January&nbsp;2006.</td></tr>
4265<tr><td class="author-text" valign="top"><a name="XEP-0163">[XEP-0163]</a></td>
4266<td class="author-text"><a href="mailto:stpeter@jabber.org">Saint-Andre, P.</a> and <a href="mailto:kevin@kismith.co.uk">K. Smith</a>, &ldquo;<a href="http://xmpp.org/extensions/xep-0163.html">Personal Eventing Protocol</a>,&rdquo; XSF XEP&nbsp;0163, July&nbsp;2010.</td></tr>
4267<tr><td class="author-text" valign="top"><a name="XEP-0191">[XEP-0191]</a></td>
4268<td class="author-text"><a href="mailto:">Saint-Andre, P.</a>, &ldquo;<a href="http://www.xmpp.org/extensions/xep-0191.html">Simple Communications Blocking</a>,&rdquo; XSF XEP&nbsp;0191, February&nbsp;2007.</td></tr>
4269<tr><td class="author-text" valign="top"><a name="XEP-0201">[XEP-0201]</a></td>
4270<td class="author-text"><a href="mailto:stpeter@jabber.org">Saint-Andre, P.</a>, <a href="mailto:ian.paterson@clientside.co.uk">Paterson, I.</a>, and <a href="mailto:kevin@kismith.co.uk">K. Smith</a>, &ldquo;<a href="http://www.xmpp.org/extensions/xep-0201.html">Best Practices for Message Threads</a>,&rdquo; XSF XEP&nbsp;0201, November&nbsp;2010.</td></tr>
4271<tr><td class="author-text" valign="top"><a name="XEP-0237">[XEP-0237]</a></td>
4272<td class="author-text"><a href="mailto:">Saint-Andre, P.</a> and <a href="mailto:dave.cridland@isode.com">D. Cridland</a>, &ldquo;<a href="http://xmpp.org/extensions/xep-0237.html">Roster Versioning</a>,&rdquo; XSF XEP&nbsp;0237, March&nbsp;2010.</td></tr>
4273<tr><td class="author-text" valign="top"><a name="XML-DATATYPES">[XML-DATATYPES]</a></td>
4274<td class="author-text">Biron, P. and A. Malhotra, &ldquo;<a href="http://www.w3.org/TR/2004/REC-xmlschema-2-20041028/">XML Schema Part 2: Datatypes Second Edition</a>,&rdquo; W3C&nbsp;REC-xmlschema-2, October&nbsp;2004 (<a href="http://www.w3.org/TR/2004/REC-xmlschema-2-20041028">HTML</a>).</td></tr>
4275<tr><td class="author-text" valign="top"><a name="XML-SCHEMA">[XML-SCHEMA]</a></td>
4276<td class="author-text">Thompson, H., Maloney, M., Mendelsohn, N., and D. Beech, &ldquo;<a href="http://www.w3.org/TR/2004/REC-xmlschema-1-20041028">XML Schema Part 1: Structures Second Edition</a>,&rdquo; World Wide Web Consortium Recommendation&nbsp;REC-xmlschema-1-20041028, October&nbsp;2004 (<a href="http://www.w3.org/TR/2004/REC-xmlschema-1-20041028">HTML</a>).</td></tr>
4277<tr><td class="author-text" valign="top"><a name="XMPP-ADDR">[XMPP-ADDR]</a></td>
4278<td class="author-text">Saint-Andre, P., &ldquo;<a href="http://tools.ietf.org/html/rfc6122">Extensible Messaging and Presence Protocol (XMPP): Address Format</a>,&rdquo; RFC&nbsp;6122, March&nbsp;2011.</td></tr>
4279<tr><td class="author-text" valign="top"><a name="XMPP-URI">[XMPP-URI]</a></td>
4280<td class="author-text">Saint-Andre, P., &ldquo;<a href="http://tools.ietf.org/html/rfc5122">Internationalized Resource Identifiers (IRIs) and Uniform Resource Identifiers (URIs) for the Extensible Messaging and Presence Protocol (XMPP)</a>,&rdquo; RFC&nbsp;5122, February&nbsp;2008 (<a href="http://www.rfc-editor.org/rfc/rfc5122.txt">TXT</a>).</td></tr>
4281<tr><td class="author-text" valign="top"><a name="VCARD">[VCARD]</a></td>
4282<td class="author-text"><a href="mailto:frank_dawson@lotus.com">Dawson, F.</a> and <a href="mailto:howes@netscape.com">T. Howes</a>, &ldquo;<a href="http://tools.ietf.org/html/rfc2426">vCard MIME Directory Profile</a>,&rdquo; RFC&nbsp;2426, September&nbsp;1998 (<a href="http://xml.resource.org/public/rfc/html/rfc2426.html">HTML</a>, <a href="http://xml.resource.org/public/rfc/xml/rfc2426.xml">XML</a>).</td></tr>
4283</table>
4284
4285<a name="substates"></a><br /><hr />
4286<table summary="layout" cellpadding="0" cellspacing="2" class="TOCbug" align="right"><tr><td class="TOCbug"><a href="#toc">&nbsp;TOC&nbsp;</a></td></tr></table>
4287<a name="rfc.section.A"></a><h3>Appendix A.&nbsp;
4288Subscription States</h3>
4289
4290<p>This section provides detailed information about subscription states and server processing of subscription-related presence stanzas (i.e., presence stanzas of type "subscribe", "subscribed", "unsubscribe", and "unsubscribed").
4291</p>
4292<a name="substates-defined"></a><br /><hr />
4293<table summary="layout" cellpadding="0" cellspacing="2" class="TOCbug" align="right"><tr><td class="TOCbug"><a href="#toc">&nbsp;TOC&nbsp;</a></td></tr></table>
4294<a name="rfc.section.A.1"></a><h3>A.1.&nbsp;
4295Defined States</h3>
4296
4297<p>There are four primary subscription states (these states are described from the perspective of the user, not the contact):
4298</p>
4299<p>
4300 </p>
4301<blockquote class="text"><dl>
4302<dt>None:</dt>
4303<dd>The user does not have a subscription to the contact's presence, and the contact does not have a subscription to the user's presence.
4304</dd>
4305<dt>To:</dt>
4306<dd>The user has a subscription to the contact's presence, but the contact does not have a subscription to the user's presence.
4307</dd>
4308<dt>From:</dt>
4309<dd>The contact has a subscription to the user's presence, but the user does not have a subscription to the contact's presence.
4310</dd>
4311<dt>Both:</dt>
4312<dd>Both the user and the contact have subscriptions to each other's presence (i.e., the union of 'from' and 'to').
4313</dd>
4314</dl></blockquote><p>
4315
4316</p>
4317<p></p>
4318<blockquote class="text">
4319<p>Implementation Note: For the purpose of processing subscription-related presence stanzas as described in the following sections, a subscription state of "None" includes the case of the contact not being in the user's roster at all, i.e., an unknown entity from the perspective of the user's roster.
4320</p>
4321</blockquote>
4322
4323<p>The foregoing states are supplemented by various sub-states related to pending inbound and outbound subscriptions, thus yielding nine possible subscription states:
4324</p>
4325<p>
4326 </p>
4327<ol class="text">
4328<li>"None" = Contact and user are not subscribed to each other, and neither has requested a subscription from the other; this is reflected in the user's roster by subscription='none'.
4329</li>
4330<li>"None + Pending Out" = Contact and user are not subscribed to each other, and user has sent contact a subscription request but contact has not replied yet; this is reflected in the user's roster by subscription='none' and ask='subscribe'.
4331</li>
4332<li>"None + Pending In" = Contact and user are not subscribed to each other, and contact has sent user a subscription request but user has not replied yet. This state might or might not be reflected in the user's roster, as follows: if the user has created a roster item for the contact then the server MUST maintain that roster item and also note the existence of the inbound presence subscription request, whereas if the user has not created a roster item for the contact then the user's server MUST note the existence of the inbound presence subscription request but MUST NOT create a roster item for the contact (instead, the server MUST wait until the user has approved the subscription request before adding the contact to the user's roster).
4333</li>
4334<li>"None + Pending Out+In" = Contact and user are not subscribed to each other, contact has sent user a subscription request but user has not replied yet, and user has sent contact a subscription request but contact has not replied yet; this is reflected in the user's roster by subscription='none' and ask='subscribe'.
4335</li>
4336<li>"To" = User is subscribed to contact (one-way); this is reflected in the user's roster by subscription='to'.
4337</li>
4338<li>"To + Pending In" = User is subscribed to contact, and contact has sent user a subscription request but user has not replied yet; this is reflected in the user's roster by subscription='to'.
4339</li>
4340<li>"From" = Contact is subscribed to user (one-way); this is reflected in the user's roster by subscription='from'.
4341</li>
4342<li>"From + Pending Out" = Contact is subscribed to user, and user has sent contact a subscription request but contact has not replied yet; this is reflected in the user's roster by subscription='from' and ask='subscribe'.
4343</li>
4344<li>"Both" = User and contact are subscribed to each other
4345 (two-way); this is reflected in the user's roster by
4346 subscription='both'.
4347</li>
4348</ol><p>
4349
4350</p>
4351<a name="substates-out"></a><br /><hr />
4352<table summary="layout" cellpadding="0" cellspacing="2" class="TOCbug" align="right"><tr><td class="TOCbug"><a href="#toc">&nbsp;TOC&nbsp;</a></td></tr></table>
4353<a name="rfc.section.A.2"></a><h3>A.2.&nbsp;
4354Server Processing of Outbound Presence Subscription Stanzas</h3>
4355
4356<p>Outbound presence subscription stanzas enable the user to manage his or her subscription to the contact's presence (via the "subscribe" and "unsubscribe" types), and to manage the contact's access to the user's presence (via the "subscribed" and "unsubscribed" types).
4357</p>
4358<p>The following rules apply to outbound routing of the stanza as well as changes to the user's roster. (These rules are described from the perspective of the user, not the contact. In addition, "S.N." stands for SHOULD NOT and "M.N." stands for MUST NOT.)
4359</p>
4360<a name="substates-out-subscribe"></a><br /><hr />
4361<table summary="layout" cellpadding="0" cellspacing="2" class="TOCbug" align="right"><tr><td class="TOCbug"><a href="#toc">&nbsp;TOC&nbsp;</a></td></tr></table>
4362<a name="rfc.section.A.2.1"></a><h3>A.2.1.&nbsp;
4363Subscribe</h3>
4364
4365<p>Table 2: Processing of outbound "subscribe" stanzas
4366</p><div style='display: table; width: 0; margin-left: 3em; margin-right: auto'><pre>
4367+------------------------------------------------------------------+
4368| EXISTING STATE | ROUTE? | NEW STATE |
4369+------------------------------------------------------------------+
4370| "None" | MUST [1] | "None + Pending Out" |
4371| "None + Pending Out" | MUST | no state change |
4372| "None + Pending In" | MUST [1] | "None + Pending Out+In" |
4373| "None + Pending Out+In" | MUST | no state change |
4374| "To" | MUST | no state change |
4375| "To + Pending In" | MUST | no state change |
4376| "From" | MUST [1] | "From + Pending Out" |
4377| "From + Pending Out" | MUST | no state change |
4378| "Both" | MUST | no state change |
4379+------------------------------------------------------------------+
4380</pre></div>
4381<p></p>
4382<blockquote class="text">
4383<p>[1] A state change to "pending out" includes setting the 'ask' flag to a value of "subscribe" in the user's roster.
4384</p>
4385</blockquote>
4386
4387<a name="substates-out-unsubscribe"></a><br /><hr />
4388<table summary="layout" cellpadding="0" cellspacing="2" class="TOCbug" align="right"><tr><td class="TOCbug"><a href="#toc">&nbsp;TOC&nbsp;</a></td></tr></table>
4389<a name="rfc.section.A.2.2"></a><h3>A.2.2.&nbsp;
4390Unsubscribe</h3>
4391
4392<p>Table 3: Processing of outbound "unsubscribe" stanzas
4393</p><div style='display: table; width: 0; margin-left: 3em; margin-right: auto'><pre>
4394+-----------------------------------------------------------------+
4395| EXISTING STATE | ROUTE? | NEW STATE |
4396+-----------------------------------------------------------------+
4397| "None" | MUST | no state change |
4398| "None + Pending Out" | MUST | "None" |
4399| "None + Pending In" | MUST | no state change |
4400| "None + Pending Out+In" | MUST | "None + Pending In" |
4401| "To" | MUST | "None" |
4402| "To + Pending In" | MUST | "None + Pending In" |
4403| "From" | MUST | no state change |
4404| "From + Pending Out" | MUST | "From" |
4405| "Both" | MUST | "From" |
4406+-----------------------------------------------------------------+
4407</pre></div>
4408<a name="substates-out-subscribed"></a><br /><hr />
4409<table summary="layout" cellpadding="0" cellspacing="2" class="TOCbug" align="right"><tr><td class="TOCbug"><a href="#toc">&nbsp;TOC&nbsp;</a></td></tr></table>
4410<a name="rfc.section.A.2.3"></a><h3>A.2.3.&nbsp;
4411Subscribed</h3>
4412
4413<p>Table 4: Processing of outbound "subscribed" stanzas
4414</p><div style='display: table; width: 0; margin-left: 3em; margin-right: auto'><pre>
4415+-----------------------------------------------------------------+
4416| EXISTING STATE | ROUTE? | NEW STATE |
4417+-----------------------------------------------------------------+
4418| "None" | M.N. | pre-approval [1] |
4419| "None + Pending Out" | M.N. | pre-approval [1] |
4420| "None + Pending In" | MUST | "From" |
4421| "None + Pending Out+In" | MUST | "From + Pending Out" |
4422| "To" | M.N. | pre-approval [1] |
4423| "To + Pending In" | MUST | "Both" |
4424| "From" | M.N. | no state change |
4425| "From + Pending Out" | M.N. | no state change |
4426| "Both" | M.N. | no state change |
4427+-----------------------------------------------------------------+
4428</pre></div>
4429<p></p>
4430<blockquote class="text">
4431<p>[1] Detailed information regarding subscription pre-approval is provided under <a class='info' href='#sub-preapproval'>Section&nbsp;3.4<span> (</span><span class='info'>Pre-Approving a Subscription Request</span><span>)</span></a>.
4432</p>
4433</blockquote>
4434
4435<a name="substates-out-unsubscribed"></a><br /><hr />
4436<table summary="layout" cellpadding="0" cellspacing="2" class="TOCbug" align="right"><tr><td class="TOCbug"><a href="#toc">&nbsp;TOC&nbsp;</a></td></tr></table>
4437<a name="rfc.section.A.2.4"></a><h3>A.2.4.&nbsp;
4438Unsubscribed</h3>
4439
4440<p>Table 5: Processing of outbound "unsubscribed" stanzas
4441</p><div style='display: table; width: 0; margin-left: 3em; margin-right: auto'><pre>
4442+-----------------------------------------------------------------+
4443| EXISTING STATE | ROUTE? | NEW STATE |
4444+-----------------------------------------------------------------+
4445| "None" | S.N. | no state change [1] |
4446| "None + Pending Out" | S.N. | no state change [1] |
4447| "None + Pending In" | MUST | "None" |
4448| "None + Pending Out+In" | MUST | "None + Pending Out" |
4449| "To" | S.N. | no state change [1] |
4450| "To + Pending In" | MUST | "To" |
4451| "From" | MUST | "None" |
4452| "From + Pending Out" | MUST | "None + Pending Out" |
4453| "Both" | MUST | "To" |
4454+-----------------------------------------------------------------+
4455</pre></div>
4456<p></p>
4457<blockquote class="text">
4458<p>[1] This event can result in cancellation of a subscription pre-approval, as described under <a class='info' href='#sub-preapproval'>Section&nbsp;3.4<span> (</span><span class='info'>Pre-Approving a Subscription Request</span><span>)</span></a>.
4459</p>
4460</blockquote>
4461
4462<a name="substates-in"></a><br /><hr />
4463<table summary="layout" cellpadding="0" cellspacing="2" class="TOCbug" align="right"><tr><td class="TOCbug"><a href="#toc">&nbsp;TOC&nbsp;</a></td></tr></table>
4464<a name="rfc.section.A.3"></a><h3>A.3.&nbsp;
4465Server Processing of Inbound Presence Subscription Stanzas</h3>
4466
4467<p>Inbound presence subscription stanzas request a subscription-related action from the user (via the "subscribe" type), inform the user of subscription-related actions taken by the contact (via the "unsubscribe" type), or enable the user to manage the contact's access to the user's presence information (via the "subscribed" and "unsubscribed" types).
4468</p>
4469<p>The following rules apply to delivery of the inbound stanza as well as changes to the user's roster. (These rules for server processing of inbound presence subscription stanzas are described from the perspective of the user, not the contact. In addition, "S.N." stands for SHOULD NOT.)
4470</p>
4471<a name="substates-in-subscribe"></a><br /><hr />
4472<table summary="layout" cellpadding="0" cellspacing="2" class="TOCbug" align="right"><tr><td class="TOCbug"><a href="#toc">&nbsp;TOC&nbsp;</a></td></tr></table>
4473<a name="rfc.section.A.3.1"></a><h3>A.3.1.&nbsp;
4474Subscribe</h3>
4475
4476<p>Table 6: Processing of inbound "subscribe" stanzas
4477</p><div style='display: table; width: 0; margin-left: 3em; margin-right: auto'><pre>
4478+------------------------------------------------------------------+
4479| EXISTING STATE | DELIVER? | NEW STATE |
4480+------------------------------------------------------------------+
4481| "None" | MUST [1] | "None + Pending In" |
4482| "None + Pending Out" | MUST | "None + Pending Out+In" |
4483| "None + Pending In" | S.N. | no state change |
4484| "None + Pending Out+In" | S.N. | no state change |
4485| "To" | MUST | "To + Pending In" |
4486| "To + Pending In" | S.N. | no state change |
4487| "From" | S.N. [2] | no state change |
4488| "From + Pending Out" | S.N. [2] | no state change |
4489| "Both" | S.N. [2] | no state change |
4490+------------------------------------------------------------------+
4491</pre></div>
4492<p></p>
4493<blockquote class="text">
4494<p>[1] If the user previously sent presence of type "subscribed" as described under <a class='info' href='#substates-out-subscribed'>Appendix&nbsp;A.2.3<span> (</span><span class='info'>Subscribed</span><span>)</span></a> and <a class='info' href='#sub-preapproval'>Section&nbsp;3.4<span> (</span><span class='info'>Pre-Approving a Subscription Request</span><span>)</span></a>, then the server MAY auto-reply with "subscribed" and change the state to "From" rather than "None + Pending In".
4495</p>
4496</blockquote>
4497
4498<p></p>
4499<blockquote class="text">
4500<p>[2] Server SHOULD auto-reply with "subscribed".
4501</p>
4502</blockquote>
4503
4504<a name="substates-in-unsubscribe"></a><br /><hr />
4505<table summary="layout" cellpadding="0" cellspacing="2" class="TOCbug" align="right"><tr><td class="TOCbug"><a href="#toc">&nbsp;TOC&nbsp;</a></td></tr></table>
4506<a name="rfc.section.A.3.2"></a><h3>A.3.2.&nbsp;
4507Unsubscribe</h3>
4508
4509<p>When the user's server receives a presence stanza of type "unsubscribe" for the user from the contact, if the stanza results in a subscription state change from the user's perspective then the user's server MUST change the state, MUST deliver the presence stanza from the contact to the user, and SHOULD auto-reply by sending a presence stanza of type "unsubscribed" to the contact on behalf of the user. Otherwise the user's server MUST NOT change the state and (because there is no state change) SHOULD NOT deliver the stanza. These rules are summarized in the following table.
4510</p>
4511<p>Table 7: Processing of inbound "unsubscribe" stanzas
4512</p><div style='display: table; width: 0; margin-left: 3em; margin-right: auto'><pre>
4513+------------------------------------------------------------------+
4514| EXISTING STATE | DELIVER? | NEW STATE |
4515+------------------------------------------------------------------+
4516| "None" | S.N. | no state change |
4517| "None + Pending Out" | S.N. | no state change |
4518| "None + Pending In" | MUST [1] | "None" |
4519| "None + Pending Out+In" | MUST [1] | "None + Pending Out" |
4520| "To" | S.N. | no state change |
4521| "To + Pending In" | MUST [1] | "To" |
4522| "From" | MUST [1] | "None" |
4523| "From + Pending Out" | MUST [1] | "None + Pending Out" |
4524| "Both" | MUST [1] | "To" |
4525+------------------------------------------------------------------+
4526</pre></div>
4527<p>[1] Server SHOULD auto-reply with "unsubscribed".
4528</p>
4529<a name="substates-in-subscribed"></a><br /><hr />
4530<table summary="layout" cellpadding="0" cellspacing="2" class="TOCbug" align="right"><tr><td class="TOCbug"><a href="#toc">&nbsp;TOC&nbsp;</a></td></tr></table>
4531<a name="rfc.section.A.3.3"></a><h3>A.3.3.&nbsp;
4532Subscribed</h3>
4533
4534<p>When the user's server receives a presence stanza of type "subscribed" for the user from the contact, if there is no pending outbound request for access to the contact's presence information, then it MUST NOT change the subscription state and (because there is no state change) SHOULD NOT deliver the stanza to the user. If there is a pending outbound request for access to the contact's presence information and the inbound presence stanza of type "subscribed" results in a subscription state change, then the user's server MUST change the subscription state and MUST deliver the stanza to the user. If the user already is subscribed to the contact's presence information, the inbound presence stanza of type "subscribed" does not result in a subscription state change; therefore the user's server MUST NOT change the subscription state and (because there is no state change) SHOULD NOT deliver the stanza to the user. These rules are summarized in the following table.
4535</p>
4536<p>Table 8: Processing of inbound "subscribed" stanzas
4537</p><div style='display: table; width: 0; margin-left: 3em; margin-right: auto'><pre>
4538+------------------------------------------------------------------+
4539| EXISTING STATE | DELIVER? | NEW STATE |
4540+------------------------------------------------------------------+
4541| "None" | S.N. | no state change |
4542| "None + Pending Out" | MUST | "To" |
4543| "None + Pending In" | S.N. | no state change |
4544| "None + Pending Out+In" | MUST | "To + Pending In" |
4545| "To" | S.N. | no state change |
4546| "To + Pending In" | S.N. | no state change |
4547| "From" | S.N. | no state change |
4548| "From + Pending Out" | MUST | "Both" |
4549| "Both" | S.N. | no state change |
4550+------------------------------------------------------------------+
4551</pre></div>
4552<a name="substates-in-unsubscribed"></a><br /><hr />
4553<table summary="layout" cellpadding="0" cellspacing="2" class="TOCbug" align="right"><tr><td class="TOCbug"><a href="#toc">&nbsp;TOC&nbsp;</a></td></tr></table>
4554<a name="rfc.section.A.3.4"></a><h3>A.3.4.&nbsp;
4555Unsubscribed</h3>
4556
4557<p>When the user's server receives a presence stanza of type "unsubscribed" for the user from the contact, if there is a pending outbound request for access to the contact's presence information or if the user currently is subscribed to the contact's presence information, then the user's server MUST change the subscription state and MUST deliver the stanza to the user. Otherwise, the user's server MUST NOT change the subscription state and (because there is no state change) SHOULD NOT deliver the stanza. These rules are summarized in the following table.
4558</p>
4559<p>Table 9: Processing of inbound "unsubscribed" stanzas
4560</p><div style='display: table; width: 0; margin-left: 3em; margin-right: auto'><pre>
4561+------------------------------------------------------------------+
4562| EXISTING STATE | DELIVER? | NEW STATE |
4563+------------------------------------------------------------------+
4564| "None" | S.N. | no state change |
4565| "None + Pending Out" | MUST | "None" |
4566| "None + Pending In" | S.N. | no state change |
4567| "None + Pending Out+In" | MUST | "None + Pending In" |
4568| "To" | MUST | "None" |
4569| "To + Pending In" | MUST | "None + Pending In" |
4570| "From" | S.N. | no state change |
4571| "From + Pending Out" | MUST | "From" |
4572| "Both" | MUST | "From" |
4573+------------------------------------------------------------------+
4574</pre></div>
4575<a name="blocking"></a><br /><hr />
4576<table summary="layout" cellpadding="0" cellspacing="2" class="TOCbug" align="right"><tr><td class="TOCbug"><a href="#toc">&nbsp;TOC&nbsp;</a></td></tr></table>
4577<a name="rfc.section.B"></a><h3>Appendix B.&nbsp;
4578Blocking Communication</h3>
4579
4580<p>Sections 2.3.5 and 5.4.10 of <a class='info' href='#IMP-REQS'>[IMP&#8209;REQS]<span> (</span><span class='info'>Day, M., Aggarwal, S., and J. Vincent, &ldquo;Instant Messaging / Presence Protocol Requirements,&rdquo; February&nbsp;2000.</span><span>)</span></a> require that a compliant instant messaging and presence technology needs to enable a user to block communications from selected users. Protocols for doing so are specified in <a class='info' href='#XEP-0016'>[XEP&#8209;0016]<span> (</span><span class='info'>Millard, P. and P. Saint-Andre, &ldquo;Privacy Lists,&rdquo; February&nbsp;2007.</span><span>)</span></a> and <a class='info' href='#XEP-0191'>[XEP&#8209;0191]<span> (</span><span class='info'>Saint-Andre, P., &ldquo;Simple Communications Blocking,&rdquo; February&nbsp;2007.</span><span>)</span></a>.
4581</p>
4582<a name="vcard"></a><br /><hr />
4583<table summary="layout" cellpadding="0" cellspacing="2" class="TOCbug" align="right"><tr><td class="TOCbug"><a href="#toc">&nbsp;TOC&nbsp;</a></td></tr></table>
4584<a name="rfc.section.C"></a><h3>Appendix C.&nbsp;
4585vCards</h3>
4586
4587<p>Sections 3.1.3 and 4.1.4 of <a class='info' href='#IMP-REQS'>[IMP&#8209;REQS]<span> (</span><span class='info'>Day, M., Aggarwal, S., and J. Vincent, &ldquo;Instant Messaging / Presence Protocol Requirements,&rdquo; February&nbsp;2000.</span><span>)</span></a> require that it be possible to retrieve out-of-band contact information for other users (e.g., telephone number or email address). An XML representation of the vCard specification defined in <a class='info' href='#VCARD'>RFC 2426<span> (</span><span class='info'>Dawson, F. and T. Howes, &ldquo;vCard MIME Directory Profile,&rdquo; September&nbsp;1998.</span><span>)</span></a> [VCARD] is in common use within the XMPP community to provide such information but is out of scope for this specification (documentation of this protocol is contained in <a class='info' href='#XEP-0054'>[XEP&#8209;0054]<span> (</span><span class='info'>Saint-Andre, P., &ldquo;vcard-temp,&rdquo; July&nbsp;2008.</span><span>)</span></a>).
4588</p>
4589<a name="schema"></a><br /><hr />
4590<table summary="layout" cellpadding="0" cellspacing="2" class="TOCbug" align="right"><tr><td class="TOCbug"><a href="#toc">&nbsp;TOC&nbsp;</a></td></tr></table>
4591<a name="rfc.section.D"></a><h3>Appendix D.&nbsp;
4592XML Schema for jabber:iq:roster</h3>
4593
4594<p>The following schema formally defines the 'jabber:iq:roster' namespace used in this document, in conformance with <a class='info' href='#XML-SCHEMA'>[XML&#8209;SCHEMA]<span> (</span><span class='info'>Thompson, H., Maloney, M., Mendelsohn, N., and D. Beech, &ldquo;XML Schema Part 1: Structures Second Edition,&rdquo; October&nbsp;2004.</span><span>)</span></a>. Because validation of XML streams and stanzas is optional, this schema is not normative and is provided for descriptive purposes only. For schemas defining core XMPP namespaces, refer to <a class='info' href='#XMPP-CORE'>[XMPP&#8209;CORE]<span> (</span><span class='info'>Saint-Andre, P., &ldquo;Extensible Messaging and Presence Protocol (XMPP): Core,&rdquo; March&nbsp;2011.</span><span>)</span></a>.
4595</p><div style='display: table; width: 0; margin-left: 3em; margin-right: auto'><pre>
4596&lt;?xml version='1.0' encoding='UTF-8'?&gt;
4597
4598&lt;xs:schema
4599 xmlns:xs='http://www.w3.org/2001/XMLSchema'
4600 targetNamespace='jabber:iq:roster'
4601 xmlns='jabber:iq:roster'
4602 elementFormDefault='qualified'&gt;
4603
4604 &lt;xs:element name='query'&gt;
4605 &lt;xs:complexType&gt;
4606 &lt;xs:sequence&gt;
4607 &lt;xs:element ref='item'
4608 minOccurs='0'
4609 maxOccurs='unbounded'/&gt;
4610 &lt;/xs:sequence&gt;
4611 &lt;xs:attribute name='ver'
4612 type='xs:string'
4613 use='optional'/&gt;
4614 &lt;/xs:complexType&gt;
4615 &lt;/xs:element&gt;
4616
4617 &lt;xs:element name='item'&gt;
4618 &lt;xs:complexType&gt;
4619 &lt;xs:sequence&gt;
4620 &lt;xs:element ref='group'
4621 minOccurs='0'
4622 maxOccurs='unbounded'/&gt;
4623 &lt;/xs:sequence&gt;
4624 &lt;xs:attribute name='approved'
4625 type='xs:boolean'
4626 use='optional'/&gt;
4627 &lt;xs:attribute name='ask'
4628 use='optional'&gt;
4629 &lt;xs:simpleType&gt;
4630 &lt;xs:restriction base='xs:NMTOKEN'&gt;
4631 &lt;xs:enumeration value='subscribe'/&gt;
4632 &lt;/xs:restriction&gt;
4633 &lt;/xs:simpleType&gt;
4634 &lt;/xs:attribute&gt;
4635 &lt;xs:attribute name='jid'
4636 type='xs:string'
4637 use='required'/&gt;
4638 &lt;xs:attribute name='name'
4639 type='xs:string'
4640 use='optional'/&gt;
4641 &lt;xs:attribute name='subscription'
4642 use='optional'
4643 default='none'&gt;
4644 &lt;xs:simpleType&gt;
4645 &lt;xs:restriction base='xs:NMTOKEN'&gt;
4646 &lt;xs:enumeration value='both'/&gt;
4647 &lt;xs:enumeration value='from'/&gt;
4648 &lt;xs:enumeration value='none'/&gt;
4649 &lt;xs:enumeration value='remove'/&gt;
4650 &lt;xs:enumeration value='to'/&gt;
4651 &lt;/xs:restriction&gt;
4652 &lt;/xs:simpleType&gt;
4653 &lt;/xs:attribute&gt;
4654 &lt;/xs:complexType&gt;
4655 &lt;/xs:element&gt;
4656
4657 &lt;xs:element name='group' type='xs:string'/&gt;
4658
4659&lt;/xs:schema&gt;
4660</pre></div>
4661<a name="diffs"></a><br /><hr />
4662<table summary="layout" cellpadding="0" cellspacing="2" class="TOCbug" align="right"><tr><td class="TOCbug"><a href="#toc">&nbsp;TOC&nbsp;</a></td></tr></table>
4663<a name="rfc.section.E"></a><h3>Appendix E.&nbsp;
4664Differences From RFC 3921</h3>
4665
4666<p>Based on consensus derived from implementation and deployment experience as well as formal interoperability testing, the following substantive modifications were made from <a class='info' href='#RFC3921'>[RFC3921]<span> (</span><span class='info'>Saint-Andre, P., Ed., &ldquo;Extensible Messaging and Presence Protocol (XMPP): Instant Messaging and Presence,&rdquo; October&nbsp;2004.</span><span>)</span></a> (in addition to numerous changes of an editorial nature).
4667</p>
4668<p>
4669 </p>
4670<ul class="text">
4671<li>The protocol for session establishment was determined to be unnecessary and therefore the content previously defined in Section 3 of RFC 3921 was removed. However, for the sake of backward-compatibility server implementations are encouraged to advertise support for the feature, even though session establishment is a "no-op".
4672</li>
4673<li>In order to more seamlessly repair lack of synchronization in subscription states between rosters located at different servers, clarified and modified error handling related to presence subscription requests, presence probes and presence notifications.
4674</li>
4675<li>Changed the 'from' address for presence probes so that it is the bare JID, not the full JID.
4676</li>
4677<li>Adjusted and clarified stanza delivery rules based on implementation and deployment experience.
4678</li>
4679<li>Explicitly specified that a server is allowed to deliver a message stanza of type "normal" or "chat" to all resources if it has a method for allowing resources to opt in to such behavior.
4680</li>
4681<li>Allowed a server to use its own algorithm for determining the "most available" resource for the purpose of message delivery, but mentioned the recommended algorithm from RFC 3921 (based on presence priority) as one possible algorithm.
4682</li>
4683<li>Added optional versioning of roster information to save bandwidth in cases where the roster has not changed (or has changed very little) between sessions; the relevant protocol interactions were originally described in <a class='info' href='#XEP-0237'>[XEP&#8209;0237]<span> (</span><span class='info'>Saint-Andre, P. and D. Cridland, &ldquo;Roster Versioning,&rdquo; March&nbsp;2010.</span><span>)</span></a>.
4684</li>
4685<li>Added optional server support for pre-approved presence subscriptions via presence stanzas of type "subscribed", including a new 'approved' attribute that can be set to "true" (for a pre-approved subscription) or "false" (the default).
4686</li>
4687<li>Added optional 'parent' attribute to &lt;thread/&gt; element.
4688</li>
4689<li>Moved the protocol for communications blocking (specified in Section 10 of RFC 3921) back to <a class='info' href='#XEP-0016'>[XEP&#8209;0016]<span> (</span><span class='info'>Millard, P. and P. Saint-Andre, &ldquo;Privacy Lists,&rdquo; February&nbsp;2007.</span><span>)</span></a>, from which it was originally taken.
4690</li>
4691<li>Recommended returning presence unavailable in response to probes.
4692</li>
4693<li>Clarified handling of presence probes sent to full JIDs.
4694</li>
4695<li>Explicitly specified that the default value for the presence &lt;priority/&gt; element is zero.
4696</li>
4697<li>Removed recommendation to support the "_im" and "_pres" SRV records.
4698</li>
4699</ul><p>
4700
4701</p>
4702<a name="acks"></a><br /><hr />
4703<table summary="layout" cellpadding="0" cellspacing="2" class="TOCbug" align="right"><tr><td class="TOCbug"><a href="#toc">&nbsp;TOC&nbsp;</a></td></tr></table>
4704<a name="rfc.section.F"></a><h3>Appendix F.&nbsp;
4705Acknowledgements</h3>
4706
4707<p>This document is an update to, and derived from, RFC 3921. This document would have been impossible without the work of the contributors and commenters acknowledged there.
4708</p>
4709<p>Hundreds of people have provided implementation feedback, bug reports, requests for clarification, and suggestions for improvement since publication of RFC 3921. Although the document editor has endeavored to address all such feedback, he is solely responsible for any remaining errors and ambiguities.
4710</p>
4711<p>Some of the text about roster versioning was borrowed from <a class='info' href='#XEP-0237'>[XEP&#8209;0237]<span> (</span><span class='info'>Saint-Andre, P. and D. Cridland, &ldquo;Roster Versioning,&rdquo; March&nbsp;2010.</span><span>)</span></a>, and some of the text about message threads was borrowed from <a class='info' href='#XEP-0201'>[XEP&#8209;0201]<span> (</span><span class='info'>Saint-Andre, P., Paterson, I., and K. Smith, &ldquo;Best Practices for Message Threads,&rdquo; November&nbsp;2010.</span><span>)</span></a>.
4712</p>
4713<p>Special thanks are due to Kevin Smith, Matthew Wild, Dave Cridland, Waqas Hussain, Philipp Hancke, Florian Zeitz, Jonas Lindberg, Jehan Pages, Tory Patnoe, and others for their comments during Working Group Last Call.
4714</p>
4715<p>Thanks also to Richard Barnes for his review on behalf of the Security Directorate.
4716</p>
4717<p>The Working Group chairs were Ben Campbell and Joe Hildebrand. The responsible Area Director was Gonzalo Camarillo.
4718</p>
4719<a name="rfc.authors"></a><br /><hr />
4720<table summary="layout" cellpadding="0" cellspacing="2" class="TOCbug" align="right"><tr><td class="TOCbug"><a href="#toc">&nbsp;TOC&nbsp;</a></td></tr></table>
4721<h3>Author's Address</h3>
4722<table width="99%" border="0" cellpadding="0" cellspacing="0">
4723<tr><td class="author-text">&nbsp;</td>
4724<td class="author-text">Peter Saint-Andre</td></tr>
4725<tr><td class="author-text">&nbsp;</td>
4726<td class="author-text">Cisco</td></tr>
4727<tr><td class="author-text">&nbsp;</td>
4728<td class="author-text">1899 Wyknoop Street, Suite 600</td></tr>
4729<tr><td class="author-text">&nbsp;</td>
4730<td class="author-text">Denver, CO 80202</td></tr>
4731<tr><td class="author-text">&nbsp;</td>
4732<td class="author-text">USA</td></tr>
4733<tr><td class="author" align="right">Phone:&nbsp;</td>
4734<td class="author-text">+1-303-308-3282</td></tr>
4735<tr><td class="author" align="right">EMail:&nbsp;</td>
4736<td class="author-text"><a href="mailto:psaintan@cisco.com">psaintan@cisco.com</a></td></tr>
4737</table>
4738</body></html>
diff --git a/examples/dhtd.hs b/examples/dhtd.hs
index 837cb210..219221e5 100644
--- a/examples/dhtd.hs
+++ b/examples/dhtd.hs
@@ -21,11 +21,12 @@ module Main where
21import Control.Arrow 21import Control.Arrow
22import Control.Applicative 22import Control.Applicative
23import Control.Concurrent.STM 23import Control.Concurrent.STM
24import Control.DeepSeq
25import Control.Exception 24import Control.Exception
26import Control.Monad 25import Control.Monad
26import Control.Monad.Trans.Resource (runResourceT)
27import Data.Bool 27import Data.Bool
28import Data.Char 28import Data.Char
29import Data.Function
29import Data.Hashable 30import Data.Hashable
30import Data.List 31import Data.List
31import qualified Data.IntMap.Strict as IntMap 32import qualified Data.IntMap.Strict as IntMap
@@ -53,6 +54,8 @@ import qualified Data.HashMap.Strict as HashMap
53import qualified Data.Vector as V 54import qualified Data.Vector as V
54import qualified Data.Text as T 55import qualified Data.Text as T
55import qualified Data.Text.Encoding as T 56import qualified Data.Text.Encoding as T
57import System.Posix.Signals
58
56 59
57import Announcer 60import Announcer
58import Crypto.Tox -- (zeros32,SecretKey,PublicKey, generateSecretKey, toPublic, encodeSecret, decodeSecret, userKeys) 61import Crypto.Tox -- (zeros32,SecretKey,PublicKey, generateSecretKey, toPublic, encodeSecret, decodeSecret, userKeys)
@@ -60,8 +63,6 @@ import Network.UPNP as UPNP
60import Network.Address hiding (NodeId, NodeInfo(..)) 63import Network.Address hiding (NodeId, NodeInfo(..))
61import Network.QueryResponse 64import Network.QueryResponse
62import Network.StreamServer 65import Network.StreamServer
63import Network.Kademlia
64import Network.Kademlia.Bootstrap
65import Network.Kademlia.Search 66import Network.Kademlia.Search
66import qualified Network.BitTorrent.MainlineDHT as Mainline 67import qualified Network.BitTorrent.MainlineDHT as Mainline
67import qualified Network.Tox as Tox 68import qualified Network.Tox as Tox
@@ -71,6 +72,7 @@ import qualified Data.Aeson as J
71import qualified Data.ByteString.Lazy as L 72import qualified Data.ByteString.Lazy as L
72import qualified Data.ByteString.Char8 as B 73import qualified Data.ByteString.Char8 as B
73import Control.Concurrent.Tasks 74import Control.Concurrent.Tasks
75import Control.Monad.Trans.Control
74import System.IO.Error 76import System.IO.Error
75import qualified Data.Serialize as S 77import qualified Data.Serialize as S
76import Network.BitTorrent.DHT.ContactInfo as Peers 78import Network.BitTorrent.DHT.ContactInfo as Peers
@@ -88,6 +90,13 @@ import Data.Typeable
88import Roster 90import Roster
89import OnionRouter 91import OnionRouter
90 92
93-- Presence imports.
94import ConsoleWriter
95import Presence
96import XMPPServer
97import Connection
98
99
91showReport :: [(String,String)] -> String 100showReport :: [(String,String)] -> String
92showReport kvs = showColumns $ map (\(x,y)->[x,y]) kvs 101showReport kvs = showColumns $ map (\(x,y)->[x,y]) kvs
93 102
@@ -146,21 +155,6 @@ data DHTAnnouncable nid = forall dta tok ni r.
146 , qresultAddr :: dta -> nid 155 , qresultAddr :: dta -> nid
147 } 156 }
148 157
149data DHTLink = forall status linkid params.
150 ( Show status
151 , Show linkid
152 , Typeable status
153 , Typeable linkid
154 , Typeable params
155 ) => DHTLink
156 { linkInit :: params -> IO (Either String status)
157 , linkParamParser :: [String] -> Either String params
158 , linkStatus :: IO (Either String status)
159 , showLinkStatus :: status -> String
160 , linkNewPipe :: String -> linkid -> IO (Either String status)
161 , linkUnPipe :: linkid -> IO (Either String status)
162 }
163
164data DHTSearch nid ni = forall addr tok r. DHTSearch 158data DHTSearch nid ni = forall addr tok r. DHTSearch
165 { searchThread :: ThreadId 159 { searchThread :: ThreadId
166 , searchState :: SearchState nid addr tok ni r 160 , searchState :: SearchState nid addr tok ni r
@@ -191,7 +185,6 @@ data DHT = forall nid ni. ( Show ni
191 , dhtPing :: Map.Map String (DHTPing ni) 185 , dhtPing :: Map.Map String (DHTPing ni)
192 , dhtQuery :: Map.Map String (DHTQuery nid ni) 186 , dhtQuery :: Map.Map String (DHTQuery nid ni)
193 , dhtAnnouncables :: Map.Map String (DHTAnnouncable nid) 187 , dhtAnnouncables :: Map.Map String (DHTAnnouncable nid)
194 , dhtLinks :: Map.Map String DHTLink
195 , dhtParseId :: String -> Either String nid 188 , dhtParseId :: String -> Either String nid
196 , dhtSearches :: TVar (Map.Map (String,nid) (DHTSearch nid ni)) 189 , dhtSearches :: TVar (Map.Map (String,nid) (DHTSearch nid ni))
197 , dhtFallbackNodes :: IO [ni] 190 , dhtFallbackNodes :: IO [ni]
@@ -375,6 +368,8 @@ reportSearchResults meth h DHTSearch{searchShowTok,searchState,searchResults} =
375 ns' = map showN ns 368 ns' = map showN ns
376 reportResult meth id (const Nothing) id h (Right (ns',rs, Just ())) 369 reportResult meth id (const Nothing) id h (Right (ns',rs, Just ()))
377 370
371data ConnectionManager = forall status k. ConnectionManager { typedManager :: Connection.Manager status k }
372
378data Session = Session 373data Session = Session
379 { netname :: String 374 { netname :: String
380 , dhts :: Map.Map String DHT 375 , dhts :: Map.Map String DHT
@@ -384,9 +379,10 @@ data Session = Session
384 , toxkeys :: TVar Tox.AnnouncedKeys 379 , toxkeys :: TVar Tox.AnnouncedKeys
385 , userkeys :: TVar [(SecretKey,PublicKey)] 380 , userkeys :: TVar [(SecretKey,PublicKey)]
386 , roster :: Roster 381 , roster :: Roster
382 , connectionManager :: ConnectionManager
387 , onionRouter :: OnionRouter 383 , onionRouter :: OnionRouter
388 , announcer :: Announcer 384 , announcer :: Announcer
389 , signalQuit :: MVar () 385 , signalQuit :: IO ()
390 } 386 }
391 387
392exceptionsToClient :: ClientHandle -> IO () -> IO () 388exceptionsToClient :: ClientHandle -> IO () -> IO ()
@@ -481,7 +477,7 @@ clientSession s@Session{..} sock cnum h = do
481 477
482 ("stop", _) -> do hPutClient h "Terminating DHT Daemon." 478 ("stop", _) -> do hPutClient h "Terminating DHT Daemon."
483 hCloseClient h 479 hCloseClient h
484 putMVar signalQuit () 480 signalQuit
485 481
486 ("throw", er) -> cmd0 $ do 482 ("throw", er) -> cmd0 $ do
487 throwIO $ userError er 483 throwIO $ userError er
@@ -633,7 +629,6 @@ clientSession s@Session{..} sock cnum h = do
633 hPutClientChunk h $ "trampolines: " ++ show (IntMap.size ts) ++ "\n" 629 hPutClientChunk h $ "trampolines: " ++ show (IntMap.size ts) ++ "\n"
634 hPutClient h $ showColumns $ ["","responses","timeouts"]:r 630 hPutClient h $ showColumns $ ["","responses","timeouts"]:r
635 631
636
637 ("g", s) | Just DHT{..} <- Map.lookup netname dhts 632 ("g", s) | Just DHT{..} <- Map.lookup netname dhts
638 -> cmd0 $ do 633 -> cmd0 $ do
639 -- arguments: method 634 -- arguments: method
@@ -901,46 +896,29 @@ clientSession s@Session{..} sock cnum h = do
901 mkentry (k :-> Down tm) = [ show cnt, show k, show (now - tm) ] 896 mkentry (k :-> Down tm) = [ show cnt, show k, show (now - tm) ]
902 where Just (_,(cnt,_)) = MM.lookup' k (Tox.keyAssoc keydb) 897 where Just (_,(cnt,_)) = MM.lookup' k (Tox.keyAssoc keydb)
903 hPutClient h $ showColumns entries 898 hPutClient h $ showColumns entries
904 ("c", s) | "" <- strp s -> cmd0 $ do 899
905 let combinedLinkMap = Map.unions $map (dhtLinks . snd) (Map.toList dhts) 900 ("c", s) | "" <- strp s -> cmd0 $ join $ atomically $ do
906 -- TODO: list all connections 901 ConnectionManager mgr <- return connectionManager
907 let connections = [[{-TODO-}]] 902 cmap <- connections mgr
908 hPutClient h $ showColumns connections 903 cs <- Map.toList <$> mapM connStatus cmap
909 ("c", s) -> cmd0 $ do 904 let mkrow = Connection.showKey mgr *** Connection.showStatus mgr
910 let combinedLinkMap = Map.unions $map (dhtLinks . snd) (Map.toList dhts) 905 rs = map mkrow cs
911 -- form new connection according of type corresponding to parameter 906 return $ do
912 let ws = words s 907 hPutClient h $ showReport rs
913 result
914 <- case ws of
915 (linktype:rest)
916 -> case (Map.lookup (head ws) combinedLinkMap) of
917 Nothing -> return . Left $ "I don't know a '" ++ head ws ++ "' link type."
918 Just l@(DHTLink
919 { linkInit {- :: params -> IO (Either String status) -}
920 , linkParamParser {- :: [String] -> Either String params -}
921 , showLinkStatus {- :: status -> String -}
922 }) -> case linkParamParser rest of
923 Left er -> return $ Left er
924 Right params -> fmap showLinkStatus <$> linkInit params
925 _ -> return $ Left "parse error"
926 case result of
927 Left er -> hPutClient h er
928 Right statusstr -> hPutClient h statusstr
929 908
930 ("help", s) | Just DHT{..} <- Map.lookup netname dhts 909 ("help", s) | Just DHT{..} <- Map.lookup netname dhts
931 -> cmd0 $ do 910 -> cmd0 $ do
932 let tolist :: a -> [a] 911 let tolist :: a -> [a]
933 tolist = (:[]) 912 tolist = (:[])
934 913
935 dhtkeys, announcables, links, ks, allcommands :: [[String]] 914 dhtkeys, announcables, ks, allcommands :: [[String]]
936 dhtkeys = map tolist $ Map.keys dhts 915 dhtkeys = map tolist $ Map.keys dhts
937 queries = map (tolist . ("s "++)) $ Map.keys dhtQuery 916 queries = map (tolist . ("s "++)) $ Map.keys dhtQuery
938 xs = map (tolist . ("x "++)) $ Map.keys dhtQuery 917 xs = map (tolist . ("x "++)) $ Map.keys dhtQuery
939 gs = map (tolist . ("g "++)) $ Map.keys dhtQuery 918 gs = map (tolist . ("g "++)) $ Map.keys dhtQuery
940 announcables = map (tolist . ("p "++)) $ Map.keys dhtAnnouncables 919 announcables = map (tolist . ("p "++)) $ Map.keys dhtAnnouncables
941 links = map (tolist . ("c "++)) $ Map.keys dhtLinks
942 ks = [["k gen"],["k public"],["k secret"]] 920 ks = [["k gen"],["k public"],["k secret"]]
943 allcommands = sortBy (comparing head) $ concat [sessionCommands, dhtkeys, announcables, links, ks, queries, gs,xs] 921 allcommands = sortBy (comparing (take 1)) $ concat [sessionCommands, dhtkeys, announcables, ks, queries, gs,xs]
944 922
945 hPutClient h ("Available commands:\n" ++ showColumns allcommands) 923 hPutClient h ("Available commands:\n" ++ showColumns allcommands)
946 924
@@ -957,27 +935,36 @@ readExternals nodeAddr vars = do
957 return $ filter (not . unspecified) as 935 return $ filter (not . unspecified) as
958 936
959data Options = Options 937data Options = Options
960 { portbt :: String 938 { portbt :: String
961 , porttox :: String 939 , porttox :: String
962 , ip6bt :: Bool 940 , ip6bt :: Bool
963 , ip6tox :: Bool 941 , ip6tox :: Bool
964 , dhtkey :: Maybe SecretKey 942 , dhtkey :: Maybe SecretKey
943 -- | Currently only relevant to XMPP server code.
944 --
945 -- [ 0 ] Don't log XMPP stanzas.
946 --
947 -- [ 1 ] Log non-ping stanzas.
948 --
949 -- [ 2 ] Log all stanzas, even pings.
950 , verbosity :: Int
965 } 951 }
966 deriving (Eq,Show) 952 deriving (Eq,Show)
967 953
968sensibleDefaults :: Options 954sensibleDefaults :: Options
969sensibleDefaults = Options 955sensibleDefaults = Options
970 { portbt = "6881" 956 { portbt = "6881"
971 , porttox = "33445" 957 , porttox = "33445"
972 , ip6bt = True 958 , ip6bt = True
973 , ip6tox = True 959 , ip6tox = True
974 , dhtkey = Nothing 960 , dhtkey = Nothing
961 , verbosity = 1
975 } 962 }
976 963
977-- bt=<port>,tox=<port> 964-- bt=<port>,tox=<port>
978-- -4 965-- -4
979parseArgs :: [String] -> Options -> Options 966parseArgs :: [String] -> Options -> Options
980parseArgs [] opts = opts 967parseArgs [] opts = opts
981parseArgs ("--dhtkey":k:args) opts = parseArgs args opts 968parseArgs ("--dhtkey":k:args) opts = parseArgs args opts
982 { dhtkey = decodeSecret $ B.pack k } 969 { dhtkey = decodeSecret $ B.pack k }
983parseArgs ("-4":args) opts = parseArgs args opts 970parseArgs ("-4":args) opts = parseArgs args opts
@@ -996,7 +983,7 @@ noArgPing f [] x = f x
996noArgPing _ _ _ = return Nothing 983noArgPing _ _ _ = return Nothing
997 984
998main :: IO () 985main :: IO ()
999main = do 986main = runResourceT $ liftBaseWith $ \resT -> do
1000 args <- getArgs 987 args <- getArgs
1001 let opts = parseArgs args sensibleDefaults 988 let opts = parseArgs args sensibleDefaults
1002 print opts 989 print opts
@@ -1010,6 +997,18 @@ main = do
1010 997
1011 announcer <- forkAnnouncer 998 announcer <- forkAnnouncer
1012 999
1000 -- XMPP initialization
1001 cw <- newConsoleWriter
1002 serverVar <- atomically $ newEmptyTMVar
1003 state <- newPresenceState cw serverVar
1004
1005 -- XMPP stanza handling
1006 sv <- resT $ xmppServer (presenceHooks state (verbosity opts))
1007 -- We now have a server object but it's not ready to use until
1008 -- we put it into the 'server' field of our /state/ record.
1009
1010 conns <- xmppConnections sv
1011
1013 (quitBt,btdhts,btips,baddrs) <- case portbt opts of 1012 (quitBt,btdhts,btips,baddrs) <- case portbt opts of
1014 "" -> return (return (), Map.empty,return [],[]) 1013 "" -> return (return (), Map.empty,return [],[])
1015 p -> do 1014 p -> do
@@ -1080,9 +1079,6 @@ main = do
1080 , qresultAddr = const $ Mainline.zeroID 1079 , qresultAddr = const $ Mainline.zeroID
1081 })] 1080 })]
1082 1081
1083 , dhtLinks = Map.fromList
1084 [ {- TODO -}
1085 ]
1086 , dhtSecretKey = return Nothing 1082 , dhtSecretKey = return Nothing
1087 , dhtBootstrap = case wantip of 1083 , dhtBootstrap = case wantip of
1088 Want_IP4 -> btBootstrap4 1084 Want_IP4 -> btBootstrap4
@@ -1262,9 +1258,6 @@ main = do
1262 1258
1263 , announceInterval = 8 1259 , announceInterval = 8
1264 })] 1260 })]
1265 , dhtLinks = Map.fromList
1266 [ {- TODO -}
1267 ]
1268 , dhtSecretKey = return $ Just $ transportSecret (Tox.toxCryptoKeys tox) 1261 , dhtSecretKey = return $ Just $ transportSecret (Tox.toxCryptoKeys tox)
1269 , dhtBootstrap = case wantip of 1262 , dhtBootstrap = case wantip of
1270 Want_IP4 -> toxStrap4 1263 Want_IP4 -> toxStrap4
@@ -1283,8 +1276,11 @@ main = do
1283 1276
1284 let dhts = Map.union btdhts toxdhts 1277 let dhts = Map.union btdhts toxdhts
1285 1278
1286 waitForSignal <- do 1279 (waitForSignal, checkQuit) <- do
1287 signalQuit <- newEmptyMVar 1280 signalQuit <- atomically $ newTVar False
1281 let quitCommand = atomically $ writeTVar signalQuit True
1282 installHandler sigTERM (CatchOnce (atomically $ writeTVar signalQuit True)) Nothing
1283 installHandler sigINT (CatchOnce (atomically $ writeTVar signalQuit True)) Nothing
1288 let defaultToxData = do 1284 let defaultToxData = do
1289 toxids <- atomically $ newTVar [] 1285 toxids <- atomically $ newTVar []
1290 rster <- newRoster 1286 rster <- newRoster
@@ -1296,20 +1292,22 @@ main = do
1296 let session = clientSession0 $ Session 1292 let session = clientSession0 $ Session
1297 { netname = concat $ take 1 $ Map.keys dhts -- initial default DHT 1293 { netname = concat $ take 1 $ Map.keys dhts -- initial default DHT
1298 , dhts = dhts -- all DHTs 1294 , dhts = dhts -- all DHTs
1299 , signalQuit = signalQuit 1295 , signalQuit = quitCommand
1300 , swarms = swarms 1296 , swarms = swarms
1301 , cryptosessions = netCryptoSessionsState 1297 , cryptosessions = netCryptoSessionsState
1302 , toxkeys = keysdb 1298 , toxkeys = keysdb
1303 , userkeys = toxids 1299 , userkeys = toxids
1304 , roster = rstr 1300 , roster = rstr
1301 , connectionManager = ConnectionManager conns
1305 , onionRouter = orouter 1302 , onionRouter = orouter
1306 , externalAddresses = liftM2 (++) btips toxips 1303 , externalAddresses = liftM2 (++) btips toxips
1307 , announcer = announcer 1304 , announcer = announcer
1308 } 1305 }
1309 srv <- streamServer (withSession session) (SockAddrUnix "dht.sock") 1306 srv <- streamServer (withSession session) (SockAddrUnix "dht.sock")
1310 return $ do 1307 return ( do atomically $ readTVar signalQuit >>= check
1311 () <- takeMVar signalQuit 1308 quitListening srv
1312 quitListening srv 1309 , readTVar signalQuit >>= check
1310 )
1313 1311
1314 1312
1315 forM_ (Map.toList dhts) 1313 forM_ (Map.toList dhts)
@@ -1331,6 +1329,25 @@ main = do
1331 bootstrap btSaved fallbackNodes 1329 bootstrap btSaved fallbackNodes
1332 return () 1330 return ()
1333 1331
1332 atomically $ do
1333 putTMVar serverVar (sv,conns) -- Okay, now it's ready. :)
1334 -- FIXME: This is error prone.
1335
1336 forkIO $ do
1337 myThreadId >>= flip labelThread "XMPP.stanzas"
1338 let console = cwPresenceChan <$> consoleWriter state
1339 fix $ \loop -> do
1340 what <- atomically
1341 $ orElse (do (client,stanza) <- maybe retry takeTMVar console
1342 return $ do informClientPresence0 state Nothing client stanza
1343 loop)
1344 (checkQuit >> return (return ()))
1345 what
1346
1347 hPutStrLn stderr "Started XMPP server."
1348
1349 -- Wait for DHT and XMPP threads to finish.
1350 -- Use ResourceT to clean-up XMPP server.
1334 waitForSignal 1351 waitForSignal
1335 1352
1336 stopAnnouncer announcer 1353 stopAnnouncer announcer
diff --git a/g b/g
new file mode 100755
index 00000000..a48efef2
--- /dev/null
+++ b/g
@@ -0,0 +1,25 @@
1#!/bin/bash
2warn="-freverse-errors -fwarn-unused-imports -Wmissing-signatures -fdefer-typed-holes"
3exts="-XOverloadedStrings -XRecordWildCards"
4defs="-DBENCODE_AESON -DTHREAD_DEBUG"
5hide="-hide-package crypto-random -hide-package crypto-api -hide-package crypto-numbers -hide-package cryptohash -hide-package prettyclass"
6
7root=${0%/*}
8cd "$root"
9
10me=${0##*/}
11me=${me%.*}
12ghc \
13 $hide \
14 $exts \
15 $defs \
16 -hidir build/$me -odir build/$me \
17 -iPresence \
18 -iArchive \
19 -isrc \
20 -icryptonite-backport \
21 build/b/Presence/monitortty.o \
22 build/b/cbits/cryptonite_salsa.o \
23 build/b/cbits/cryptonite_xsalsa.o\
24 $warn \
25 "$@"
diff --git a/gi b/gi
new file mode 100755
index 00000000..8101348e
--- /dev/null
+++ b/gi
@@ -0,0 +1,14 @@
1#!/bin/bash
2args="-fwarn-unused-imports"
3
4root=${0%/*}
5cd "$root"
6
7me=g
8ghci \
9 -hidir build/$me -odir build/$me \
10 -iPresence \
11 -iArchive \
12 build/b/Presence/monitortty.o \
13 $args \
14 "$@"
diff --git a/graphdeps b/graphdeps
new file mode 100755
index 00000000..4ee6939a
--- /dev/null
+++ b/graphdeps
@@ -0,0 +1,19 @@
1#!/bin/bash
2
3args="-r Todo"
4
5graphmod $args "$@" \
6 -i . -i Presence \
7 Presence/main.hs \
8 | awk 'BEGIN{n=1;}
9 !/label="Main"/{print;}
10 /label="Main"/{if(n==1) print;n=n+1;}' \
11 | sed '2isize="13,8!"; ratio=fill;' \
12 > modules.dot
13
14fgnode="$(sed -n '/label="FGConsole"/{s#\(.*\)\[.*#\1#; p}' modules.dot)"
15
16cat modules.dot | sed '3'i$fgnode'->monitortty;\
17monitortty[label="monitortty.c"];' | dot -Tsvg > modules.svg
18
19
diff --git a/modules.svg b/modules.svg
new file mode 100644
index 00000000..32e85a40
--- /dev/null
+++ b/modules.svg
@@ -0,0 +1,337 @@
1<?xml version="1.0" encoding="UTF-8" standalone="no"?>
2<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN"
3 "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd">
4<!-- Generated by graphviz version 2.26.3 (20100126.1600)
5 -->
6<!-- Title: G Pages: 1 -->
7<svg width="933pt" height="576pt"
8 viewBox="0.00 0.00 932.73 576.00" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">
9<g id="graph1" class="graph" transform="scale(0.654088 0.654088) rotate(0) translate(4 876.615)">
10<title>G</title>
11<polygon fill="white" stroke="white" points="-4,5 -4,-876.615 1423,-876.615 1423,5 -4,5"/>
12<g id="graph2" class="cluster"><title>cluster_0</title>
13<polygon fill="#ccffcc" stroke="#ccffcc" points="1174,-486.35 1174,-606.765 1308,-606.765 1308,-486.35 1174,-486.35"/>
14<text text-anchor="middle" x="1241" y="-590.165" font-family="Times Roman,serif" font-size="14.00">Data</text>
15</g>
16<g id="graph3" class="cluster"><title>cluster_1</title>
17<polygon fill="#ccffcc" stroke="#ccffcc" points="1268,-619.275 1268,-803.807 1410,-803.807 1410,-619.275 1268,-619.275"/>
18<text text-anchor="middle" x="1339" y="-787.207" font-family="Times Roman,serif" font-size="14.00">Holumbus</text>
19</g>
20<g id="graph4" class="cluster"><title>cluster_2</title>
21<polygon fill="#99ff99" stroke="#99ff99" points="1276,-631.786 1276,-752.201 1402,-752.201 1402,-631.786 1276,-631.786"/>
22<text text-anchor="middle" x="1339" y="-735.601" font-family="Times Roman,serif" font-size="14.00">Data</text>
23</g>
24<g id="graph5" class="cluster"><title>cluster_3</title>
25<polygon fill="#ccffcc" stroke="#ccffcc" points="375,-12.5106 375,-373.755 513,-373.755 513,-12.5106 375,-12.5106"/>
26<text text-anchor="middle" x="444" y="-357.155" font-family="Times Roman,serif" font-size="14.00">Text</text>
27</g>
28<g id="graph6" class="cluster"><title>cluster_4</title>
29<polygon fill="#99ff99" stroke="#99ff99" points="383,-25.0212 383,-322.148 505,-322.148 505,-25.0212 383,-25.0212"/>
30<text text-anchor="middle" x="444" y="-305.548" font-family="Times Roman,serif" font-size="14.00">XML</text>
31</g>
32<g id="graph7" class="cluster"><title>cluster_5</title>
33<polygon fill="#66ff66" stroke="#66ff66" points="391,-37.5318 391,-270.542 497,-270.542 497,-37.5318 391,-37.5318"/>
34<text text-anchor="middle" x="444" y="-253.942" font-family="Times Roman,serif" font-size="14.00">Stream</text>
35</g>
36<!-- u6 -->
37<g id="node1" class="node"><title>u6</title>
38<ellipse fill="none" stroke="black" cx="114" cy="-672.511" rx="62.0391" ry="18"/>
39<text text-anchor="middle" x="114" y="-668.411" font-family="Times Roman,serif" font-size="14.00">FGConsole</text>
40</g>
41<!-- monitortty -->
42<g id="node3" class="node"><title>monitortty</title>
43<ellipse fill="none" stroke="black" cx="69" cy="-526.511" rx="68.9883" ry="18"/>
44<text text-anchor="middle" x="69" y="-522.411" font-family="Times Roman,serif" font-size="14.00">monitortty.c</text>
45</g>
46<!-- u6&#45;&gt;monitortty -->
47<g id="edge2" class="edge"><title>u6&#45;&gt;monitortty</title>
48<path fill="none" stroke="black" d="M108.392,-654.315C100.636,-629.151 86.5695,-583.514 77.5134,-554.132"/>
49<polygon fill="black" stroke="black" points="80.8279,-553.003 74.5376,-544.477 74.1384,-555.064 80.8279,-553.003"/>
50</g>
51<!-- u7 -->
52<g id="node13" class="node"><title>u7</title>
53<ellipse fill="none" stroke="black" cx="261" cy="-190.511" rx="48.8383" ry="18"/>
54<text text-anchor="middle" x="261" y="-186.411" font-family="Times Roman,serif" font-size="14.00">Logging</text>
55</g>
56<!-- u6&#45;&gt;u7 -->
57<g id="edge34" class="edge"><title>u6&#45;&gt;u7</title>
58<path fill="none" stroke="black" d="M120.877,-654.474C127.969,-635.494 139.08,-604.664 147,-577.511 170.151,-498.134 166.945,-475.915 190,-396.511 208.824,-331.678 235.908,-257.125 250.587,-217.912"/>
59<polygon fill="black" stroke="black" points="253.88,-219.097 254.124,-208.505 247.328,-216.633 253.88,-219.097"/>
60</g>
61<!-- u18 -->
62<g id="node4" class="node"><title>u18</title>
63<ellipse fill="none" stroke="black" cx="350" cy="-526.511" rx="79.9115" ry="18"/>
64<text text-anchor="middle" x="350" y="-522.411" font-family="Times Roman,serif" font-size="14.00">LocalPeerCred</text>
65</g>
66<!-- u10 -->
67<g id="node10" class="node"><title>u10</title>
68<ellipse fill="none" stroke="black" cx="613" cy="-190.511" rx="62.0391" ry="18"/>
69<text text-anchor="middle" x="613" y="-186.411" font-family="Times Roman,serif" font-size="14.00">SocketLike</text>
70</g>
71<!-- u18&#45;&gt;u10 -->
72<g id="edge84" class="edge"><title>u18&#45;&gt;u10</title>
73<path fill="none" stroke="black" d="M341.723,-508.218C331.03,-481.613 316.121,-431.596 337,-396.511 379.409,-325.244 435.092,-357.845 501,-307.511 536.538,-280.37 571.142,-241.801 592.259,-216.475"/>
74<polygon fill="black" stroke="black" points="595.23,-218.374 598.886,-208.429 589.827,-213.923 595.23,-218.374"/>
75</g>
76<!-- u18&#45;&gt;u7 -->
77<g id="edge82" class="edge"><title>u18&#45;&gt;u7</title>
78<path fill="none" stroke="black" d="M339.25,-508.427C328.733,-489.956 313.019,-460.146 304,-432.511 279.486,-357.4 267.938,-264.346 263.424,-218.595"/>
79<polygon fill="black" stroke="black" points="266.899,-218.163 262.471,-208.538 259.93,-218.823 266.899,-218.163"/>
80</g>
81<!-- u3 -->
82<g id="node15" class="node"><title>u3</title>
83<ellipse fill="none" stroke="black" cx="944" cy="-414.511" rx="78.0216" ry="18"/>
84<text text-anchor="middle" x="944" y="-410.411" font-family="Times Roman,serif" font-size="14.00">ControlMaybe</text>
85</g>
86<!-- u18&#45;&gt;u3 -->
87<g id="edge80" class="edge"><title>u18&#45;&gt;u3</title>
88<path fill="none" stroke="black" d="M412.916,-515.278C508.833,-498.056 697.338,-463.825 857,-432.511 863.158,-431.303 869.557,-430.024 875.963,-428.728"/>
89<polygon fill="black" stroke="black" points="876.904,-432.108 886.004,-426.684 875.507,-425.249 876.904,-432.108"/>
90</g>
91<!-- u17 -->
92<g id="node5" class="node"><title>u17</title>
93<ellipse fill="none" stroke="black" cx="593" cy="-526.511" rx="68.9883" ry="18"/>
94<text text-anchor="middle" x="593" y="-522.411" font-family="Times Roman,serif" font-size="14.00">NestingXML</text>
95</g>
96<!-- u16 -->
97<g id="node6" class="node"><title>u16</title>
98<ellipse fill="none" stroke="black" cx="756" cy="-526.511" rx="75.9375" ry="18"/>
99<text text-anchor="middle" x="756" y="-522.411" font-family="Times Roman,serif" font-size="14.00">SendMessage</text>
100</g>
101<!-- u13 -->
102<g id="node7" class="node"><title>u13</title>
103<ellipse fill="none" stroke="black" cx="444" cy="-414.511" rx="97.9784" ry="18"/>
104<text text-anchor="middle" x="444" y="-410.411" font-family="Times Roman,serif" font-size="14.00">XMLToByteStrings</text>
105</g>
106<!-- u16&#45;&gt;u13 -->
107<g id="edge78" class="edge"><title>u16&#45;&gt;u13</title>
108<path fill="none" stroke="black" d="M713.922,-511.406C658.109,-491.37 559.519,-455.979 498.193,-433.964"/>
109<polygon fill="black" stroke="black" points="499.277,-430.635 488.683,-430.551 496.912,-437.223 499.277,-430.635"/>
110</g>
111<!-- u11 -->
112<g id="node9" class="node"><title>u11</title>
113<ellipse fill="none" stroke="black" cx="782" cy="-414.511" rx="66.0138" ry="18"/>
114<text text-anchor="middle" x="782" y="-410.411" font-family="Times Roman,serif" font-size="14.00">XMPPTypes</text>
115</g>
116<!-- u16&#45;&gt;u11 -->
117<g id="edge76" class="edge"><title>u16&#45;&gt;u11</title>
118<path fill="none" stroke="black" d="M760.177,-508.516C764.303,-490.742 770.675,-463.297 775.47,-442.641"/>
119<polygon fill="black" stroke="black" points="778.895,-443.365 777.747,-432.833 772.076,-441.782 778.895,-443.365"/>
120</g>
121<!-- u16&#45;&gt;u10 -->
122<g id="edge74" class="edge"><title>u16&#45;&gt;u10</title>
123<path fill="none" stroke="black" d="M745.818,-508.433C735.458,-489.72 719.231,-459.498 707,-432.511 672.493,-356.369 638.646,-263.53 622.615,-218.155"/>
124<polygon fill="black" stroke="black" points="625.91,-216.975 619.291,-208.703 619.307,-219.297 625.91,-216.975"/>
125</g>
126<!-- u9 -->
127<g id="node11" class="node"><title>u9</title>
128<ellipse fill="none" stroke="black" cx="610" cy="-414.511" rx="50.0315" ry="18"/>
129<text text-anchor="middle" x="610" y="-410.411" font-family="Times Roman,serif" font-size="14.00">ServerC</text>
130</g>
131<!-- u16&#45;&gt;u9 -->
132<g id="edge72" class="edge"><title>u16&#45;&gt;u9</title>
133<path fill="none" stroke="black" d="M733.507,-509.256C708.281,-489.904 667.271,-458.445 639.494,-437.136"/>
134<polygon fill="black" stroke="black" points="641.394,-434.183 631.33,-430.873 637.134,-439.737 641.394,-434.183"/>
135</g>
136<!-- u16&#45;&gt;u3 -->
137<g id="edge70" class="edge"><title>u16&#45;&gt;u3</title>
138<path fill="none" stroke="black" d="M784.145,-509.743C816.818,-490.278 870.823,-458.105 906.9,-436.613"/>
139<polygon fill="black" stroke="black" points="908.862,-439.518 915.662,-431.393 905.28,-433.504 908.862,-439.518"/>
140</g>
141<!-- u13&#45;&gt;u7 -->
142<g id="edge64" class="edge"><title>u13&#45;&gt;u7</title>
143<path fill="none" stroke="black" d="M429.334,-396.558C396.917,-356.878 319.091,-261.617 281.718,-215.87"/>
144<polygon fill="black" stroke="black" points="284.267,-213.459 275.23,-207.929 278.846,-217.887 284.267,-213.459"/>
145</g>
146<!-- u14 -->
147<g id="node28" class="node"><title>u14</title>
148<ellipse fill="none" stroke="black" cx="444" cy="-190.511" rx="45.1673" ry="18"/>
149<text text-anchor="middle" x="444" y="-186.411" font-family="Times Roman,serif" font-size="14.00">Render</text>
150</g>
151<!-- u13&#45;&gt;u14 -->
152<g id="edge66" class="edge"><title>u13&#45;&gt;u14</title>
153<path fill="none" stroke="black" d="M444,-396.18C444,-357.114 444,-265.433 444,-218.809"/>
154<polygon fill="black" stroke="black" points="447.5,-218.781 444,-208.781 440.5,-218.781 447.5,-218.781"/>
155</g>
156<!-- u12 -->
157<g id="node8" class="node"><title>u12</title>
158<ellipse fill="none" stroke="black" cx="782" cy="-190.511" rx="86.1654" ry="18"/>
159<text text-anchor="middle" x="782" y="-186.411" font-family="Times Roman,serif" font-size="14.00">GetHostByAddr</text>
160</g>
161<!-- u11&#45;&gt;u12 -->
162<g id="edge62" class="edge"><title>u11&#45;&gt;u12</title>
163<path fill="none" stroke="black" d="M782,-396.18C782,-357.114 782,-265.433 782,-218.809"/>
164<polygon fill="black" stroke="black" points="785.5,-218.781 782,-208.781 778.5,-218.781 785.5,-218.781"/>
165</g>
166<!-- u11&#45;&gt;u10 -->
167<g id="edge60" class="edge"><title>u11&#45;&gt;u10</title>
168<path fill="none" stroke="black" d="M764.935,-397.094C745.163,-376.519 712.091,-340.86 687,-307.511 664.706,-277.878 642.405,-241.466 628.204,-217.209"/>
169<polygon fill="black" stroke="black" points="631.223,-215.438 623.175,-208.547 625.169,-218.952 631.223,-215.438"/>
170</g>
171<!-- u2 -->
172<g id="node16" class="node"><title>u2</title>
173<ellipse fill="none" stroke="black" cx="1050" cy="-190.511" rx="111.181" ry="18"/>
174<text text-anchor="middle" x="1050" y="-186.411" font-family="Times Roman,serif" font-size="14.00">ByteStringOperators</text>
175</g>
176<!-- u11&#45;&gt;u2 -->
177<g id="edge58" class="edge"><title>u11&#45;&gt;u2</title>
178<path fill="none" stroke="black" d="M802.585,-397.306C849.801,-357.841 966.027,-260.697 1020.69,-215.009"/>
179<polygon fill="black" stroke="black" points="1023.18,-217.493 1028.6,-208.394 1018.69,-212.122 1023.18,-217.493"/>
180</g>
181<!-- u9&#45;&gt;u10 -->
182<g id="edge56" class="edge"><title>u9&#45;&gt;u10</title>
183<path fill="none" stroke="black" d="M610.246,-396.18C610.769,-357.114 611.997,-265.433 612.621,-218.809"/>
184<polygon fill="black" stroke="black" points="616.121,-218.827 612.755,-208.781 609.122,-218.733 616.121,-218.827"/>
185</g>
186<!-- u9&#45;&gt;u7 -->
187<g id="edge54" class="edge"><title>u9&#45;&gt;u7</title>
188<path fill="none" stroke="black" d="M575.027,-401.554C529.583,-383.885 448.757,-349.568 387,-307.511 346.975,-280.253 307.082,-240.56 283.225,-215.137"/>
189<polygon fill="black" stroke="black" points="285.722,-212.682 276.353,-207.735 280.592,-217.445 285.722,-212.682"/>
190</g>
191<!-- u9&#45;&gt;u2 -->
192<g id="edge52" class="edge"><title>u9&#45;&gt;u2</title>
193<path fill="none" stroke="black" d="M647.388,-402.369C700.07,-384.633 798.482,-349.179 877,-307.511 929.408,-279.698 985.5,-239.639 1019.15,-214.351"/>
194<polygon fill="black" stroke="black" points="1021.35,-217.081 1027.21,-208.257 1017.12,-211.499 1021.35,-217.081"/>
195</g>
196<!-- u8 -->
197<g id="node12" class="node"><title>u8</title>
198<ellipse fill="none" stroke="black" cx="756" cy="-672.511" rx="39.1069" ry="18"/>
199<text text-anchor="middle" x="756" y="-668.411" font-family="Times Roman,serif" font-size="14.00">XMPP</text>
200</g>
201<!-- u8&#45;&gt;u17 -->
202<g id="edge50" class="edge"><title>u8&#45;&gt;u17</title>
203<path fill="none" stroke="black" d="M737.933,-656.328C709.311,-630.691 653.37,-580.584 619.98,-550.677"/>
204<polygon fill="black" stroke="black" points="622.194,-547.961 612.41,-543.896 617.524,-553.175 622.194,-547.961"/>
205</g>
206<!-- u8&#45;&gt;u16 -->
207<g id="edge48" class="edge"><title>u8&#45;&gt;u16</title>
208<path fill="none" stroke="black" d="M756,-654.315C756,-629.397 756,-584.404 756,-554.998"/>
209<polygon fill="black" stroke="black" points="759.5,-554.936 756,-544.936 752.5,-554.936 759.5,-554.936"/>
210</g>
211<!-- u8&#45;&gt;u13 -->
212<g id="edge46" class="edge"><title>u8&#45;&gt;u13</title>
213<path fill="none" stroke="black" d="M717.738,-668.663C662.059,-661.059 558.838,-639.087 499,-577.511 462.878,-540.339 450.455,-478.656 446.2,-442.778"/>
214<polygon fill="black" stroke="black" points="449.649,-442.107 445.124,-432.527 442.687,-442.838 449.649,-442.107"/>
215</g>
216<!-- u8&#45;&gt;u11 -->
217<g id="edge44" class="edge"><title>u8&#45;&gt;u11</title>
218<path fill="none" stroke="black" d="M776.789,-657.038C797.565,-640.149 828.204,-611.002 841,-577.511 853.214,-545.542 851.135,-533.198 841,-500.511 834.014,-477.978 818.857,-456.105 805.655,-440.057"/>
219<polygon fill="black" stroke="black" points="808.132,-437.567 798.983,-432.223 802.802,-442.106 808.132,-437.567"/>
220</g>
221<!-- u8&#45;&gt;u9 -->
222<g id="edge42" class="edge"><title>u8&#45;&gt;u9</title>
223<path fill="none" stroke="black" d="M721.477,-663.99C660.787,-648.237 539.105,-612.923 515,-577.511 495.743,-549.221 501.122,-531.793 515,-500.511 527.185,-473.043 552.959,-450.619 574.589,-435.564"/>
224<polygon fill="black" stroke="black" points="576.586,-438.439 582.942,-429.963 572.687,-432.625 576.586,-438.439"/>
225</g>
226<!-- u8&#45;&gt;u7 -->
227<g id="edge40" class="edge"><title>u8&#45;&gt;u7</title>
228<path fill="none" stroke="black" d="M716.818,-671.159C610.215,-666.578 319.04,-647.749 261,-577.511 216.241,-523.345 244.622,-299.347 256.505,-219.195"/>
229<polygon fill="black" stroke="black" points="260.031,-219.283 258.063,-208.872 253.11,-218.238 260.031,-219.283"/>
230</g>
231<!-- u8&#45;&gt;u3 -->
232<g id="edge38" class="edge"><title>u8&#45;&gt;u3</title>
233<path fill="none" stroke="black" d="M776.785,-657.179C799.362,-639.756 835.478,-609.554 860,-577.511 893.106,-534.252 919.483,-476 933.337,-442.124"/>
234<polygon fill="black" stroke="black" points="936.585,-443.426 937.068,-432.843 930.09,-440.816 936.585,-443.426"/>
235</g>
236<!-- u8&#45;&gt;u2 -->
237<g id="edge36" class="edge"><title>u8&#45;&gt;u2</title>
238<path fill="none" stroke="black" d="M783.348,-659.313C842.428,-629.028 980.699,-548.146 1031,-432.511 1062.27,-360.626 1058.13,-265.44 1053.53,-218.766"/>
239<polygon fill="black" stroke="black" points="1057,-218.348 1052.46,-208.776 1050.04,-219.091 1057,-218.348"/>
240</g>
241<!-- u4 -->
242<g id="node14" class="node"><title>u4</title>
243<ellipse fill="none" stroke="black" cx="1221" cy="-672.511" rx="39.1069" ry="18"/>
244<text text-anchor="middle" x="1221" y="-668.411" font-family="Times Roman,serif" font-size="14.00">UTmp</text>
245</g>
246<!-- u5 -->
247<g id="node20" class="node"><title>u5</title>
248<ellipse fill="none" stroke="black" cx="1241" cy="-526.511" rx="59.065" ry="18"/>
249<text text-anchor="middle" x="1241" y="-522.411" font-family="Times Roman,serif" font-size="14.00">BitSyntax</text>
250</g>
251<!-- u4&#45;&gt;u5 -->
252<g id="edge32" class="edge"><title>u4&#45;&gt;u5</title>
253<path fill="none" stroke="black" d="M1223.49,-654.315C1226.91,-629.397 1233.07,-584.404 1237.1,-554.998"/>
254<polygon fill="black" stroke="black" points="1240.59,-555.318 1238.48,-544.936 1233.65,-554.368 1240.59,-555.318"/>
255</g>
256<!-- u1 -->
257<g id="node17" class="node"><title>u1</title>
258<ellipse fill="none" stroke="black" cx="1064" cy="-526.511" rx="62.0391" ry="18"/>
259<text text-anchor="middle" x="1064" y="-522.411" font-family="Times Roman,serif" font-size="14.00">ConfigFiles</text>
260</g>
261<!-- u1&#45;&gt;u3 -->
262<g id="edge30" class="edge"><title>u1&#45;&gt;u3</title>
263<path fill="none" stroke="black" d="M1045.51,-509.256C1025.43,-490.512 993.177,-460.409 970.424,-439.173"/>
264<polygon fill="black" stroke="black" points="972.802,-436.605 963.103,-432.341 968.026,-441.722 972.802,-436.605"/>
265</g>
266<!-- u1&#45;&gt;u2 -->
267<g id="edge28" class="edge"><title>u1&#45;&gt;u2</title>
268<path fill="none" stroke="black" d="M1064.39,-508.418C1064.84,-483.297 1065.36,-436.436 1064,-396.511 1061.84,-332.846 1055.93,-258.304 1052.52,-218.664"/>
269<polygon fill="black" stroke="black" points="1056.01,-218.335 1051.65,-208.677 1049.03,-218.943 1056.01,-218.335"/>
270</g>
271<!-- u0 -->
272<g id="node18" class="node"><title>u0</title>
273<ellipse fill="none" stroke="black" cx="974" cy="-844.511" rx="34.2406" ry="18"/>
274<text text-anchor="middle" x="974" y="-840.411" font-family="Times Roman,serif" font-size="14.00">Main</text>
275</g>
276<!-- u0&#45;&gt;u6 -->
277<g id="edge18" class="edge"><title>u0&#45;&gt;u6</title>
278<path fill="none" stroke="black" d="M939.803,-843.856C806.714,-840.826 324.082,-825.222 190,-756.511 164.653,-743.522 143.663,-718.347 130.211,-698.93"/>
279<polygon fill="black" stroke="black" points="133.034,-696.854 124.572,-690.478 127.211,-700.739 133.034,-696.854"/>
280</g>
281<!-- u0&#45;&gt;u18 -->
282<g id="edge24" class="edge"><title>u0&#45;&gt;u18</title>
283<path fill="none" stroke="black" d="M942.708,-836.902C891.962,-823.966 789.213,-795.269 708,-756.511 579.32,-695.099 441.178,-595.552 380.987,-550.28"/>
284<polygon fill="black" stroke="black" points="382.771,-547.241 372.682,-544.005 378.551,-552.826 382.771,-547.241"/>
285</g>
286<!-- u0&#45;&gt;u8 -->
287<g id="edge22" class="edge"><title>u0&#45;&gt;u8</title>
288<path fill="none" stroke="black" d="M955.035,-829.548C916.417,-799.078 828.516,-729.725 783.574,-694.266"/>
289<polygon fill="black" stroke="black" points="785.722,-691.503 775.703,-688.056 781.386,-696.998 785.722,-691.503"/>
290</g>
291<!-- u0&#45;&gt;u7 -->
292<g id="edge20" class="edge"><title>u0&#45;&gt;u7</title>
293<path fill="none" stroke="black" d="M940.012,-842.777C860.903,-837.764 659.438,-819.328 505,-756.511 371.977,-702.404 305.122,-703.387 236,-577.511 170.19,-457.665 224.521,-284.432 249.798,-217.926"/>
294<polygon fill="black" stroke="black" points="253.082,-219.138 253.441,-208.55 246.557,-216.603 253.082,-219.138"/>
295</g>
296<!-- u0&#45;&gt;u4 -->
297<g id="edge16" class="edge"><title>u0&#45;&gt;u4</title>
298<path fill="none" stroke="black" d="M1004.62,-836.63C1045.64,-824.834 1118.93,-799.278 1168,-756.511 1185.88,-740.929 1199.84,-717.845 1208.94,-699.817"/>
299<polygon fill="black" stroke="black" points="1212.29,-700.929 1213.49,-690.402 1205.99,-697.885 1212.29,-700.929"/>
300</g>
301<!-- u0&#45;&gt;u3 -->
302<g id="edge14" class="edge"><title>u0&#45;&gt;u3</title>
303<path fill="none" stroke="black" d="M972.73,-826.309C968.045,-759.149 951.703,-524.925 945.99,-443.037"/>
304<polygon fill="black" stroke="black" points="949.475,-442.69 945.287,-432.958 942.492,-443.177 949.475,-442.69"/>
305</g>
306<!-- u0&#45;&gt;u2 -->
307<g id="edge12" class="edge"><title>u0&#45;&gt;u2</title>
308<path fill="none" stroke="black" d="M988.643,-827.967C1022.67,-788.265 1106.34,-683.028 1135,-577.511 1171.28,-443.966 1098.05,-281.324 1065.02,-217.784"/>
309<polygon fill="black" stroke="black" points="1068.04,-216.005 1060.27,-208.799 1061.85,-219.276 1068.04,-216.005"/>
310</g>
311<!-- u0&#45;&gt;u1 -->
312<g id="edge10" class="edge"><title>u0&#45;&gt;u1</title>
313<path fill="none" stroke="black" d="M979.097,-826.502C994.067,-773.607 1037.99,-618.418 1056.08,-554.507"/>
314<polygon fill="black" stroke="black" points="1059.49,-555.291 1058.85,-544.715 1052.76,-553.384 1059.49,-555.291"/>
315</g>
316<!-- u19 -->
317<g id="node23" class="node"><title>u19</title>
318<ellipse fill="none" stroke="black" cx="1339" cy="-672.511" rx="55.0898" ry="18"/>
319<text text-anchor="middle" x="1339" y="-668.411" font-family="Times Roman,serif" font-size="14.00">MultiMap</text>
320</g>
321<!-- u0&#45;&gt;u19 -->
322<g id="edge26" class="edge"><title>u0&#45;&gt;u19</title>
323<path fill="none" stroke="black" d="M1007.95,-842.09C1068.01,-836.318 1194.7,-817.311 1280,-756.511 1300.48,-741.91 1316.32,-717.873 1326.4,-699.244"/>
324<polygon fill="black" stroke="black" points="1329.52,-700.827 1331.01,-690.337 1323.3,-697.607 1329.52,-700.827"/>
325</g>
326<!-- u15 -->
327<g id="node27" class="node"><title>u15</title>
328<ellipse fill="none" stroke="black" cx="444" cy="-78.5106" rx="38.9134" ry="18"/>
329<text text-anchor="middle" x="444" y="-74.4106" font-family="Times Roman,serif" font-size="14.00">Token</text>
330</g>
331<!-- u14&#45;&gt;u15 -->
332<g id="edge68" class="edge"><title>u14&#45;&gt;u15</title>
333<path fill="none" stroke="black" d="M444,-172.016C444,-154.239 444,-127.129 444,-106.669"/>
334<polygon fill="black" stroke="black" points="447.5,-106.661 444,-96.661 440.5,-106.661 447.5,-106.661"/>
335</g>
336</g>
337</svg>
diff --git a/nalias.hs b/nalias.hs
new file mode 100644
index 00000000..fa1b6f71
--- /dev/null
+++ b/nalias.hs
@@ -0,0 +1,70 @@
1import Network.Socket
2import qualified Network.BSD as BSD
3import ControlMaybe
4import Control.Exception ({-evaluate,-}handle,SomeException(..),bracketOnError,ErrorCall(..))
5import System.IO.Error (isDoesNotExistError)
6import System.Endian
7import Data.List (nub)
8import qualified Data.Text as Text
9import GetHostByAddr (getHostByAddr)
10import Control.Concurrent
11import Control.Concurrent.STM
12import Control.Monad
13import System.Environment
14
15unmap6mapped4 addr@(SockAddrInet6 port _ (0,0,0xFFFF,a) _) =
16 SockAddrInet port (toBE32 a)
17unmap6mapped4 addr = addr
18
19make6mapped4 addr@(SockAddrInet6 {}) = addr
20make6mapped4 addr@(SockAddrInet port a) = SockAddrInet6 port 0 (0,0,0xFFFF,fromBE32 a) 0
21
22
23reverseResolve addr =
24 handleIO_ (return []) $ do
25 ent <- getHostByAddr (unmap6mapped4 addr) -- AF_UNSPEC addr
26 let names = BSD.hostName ent : BSD.hostAliases ent
27 return $ map Text.pack $ nub names
28
29forwardResolve addrtext = do
30 r <- atomically newEmptyTMVar
31 mvar <- atomically newEmptyTMVar
32 rt <- forkOS $ resolver r mvar
33 tt <- forkIO $ timer r rt
34 atomically $ putTMVar mvar tt
35 atomically $ readTMVar r
36 where
37 resolver r mvar = do
38 xs <- handle (\e -> let _ = isDoesNotExistError e in return [])
39 $ do fmap (map $ make6mapped4 . addrAddress) $
40 getAddrInfo (Just $ defaultHints { addrFlags = [ AI_CANONNAME, AI_V4MAPPED ]})
41 (Just $ Text.unpack $ strip_brackets addrtext)
42 (Just "5269")
43 did <- atomically $ tryPutTMVar r (nub xs)
44 when did $ do
45 tt <- atomically $ readTMVar mvar
46 throwTo tt (ErrorCall "Interrupted delay")
47 return ()
48 timer r rt = do
49 handle (\(ErrorCall _)-> return ()) $ do
50 threadDelay 2000000
51 did <- atomically $ tryPutTMVar r []
52 when did $ do
53 putStrLn $ "timeout resolving: "++show addrtext
54 killThread rt
55 strip_brackets s =
56 case Text.uncons s of
57 Just ('[',t) -> Text.takeWhile (/=']') t
58 _ -> s
59
60main = do
61 args <- getArgs
62 forM args $ \arg -> do
63 putStrLn $ arg ++ ":"
64 let targ = Text.pack arg
65 addrs <- forwardResolve targ
66 putStrLn $ " forward: " ++ show addrs
67 forM addrs $ \addr -> do
68 names <- reverseResolve addr
69 putStrLn $ " reverse "++show addr++": "++show names
70 return ()
diff --git a/nalias2.hs b/nalias2.hs
new file mode 100644
index 00000000..609f2ec6
--- /dev/null
+++ b/nalias2.hs
@@ -0,0 +1,18 @@
1import System.Environment
2import Control.Monad
3import qualified Data.Text as Text
4
5import DNSCache
6
7main = do
8 dns <- newDNSCache
9 args <- getArgs
10 forM args $ \arg -> do
11 putStrLn $ arg ++ ":"
12 let targ = Text.pack arg
13 addrs <- forwardResolve dns targ
14 putStrLn $ " forward: " ++ show addrs
15 forM addrs $ \addr -> do
16 names <- reverseResolve dns addr
17 putStrLn $ " reverse "++show addr++": "++show names
18 return ()
diff --git a/p b/p
new file mode 100755
index 00000000..1ed6e374
--- /dev/null
+++ b/p
@@ -0,0 +1,28 @@
1#!/bin/bash
2warn="-freverse-errors -fwarn-unused-imports -Wmissing-signatures -fdefer-typed-holes"
3exts="-XOverloadedStrings -XRecordWildCards"
4defs="-DBENCODE_AESON -DTHREAD_DEBUG"
5hide="-hide-package crypto-random -hide-package crypto-api -hide-package crypto-numbers -hide-package cryptohash -hide-package prettyclass"
6opts="-rtsopts -hisuf p_hi -osuf p_o -prof -fprof-auto -fprof-auto-exported"
7
8root=${0%/*}
9cd "$root"
10
11me=${0##*/}
12me=${me%.*}
13set -x
14ghc \
15 $opts \
16 $hide \
17 $exts \
18 $defs \
19 -hidir build/$me -odir build/$me \
20 -iPresence \
21 -iArchive \
22 -isrc \
23 -icryptonite-backport \
24 build/b/Presence/monitortty.o \
25 build/b/cbits/cryptonite_salsa.o \
26 build/b/cbits/cryptonite_xsalsa.o\
27 $warn \
28 "$@"
diff --git a/presence.cabal.bak b/presence.cabal.bak
new file mode 100644
index 00000000..81ca59b2
--- /dev/null
+++ b/presence.cabal.bak
@@ -0,0 +1,156 @@
1name: presence
2version: 0.0.1
3cabal-version: >=1.10
4build-type: Simple
5license: AllRightsReserved
6synopsis: XMPP Server which detects unix logins
7description: When users login to your localhost, their presence is detected and announced
8 to connected xmpp clients. presence is a modern XMPP variant of the old Unix Talk
9 program. Eventually, this will be expanded to become a peer-to-peer service allowing
10 xmpp instant messaging between separate computers as well. And somewhere down the
11 road, extended again to make use of Jingle to facilitate VOIP.
12author: Joe Crayne
13data-dir: ""
14
15library
16 cpp-options: -DRENDERFLUSH
17 c-sources: Presence/monitortty.c
18 hs-source-dirs: . Presence
19 ghc-options: -O2 -fwarn-unused-binds
20 hs-source-dirs: . Presence
21 build-depends:
22 base,
23 binary,
24 blaze-builder,
25 bytestring,
26 conduit (>=1.0.4),
27 conduit-extra,
28 containers,
29 cpu,
30 deepseq,
31 directory,
32 filepath,
33 hinotify,
34 mtl,
35 network,
36 process,
37 random,
38 resourcet,
39 stm,
40 template-haskell,
41 text (>=0.11.2.0),
42 time,
43 transformers,
44 unix,
45 void,
46 xml-conduit,
47 xml-types
48 exposed-modules:
49 ByteStringOperators,
50 ClientState,
51 ConfigFiles,
52 ConnectionKey,
53 ConsoleWriter,
54 Control.Concurrent.STM.StatusCache,
55 Control.Concurrent.STM.UpdateStream,
56 ControlMaybe,
57 Data.BitSyntax,
58 DNSCache,
59 EventUtil,
60 FGConsole,
61 GetHostByAddr,
62 LocalPeerCred,
63 LockedChan,
64 Logging,
65 Nesting,
66 Paths,
67 PeerResolve,
68 Server,
69 SockAddr,
70 SocketLike,
71 TraversableT,
72 UTmp,
73 XMPPServer
74
75executable presence
76 main-is: xmppServer.hs
77 buildable: True
78 cpp-options: -DRENDERFLUSH
79 hs-source-dirs: .
80 ghc-options: -O2 -fwarn-unused-binds -threaded
81 build-depends:
82 base, presence,
83 bytestring,
84 containers,
85 cpu,
86 mtl,
87 network,
88 resourcet,
89 stm,
90 text (>=0.11.2.0),
91 transformers,
92 unix,
93 xml-types
94
95executable whosocket
96 main-is: whosocket.hs
97 hs-source-dirs: .
98 cpp-options: -DRENDERFLUSH
99 ghc-options: -O2 -fwarn-unused-binds -threaded
100 build-depends:
101 base, presence,
102 bytestring,
103 cpu,
104 directory,
105 network,
106 unix
107
108executable nalias2
109 main-is: nalias2.hs
110 hs-source-dirs: .
111 ghc-options: -O2 -fwarn-unused-binds -threaded
112 build-depends: base, presence, text (>=0.11.2.0)
113
114executable consolation
115 main-is: consolation.hs
116 hs-source-dirs: .
117 ghc-options: -O2 -fwarn-unused-binds -threaded
118 cpp-options: -DRENDERFLUSH
119 build-depends:
120 base, presence,
121 bytestring,
122 containers,
123 cpu,
124 mtl,
125 network,
126 resourcet,
127 stm,
128 text (>=0.11.2.0),
129 transformers,
130 unix,
131 xml-types
132 main-is: xmppServer.hs
133
134executable pwrite
135 main-is: pwrite.hs
136 hs-source-dirs: .
137 ghc-options: -O2 -fwarn-unused-binds -threaded
138 build-depends:
139 base,
140 presence,
141 text (>=0.11.2.0),
142 unix
143
144-- [ ] ConduitServer.hs:main = mainC
145-- [ ] Control/Concurrent/STM/StatusCache.hs:-- > main = do q <- atomically $ Cache.new (== '(') (==')')
146-- [ ] Control/Concurrent/STM/UpdateStream.hs:-- > main = do
147-- [ ] Presence/Server.hs:-- > main = runResourceT $ do
148-- [ ] Presence/main.hs:main = do
149-- [x] consolation.hs:main = do
150-- [ ] nalias.hs:main = do
151-- [x] nalias2.hs:main = do
152-- [x] pwrite.hs:main = do
153-- [ ] simplechat.hs:main = do
154-- [ ] test-server.hs:main = do
155-- [x] whosocket.hs:main = do
156-- [x] xmppServer.hs:main = runResourceT $ do
diff --git a/presence.service b/presence.service
new file mode 100644
index 00000000..85f20cda
--- /dev/null
+++ b/presence.service
@@ -0,0 +1,11 @@
1[Unit]
2Description=XMPP Daemon
3
4[Service]
5ExecStart=/usr/local/bin/presence
6StandardOutput=journal
7StandardError=journal
8Restart=always
9
10[Install]
11WantedBy=multi-user.target
diff --git a/pwrite.hs b/pwrite.hs
new file mode 100644
index 00000000..bad6af06
--- /dev/null
+++ b/pwrite.hs
@@ -0,0 +1,105 @@
1{-# LANGUAGE CPP #-}
2{-# LANGUAGE RankNTypes #-}
3{-# LANGUAGE OverloadedStrings #-}
4import System.Environment
5import System.Posix.Files ( getFileStatus, fileMode )
6import Data.Bits ( (.&.) )
7import Data.Text ( Text )
8import qualified Data.Text as Text
9import qualified Data.Text.IO as Text
10import Control.Applicative
11import Control.Monad
12import Data.Maybe
13import XMPPServer
14import Data.Monoid
15
16-- Transforms a string of form language[_territory][.codeset][@modifier]
17-- typically used in LC_ locale variables into the BCP 47
18-- language codes used in xml:lang attributes.
19toBCP47 :: [Char] -> [Char]
20toBCP47 lang = map hyphen $ takeWhile (/='.') lang
21 where hyphen '_' = '-'
22 hyphen c = c
23
24
25#if MIN_VERSION_base(4,6,0)
26#else
27lookupEnv k = fmap (lookup k) getEnvironment
28#endif
29
30getPreferedLang :: IO Text
31getPreferedLang = do
32 lang <- do
33 lc_all <- lookupEnv "LC_ALL"
34 lc_messages <- lookupEnv "LC_MESSAGES"
35 lang <- lookupEnv "LANG"
36 return $ lc_all `mplus` lc_messages `mplus` lang
37 return $ maybe "en" (Text.pack . toBCP47) lang
38
39cimatch :: Text -> Text -> Bool
40cimatch w t = Text.toLower w == Text.toLower t
41
42cimatches :: Text -> [Text] -> [Text]
43cimatches w ts = dropWhile (not . cimatch w) ts
44
45-- rfc4647 lookup of best match language tag
46lookupLang :: [Text] -> [Text] -> Maybe Text
47lookupLang (w:ws) tags
48 | Text.null w = lookupLang ws tags
49 | otherwise = case cimatches w tags of
50 (t:_) -> Just t
51 [] -> lookupLang (reduce w:ws) tags
52 where
53 reduce w = Text.concat $ reverse nopriv
54 where
55 rparts = reverse . init $ Text.groupBy (\_ c -> c/='-') w
56 nopriv = dropWhile ispriv rparts
57 ispriv t = Text.length t == 2 && Text.head t == '-'
58
59lookupLang [] tags | "" `elem` tags = Just ""
60 | otherwise = listToMaybe $ tags
61
62
63messageText :: Stanza -> IO Text
64messageText msg = do
65 pref <- getPreferedLang
66 let m = msgLangMap (stanzaType msg)
67 key = lookupLang [pref] (map fst m)
68 choice = do
69 k <- key
70 lookup k m
71 flip (maybe $ return "") choice $ \choice -> do
72 let subj = fmap ("Subject: " <>) $ msgSubject choice
73 ts = catMaybes [subj, msgBody choice]
74 return $ Text.intercalate "\n\n" ts
75
76crlf :: Text -> Text
77crlf t = Text.unlines $ map cr (Text.lines t)
78 where
79 cr t | Text.last t == '\r' = t
80 | otherwise = t <> "\r"
81
82deliverTerminalMessage ::
83 forall t t1. t -> Text -> t1 -> Stanza -> IO Bool
84deliverTerminalMessage cw tty utmp msg = do
85 mode <- fmap fileMode (getFileStatus $ Text.unpack tty)
86 let mesgy = mode .&. 0o020 /= 0 -- verify mode g+w
87 if not mesgy then return False else do
88 text <- do
89 t <- messageText msg
90 return $ Text.unpack
91 $ case stanzaFrom msg of
92 Just from -> "\r\n" <> from <> " says...\r\n" <> crlf t <> "\r\n"
93 Nothing -> crlf t <> "\r\n"
94 writeFile (Text.unpack tty) text
95 return True -- return True if a message was delivered
96
97main = do
98 args <- getArgs
99 let mas = (,) <$> listToMaybe args <*> listToMaybe (drop 1 args)
100 flip (maybe $ putStrLn "pwrite user tty") mas $ \(usr,tty) -> do
101 bod <- Text.getContents
102 stanza <- makeMessage "jabber:client" "nobody" (Text.pack usr) bod
103 b <- deliverTerminalMessage () (Text.pack tty) () stanza
104 when b $ putStrLn "delivered."
105 return ()
diff --git a/simplechat.hs b/simplechat.hs
new file mode 100644
index 00000000..bf592db3
--- /dev/null
+++ b/simplechat.hs
@@ -0,0 +1,66 @@
1{-# LANGUAGE OverloadedStrings #-}
2{-# LANGUAGE ScopedTypeVariables #-}
3
4import Data.HList.TypeEqGeneric1()
5import Data.HList.TypeCastGeneric1()
6import ByteStringOperators
7
8import Data.ByteString.Lazy.Char8 as L
9 ( ByteString
10 , hPutStrLn
11 , init )
12import System.IO
13 ( Handle
14 )
15import Control.Concurrent (forkIO)
16import Control.Concurrent.Chan
17import Data.HList
18
19import Server
20
21
22startCon socket st = do
23 let chan = hOccursFst st
24 nr = hOccursFst st :: ConnId
25 hdl = hOccursFst st :: Handle
26 quit = writeChan chan (nr,Nothing)
27 broadcast msg = writeChan chan (nr,Just msg)
28 chan' <- dupChan chan
29 reader <- forkIO $ fix $ \loop -> do
30 (nr', line) <- readChan chan'
31 case ( line, nr==nr') of
32 ( Nothing , True ) -> Prelude.putStrLn "quit-client."
33 ( Just msg , False ) -> hPutStrLn hdl msg >> loop
34 _ -> loop
35
36 hPutStrLn hdl "Hi, what's your name?"
37 line <- getPacket hdl
38 let name = L.init line
39 Prelude.putStrLn $ "readFst: " ++ show line
40 hPutStrLn hdl ("Welcome, " <++> name <++> "!")
41 broadcast ("--> " <++> name <++> " entered.")
42
43 return (name .*. ConnectionFinalizer quit .*. st)
44
45doCon st bs cont = do
46 let hdl = hOccursFst st :: Handle
47 nr = hOccursFst st :: ConnId
48 chan = hOccursFst st
49 broadcast msg = writeChan chan (nr,Just msg)
50 name = hHead st
51 Prelude.putStrLn $ "read: " ++ show bs
52 case bs of
53 "quit\n" -> hPutStrLn hdl "Bye!"
54 _ -> do
55 broadcast (name <++> ": " <++> L.init bs)
56 cont ()
57
58
59main = do
60 (chan :: Chan (ConnId, Maybe ByteString)) <- newChan
61 doServer (5222 .*. chan .*. HNil)
62 doCon
63 startCon
64 getLine
65
66
diff --git a/stack.yaml b/stack.yaml
new file mode 100644
index 00000000..e2280624
--- /dev/null
+++ b/stack.yaml
@@ -0,0 +1,35 @@
1# This file was automatically generated by stack init
2# For more information, see: http://docs.haskellstack.org/en/stable/yaml_configuration.html
3
4# Specifies the GHC version and set of packages available (e.g., lts-3.5, nightly-2015-09-21, ghc-7.10.2)
5resolver: lts-5.4
6
7# Local packages, usually specified by relative directory name
8packages:
9- '.'
10# Packages to be pulled from upstream that are not in the resolver (e.g., acme-missiles-0.3)
11extra-deps: []
12
13# Override default flag values for local packages and extra-deps
14flags: {}
15
16# Extra package databases containing global packages
17extra-package-dbs: []
18
19# Control whether we use the GHC we find on the path
20# system-ghc: true
21
22# Require a specific version of stack, using version ranges
23# require-stack-version: -any # Default
24# require-stack-version: >= 1.0.0
25
26# Override the architecture used by stack, especially useful on Windows
27# arch: i386
28# arch: x86_64
29
30# Extra directories used by stack for building
31# extra-include-dirs: [/path/to/dir]
32# extra-lib-dirs: [/path/to/dir]
33
34# Allow a newer minor version of GHC than the snapshot specifies
35# compiler-check: newer-minor
diff --git a/t b/t
new file mode 100755
index 00000000..22b21361
--- /dev/null
+++ b/t
@@ -0,0 +1,14 @@
1#!/bin/bash
2args="-threaded -fwarn-unused-imports -rtsopts -DRENDERFLUSH -optP-include -optPdist/build/autogen/cabal_macros.h"
3
4root=${0%/*}
5cd "$root"
6
7me=${0##*/}
8me=${me%.*}
9ghc \
10 -hidir build/$me -odir build/$me \
11 -iPresence \
12 $args \
13 Presence/monitortty.c \
14 "$@"
diff --git a/test-server.hs b/test-server.hs
new file mode 100644
index 00000000..795a8190
--- /dev/null
+++ b/test-server.hs
@@ -0,0 +1,541 @@
1{-# LANGUAGE OverloadedStrings #-}
2module Main where
3
4import Debug.Trace
5import Control.Exception (evaluate) -- ,handle,SomeException(..),bracketOnError)
6import Control.Exception ({-evaluate,-}handle,SomeException(..),bracketOnError,ErrorCall(..))
7import System.IO.Error (ioeGetErrorType)
8import Server
9import Control.Monad
10import Control.Monad.Trans.Resource
11import Control.Monad.IO.Class
12import Control.Monad.STM
13import Control.Monad.Fix
14import Control.Concurrent (threadDelay,forkOS,forkIO)
15import Control.Concurrent.STM.TMVar
16import Control.Concurrent.STM.TChan
17import Network.Socket
18import System.Process.Internals
19import System.Process
20import Data.Char
21import System.IO hiding (isEOF)
22import System.Posix.Signals hiding (Ignore)
23
24
25makeGots sv = do
26 let chan = serverEvent sv
27 gotchan <- atomically $ dupTChan chan
28 forkIO $ do
29 fix $ \loop -> do
30 (k,e) <- atomically $ readTChan chan
31 case e of
32 Connection pingflag read write -> todo
33 EOF -> todo
34 loop
35 return gotchan
36
37isConnection (_,Connection {}) = True
38isConnection _ = False
39isPending want (_,HalfConnection got) | got/=want = True
40isPending _ _ = False
41isRead str (_,Got r) | r==str = True
42isRead _ _ = False
43isEOF (_,EOF) = True
44isEOF _ = False
45
46-- localhost port = SockAddrInet port 127
47localhost port = SockAddrInet6 port 0 (0,0,0,1) 0
48
49withServer f = runResourceT $ do
50 sv <- server
51 result <- liftIO $ f sv
52 release (serverReleaseKey sv)
53 return result
54
55writeToPort port str = do
56 s <- readProcess "/usr/bin/socat" ["-","TCP6:localhost:"++show port] str
57 reverse s `seq` return ()
58
59connectToPort port = do
60 (inp,outp,err,p) <-
61 runInteractiveProcess "/usr/bin/socat"
62 ["-","TCP6:localhost:"++show port]
63 Nothing
64 Nothing
65 hSetBuffering inp NoBuffering
66 hSetBuffering outp NoBuffering
67 hSetBuffering err NoBuffering
68 forkOS $ do putStrLn $ "SOCAT-ConnectToPort:"++show (port,(inp,outp,err))
69 hGetContents err >>= putStrLn
70 return (inp,outp,err,p)
71
72listenOnPort port = do
73 putStrLn $ "socat - TCP6-LISTEN:"++show port++",fork"
74 (inp,outp,err,p) <-
75 runInteractiveProcess "/usr/bin/socat"
76 ["-","TCP6-LISTEN:"++show port++",fork"]
77 Nothing
78 Nothing
79 hSetBuffering inp NoBuffering
80 hSetBuffering outp NoBuffering
81 hSetBuffering err NoBuffering
82 forkOS $ do { putStrLn "SOCAT-listenOnPort:"; hGetContents err >>= putStrLn }
83 -- forkOS $ do { putStrLn "SOCAT-listenOnPort:"; hGetContents outp >>= putStrLn }
84 return (inp,outp,err,p)
85
86stopListening (inp,outp,err,p) = do
87 {-
88 forkOS $ do
89 o <- hGetContents outp
90 void $ evaluate (length o)
91 forkOS $ do
92 e <- hGetContents err
93 void $ evaluate (length e)
94 threadDelay 1000000
95 hClose inp
96 threadDelay 1000000
97 forkOS $ do
98 threadDelay 100000
99 mapM_ hClose [outp,err]
100 -}
101 withProcessHandle p $ \p -> do
102 case p of
103 OpenHandle pid -> trace ("interrupting: "++show pid)
104 $ signalProcess sigINT pid
105 _ -> return ()
106 return (p,())
107 {-
108 threadDelay 500000
109 terminateProcess p
110 -}
111 e <- waitForProcess p
112 putStrLn $ "SOCAT-LISTEN exit: "++show e
113
114
115
116chanContents ch = do
117 x <- atomically $ do
118 bempty <- isEmptyTChan ch
119 if bempty
120 then return Nothing
121 else fmap Just $ readTChan ch
122 maybe (return [])
123 (\x -> do
124 xs <- chanContents ch
125 return (x:xs))
126 x
127
128control sv = atomically . putTMVar (serverCommand sv)
129
130testListen = do
131 let send con str = do hPutStr con str
132 hFlush con
133 threadDelay 100000
134 events <- withServer $ \sv -> do
135 let _ = sv :: Server SockAddr
136 events = serverEvent sv
137 params :: ConnectionParameters SockAddr
138 params = connectionDefaults (return . snd)
139 control sv (Listen 39242 params)
140 h1@(con1,con2,_,_)<- connectToPort 39242
141 send con1 "Joe was here"
142 control sv (Ignore 39242)
143 threadDelay 500000
144 stopListening h1
145 threadDelay 500000
146 return events
147 e <- chanContents events
148 putStrLn $ "testListen: "++ show e
149 return $
150 and [ length e == 3
151 , isConnection $ e !! 0
152 , isRead "Joe was here" $ e !! 1
153 , isEOF $ e !! 2
154 ]
155
156
157testReplace = do
158 let send con str = do hPutStrLn con str
159 hFlush con
160 threadDelay 100000
161 events <- withServer $ \sv -> do
162 let _ = sv :: Server ()
163 events = serverEvent sv
164 params = connectionDefaults (const $ return ())
165 control sv (Listen 39242 params)
166 h1@(con1,_,_,_)<- connectToPort 39242
167 send con1 "Joe was here"
168 h2@(con2,_,_,_) <- connectToPort 39242
169 send con2 "Jim also"
170 send con1 "What?"
171 threadDelay 500000
172 stopListening h1 -- misnomer
173 stopListening h2 -- misnomer
174 threadDelay 500000
175 return events
176 e <- chanContents events
177 -- [([::ffff:127.0.0.1]:43722,Connection)
178 -- ,([::ffff:127.0.0.1]:43722,Got "Joe was here\n")
179 -- ,([::ffff:127.0.0.1]:43723,Connection)
180 -- ,([::ffff:127.0.0.1]:43723,Got "Jim also\n")
181 -- ,([::ffff:127.0.0.1]:43722,Got "What?\n")
182 -- ,([::ffff:127.0.0.1,EOF)]:43722
183 -- ,([::ffff:127.0.0.1,EOF)]:43723]
184 -- putStrLn $ show e
185 putStrLn $ "testReplace: "++ show e
186 return $ case e of
187 [(_,Connection {})
188 ,(_,Got "Joe was here\n")
189 ,(_,EOF)
190 ,(_,Connection {})
191 ,(_,Got "Jim also\n")
192 ,(_,EOF)]
193 -> True
194 _ -> False
195
196testPendingOut = do
197 let send con str = do hPutStr con str
198 hFlush con
199 threadDelay 100000
200 events <- withServer $ \sv -> do
201 let _ = sv :: Server SockAddr
202 events = serverEvent sv
203 params :: ConnectionParameters SockAddr
204 params = (connectionDefaults (return . snd))
205 { duplex = False }
206 control sv (Listen 39249 params)
207 h1@(con1,con2,_,_)<- connectToPort 39249
208 send con1 "Joe was here"
209 stopListening h1
210 threadDelay 500000
211 return events
212
213 e <- chanContents events
214 putStrLn $ "testPendingOut: "++ show e
215 return $
216 and [ length e == 3
217 , isPending Out $ e !! 0
218 , isRead "Joe was here" $ e !! 1
219 , isEOF $ e !! 2
220 ]
221
222testReplacePendingOut = do
223 let send con str = do hPutStrLn con str
224 hFlush con
225 threadDelay 100000
226 events <- withServer $ \sv -> do
227 let _ = sv :: Server ()
228 events = serverEvent sv
229 params = (connectionDefaults (const $ return ()))
230 { duplex = False }
231 control sv (Ignore 39242)
232 control sv (Listen 39242 params)
233 threadDelay 500000
234 h1@(con1,_,_,_) <- connectToPort 39242
235 send con1 "Joe was here"
236 h2@(con2,_,_,_) <- connectToPort 39242
237 send con2 "Jim also"
238 send con1 "What?"
239 threadDelay 500000
240 control sv (Ignore 39242)
241 threadDelay 500000
242 stopListening h1 -- misnomer
243 stopListening h2 -- misnomer
244 threadDelay 500000
245 return events
246 e <- chanContents events
247 putStrLn $ "testReplacePendingOut: "++ show e
248 return $ case e of
249 [ (_,HalfConnection In)
250 ,(_,Got "Joe was here\n")
251 ,(_,EOF)
252 ,(_,HalfConnection In)
253 ,(_,Got "Jim also\n")
254 ,(_,EOF)]
255 -> True
256 _ -> False
257
258testReplacePendingIn = do
259 let send con str = do hPutStrLn con str
260 hFlush con
261 threadDelay 100000
262 (events,socat) <- withServer $ \sv -> do
263 let _ = sv :: Server ()
264 events = serverEvent sv
265 params = (connectionDefaults (const $ return ()))
266 { duplex = False }
267 threadDelay 500000
268 socat <- listenOnPort 39242
269 threadDelay 500000
270 control sv (Connect (localhost 39242) params)
271 control sv (Connect (localhost 39242) params)
272 return (events,socat)
273 threadDelay 500000
274 stopListening socat
275 threadDelay 500000
276 e <- chanContents events
277 putStrLn $ "testReplacePendingIn: "++ show e
278 return $ e==[((),HalfConnection Out)
279 ,((),EOF)
280 ,((),HalfConnection Out)
281 ,((),EOF)]
282
283testPromotePendingOut = do
284 putStrLn "----------- testPromotePendingOut"
285 hFlush stdout
286 let send con str = do hPutStr con str
287 hFlush con
288 threadDelay 100000
289 (events,s,socat) <- withServer $ \sv -> do
290 let _ = sv :: Server ()
291 events = serverEvent sv
292 params = (connectionDefaults (const $ return ()))
293 { duplex = False }
294 control sv (Ignore 39244)
295 threadDelay 500000
296 control sv (Listen 39244 params)
297 socat <- listenOnPort 39243
298 h@(con1,con2,_,_) <- connectToPort 39244
299 putStrLn $ "connected to 39244, Sending Joe was here"
300 send con1 "Joe was here"
301 threadDelay 500000
302 putStrLn $ "Connecting to 39243"
303 control sv (Connect (localhost 39243) params)
304 threadDelay 500000
305 putStrLn $ "probably connected to 39243"
306 control sv (Send () "and jim")
307 putStrLn $ "connected to 39244, Sending Joe was here twice"
308 hFlush stdout
309 send con1 "Joe was here twice"
310 threadDelay 500000
311 s <- fmap (take 7) $ hGetContents ((\(_,x,_,_)->x) socat)
312 last s `seq` threadDelay 500000
313 stopListening h -- misnomer
314 threadDelay 50000
315 return (events,s,socat)
316 stopListening socat
317 threadDelay 500000
318 e <- chanContents events
319 putStrLn $ "testPromotePendingOut: "++ show (s,e)
320 -- testPromotePendingOut: ("and jim",[HalfConnection () In,((),Got "Joe was here"),((),Read () "Joe was here twice",((),EOF)]),Connection)
321 --
322 return . and $
323 [ s== "and jim"
324 , e== [ ((),HalfConnection In)
325 , ((),Got "Joe was here")
326 , ((),Connection {})
327 , ((),Got "Joe was here twice")
328 , ((),EOF) ]
329 ]
330
331testPromotePendingIn = do
332 putStrLn "----------- testPromotePendingIn"
333 hFlush stdout
334 let send con str = do handle (\e -> putStrLn . show $ ioeGetErrorType e) $ do
335 hPutStrLn con str
336 hFlush con
337 threadDelay 500000
338 (events,socat,s) <- withServer $ \sv -> do
339 let _ = sv :: Server ()
340 events = serverEvent sv
341 params = (connectionDefaults (const $ return ()))
342 { duplex = False }
343
344 -- Outgoing connection
345 socat <- listenOnPort 39248
346 threadDelay 500000
347 putStrLn $ "Connecting to 39248..."
348 control sv (Connect (localhost 39248) params)
349 threadDelay 1000000
350 putStrLn $ "...probably connected to 39248"
351 control sv (Send () "and jim")
352 threadDelay 1000000
353
354 s <- fmap (take 7) $ hGetContents ((\(_,x,_,_)->x) socat)
355 length s `seq` threadDelay 500000
356
357 control sv (Listen 39247 params)
358 threadDelay 500000
359 h@(con1,con2,_,_) <- connectToPort 39247
360 send con1 "howdy!"
361 h2@(con1',con2',_,_) <- connectToPort 39247
362 threadDelay 500000
363 send con1' "what?"
364 threadDelay 1000000
365 hClose con1
366 hClose con1'
367 threadDelay 1000000
368 stopListening socat
369 threadDelay 1000000
370
371 return (events,socat,s)
372 e <- chanContents events
373 putStrLn $ "testPromotePendingIn: "++ show (s,e)
374 -- testPromotePendingIn: ("and jim",[HalfConnection () Out,((),((),Got "howdy!\n"),((),EOF (),HalfConnection () In,Read () "what?\n",EOF (),EOF)]),Connection)
375 -- ("and jim",[HalfConnection () Out,((),((),Got "howdy!\n"),((),HalfConnection () In,Read () "what?\n",EOF (),EOF)]),Connection)
376 return . and $
377 [ s == "and jim"
378 , e == [ ((),HalfConnection Out)
379 ,((),Connection {})
380 ,((),Got "howdy!\n")
381 ,((),EOF)
382 ,((),HalfConnection In)
383 ,((),Got "what?\n")
384 ,((),EOF)]
385 ]
386
387testPing = do
388 putStrLn "----------- testPing"
389 let send con str = do handle (\e -> putStrLn . show $ ioeGetErrorType e) $ do
390 hPutStrLn con str
391 hFlush con
392 threadDelay 500000
393 events <- withServer $ \sv -> do
394 let _ = sv :: Server ()
395 events = serverEvent sv
396 params = (connectionDefaults (const $ return ()))
397 { pingInterval = 2000
398 , timeout = 1000 }
399 control sv (Listen 32957 params)
400 threadDelay 500000
401 socat@(h,_,_,_) <- connectToPort 32957
402
403 -- putStrLn $ "sending hey you!"
404 send h "hey you!"
405 -- putStrLn $ "delay"
406 threadDelay 3500000 -- ping timeout
407 -- putStrLn $ "sending what?"
408 send h "what?" -- lost due to timeout
409 -- putStrLn $ "delay-2"
410 threadDelay 500000
411 -- putStrLn $ "close h"
412 hClose h
413
414 threadDelay 500000
415 socat@(h,_,_,_) <- connectToPort 32957
416 send h "try 2: hey you!"
417 threadDelay 2500000 -- ping warning
418 send h "try 2: what?"
419 threadDelay 1000000 -- no warning or timeout
420 send h "try 2: yes."
421 stopListening socat
422 threadDelay 1000000
423 return events
424
425 e <- chanContents events
426 putStrLn $ "testPing: "++show e
427 -- testPing: [((),Connection <STM action> <IO action> <function>)
428{-
429,((),Got "hey you!\n")
430,((),RequiresPing)
431,((),RequiresPing)
432,((),Got "what?\n")
433,((),EOF)
434,((),Connection <STM action> <IO action> <function>)
435,((),Got "try 2: hey you!\n")
436,((),RequiresPing)
437,((),Got "try 2: what?\n")
438,((),Got "try 2: yes.\n")
439,((),EOF)]
440testPing: [((),Connection <STM action> <IO action> <function>)
441,((),Got "hey you!\n")
442,((),RequiresPing)
443,((),Got "what?\n")
444,((),RequiresPing)
445,((),EOF)
446,((),Connection <STM action> <IO action> <function>)
447,((),Got "try 2: hey you!\n")
448,((),RequiresPing)
449,((),Got "try 2: what?\n")
450,((),RequiresPing)]
451testPing: [((),Connection <STM action> <IO action> <function>)
452,((),Got "hey you!\n")
453,((),RequiresPing)
454,((),Got "what?\n")
455,((),RequiresPing)
456,((),EOF)
457,((),Connection <STM action> <IO action> <function>)
458,((),Got "try 2: hey you!\n")
459,((),RequiresPing)
460,((),Got "try 2: what?\n")
461,((),Got "try 2: yes.\n")
462,((),EOF)]
463
464-}
465
466 return $ e == [((),Connection {})
467 ,((),Got "hey you!\n")
468 ,((),RequiresPing)
469 ,((),EOF)
470 ,((),Connection {})
471 ,((),Got "try 2: hey you!\n")
472 ,((),RequiresPing)
473 ,((),Got "try 2: what?\n")
474 ,((),Got "try 2: yes.\n")
475 ,((),EOF)]
476
477testDisabledPing = do
478 let send con str = do hPutStrLn con str
479 hFlush con
480 threadDelay 500000
481 events <- withServer $ \sv -> do
482 let _ = sv :: Server ()
483 events = serverEvent sv
484 params = (connectionDefaults (const $ return ()))
485 { pingInterval = 0
486 , timeout = 0 }
487 control sv (Listen 32958 params)
488 threadDelay 500000
489 socat@(h,_,_,_) <- connectToPort 32958
490
491 send h "hey you!"
492 threadDelay 3500000 -- ping timeout
493 send h "what?" -- lost due to timeout
494 threadDelay 500000
495 hClose h
496
497 threadDelay 500000
498 socat@(h,_,_,_) <- connectToPort 32958
499 send h "try 2: hey you!"
500 threadDelay 2500000 -- ping warning
501 send h "try 2: what?"
502 threadDelay 1000000 -- no warning or timeout
503 send h "try 2: yes."
504 stopListening socat
505 threadDelay 5000000
506 return events
507
508 e <- chanContents events
509 putStrLn $ "testDisabledPing: "++show e
510 return $ e == [((),Connection {})
511 ,((),Got "hey you!\n")
512 ,((),Got "what?\n")
513 ,((),EOF)
514 ,((),Connection {})
515 ,((),Got "try 2: hey you!\n")
516 ,((),Got "try 2: what?\n")
517 ,((),Got "try 2: yes.\n")
518 ,((),EOF)]
519main = do
520 result1 <- testListen
521 result2 <- testReplace
522 result3 <- testPendingOut
523 result4 <- testReplacePendingOut
524 threadDelay 100000
525 result5 <- testReplacePendingIn
526 result6 <- testPromotePendingOut
527 result7 <- testPromotePendingIn
528 result8 <- testPing
529 result9 <- testDisabledPing
530 let passOrFail str True = putStrLn $ str ++ ": passed"
531 passOrFail str False = putStrLn $ str ++ ": failed"
532 passOrFail "testListen" result1
533 passOrFail "testReplace" result2
534 passOrFail "testPendingOut" result3
535 passOrFail "testReplacePendingOut" result4
536 passOrFail "testReplacePendingIn" result5
537 passOrFail "testPromotePendingOut" result6
538 passOrFail "testPromotePendingIn" result7
539 passOrFail "testPing" result8
540 passOrFail "testDisabledPing" result9
541 return ()
diff --git a/whosocket.hs b/whosocket.hs
new file mode 100644
index 00000000..f84e3178
--- /dev/null
+++ b/whosocket.hs
@@ -0,0 +1,60 @@
1{-# LANGUAGE OverloadedStrings #-}
2{-# LANGUAGE TupleSections #-}
3module Main where
4
5import LocalPeerCred
6import ControlMaybe
7import UTmp
8import ByteStringOperators
9
10import System.Directory
11import Data.Char
12import System.Posix.Types
13import System.Posix.Files
14import qualified Data.ByteString.Lazy.Char8 as L
15 ( unpack
16 , pack
17 , take
18 , putStrLn
19 )
20import Data.List (groupBy)
21import Data.Maybe (listToMaybe,mapMaybe,catMaybes)
22
23import Network.Socket
24import System.Environment
25import Control.Arrow (first)
26import System.Endian
27
28usage = do
29 putStrLn $ "whosocket numeric-address port"
30
31main = do
32 args <- getArgs
33 case (args??0,args??1) of
34 (Just addr_str,Just port_str) -> whosocket addr_str port_str
35 _ -> usage
36
37whosocket :: HostName -> ServiceName -> IO ()
38whosocket addr_str port_str = do
39 info <- getAddrInfo (Just $ defaultHints { addrFlags = [ AI_NUMERICHOST ] })
40 (Just addr_str)
41 (Just port_str)
42 let addr = head $ map addrAddress info
43 r <- getLocalPeerCred' addr
44 putStrLn $ "r{"++show addr++"} = " ++ show r
45
46 us <- UTmp.users
47 let filterTTYs (_,tty,pid) =
48 if L.take 3 tty == "tty"
49 then Just (tty,pid)
50 else Nothing
51 tty_pids = mapMaybe filterTTYs us
52
53 tty <- maybe (return Nothing)
54 (fmap fst . uncurry (identifyTTY tty_pids))
55 r
56 putStrLn $ "uid = " ++ show (fmap fst r)
57 L.putStrLn $ "tty = " <++?> tty
58
59 return ()
60
diff --git a/xmppServer.hs b/xmppServer.hs
new file mode 100644
index 00000000..b0a53e8b
--- /dev/null
+++ b/xmppServer.hs
@@ -0,0 +1,47 @@
1{-# LANGUAGE OverloadedStrings #-}
2{-# LANGUAGE TupleSections #-}
3{-# LANGUAGE LambdaCase #-}
4import Control.Concurrent
5import Control.Concurrent.STM
6import Control.Monad.Fix
7import Control.Monad.IO.Class
8import Control.Monad.Trans.Resource (runResourceT)
9import Data.Monoid
10import System.Environment
11import System.Posix.Signals
12
13import ConsoleWriter
14import Presence
15import XMPPServer
16
17main :: IO ()
18main = runResourceT $ do
19 args <- liftIO getArgs
20 let verbosity = getSum $ flip foldMap args $ \case
21 ('-':xs) -> Sum $ length (filter (=='-') xs)
22 _ -> mempty
23 cw <- liftIO newConsoleWriter
24 state <- liftIO $ newPresenceState cw
25 sv <- xmppServer (presenceHooks state verbosity)
26 liftIO $ do
27 atomically $ putTMVar (server state) sv
28
29 quitVar <- newEmptyTMVarIO
30 installHandler sigTERM (CatchOnce (atomically $ putTMVar quitVar True)) Nothing
31 installHandler sigINT (CatchOnce (atomically $ putTMVar quitVar True)) Nothing
32
33 forkIO $ do
34 let console = cwPresenceChan $ consoleWriter state
35 fix $ \loop -> do
36 what <- atomically
37 $ orElse (do (client,stanza) <- takeTMVar console
38 return $ do informClientPresence0 state Nothing client stanza
39 loop)
40 (do readTMVar quitVar
41 return $ return ())
42 what
43
44 quitMessage <- atomically $ takeTMVar quitVar
45
46 putStrLn "goodbye."
47 return ()