1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438
|
{-# LANGUAGE DeriveDataTypeable #-}
{-# LANGUAGE ExistentialQuantification #-}
{-# LANGUAGE TypeFamilies #-}
-- Copyright (C) 2009-2012 John Millikin <john@john-millikin.com>
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-- | D-Bus sockets are used for communication between two peers. In this model,
-- there is no \"bus\" or \"client\", simply two endpoints sending messages.
--
-- Most users will want to use the "DBus.Client" module instead.
module DBus.Socket
(
-- * Sockets
Socket
, send
, receive
-- * Socket errors
, SocketError
, socketError
, socketErrorMessage
, socketErrorFatal
, socketErrorAddress
-- * Socket options
, SocketOptions
, socketAuthenticator
, socketTransportOptions
, defaultSocketOptions
-- * Opening and closing sockets
, open
, openWith
, close
-- * Listening for connections
, SocketListener
, listen
, listenWith
, accept
, closeListener
, socketListenerAddress
-- * Authentication
, Authenticator
, authenticator
, authenticatorWithUnixFds
, authenticatorClient
, authenticatorServer
) where
import Prelude hiding (getLine)
import Control.Concurrent
import Control.Exception
import Control.Monad (mplus)
import qualified Data.ByteString
import qualified Data.ByteString.Char8 as Char8
import Data.Char (ord)
import Data.IORef
import Data.List (isPrefixOf)
import Data.Typeable (Typeable)
import qualified System.Posix.User
import Text.Printf (printf)
import DBus
import DBus.Transport
import DBus.Internal.Wire (unmarshalMessageM)
-- | Stores information about an error encountered while creating or using a
-- 'Socket'.
data SocketError = SocketError
{ socketErrorMessage :: String
, socketErrorFatal :: Bool
, socketErrorAddress :: Maybe Address
}
deriving (Eq, Show, Typeable)
instance Exception SocketError
socketError :: String -> SocketError
socketError msg = SocketError msg True Nothing
data SomeTransport = forall t. (Transport t) => SomeTransport t
instance Transport SomeTransport where
data TransportOptions SomeTransport = SomeTransportOptions
transportDefaultOptions = SomeTransportOptions
transportPut (SomeTransport t) = transportPut t
transportPutWithFds (SomeTransport t) = transportPutWithFds t
transportGet (SomeTransport t) = transportGet t
transportGetWithFds (SomeTransport t) = transportGetWithFds t
transportClose (SomeTransport t) = transportClose t
-- | An open socket to another process. Messages can be sent to the remote
-- peer using 'send', or received using 'receive'.
data Socket = Socket
{ socketTransport :: SomeTransport
, socketAddress :: Maybe Address
, socketSerial :: IORef Serial
, socketReadLock :: MVar ()
, socketWriteLock :: MVar ()
}
-- | An Authenticator defines how the local peer (client) authenticates
-- itself to the remote peer (server).
data Authenticator t = Authenticator
{
-- | Defines the client-side half of an authenticator.
authenticatorClient :: t -> IO Bool
-- | Defines the server-side half of an authenticator. The UUID is
-- allocated by the socket listener.
, authenticatorServer :: t -> UUID -> IO Bool
}
-- | Used with 'openWith' and 'listenWith' to provide custom authenticators or
-- transport options.
data SocketOptions t = SocketOptions
{
-- | Used to perform authentication with the remote peer. After a
-- transport has been opened, it will be passed to the authenticator.
-- If the authenticator returns true, then the socket was
-- authenticated.
socketAuthenticator :: Authenticator t
-- | Options for the underlying transport, to be used by custom transports
-- for controlling how to connect to the remote peer.
--
-- See "DBus.Transport" for details on defining custom transports
, socketTransportOptions :: TransportOptions t
}
-- | Default 'SocketOptions', which uses the default Unix/TCP transport and
-- authenticator (without support for Unix file descriptor passing).
defaultSocketOptions :: SocketOptions SocketTransport
defaultSocketOptions = SocketOptions
{ socketTransportOptions = transportDefaultOptions
, socketAuthenticator = authExternal UnixFdsNotSupported
}
-- | Open a socket to a remote peer listening at the given address.
--
-- @
--open = 'openWith' 'defaultSocketOptions'
-- @
--
-- Throws 'SocketError' on failure.
open :: Address -> IO Socket
open = openWith defaultSocketOptions
-- | Open a socket to a remote peer listening at the given address.
--
-- Most users should use 'open'. This function is for users who need to define
-- custom authenticators or transports.
--
-- Throws 'SocketError' on failure.
openWith :: TransportOpen t => SocketOptions t -> Address -> IO Socket
openWith opts addr = toSocketError (Just addr) $ bracketOnError
(transportOpen (socketTransportOptions opts) addr)
transportClose
(\t -> do
authed <- authenticatorClient (socketAuthenticator opts) t
if not authed
then throwIO (socketError "Authentication failed")
{ socketErrorAddress = Just addr
}
else do
serial <- newIORef firstSerial
readLock <- newMVar ()
writeLock <- newMVar ()
return (Socket (SomeTransport t) (Just addr) serial readLock writeLock))
data SocketListener = forall t. (TransportListen t) => SocketListener (TransportListener t) (Authenticator t)
-- | Begin listening at the given address.
--
-- Use 'accept' to create sockets from incoming connections.
--
-- Use 'closeListener' to stop listening, and to free underlying transport
-- resources such as file descriptors.
--
-- Throws 'SocketError' on failure.
listen :: Address -> IO SocketListener
listen = listenWith defaultSocketOptions
-- | Begin listening at the given address.
--
-- Use 'accept' to create sockets from incoming connections.
--
-- Use 'closeListener' to stop listening, and to free underlying transport
-- resources such as file descriptors.
--
-- This function is for users who need to define custom authenticators
-- or transports.
--
-- Throws 'SocketError' on failure.
listenWith :: TransportListen t => SocketOptions t -> Address -> IO SocketListener
listenWith opts addr = toSocketError (Just addr) $ bracketOnError
(transportListen (socketTransportOptions opts) addr)
transportListenerClose
(\l -> return (SocketListener l (socketAuthenticator opts)))
-- | Accept a new connection from a socket listener.
--
-- Throws 'SocketError' on failure.
accept :: SocketListener -> IO Socket
accept (SocketListener l auth) = toSocketError Nothing $ bracketOnError
(transportAccept l)
transportClose
(\t -> do
let uuid = transportListenerUUID l
authed <- authenticatorServer auth t uuid
if not authed
then throwIO (socketError "Authentication failed")
else do
serial <- newIORef firstSerial
readLock <- newMVar ()
writeLock <- newMVar ()
return (Socket (SomeTransport t) Nothing serial readLock writeLock))
-- | Close an open 'Socket'. Once closed, the socket is no longer valid and
-- must not be used.
close :: Socket -> IO ()
close = transportClose . socketTransport
-- | Close an open 'SocketListener'. Once closed, the listener is no longer
-- valid and must not be used.
closeListener :: SocketListener -> IO ()
closeListener (SocketListener l _) = transportListenerClose l
-- | Get the address to use to connect to a listener.
socketListenerAddress :: SocketListener -> Address
socketListenerAddress (SocketListener l _) = transportListenerAddress l
-- | Send a single message, with a generated 'Serial'. The second parameter
-- exists to prevent race conditions when registering a reply handler; it
-- receives the serial the message /will/ be sent with, before it's
-- actually sent.
--
-- Sockets are thread-safe. Only one message may be sent at a time; if
-- multiple threads attempt to send messages concurrently, one will block
-- until after the other has finished.
--
-- Throws 'SocketError' on failure.
send :: Message msg => Socket -> msg -> (Serial -> IO a) -> IO a
send sock msg io = toSocketError (socketAddress sock) $ do
serial <- nextSocketSerial sock
case marshalWithFds LittleEndian serial msg of
Right (bytes, fds) -> do
let t = socketTransport sock
a <- io serial
withMVar (socketWriteLock sock) (\_ -> transportPutWithFds t bytes fds)
return a
Left err -> throwIO (socketError ("Message cannot be sent: " ++ show err))
{ socketErrorFatal = False
}
nextSocketSerial :: Socket -> IO Serial
nextSocketSerial sock = atomicModifyIORef (socketSerial sock) (\x -> (nextSerial x, x))
-- | Receive the next message from the socket , blocking until one is available.
--
-- Sockets are thread-safe. Only one message may be received at a time; if
-- multiple threads attempt to receive messages concurrently, one will block
-- until after the other has finished.
--
-- Throws 'SocketError' on failure.
receive :: Socket -> IO ReceivedMessage
receive sock = toSocketError (socketAddress sock) $ do
-- TODO: after reading the length, read all bytes from the
-- handle, then return a closure to perform the parse
-- outside of the lock.
let t = socketTransport sock
let get n = if n == 0
then return (Data.ByteString.empty, [])
else transportGetWithFds t n
received <- withMVar (socketReadLock sock) (\_ -> unmarshalMessageM get)
case received of
Left err -> throwIO (socketError ("Error reading message from socket: " ++ show err))
Right msg -> return msg
toSocketError :: Maybe Address -> IO a -> IO a
toSocketError addr io = catches io handlers where
handlers =
[ Handler catchTransportError
, Handler updateSocketError
, Handler catchIOException
]
catchTransportError err = throwIO (socketError (transportErrorMessage err))
{ socketErrorAddress = addr
}
updateSocketError err = throwIO err
{ socketErrorAddress = mplus (socketErrorAddress err) addr
}
catchIOException exc = throwIO (socketError (show (exc :: IOException)))
{ socketErrorAddress = addr
}
-- | An empty authenticator. Use 'authenticatorClient' or 'authenticatorServer'
-- to control how the authentication is performed.
--
-- @
--myAuthenticator :: Authenticator MyTransport
--myAuthenticator = authenticator
-- { 'authenticatorClient' = clientMyAuth
-- , 'authenticatorServer' = serverMyAuth
-- }
--
--clientMyAuth :: MyTransport -> IO Bool
--serverMyAuth :: MyTransport -> String -> IO Bool
-- @
authenticator :: Authenticator t
authenticator = Authenticator (\_ -> return False) (\_ _ -> return False)
data UnixFdSupport = UnixFdsSupported | UnixFdsNotSupported
-- | An authenticator that implements the D-Bus @EXTERNAL@ mechanism, which uses
-- credential passing over a Unix socket, with support for Unix file descriptor passing.
authenticatorWithUnixFds :: Authenticator SocketTransport
authenticatorWithUnixFds = authExternal UnixFdsSupported
-- | Implements the D-Bus @EXTERNAL@ mechanism, which uses credential
-- passing over a Unix socket, optionally supporting Unix file descriptor passing.
authExternal :: UnixFdSupport -> Authenticator SocketTransport
authExternal unixFdSupport = authenticator
{ authenticatorClient = clientAuthExternal unixFdSupport
, authenticatorServer = serverAuthExternal unixFdSupport
}
clientAuthExternal :: UnixFdSupport -> SocketTransport -> IO Bool
clientAuthExternal unixFdSupport t = do
transportPut t (Data.ByteString.pack [0])
uid <- System.Posix.User.getRealUserID
let token = concatMap (printf "%02X" . ord) (show uid)
transportPutLine t ("AUTH EXTERNAL " ++ token)
resp <- transportGetLine t
case splitPrefix "OK " resp of
Just _ -> do
ok <- do
case unixFdSupport of
UnixFdsSupported -> do
transportPutLine t "NEGOTIATE_UNIX_FD"
respFd <- transportGetLine t
return (respFd == "AGREE_UNIX_FD")
UnixFdsNotSupported -> do
return True
if ok then do
transportPutLine t "BEGIN"
return True
else
return False
Nothing -> return False
serverAuthExternal :: UnixFdSupport -> SocketTransport -> UUID -> IO Bool
serverAuthExternal unixFdSupport t uuid = do
let negotiateFdsAndBegin = do
line <- transportGetLine t
case line of
"NEGOTIATE_UNIX_FD" -> do
let msg = case unixFdSupport of
UnixFdsSupported ->
"AGREE_UNIX_FD"
UnixFdsNotSupported ->
"ERROR Unix File Descriptor support is not configured."
transportPutLine t msg
negotiateFdsAndBegin
"BEGIN" ->
return ()
_ ->
negotiateFdsAndBegin
let checkToken token = do
(_, uid, _) <- socketTransportCredentials t
let wantToken = concatMap (printf "%02X" . ord) (maybe "XXX" show uid)
if token == wantToken
then do
transportPutLine t ("OK " ++ formatUUID uuid)
negotiateFdsAndBegin
return True
else return False
c <- transportGet t 1
if c /= Char8.pack "\x00"
then return False
else do
line <- transportGetLine t
case splitPrefix "AUTH EXTERNAL " line of
Just token -> checkToken token
Nothing -> if line == "AUTH EXTERNAL"
then do
dataLine <- transportGetLine t
case splitPrefix "DATA " dataLine of
Just token -> checkToken token
Nothing -> return False
else return False
transportPutLine :: Transport t => t -> String -> IO ()
transportPutLine t line = transportPut t (Char8.pack (line ++ "\r\n"))
transportGetLine :: Transport t => t -> IO String
transportGetLine t = do
let getchr = Char8.head `fmap` transportGet t 1
raw <- readUntil "\r\n" getchr
return (dropEnd 2 raw)
-- | Drop /n/ items from the end of a list
dropEnd :: Int -> [a] -> [a]
dropEnd n xs = take (length xs - n) xs
splitPrefix :: String -> String -> Maybe String
splitPrefix prefix str = if isPrefixOf prefix str
then Just (drop (length prefix) str)
else Nothing
-- | Read values from a monad until a guard value is read; return all
-- values, including the guard.
readUntil :: (Monad m, Eq a) => [a] -> m a -> m [a]
readUntil guard getx = readUntil' [] where
guard' = reverse guard
step xs | isPrefixOf guard' xs = return (reverse xs)
| otherwise = readUntil' xs
readUntil' xs = do
x <- getx
step (x:xs)
|