{-# LANGUAGE CPP #-}------------------------------------------------------------------------------- |-- Module : Network-- Copyright : (c) The University of Glasgow 2001-- License : BSD-style (see the file libraries/network/LICENSE)-- -- Maintainer : libraries@haskell.org-- Stability : provisional-- Portability : portable---- The "Network" interface is a \"higher-level\" interface to-- networking facilities, and it is recommended unless you need the-- lower-level interface in "Network.Socket".-------------------------------------------------------------------------------#include "HsNetworkConfig.h"#ifdef HAVE_GETADDRINFO-- Use IPv6-capable function definitions if the OS supports it.#define IPV6_SOCKET_SUPPORT 1#endifmoduleNetwork(-- * Basic data typesSocket,PortID(..),HostName,PortNumber-- * Initialisation,withSocketsDo-- * Server-side connections,listenOn,accept,sClose-- * Client-side connections,connectTo-- * Simple sending and receiving{-$sendrecv-},sendTo,recvFrom-- * Miscellaneous,socketPort-- * Networking Issues-- ** Buffering{-$buffering-}-- ** Improving I\/O Performance over sockets{-$performance-}-- ** @SIGPIPE@{-$sigpipe-})whereimportControl.Monad(liftM)importData.Maybe(fromJust)importNetwork.BSDimportNetwork.Sockethiding(accept,socketPort,recvFrom,sendTo,PortNumber)importqualifiedNetwork.SocketasSocket(accept)importSystem.IOimportPreludeimportqualifiedControl.ExceptionasException-- ----------------------------------------------------------------------------- High Level ``Setup'' functions-- If the @PortID@ specifies a unix family socket and the @Hostname@-- differs from that returned by @getHostname@ then an error is-- raised. Alternatively an empty string may be given to @connectTo@-- signalling that the current hostname applies.dataPortID=ServiceString-- Service Name eg "ftp"|PortNumberPortNumber-- User defined Port Number#if !defined(mingw32_HOST_OS) && !defined(cygwin32_HOST_OS) && !defined(_WIN32)|UnixSocketString-- Unix family socket in file system#endif-- | Calling 'connectTo' creates a client side socket which is-- connected to the given host and port. The Protocol and socket type is-- derived from the given port identifier. If a port number is given-- then the result is always an internet family 'Stream' socket. connectTo::HostName-- Hostname->PortID-- Port Identifier->IOHandle-- Connected Socket#if defined(IPV6_SOCKET_SUPPORT)-- IPv6 and IPv4.connectTohostname(Serviceserv)=connect'hostnameservconnectTohostname(PortNumberport)=connect'hostname(showport)#else-- IPv4 only.connectTohostname(Serviceserv)=doproto<-getProtocolNumber"tcp"bracketOnError(socketAF_INETStreamproto)(sClose)-- only done if there's an error(\sock->doport<-getServicePortNumberservhe<-getHostByNamehostnameconnectsock(SockAddrInetport(hostAddresshe))socketToHandlesockReadWriteMode)connectTohostname(PortNumberport)=doproto<-getProtocolNumber"tcp"bracketOnError(socketAF_INETStreamproto)(sClose)-- only done if there's an error(\sock->dohe<-getHostByNamehostnameconnectsock(SockAddrInetport(hostAddresshe))socketToHandlesockReadWriteMode)#endif#if !defined(mingw32_HOST_OS) && !defined(cygwin32_HOST_OS) && !defined(_WIN32)connectTo_(UnixSocketpath)=dobracketOnError(socketAF_UNIXStream0)(sClose)(\sock->doconnectsock(SockAddrUnixpath)socketToHandlesockReadWriteMode)#endif#if defined(IPV6_SOCKET_SUPPORT)connect'::HostName->ServiceName->IOHandleconnect'hostserv=doproto<-getProtocolNumber"tcp"lethints=defaultHints{addrFlags=[AI_ADDRCONFIG],addrProtocol=proto,addrSocketType=Stream}addrs<-getAddrInfo(Justhints)(Justhost)(Justserv)firstSuccessful$maptryToConnectaddrswheretryToConnectaddr=bracketOnError(socket(addrFamilyaddr)(addrSocketTypeaddr)(addrProtocoladdr))(sClose)-- only done if there's an error(\sock->doconnectsock(addrAddressaddr)socketToHandlesockReadWriteMode)#endif-- | Creates the server side socket which has been bound to the-- specified port.---- NOTE: To avoid the \"Address already in use\"-- problems popped up several times on the GHC-Users mailing list we-- set the 'ReuseAddr' socket option on the listening socket. If you-- don't want this behaviour, please use the lower level-- 'Network.Socket.listen' instead.---- If available, the 'IPv6Only' socket option is set to 0-- so that both IPv4 and IPv6 can be accepted with this socket.listenOn::PortID-- ^ Port Identifier->IOSocket-- ^ Connected Socket#if defined(IPV6_SOCKET_SUPPORT)-- IPv6 and IPv4.listenOn(Serviceserv)=listen'servlistenOn(PortNumberport)=listen'(showport)#else-- IPv4 only.listenOn(Serviceserv)=doproto<-getProtocolNumber"tcp"bracketOnError(socketAF_INETStreamproto)(sClose)(\sock->doport<-getServicePortNumberservsetSocketOptionsockReuseAddr1bindSocketsock(SockAddrInetportiNADDR_ANY)listensockmaxListenQueuereturnsock)listenOn(PortNumberport)=doproto<-getProtocolNumber"tcp"bracketOnError(socketAF_INETStreamproto)(sClose)(\sock->dosetSocketOptionsockReuseAddr1bindSocketsock(SockAddrInetportiNADDR_ANY)listensockmaxListenQueuereturnsock)#endif#if !defined(mingw32_HOST_OS) && !defined(cygwin32_HOST_OS) && !defined(_WIN32)listenOn(UnixSocketpath)=bracketOnError(socketAF_UNIXStream0)(sClose)(\sock->dosetSocketOptionsockReuseAddr1bindSocketsock(SockAddrUnixpath)listensockmaxListenQueuereturnsock)#endif#if defined(IPV6_SOCKET_SUPPORT)listen'::ServiceName->IOSocketlisten'serv=doproto<-getProtocolNumber"tcp"-- We should probably specify addrFamily = AF_INET6 and the filter-- code below should be removed. AI_ADDRCONFIG is probably not-- necessary. But this code is well-tested. So, let's keep it.lethints=defaultHints{addrFlags=[AI_ADDRCONFIG,AI_PASSIVE],addrSocketType=Stream,addrProtocol=proto}addrs<-getAddrInfo(Justhints)Nothing(Justserv)-- Choose an IPv6 socket if exists. This ensures the socket can-- handle both IPv4 and IPv6 if v6only is false.letaddrs'=filter(\x->addrFamilyx==AF_INET6)addrsaddr=ifnulladdrs'thenheadaddrselseheadaddrs'bracketOnError(socket(addrFamilyaddr)(addrSocketTypeaddr)(addrProtocoladdr))(sClose)(\sock->dosetSocketOptionsockReuseAddr1bindSocketsock(addrAddressaddr)listensockmaxListenQueuereturnsock)#endif-- ------------------------------------------------------------------------------- accept-- | Accept a connection on a socket created by 'listenOn'. Normal-- I\/O operations (see "System.IO") can be used on the 'Handle'-- returned to communicate with the client.-- Notice that although you can pass any Socket to Network.accept,-- only sockets of either AF_UNIX, AF_INET, or AF_INET6 will work-- (this shouldn't be a problem, though). When using AF_UNIX, HostName-- will be set to the path of the socket and PortNumber to -1.--accept::Socket-- ^ Listening Socket->IO(Handle,HostName,PortNumber)-- ^ Triple of: read\/write 'Handle' for -- communicating with the client,-- the 'HostName' of the peer socket, and-- the 'PortNumber' of the remote connection.acceptsock@(MkSocket_AF_INET___)=do~(sock',(SockAddrInetporthaddr))<-Socket.acceptsockpeer<-catchIO(do(HostEntrypeer___)<-getHostByAddrAF_INEThaddrreturnpeer)(\_e->inet_ntoahaddr)-- if getHostByName fails, we fall back to the IP addresshandle<-socketToHandlesock'ReadWriteModereturn(handle,peer,port)#if defined(IPV6_SOCKET_SUPPORT)acceptsock@(MkSocket_AF_INET6___)=do(sock',addr)<-Socket.acceptsockpeer<-catchIO((fromJust.fst)`liftM`getNameInfo[]TrueFalseaddr)$\_->caseaddrofSockAddrInet_a->inet_ntoaaSockAddrInet6__a_->return(showa)# if !defined(mingw32_HOST_OS) && !defined(cygwin32_HOST_OS) && !defined(_WIN32)SockAddrUnixa->returna# endifhandle<-socketToHandlesock'ReadWriteModeletport=caseaddrofSockAddrInetp_->pSockAddrInet6p___->p_->-1return(handle,peer,port)#endif#if !defined(mingw32_HOST_OS) && !defined(cygwin32_HOST_OS) && !defined(_WIN32)acceptsock@(MkSocket_AF_UNIX___)=do~(sock',(SockAddrUnixpath))<-Socket.acceptsockhandle<-socketToHandlesock'ReadWriteModereturn(handle,path,-1)#endifaccept(MkSocket_family___)=error$"Sorry, address family "++(showfamily)++" is not supported!"-- ------------------------------------------------------------------------------- sendTo/recvFrom{-$sendrecv
Send and receive data from\/to the given host and port number. These
should normally only be used where the socket will not be required for
further calls. Also, note that due to the use of 'hGetContents' in 'recvFrom'
the socket will remain open (i.e. not available) even if the function already
returned. Their use is strongly discouraged except for small test-applications
or invocations from the command line.
-}sendTo::HostName-- Hostname->PortID-- Port Number->String-- Message to send->IO()sendTohpmsg=dos<-connectTohphPutStrsmsghClosesrecvFrom::HostName-- Hostname->PortID-- Port Number->IOString-- Received Data#if defined(IPV6_SOCKET_SUPPORT)recvFromhostport=doproto<-getProtocolNumber"tcp"lethints=defaultHints{addrFlags=[AI_ADDRCONFIG],addrProtocol=proto,addrSocketType=Stream}allowed<-mapaddrAddress`liftM`getAddrInfo(Justhints)(Justhost)Nothings<-listenOnportletwaiting=do(s',addr)<-Socket.acceptsifnot(addr`oneOf`allowed)thensCloses'>>waitingelsesocketToHandles'ReadMode>>=hGetContentswaitingwherea@(SockAddrInet_ha)`oneOf`((SockAddrInet_hb):bs)|ha==hb=True|otherwise=a`oneOf`bsa@(SockAddrInet6__ha_)`oneOf`((SockAddrInet6__hb_):bs)|ha==hb=True|otherwise=a`oneOf`bs_`oneOf`_=False#elserecvFromhostport=doip<-getHostByNamehostletipHs=hostAddressesips<-listenOnportletwaiting=do~(s',SockAddrInet_haddr)<-Socket.acceptshe<-getHostByAddrAF_INEThaddrifnot(any(`elem`ipHs)(hostAddresseshe))thendosCloses'waitingelsedoh<-socketToHandles'ReadModemsg<-hGetContentshreturnmsgmessage<-waitingreturnmessage#endif-- ----------------------------------------------------------------------------- Access function returning the port type/id of socket.-- | Returns the 'PortID' associated with a given socket.socketPort::Socket->IOPortIDsocketPorts=dosockaddr<-getSocketNamesreturn(portIDsockaddr)whereportIDsa=casesaofSockAddrInetport_->PortNumberport#if defined(IPV6_SOCKET_SUPPORT)SockAddrInet6port___->PortNumberport#endif#if !defined(mingw32_HOST_OS) && !defined(cygwin32_HOST_OS) && !defined(_WIN32)SockAddrUnixpath->UnixSocketpath#endif-- ----------------------------------------------------------------------------- Utils-- Like bracket, but only performs the final action if there was an -- exception raised by the middle bit.bracketOnError::IOa-- ^ computation to run first (\"acquire resource\")->(a->IOb)-- ^ computation to run last (\"release resource\")->(a->IOc)-- ^ computation to run in-between->IOc-- returns the value from the in-between computation#if __GLASGOW_HASKELL__ && __GLASGOW_HASKELL__ < 606bracketOnErrorbeforeafterthing=Exception.block(doa<-beforer<-Exception.catch(Exception.unblock(thinga))(\e->do{aftera;Exception.throwe})returnr)#elsebracketOnError=Exception.bracketOnError#endif------------------------------------------------------------------------------- Extra documentation{-$buffering
The 'Handle' returned by 'connectTo' and 'accept' is block-buffered by
default. For an interactive application you may want to set the
buffering mode on the 'Handle' to
'LineBuffering' or 'NoBuffering', like so:
> h <- connectTo host port
> hSetBuffering h LineBuffering
-}{-$performance
For really fast I\/O, it might be worth looking at the 'hGetBuf' and
'hPutBuf' family of functions in "System.IO".
-}{-$sigpipe
On Unix, when writing to a socket and the reading end is
closed by the remote client, the program is normally sent a
@SIGPIPE@ signal by the operating system. The
default behaviour when a @SIGPIPE@ is received is
to terminate the program silently, which can be somewhat confusing
if you haven't encountered this before. The solution is to
specify that @SIGPIPE@ is to be ignored, using
the POSIX library:
> import Posix
> main = do installHandler sigPIPE Ignore Nothing; ...
-}catchIO::IOa->(Exception.IOException->IOa)->IOa#if MIN_VERSION_base(4,0,0)catchIO=Exception.catch#elsecatchIO=Exception.catchJustException.ioErrors#endif-- Returns the first action from a list which does not throw an exception.-- If all the actions throw exceptions (and the list of actions is not empty),-- the last exception is thrown.firstSuccessful::[IOa]->IOafirstSuccessful[]=error"firstSuccessful: empty list"firstSuccessful(p:ps)=catchIOp$\e->casepsof[]->Exception.throwe_->firstSuccessfulps