1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466
|
{-# LANGUAGE CPP #-}
{-# LANGUAGE OverloadedStrings #-}
module Network.SocketSpec (main, spec) where
import Control.Concurrent (threadDelay, forkIO)
import Control.Concurrent.MVar (readMVar)
import Control.Monad
import Data.Maybe (fromJust)
import Data.List (nub)
import Network.Socket
import Network.Socket.ByteString
import Network.Test.Common
import System.Mem (performGC)
import System.IO.Error (tryIOError)
import System.IO.Temp (withSystemTempDirectory)
import Foreign.C.Types ()
import Test.Hspec
import Test.QuickCheck
main :: IO ()
main = hspec spec
spec :: Spec
spec = do
describe "connect" $ do
let
hints = defaultHints { addrSocketType = Stream }
connect' serverPort = do
addr:_ <- getAddrInfo (Just hints) (Just serverAddr) (Just $ show serverPort)
sock <- socket (addrFamily addr) (addrSocketType addr) (addrProtocol addr)
connect sock (addrAddress addr)
return sock
it "fails to connect and throws an IOException" $ do
connect' (8003 :: Int) `shouldThrow` anyIOException
it "successfully connects to a socket with no exception" $ do
withPort $ \portVar -> test (tcp serverAddr return portVar)
{ clientSetup = readMVar portVar >>= connect'
}
describe "bind" $ do
let hints = defaultHints
{ addrFlags = [AI_PASSIVE]
, addrSocketType = Stream
}
it "successfully binds to an ipv4 socket" $ do
addr:_ <- getAddrInfo (Just hints) (Just serverAddr) Nothing
sock <- socket (addrFamily addr) (addrSocketType addr) (addrProtocol addr)
bind sock $ addrAddress addr
{- This does not work on Windows and Linux.
it "fails to bind to unknown ipv4 socket" $ do
addr:_ <- getAddrInfo (Just hints) (Just "127.0.0.3") Nothing
sock <- socket (addrFamily addr) (addrSocketType addr) (addrProtocol addr)
bind sock (addrAddress addr) `shouldThrow` anyIOException
-}
#ifdef DEVELOPMENT
it "successfully binds to an ipv6 socket" $ do
addr:_ <- getAddrInfo (Just hints) (Just serverAddr6) Nothing
sock <- socket (addrFamily addr) (addrSocketType addr) (addrProtocol addr)
bind sock $ addrAddress addr
it "fails to bind to unknown ipv6 socket" $ do
addr:_ <- getAddrInfo (Just hints) (Just "::6") Nothing
sock <- socket (addrFamily addr) (addrSocketType addr) (addrProtocol addr)
bind sock (addrAddress addr) `shouldThrow` anyIOException
#endif
it "successfully binds to a unix socket" $ do
withSystemTempDirectory "haskell-network" $ \path -> do
let sfile = path ++ "/socket-file"
-- exist <- doesFileExist sfile
-- when exist $ removeFile sfile
-- removeFile sfile
let addr = SockAddrUnix sfile
when (isSupportedSockAddr addr) $ do
sock0 <- socket AF_UNIX Stream defaultProtocol
bind sock0 addr
listen sock0 1
sock1 <- socket AF_UNIX Stream defaultProtocol
tryIOError (bind sock1 addr) >>= \o -> case o of
Right () -> error "bind should have failed but succeeded"
_ -> return ()
close sock0
close sock1
describe "UserTimeout" $ do
it "can be set" $ do
when (isSupportedSocketOption UserTimeout) $ do
sock <- socket AF_INET Stream defaultProtocol
setSocketOption sock UserTimeout 1000
getSocketOption sock UserTimeout `shouldReturn` 1000
setSocketOption sock UserTimeout 2000
getSocketOption sock UserTimeout `shouldReturn` 2000
close sock
describe "getAddrInfo" $ do
it "works for IPv4 address" $ do
let hints = defaultHints { addrFlags = [AI_NUMERICHOST, AI_ADDRCONFIG] }
AddrInfo{addrAddress = (SockAddrInet _ hostAddr)}:_ <-
getAddrInfo (Just hints) (Just "127.128.129.130") Nothing
hostAddressToTuple hostAddr `shouldBe` (0x7f, 0x80, 0x81, 0x82)
it "works for IPv6 address" $ do
let hints = defaultHints { addrFlags = [AI_NUMERICHOST, AI_ADDRCONFIG] }
host = "2001:0db8:85a3:0000:0000:8a2e:0370:7334"
AddrInfo{addrAddress = (SockAddrInet6 _ _ hostAddr _)}:_ <-
getAddrInfo (Just hints) (Just host) Nothing
hostAddress6ToTuple hostAddr
`shouldBe` (0x2001, 0x0db8, 0x85a3, 0x0000, 0x0000, 0x8a2e, 0x0370, 0x7334)
it "does not cause segfault on macOS 10.8.2 due to AI_NUMERICSERV" $ do
let hints = defaultHints { addrFlags = [AI_NUMERICSERV] }
void $ getAddrInfo (Just hints) (Just "localhost") Nothing
#if defined(mingw32_HOST_OS)
let lpdevname = "loopback_0"
#elif defined(darwin_HOST_OS) || defined(freebsd_HOST_OS) || defined(openbsd_HOST_OS)
let lpdevname = "lo0"
#else
let lpdevname = "lo"
#endif
describe "ifNameToIndex and ifIndexToName" $ do
it "convert a name to an index and back" $
do
n <- ifNameToIndex lpdevname
n `shouldNotBe` Nothing
ifIndexToName (fromJust n) `shouldReturn` Just lpdevname
describe "socket" $ do
let gc = do
threadDelay 100000
performGC
connect' = do
threadDelay 200000
sock <- socket AF_INET Stream defaultProtocol
connect sock $ SockAddrInet 6000 $ tupleToHostAddress (127, 0, 0, 1)
it "should not be GCed while blocking" $ do
sock <- socket AF_INET Stream defaultProtocol
setSocketOption sock ReuseAddr 1
bind sock $ SockAddrInet 6000 $ tupleToHostAddress (127, 0, 0, 1)
listen sock 1
_ <- forkIO gc
_ <- forkIO connect'
(_sock', addr) <- accept sock
-- check if an exception is not thrown.
isSupportedSockAddr addr `shouldBe` True
#if !defined(mingw32_HOST_OS)
when isUnixDomainSocketAvailable $ do
context "unix sockets" $ do
it "basic unix sockets end-to-end" $ do
let client sock = send sock testMsg
server (sock, addr) = do
recv sock 1024 `shouldReturn` testMsg
addr `shouldBe` (SockAddrUnix "")
test . setClientAction client $ unixWithUnlink unixAddr server
#endif
#ifdef linux_HOST_OS
it "can end-to-end with an abstract socket" $ do
let
abstractAddress = toEnum 0:"/haskell/network/abstract"
client sock = send sock testMsg
server (sock, addr) = do
recv sock 1024 `shouldReturn` testMsg
addr `shouldBe` (SockAddrUnix "")
test . setClientAction client $
unix abstractAddress (const $ return ()) $ server
it "safely throws an exception" $ do
when isUnixDomainSocketAvailable $ do
let abstractAddress = toEnum 0:"/haskell/network/abstract-longlonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglong"
sock <- socket AF_UNIX Stream defaultProtocol
bind sock (SockAddrUnix abstractAddress) `shouldThrow` anyErrorCall
#endif
#if !defined(mingw32_HOST_OS)
describe "socketPair" $ do
it "can send and recieve bi-directionally" $ do
(s1, s2) <- socketPair AF_UNIX Stream defaultProtocol
void $ send s1 testMsg
recv s2 1024 `shouldReturn` testMsg
void $ send s2 testMsg
recv s1 1024 `shouldReturn` testMsg
describe "sendFd/recvFd" $ do
it "can send and recieve a file descriptor" $ do
(s1, s2) <- socketPair AF_UNIX Stream defaultProtocol
(s3, s4) <- socketPair AF_UNIX Stream defaultProtocol
withFdSocket s1 $ \fd1 -> void $ sendFd s3 fd1
fd1' <- recvFd s4
s1' <- mkSocket fd1'
void $ send s1' testMsg
recv s2 1024 `shouldReturn` testMsg
-- On various BSD systems the peer credentials are exchanged during
-- connect(), and this does not happen with `socketpair()`. Therefore,
-- we must actually set up a listener and connect, rather than use a
-- socketpair().
--
describe "getPeerCredential" $ do
it "can return something" $ do
-- It would be useful to check that we did not get garbage
-- back, but rather the actual uid of the test program. For
-- that we'd need System.Posix.User, but that is not available
-- under Windows. For now, accept the risk that we did not get
-- the right answer.
--
let server (sock, _) = do
(_, uid, _) <- getPeerCredential sock
uid `shouldNotBe` Nothing
client sock = do
(_, uid, _) <- getPeerCredential sock
uid `shouldNotBe` Nothing
test . setClientAction client $ unixWithUnlink unixAddr server
{- The below test fails on many *BSD systems, because the getsockopt()
call that underlies getpeereid() does not have the same meaning for
all address families, but the C-library was not checking that the
provided sock is an AF_UNIX socket. This will fixed some day, but
we should not fail on those systems in the mean-time. The upstream
C-library fix is to call getsockname() and check the address family
before calling `getpeereid()`. We could duplicate that in our own
code, and then this test would work on those platforms that have
`getpeereid()` and not the SO_PEERCRED socket option.
it "return nothing for non-UNIX-domain socket" $ do
when isUnixDomainSocketAvailable $ do
s <- socket AF_INET Stream defaultProtocol
cred1 <- getPeerCredential s
cred1 `shouldBe` (Nothing,Nothing,Nothing)
-}
#endif
describe "gracefulClose" $ do
it "does not send TCP RST back" $ do
let server sock = do
void $ recv sock 1024 -- receiving "GOAWAY"
gracefulClose sock 3000
client sock = do
sendAll sock "GOAWAY"
threadDelay 10000
sendAll sock "PING"
threadDelay 10000
void $ recv sock 1024
tcpTest client server
describe "socketToFd" $ do
it "socketToFd can send using fd" $ do
let server sock = do
void $ recv sock 1024
client sock = do
fd <- socketToFd sock
s <- mkSocket fd
sendAll s "HELLO WORLD"
tcpTest client server
describe "getNameInfo" $ do
it "works for IPv4 address" $ do
let addr = SockAddrInet 80 (tupleToHostAddress (127, 0, 0, 1))
(hn_m, sn_m) <- getNameInfo [NI_NUMERICHOST, NI_NUMERICSERV] True True addr
hn_m `shouldBe` (Just "127.0.0.1")
sn_m `shouldBe` (Just "80")
it "works for IPv6 address" $ do
let addr = SockAddrInet6 80 0
(tupleToHostAddress6 (0x2001, 0x0db8, 0x2, 0x3, 0x4, 0x5, 0x6, 0x7)) 0
(hn_m, sn_m) <- getNameInfo [NI_NUMERICHOST, NI_NUMERICSERV] True True addr
hn_m `shouldBe`(Just "2001:db8:2:3:4:5:6:7")
sn_m `shouldBe` (Just "80")
it "works for IPv6 address" $ do
let addr = SockAddrInet6 80 0
(tupleToHostAddress6 (0x2001, 0x0db8, 0x2, 0x3, 0x4, 0x5, 0x6, 0x7)) 0
(hn_m, sn_m) <- getNameInfo [NI_NUMERICHOST, NI_NUMERICSERV] True True addr
hn_m `shouldBe`(Just "2001:db8:2:3:4:5:6:7")
sn_m `shouldBe` (Just "80")
it "works for global multicast IPv6 address" $ do
let addr = SockAddrInet6 80 0
(tupleToHostAddress6 (0xfe01, 0x0db8, 0x2, 0x3, 0x4, 0x5, 0x6, 0x7)) 0
(hn_m, sn_m) <- getNameInfo [NI_NUMERICHOST, NI_NUMERICSERV] True True addr
hn_m `shouldBe`(Just "fe01:db8:2:3:4:5:6:7")
sn_m `shouldBe` (Just "80")
describe "show SocketAddr" $ do
it "works for IPv4 address" $
let addr = SockAddrInet 80 (tupleToHostAddress (127, 0, 0, 1)) in
show addr `shouldBe` "127.0.0.1:80"
it "works for IPv6 address" $
let addr = SockAddrInet6 80 0
(tupleToHostAddress6 (0x2001, 0x0db8, 0x2, 0x3, 0x4, 0x5, 0x6, 0x7)) 0 in
show addr `shouldBe` "[2001:db8:2:3:4:5:6:7]:80"
it "works for IPv6 address with zeros" $
let addr = SockAddrInet6 80 0
(tupleToHostAddress6 (0x2001, 0x0db8, 0x2, 0x3, 0x0, 0x0, 0x0, 0x7)) 0 in
show addr `shouldBe` "[2001:db8:2:3::7]:80"
it "works for multicast IPv6 address with reserved scope" $ do
let addr = SockAddrInet6 80 0
(tupleToHostAddress6 (0xff01, 0x1234, 0x2, 0x3, 0x4, 0x5, 0x6, 0x7)) 0
show addr `shouldBe` "[ff01:1234:2:3:4:5:6:7]:80"
describe "show Family" $ do
it "works for pattern synonyms" $
let fam = AF_UNSPEC in
show fam `shouldBe` "AF_UNSPEC"
it "works for unsupported" $
let fam = GeneralFamily (-1) in
show fam `shouldBe` "UnsupportedFamily"
it "works for positive values" $
let fam = GeneralFamily 300 in
show fam `shouldBe` "GeneralFamily 300"
it "works for negative values" $
let fam = GeneralFamily (-300) in
show fam `shouldBe` "GeneralFamily (-300)"
describe "show SocketType" $ do
it "works for pattern synonyms" $
let socktype = NoSocketType in
show socktype `shouldBe` "NoSocketType"
it "works for unsupported" $
let socktype = GeneralSocketType (-1) in
show socktype `shouldBe` "UnsupportedSocketType"
it "works for positive values" $
let socktype = GeneralSocketType 300 in
show socktype `shouldBe` "GeneralSocketType 300"
it "works for negative values" $
let socktype = GeneralSocketType (-300) in
show socktype `shouldBe` "GeneralSocketType (-300)"
describe "show SocketOptions" $ do
it "works for pattern synonyms" $
let opt = ReuseAddr in
show opt `shouldBe` "ReuseAddr"
it "works for unsupported" $
let opt = SockOpt (-1) (-1) in
show opt `shouldBe` "UnsupportedSocketOption"
it "works for positive values" $
let opt = SockOpt 300 300 in
show opt `shouldBe` "SockOpt 300 300"
it "works for negative values" $
let opt = SockOpt (-300) (-300) in
show opt `shouldBe` "SockOpt (-300) (-300)"
describe "show CmsgId" $ do
it "works for pattern synonyms" $
let msgid = CmsgIdIPv6HopLimit in
show msgid `shouldBe` "CmsgIdIPv6HopLimit"
it "works for unsupported" $
let msgid = CmsgId (-1) (-1) in
show msgid `shouldBe` "UnsupportedCmsgId"
it "works for positive values" $
let msgid = CmsgId 300 300 in
show msgid `shouldBe` "CmsgId 300 300"
it "works for negative values" $
let msgid = CmsgId (-300) (-300) in
show msgid `shouldBe` "CmsgId (-300) (-300)"
describe "bijective read-show roundtrip equality" $ do
it "holds for Family" $ forAll familyGen $
\x -> (read . show $ x) == (x :: Family)
it "holds for SocketType" $ forAll socktypeGen $
\x -> (read . show $ x) == (x :: SocketType)
it "holds for SocketOption" $ forAll sockoptGen $
\x -> (read . show $ x) == (x :: SocketOption)
it "holds for CmsgId" $ forAll cmsgidGen $
\x -> (read . show $ x) == (x :: CmsgId)
-- Type-specific generators with strong bias towards pattern synonyms
-- Generator combinator that biases elements of a given list and otherwise
-- applies a function to a given generator
biasedGen :: (Gen a -> Gen b) -> [b] -> Gen a -> Gen b
biasedGen f xs g = do
useBias <- (arbitrary :: Gen Bool)
if useBias
then elements xs
else f g
familyGen :: Gen Family
familyGen = biasedGen (fmap GeneralFamily) familyPatterns arbitrary
socktypeGen :: Gen SocketType
socktypeGen = biasedGen (fmap GeneralSocketType) socktypePatterns arbitrary
sockoptGen :: Gen SocketOption
sockoptGen = biasedGen (\g -> SockOpt <$> g <*> g) sockoptPatterns arbitrary
cmsgidGen :: Gen CmsgId
cmsgidGen = biasedGen (\g -> CmsgId <$> g <*> g) cmsgidPatterns arbitrary
-- pruned lists of pattern synonym values for each type to generate values from
familyPatterns :: [Family]
familyPatterns = nub
[UnsupportedFamily
,AF_UNSPEC,AF_UNIX,AF_INET,AF_INET6,AF_IMPLINK,AF_PUP,AF_CHAOS
,AF_NS,AF_NBS,AF_ECMA,AF_DATAKIT,AF_CCITT,AF_SNA,AF_DECnet
,AF_DLI,AF_LAT,AF_HYLINK,AF_APPLETALK,AF_ROUTE,AF_NETBIOS
,AF_NIT,AF_802,AF_ISO,AF_OSI,AF_NETMAN,AF_X25,AF_AX25,AF_OSINET
,AF_GOSSIP,AF_IPX,Pseudo_AF_XTP,AF_CTF,AF_WAN,AF_SDL,AF_NETWARE
,AF_NDD,AF_INTF,AF_COIP,AF_CNT,Pseudo_AF_RTIP,Pseudo_AF_PIP
,AF_SIP,AF_ISDN,Pseudo_AF_KEY,AF_NATM,AF_ARP,Pseudo_AF_HDRCMPLT
,AF_ENCAP,AF_LINK,AF_RAW,AF_RIF,AF_NETROM,AF_BRIDGE,AF_ATMPVC
,AF_ROSE,AF_NETBEUI,AF_SECURITY,AF_PACKET,AF_ASH,AF_ECONET
,AF_ATMSVC,AF_IRDA,AF_PPPOX,AF_WANPIPE,AF_BLUETOOTH,AF_CAN]
socktypePatterns :: [SocketType]
socktypePatterns = nub
[ UnsupportedSocketType
, NoSocketType
, Stream
, Datagram
, Raw
, RDM
, SeqPacket
]
sockoptPatterns :: [SocketOption]
sockoptPatterns = nub
[UnsupportedSocketOption
,Debug,ReuseAddr,SoDomain,Type,SoProtocol,SoError,DontRoute
,Broadcast,SendBuffer,RecvBuffer,KeepAlive,OOBInline,TimeToLive
,MaxSegment,NoDelay,Cork,Linger,ReusePort
,RecvLowWater,SendLowWater,RecvTimeOut,SendTimeOut
,UseLoopBack,UserTimeout,IPv6Only
,RecvIPv4TTL,RecvIPv4TOS,RecvIPv4PktInfo
,RecvIPv6HopLimit,RecvIPv6TClass,RecvIPv6PktInfo]
cmsgidPatterns :: [CmsgId]
cmsgidPatterns = nub
[ UnsupportedCmsgId
, CmsgIdIPv4TTL
, CmsgIdIPv6HopLimit
, CmsgIdIPv4TOS
, CmsgIdIPv6TClass
, CmsgIdIPv4PktInfo
, CmsgIdIPv6PktInfo
, CmsgIdFd
]
|