-- Hoogle documentation, generated by Haddock -- See Hoogle, http://www.haskell.org/hoogle/ -- | A library for client-side HTTP -- -- The HTTP package supports client-side web programming in Haskell. It -- lets you set up HTTP connections, transmitting requests and processing -- the responses coming back, all from within the comforts of Haskell. -- It's dependent on the network package to operate, but other than that, -- the implementation is all written in Haskell. -- -- A basic API for issuing single HTTP requests + receiving responses is -- provided. On top of that, a session-level abstraction is also on offer -- (the BrowserAction monad); it taking care of handling the -- management of persistent connections, proxies, state (cookies) and -- authentication credentials required to handle multi-step interactions -- with a web server. -- -- The representation of the bytes flowing across is extensible via the -- use of a type class, letting you pick the representation of requests -- and responses that best fits your use. Some pre-packaged, common -- instances are provided for you (ByteString, String). -- -- Here's an example use: -- --
--   do
--     rsp <- Network.HTTP.simpleHTTP (getRequest "http://www.haskell.org/")
--             -- fetch document and return it (as a 'String'.)
--     fmap (take 100) (getResponseBody rsp)
--   
--   do
--     (_, rsp)
--        <- Network.Browser.browse $ do
--              setAllowRedirects True -- handle HTTP redirects
--              request $ getRequest "http://www.haskell.org/"
--     return (take 100 (rspBody rsp))
--   
@package HTTP @version 4000.3.4 -- | An library for creating abstract streams. Originally part of -- Gray's\/Bringert's HTTP module. -- -- module Network.Stream -- | Streams should make layering of TLS protocol easier in future, they -- allow reading/writing to files etc for debugging, they allow use of -- protocols other than TCP/IP and they allow customisation. -- -- Instances of this class should not trim the input in any way, e.g. -- leave LF on line endings etc. Unless that is exactly the behaviour you -- want from your twisted instances ;) class Stream x readLine :: Stream x => x -> IO (Result String) readBlock :: Stream x => x -> Int -> IO (Result String) writeBlock :: Stream x => x -> String -> IO (Result ()) close :: Stream x => x -> IO () closeOnEnd :: Stream x => x -> Bool -> IO () data ConnError ErrorReset :: ConnError ErrorClosed :: ConnError ErrorParse :: String -> ConnError ErrorMisc :: String -> ConnError -- | This is the type returned by many exported network functions. type Result a = Either ConnError a bindE :: Result a -> (a -> Result b) -> Result b fmapE :: (a -> Result b) -> IO (Result a) -> IO (Result b) failParse :: String -> Result a failWith :: ConnError -> Result a failMisc :: String -> Result a instance GHC.Classes.Eq Network.Stream.ConnError instance GHC.Show.Show Network.Stream.ConnError instance Control.Monad.Trans.Error.Error Network.Stream.ConnError -- | This module provides the data types for representing HTTP headers, and -- operations for looking up header values and working with sequences of -- header values in Requests and Responses. To avoid -- having to provide separate set of operations for doing so, we -- introduce a type class HasHeaders to facilitate writing such -- processing using overloading instead. module Network.HTTP.Headers -- | HasHeaders is a type class for types containing HTTP headers, -- allowing you to write overloaded header manipulation functions for -- both Request and Response data types, for instance. class HasHeaders x getHeaders :: HasHeaders x => x -> [Header] setHeaders :: HasHeaders x => x -> [Header] -> x -- | The Header data type pairs header names & values. data Header Header :: HeaderName -> String -> Header -- | Header constructor as a function, hiding above rep. mkHeader :: HeaderName -> String -> Header hdrName :: Header -> HeaderName hdrValue :: Header -> String -- | HTTP HeaderName type, a Haskell data constructor for each -- specification-defined header, prefixed with Hdr and -- CamelCased, (i.e., eliding the - in the process.) Should you -- require using a custom header, there's the HdrCustom -- constructor which takes a String argument. -- -- Encoding HTTP header names differently, as Strings perhaps, is an -- equally fine choice..no decidedly clear winner, but let's stick with -- data constructors here. data HeaderName HdrCacheControl :: HeaderName HdrConnection :: HeaderName HdrDate :: HeaderName HdrPragma :: HeaderName HdrTransferEncoding :: HeaderName HdrUpgrade :: HeaderName HdrVia :: HeaderName HdrAccept :: HeaderName HdrAcceptCharset :: HeaderName HdrAcceptEncoding :: HeaderName HdrAcceptLanguage :: HeaderName HdrAuthorization :: HeaderName HdrCookie :: HeaderName HdrExpect :: HeaderName HdrFrom :: HeaderName HdrHost :: HeaderName HdrIfModifiedSince :: HeaderName HdrIfMatch :: HeaderName HdrIfNoneMatch :: HeaderName HdrIfRange :: HeaderName HdrIfUnmodifiedSince :: HeaderName HdrMaxForwards :: HeaderName HdrProxyAuthorization :: HeaderName HdrRange :: HeaderName HdrReferer :: HeaderName HdrUserAgent :: HeaderName HdrAge :: HeaderName HdrLocation :: HeaderName HdrProxyAuthenticate :: HeaderName HdrPublic :: HeaderName HdrRetryAfter :: HeaderName HdrServer :: HeaderName HdrSetCookie :: HeaderName HdrTE :: HeaderName HdrTrailer :: HeaderName HdrVary :: HeaderName HdrWarning :: HeaderName HdrWWWAuthenticate :: HeaderName HdrAllow :: HeaderName HdrContentBase :: HeaderName HdrContentEncoding :: HeaderName HdrContentLanguage :: HeaderName HdrContentLength :: HeaderName HdrContentLocation :: HeaderName HdrContentMD5 :: HeaderName HdrContentRange :: HeaderName HdrContentType :: HeaderName HdrETag :: HeaderName HdrExpires :: HeaderName HdrLastModified :: HeaderName -- | MIME entity headers (for sub-parts) HdrContentTransferEncoding :: HeaderName -- | Allows for unrecognised or experimental headers. HdrCustom :: String -> HeaderName -- | insertHeader hdr val x inserts a header with the given header -- name and value. Does not check for existing headers with same name, -- allowing duplicates to be introduce (use replaceHeader if you -- want to avoid this.) insertHeader :: HasHeaders a => HeaderSetter a -- | insertHeaderIfMissing hdr val x adds the new header only if -- no previous header with name hdr exists in x. insertHeaderIfMissing :: HasHeaders a => HeaderSetter a -- | insertHeaders hdrs x appends multiple headers to x's -- existing set. insertHeaders :: HasHeaders a => [Header] -> a -> a -- | retrieveHeaders hdrNm x gets a list of headers with -- HeaderName hdrNm. retrieveHeaders :: HasHeaders a => HeaderName -> a -> [Header] -- | replaceHeader hdr val o replaces the header hdr with -- the value val, dropping any existing replaceHeader :: HasHeaders a => HeaderSetter a -- | findHeader hdrNm x looks up hdrNm in x, -- returning the first header that matches, if any. findHeader :: HasHeaders a => HeaderName -> a -> Maybe String -- | lookupHeader hdr hdrs locates the first header matching -- hdr in the list hdrs. lookupHeader :: HeaderName -> [Header] -> Maybe String -- | parseHeader headerNameAndValueString tries to unscramble a -- header: value pairing and returning it as a Header. parseHeader :: String -> Result Header -- | parseHeaders hdrs takes a sequence of strings holding header -- information and parses them into a set of headers (preserving their -- order in the input argument.) Handles header values split up over -- multiple lines. parseHeaders :: [String] -> Result [Header] -- | headerMap is a straight assoc list for translating between -- header names and values. headerMap :: [(String, HeaderName)] type HeaderSetter a = HeaderName -> String -> a -> a instance GHC.Classes.Eq Network.HTTP.Headers.HeaderName instance GHC.Show.Show Network.HTTP.Headers.Header instance GHC.Show.Show Network.HTTP.Headers.HeaderName -- | This module provides the data types and functions for working with -- HTTP cookies. Right now, it contains mostly functionality needed by -- Browser. module Network.HTTP.Cookie -- | Cookie is the Haskell representation of HTTP cookie values. -- See its relevant specs for authoritative details. data Cookie MkCookie :: String -> String -> String -> Maybe String -> Maybe String -> Maybe String -> Cookie [ckDomain] :: Cookie -> String [ckName] :: Cookie -> String [ckValue] :: Cookie -> String [ckPath] :: Cookie -> Maybe String [ckComment] :: Cookie -> Maybe String [ckVersion] :: Cookie -> Maybe String -- | cookieMatch (domain,path) ck performs the standard cookie -- match wrt the given domain and path. cookieMatch :: (String, String) -> Cookie -> Bool -- | cookieToHeaders ck serialises Cookies to an HTTP -- request header. cookiesToHeader :: [Cookie] -> Header -- |
--   processCookieHeaders dom hdrs
--   
processCookieHeaders :: String -> [Header] -> ([String], [Cookie]) instance GHC.Read.Read Network.HTTP.Cookie.Cookie instance GHC.Show.Show Network.HTTP.Cookie.Cookie instance GHC.Classes.Eq Network.HTTP.Cookie.Cookie -- | In order to give the user freedom in how request and response content -- is represented, a sufficiently abstract representation is needed of -- these internally. The Network.BufferType module provides this, -- defining the BufferType class and its ad-hoc representation of -- buffer operations via the BufferOp record. -- -- This module provides definitions for the standard buffer types that -- the package supports, i.e., for String and -- ByteString (strict and lazy.) module Network.BufferType -- | The BufferType class encodes, in a mixed-mode way, the -- interface that the library requires to operate over data embedded in -- HTTP requests and responses. That is, we use explicit dictionaries for -- the operations, but overload the name of the dicts themselves. class BufferType bufType bufferOps :: BufferType bufType => BufferOp bufType -- | BufferOp encodes the I/O operations of the underlying buffer -- over a Handle in an (explicit) dictionary type. May not be needed, but -- gives us flexibility in explicit overriding and wrapping up of these -- methods. -- -- Along with IO operations is an ad-hoc collection of functions for -- working with these abstract buffers, as needed by the internals of the -- code that processes requests and responses. -- -- We supply three default BufferOp values, for String -- along with the strict and lazy versions of ByteString. To add -- others, provide BufferOp definitions for data BufferOp a BufferOp :: (Handle -> Int -> IO a) -> (Handle -> IO a) -> (Handle -> a -> IO ()) -> (Handle -> IO a) -> a -> (a -> a -> a) -> ([a] -> a) -> (String -> a) -> (a -> String) -> (a -> Word8 -> a) -> (Int -> a -> (a, a)) -> ((Char -> Bool) -> a -> (a, a)) -> (a -> Bool) -> (a -> Bool) -> BufferOp a [buf_hGet] :: BufferOp a -> Handle -> Int -> IO a [buf_hGetContents] :: BufferOp a -> Handle -> IO a [buf_hPut] :: BufferOp a -> Handle -> a -> IO () [buf_hGetLine] :: BufferOp a -> Handle -> IO a [buf_empty] :: BufferOp a -> a [buf_append] :: BufferOp a -> a -> a -> a [buf_concat] :: BufferOp a -> [a] -> a [buf_fromStr] :: BufferOp a -> String -> a [buf_toStr] :: BufferOp a -> a -> String [buf_snoc] :: BufferOp a -> a -> Word8 -> a [buf_splitAt] :: BufferOp a -> Int -> a -> (a, a) [buf_span] :: BufferOp a -> (Char -> Bool) -> a -> (a, a) [buf_isLineTerm] :: BufferOp a -> a -> Bool [buf_isEmpty] :: BufferOp a -> a -> Bool -- | strictBufferOp is the BufferOp definition over -- ByteStrings, the non-lazy kind. strictBufferOp :: BufferOp ByteString -- | lazyBufferOp is the BufferOp definition over -- ByteStrings, the non-strict kind. lazyBufferOp :: BufferOp ByteString -- | stringBufferOp is the BufferOp definition over -- Strings. It is defined in terms of strictBufferOp -- operations, unpacking/converting to String when needed. stringBufferOp :: BufferOp String instance Network.BufferType.BufferType Data.ByteString.Lazy.Internal.ByteString instance Network.BufferType.BufferType Data.ByteString.Internal.ByteString instance Network.BufferType.BufferType GHC.Base.String instance GHC.Classes.Eq (Network.BufferType.BufferOp a) -- | Definitions of Request and Response types along with -- functions for normalizing them. It is assumed to be an internal -- module; user code should, if possible, import Network.HTTP to -- access the functionality that this module provides. -- -- Additionally, the module exports internal functions for working with -- URLs, and for handling the processing of requests and responses coming -- back. module Network.HTTP.Base httpVersion :: String -- | An HTTP Request. The Show instance of this type is used for -- message serialisation, which means no body data is output. data Request a Request :: URI -> RequestMethod -> [Header] -> a -> Request a -- | might need changing in future 1) to support * uri in OPTIONS -- request 2) transparent support for both relative & absolute uris, -- although this should already work (leave scheme & host parts -- empty). [rqURI] :: Request a -> URI [rqMethod] :: Request a -> RequestMethod [rqHeaders] :: Request a -> [Header] [rqBody] :: Request a -> a -- | An HTTP Response. The Show instance of this type is used for -- message serialisation, which means no body data is output, -- additionally the output will show an HTTP version of 1.1 instead of -- the actual version returned by a server. data Response a Response :: ResponseCode -> String -> [Header] -> a -> Response a [rspCode] :: Response a -> ResponseCode [rspReason] :: Response a -> String [rspHeaders] :: Response a -> [Header] [rspBody] :: Response a -> a -- | The HTTP request method, to be used in the Request object. We -- are missing a few of the stranger methods, but these are not really -- necessary until we add full TLS. data RequestMethod HEAD :: RequestMethod PUT :: RequestMethod GET :: RequestMethod POST :: RequestMethod DELETE :: RequestMethod OPTIONS :: RequestMethod TRACE :: RequestMethod CONNECT :: RequestMethod Custom :: String -> RequestMethod type Request_String = Request String type Response_String = Response String type HTTPRequest a = Request a type HTTPResponse a = Response a urlEncode :: String -> String urlDecode :: String -> String urlEncodeVars :: [(String, String)] -> String data URIAuthority URIAuthority :: Maybe String -> Maybe String -> String -> Maybe Int -> URIAuthority [user] :: URIAuthority -> Maybe String [password] :: URIAuthority -> Maybe String [host] :: URIAuthority -> String [port] :: URIAuthority -> Maybe Int -- | Parse the authority part of a URL. -- --
--   RFC 1732, section 3.1:
--   
--         //<user>:<password>@<host>:<port>/<url-path>
--    Some or all of the parts "<user>:<password>@", ":<password>",
--    ":<port>", and "/<url-path>" may be excluded.
--   
parseURIAuthority :: String -> Maybe URIAuthority uriToAuthorityString :: URI -> String uriAuthToString :: URIAuth -> String uriAuthPort :: Maybe URI -> URIAuth -> Int reqURIAuth :: Request ty -> URIAuth parseResponseHead :: [String] -> Result ResponseData parseRequestHead :: [String] -> Result RequestData data ResponseNextStep Continue :: ResponseNextStep Retry :: ResponseNextStep Done :: ResponseNextStep ExpectEntity :: ResponseNextStep DieHorribly :: String -> ResponseNextStep matchResponse :: RequestMethod -> ResponseCode -> ResponseNextStep -- | ResponseData contains the head of a response payload; HTTP -- response code, accompanying text description + header fields. type ResponseData = (ResponseCode, String, [Header]) -- | For easy pattern matching, HTTP response codes xyz are -- represented as (x,y,z). type ResponseCode = (Int, Int, Int) -- | RequestData contains the head of a HTTP request; method, its -- URL along with the auxillary/supporting header data. type RequestData = (RequestMethod, URI, [Header]) -- | NormalizeRequestOptions brings together the various -- defaulting/normalization options over Requests. Use -- defaultNormalizeRequestOptions for the standard selection of -- option data NormalizeRequestOptions ty NormalizeRequestOptions :: Bool -> Bool -> Maybe String -> [RequestNormalizer ty] -> NormalizeRequestOptions ty [normDoClose] :: NormalizeRequestOptions ty -> Bool [normForProxy] :: NormalizeRequestOptions ty -> Bool [normUserAgent] :: NormalizeRequestOptions ty -> Maybe String [normCustoms] :: NormalizeRequestOptions ty -> [RequestNormalizer ty] defaultNormalizeRequestOptions :: NormalizeRequestOptions ty -- | RequestNormalizer is the shape of a (pure) function that -- rewrites a request into some normalized form. type RequestNormalizer ty = NormalizeRequestOptions ty -> Request ty -> Request ty -- | normalizeRequest opts req is the entry point to use to -- normalize your request prior to transmission (or other use.) -- Normalization is controlled via the NormalizeRequestOptions -- record. normalizeRequest :: NormalizeRequestOptions ty -> Request ty -> Request ty splitRequestURI :: URI -> (String, URI) -- | getAuth req fishes out the authority portion of the URL in a -- request's Host header. getAuth :: Monad m => Request ty -> m URIAuthority -- | Deprecated: Please use Network.HTTP.Base.normalizeRequest -- instead normalizeRequestURI :: Bool -> String -> Request ty -> Request ty -- | Deprecated: Please use Network.HTTP.Base.normalizeRequest -- instead normalizeHostHeader :: Request ty -> Request ty findConnClose :: [Header] -> Bool -- | Used when we know exactly how many bytes to expect. linearTransfer :: (Int -> IO (Result a)) -> Int -> IO (Result ([Header], a)) -- | Used when nothing about data is known, Unfortunately waiting for a -- socket closure causes bad behaviour. Here we just take data once and -- give up the rest. hopefulTransfer :: BufferOp a -> IO (Result a) -> [a] -> IO (Result ([Header], a)) -- | A necessary feature of HTTP/1.1 Also the only transfer variety likely -- to return any footers. chunkedTransfer :: BufferOp a -> IO (Result a) -> (Int -> IO (Result a)) -> IO (Result ([Header], a)) -- | Maybe in the future we will have a sensible thing to do here, at that -- time we might want to change the name. uglyDeathTransfer :: String -> IO (Result ([Header], a)) -- | Remove leading crlfs then call readTillEmpty2 (not required by RFC) readTillEmpty1 :: BufferOp a -> IO (Result a) -> IO (Result [a]) -- | Read lines until an empty line (CRLF), also accepts a connection close -- as end of input, which is not an HTTP/1.1 compliant thing to do - so -- probably indicates an error condition. readTillEmpty2 :: BufferOp a -> IO (Result a) -> [a] -> IO (Result [a]) defaultGETRequest :: URI -> Request_String defaultGETRequest_ :: BufferType a => URI -> Request a -- | 'mkRequest method uri' constructs a well formed request for the given -- HTTP method and URI. It does not normalize the URI for the request -- _nor_ add the required Host: header. That is done either explicitly by -- the user or when requests are normalized prior to transmission. mkRequest :: BufferType ty => RequestMethod -> URI -> Request ty setRequestBody :: Request_String -> (String, String) -> Request_String -- | A default user agent string. The string is -- "haskell-HTTP/$version" where $version is the -- version of this HTTP package. defaultUserAgent :: String -- | The version of this HTTP package as a string, e.g. -- "4000.1.2". This may be useful to include in a user agent -- string so that you can determine from server logs what version of this -- package HTTP clients are using. This can be useful for tracking down -- HTTP compatibility quirks. httpPackageVersion :: String -- | Deprecated. Use defaultUserAgent -- | Deprecated: Use defaultUserAgent instead (but note the user agent -- name change) libUA :: String -- | catchIO a h handles IO action exceptions throughout codebase; -- version-specific tweaks better go here. catchIO :: IO a -> (IOException -> IO a) -> IO a catchIO_ :: IO a -> IO a -> IO a responseParseError :: String -> String -> Result a -- | getRequestVersion req returns the HTTP protocol version of -- the request req. If Nothing, the default -- httpVersion can be assumed. getRequestVersion :: Request a -> Maybe String -- | getResponseVersion rsp returns the HTTP protocol version of -- the response rsp. If Nothing, the default -- httpVersion can be assumed. getResponseVersion :: Response a -> Maybe String -- | setRequestVersion v req returns a new request, identical to -- req, but with its HTTP version set to v. setRequestVersion :: String -> Request a -> Request a -- | setResponseVersion v rsp returns a new response, identical to -- rsp, but with its HTTP version set to v. setResponseVersion :: String -> Response a -> Response a failHTTPS :: Monad m => URI -> m () instance GHC.Classes.Eq Network.HTTP.Base.RequestMethod instance GHC.Show.Show Network.HTTP.Base.URIAuthority instance GHC.Classes.Eq Network.HTTP.Base.URIAuthority instance GHC.Show.Show Network.HTTP.Base.RequestMethod instance GHC.Show.Show (Network.HTTP.Base.Request a) instance Network.HTTP.Headers.HasHeaders (Network.HTTP.Base.Request a) instance GHC.Show.Show (Network.HTTP.Base.Response a) instance Network.HTTP.Headers.HasHeaders (Network.HTTP.Base.Response a) -- | Representing HTTP Auth values in Haskell. Right now, it contains -- mostly functionality needed by Browser. module Network.HTTP.Auth -- | Authority specifies the HTTP Authentication method to use for -- a given domain/realm; Basic or Digest. data Authority AuthBasic :: String -> String -> String -> URI -> Authority [auRealm] :: Authority -> String [auUsername] :: Authority -> String [auPassword] :: Authority -> String [auSite] :: Authority -> URI AuthDigest :: String -> String -> String -> String -> Maybe Algorithm -> [URI] -> Maybe String -> [Qop] -> Authority [auRealm] :: Authority -> String [auUsername] :: Authority -> String [auPassword] :: Authority -> String [auNonce] :: Authority -> String [auAlgorithm] :: Authority -> Maybe Algorithm [auDomain] :: Authority -> [URI] [auOpaque] :: Authority -> Maybe String [auQop] :: Authority -> [Qop] -- | Algorithm controls the digest algorithm to, MD5 or -- MD5Session. data Algorithm AlgMD5 :: Algorithm AlgMD5sess :: Algorithm data Challenge ChalBasic :: String -> Challenge [chRealm] :: Challenge -> String ChalDigest :: String -> [URI] -> String -> Maybe String -> Bool -> Maybe Algorithm -> [Qop] -> Challenge [chRealm] :: Challenge -> String [chDomain] :: Challenge -> [URI] [chNonce] :: Challenge -> String [chOpaque] :: Challenge -> Maybe String [chStale] :: Challenge -> Bool [chAlgorithm] :: Challenge -> Maybe Algorithm [chQop] :: Challenge -> [Qop] data Qop QopAuth :: Qop QopAuthInt :: Qop -- | headerToChallenge base www_auth tries to convert the -- WWW-Authenticate header www_auth into a -- Challenge value. headerToChallenge :: URI -> Header -> Maybe Challenge -- | withAuthority auth req generates a credentials value from the -- auth Authority, in the context of the given request. -- -- If a client nonce was to be used then this function might need to be -- of type ... -> BrowserAction String withAuthority :: Authority -> Request ty -> String instance GHC.Show.Show Network.HTTP.Auth.Qop instance GHC.Classes.Eq Network.HTTP.Auth.Qop instance GHC.Classes.Eq Network.HTTP.Auth.Algorithm instance GHC.Show.Show Network.HTTP.Auth.Algorithm -- | Handling proxy server settings and their resolution. module Network.HTTP.Proxy -- | HTTP proxies (or not) are represented via Proxy, specifying if -- a proxy should be used for the request (see setProxy) data Proxy -- | Don't use a proxy. NoProxy :: Proxy -- | Use the proxy given. Should be of the form "http://host:port", "host", -- "host:port", or "http://host". Additionally, an optional -- Authority for authentication with the proxy. Proxy :: String -> (Maybe Authority) -> Proxy noProxy :: Proxy -- | fetchProxy flg gets the local proxy settings and parse the -- string into a Proxy value. If you want to be informed of -- ill-formed proxy configuration strings, supply True for -- flg. Proxy settings are sourced from the HTTP_PROXY -- environment variable, and in the case of Windows platforms, by -- consulting IE/WinInet's proxy setting in the Registry. fetchProxy :: Bool -> IO Proxy -- | parseProxy str translates a proxy server string into a -- Proxy value; returns Nothing if not well-formed. parseProxy :: String -> Maybe Proxy -- | Socket Stream instance. Originally part of Gray's\/Bringert's HTTP -- module. -- -- module Network.StreamSocket -- | Exception handler for socket operations. handleSocketError :: Socket -> IOException -> IO (Result a) myrecv :: Socket -> Int -> IO String instance Network.Stream.Stream Network.Socket.Types.Socket -- | Some utility functions for working with the Haskell network -- package. Mostly for internal use by the Network.HTTP code. module Network.TCP -- | The Connection newtype is a wrapper that allows us to make -- connections an instance of the Stream class, without GHC extensions. -- While this looks sort of like a generic reference to the transport -- layer it is actually TCP specific, which can be seen in the -- implementation of the 'Stream Connection' instance. data Connection data EndPoint EndPoint :: String -> Int -> EndPoint [epHost] :: EndPoint -> String [epPort] :: EndPoint -> Int -- | openTCPPort uri port establishes a connection to a remote -- host, using getHostByName which possibly queries the DNS -- system, hence may trigger a network connection. openTCPPort :: String -> Int -> IO Connection -- | Checks both that the underlying Socket is connected and that the -- connection peer matches the given host name (which is recorded -- locally). isConnectedTo :: Connection -> EndPoint -> IO Bool openTCPConnection :: BufferType ty => String -> Int -> IO (HandleStream ty) -- | socketConnection, like openConnection but using a -- pre-existing Socket. socketConnection :: BufferType ty => String -> Int -> Socket -> IO (HandleStream ty) isTCPConnectedTo :: HandleStream ty -> EndPoint -> IO Bool data HandleStream a -- | HStream overloads the use of HandleStreams, letting -- you overload the handle operations over the type that is communicated -- across the handle. It comes in handy for Network.HTTP -- Request and Responses as the payload representation -- isn't fixed, but overloaded. -- -- The library comes with instances for ByteStrings and -- String, but should you want to plug in your own payload -- representation, defining your own HStream instance _should_ -- be all that it takes. class BufferType bufType => HStream bufType openStream :: HStream bufType => String -> Int -> IO (HandleStream bufType) openSocketStream :: HStream bufType => String -> Int -> Socket -> IO (HandleStream bufType) readLine :: HStream bufType => HandleStream bufType -> IO (Result bufType) readBlock :: HStream bufType => HandleStream bufType -> Int -> IO (Result bufType) writeBlock :: HStream bufType => HandleStream bufType -> bufType -> IO (Result ()) close :: HStream bufType => HandleStream bufType -> IO () closeQuick :: HStream bufType => HandleStream bufType -> IO () closeOnEnd :: HStream bufType => HandleStream bufType -> Bool -> IO () data StreamHooks ty StreamHooks :: ((ty -> String) -> Result ty -> IO ()) -> ((ty -> String) -> Int -> Result ty -> IO ()) -> ((ty -> String) -> ty -> Result () -> IO ()) -> IO () -> String -> StreamHooks ty [hook_readLine] :: StreamHooks ty -> (ty -> String) -> Result ty -> IO () [hook_readBlock] :: StreamHooks ty -> (ty -> String) -> Int -> Result ty -> IO () [hook_writeBlock] :: StreamHooks ty -> (ty -> String) -> ty -> Result () -> IO () [hook_close] :: StreamHooks ty -> IO () [hook_name] :: StreamHooks ty -> String nullHooks :: StreamHooks ty setStreamHooks :: HandleStream ty -> StreamHooks ty -> IO () getStreamHooks :: HandleStream ty -> IO (Maybe (StreamHooks ty)) hstreamToConnection :: HandleStream String -> Connection instance GHC.Classes.Eq a => GHC.Classes.Eq (Network.TCP.Conn a) instance GHC.Classes.Eq Network.TCP.EndPoint instance GHC.Classes.Eq ty => GHC.Classes.Eq (Network.TCP.StreamHooks ty) instance Network.TCP.HStream Data.ByteString.Internal.ByteString instance Network.TCP.HStream Data.ByteString.Lazy.Internal.ByteString instance Network.Stream.Stream Network.TCP.Connection instance Network.TCP.HStream GHC.Base.String -- | Implements debugging of Streams. Originally part of -- Gray's\/Bringert's HTTP module. -- -- module Network.StreamDebugger -- | Allows stream logging. Refer to debugStream below. data StreamDebugger x -- | Wraps a stream with logging I/O. The first argument is a filename -- which is opened in AppendMode. debugStream :: (Stream a) => FilePath -> a -> IO (StreamDebugger a) debugByteStream :: HStream ty => FilePath -> HandleStream ty -> IO (HandleStream ty) instance Network.Stream.Stream x => Network.Stream.Stream (Network.StreamDebugger.StreamDebugger x) -- | A HandleStream-based version of Network.HTTP interface. -- -- For more detailed information about what the individual exports do, -- please consult the documentation for Network.HTTP. -- Notice however that the functions here do not perform any kind -- of normalization prior to transmission (or receipt); you are -- responsible for doing any such yourself, or, if you prefer, just -- switch to using Network.HTTP function instead. module Network.HTTP.HandleStream -- | simpleHTTP transmits a resource across a non-persistent -- connection. simpleHTTP :: HStream ty => Request ty -> IO (Result (Response ty)) -- | Like simpleHTTP, but acting on an already opened stream. simpleHTTP_ :: HStream ty => HandleStream ty -> Request ty -> IO (Result (Response ty)) -- | sendHTTP hStream httpRequest transmits httpRequest -- over hStream, but does not alter the status of the -- connection, nor request it to be closed upon receiving the response. sendHTTP :: HStream ty => HandleStream ty -> Request ty -> IO (Result (Response ty)) -- | sendHTTP_notify hStream httpRequest action behaves like -- sendHTTP, but lets you supply an IO action to execute -- once the request has been successfully transmitted over the -- connection. Useful when you want to set up tracing of request -- transmission and its performance. sendHTTP_notify :: HStream ty => HandleStream ty -> Request ty -> IO () -> IO (Result (Response ty)) -- | receiveHTTP hStream reads a Request from the -- HandleStream hStream receiveHTTP :: HStream bufTy => HandleStream bufTy -> IO (Result (Request bufTy)) -- | respondHTTP hStream httpResponse transmits an HTTP -- Response over the HandleStream hStream. It -- could be used to implement simple web server interactions, performing -- the dual role to sendHTTP. respondHTTP :: HStream ty => HandleStream ty -> Response ty -> IO () -- | simpleHTTP_debug debugFile req behaves like -- simpleHTTP, but logs the HTTP operation via the debug file -- debugFile. simpleHTTP_debug :: HStream ty => FilePath -> Request ty -> IO (Result (Response ty)) -- | The HTTP module provides a simple interface for sending and -- receiving content over HTTP in Haskell. Here's how to fetch a document -- from a URL and return it as a String: -- --
--   simpleHTTP (getRequest "http://www.haskell.org/") >>= fmap (take 100) . getResponseBody
--       -- fetch document and return it (as a 'String'.)
--   
-- -- Other functions let you control the submission and transfer of HTTP -- Requests and Responses more carefully, letting you -- integrate the use of HTTP functionality into your application. -- -- The module also exports the main types of the package, Request -- and Response, along with Header and functions for -- working with these. -- -- The actual functionality is implemented by modules in the -- Network.HTTP.* namespace, letting you either use the default -- implementation here by importing Network.HTTP or, for more -- specific uses, selectively import the modules in -- Network.HTTP.*. To wit, more than one kind of representation -- of the bulk data that flows across a HTTP connection is supported. -- (see Network.HTTP.HandleStream.) -- -- NOTE: The Request send actions will normalize the -- Request prior to transmission. Normalization such as having -- the request path be in the expected form and, possibly, introduce a -- default Host: header if one isn't already present. -- Normalization also takes the "user:pass@" portion out of the -- the URI, if it was supplied, and converts it into Authorization: -- Basic$ header. If you do not want the requests tampered with, but sent -- as-is, please import and use the the Network.HTTP.HandleStream -- or Network.HTTP.Stream modules instead. They export the same -- functions, but leaves construction and any normalization of -- Request@s to the user. -- -- NOTE: This package only supports HTTP; it does not support -- HTTPS. Attempts to use HTTPS result in an error. module Network.HTTP -- | simpleHTTP req transmits the Request req by -- opening a direct, non-persistent connection to the HTTP server -- that req is destined for, followed by transmitting it and -- gathering up the response as a Result. Prior to sending the -- request, it is normalized (via normalizeRequest). If you have -- to mediate the request via an HTTP proxy, you will have to normalize -- the request yourself. Or switch to using Browser instead. -- -- Examples: -- --
--   simpleHTTP (getRequest "http://hackage.haskell.org/")
--   simpleHTTP (getRequest "http://hackage.haskell.org:8012/")
--   
simpleHTTP :: (HStream ty) => Request ty -> IO (Result (Response ty)) -- | Identical to simpleHTTP, but acting on an already opened -- stream. simpleHTTP_ :: HStream ty => HandleStream ty -> Request ty -> IO (Result (Response ty)) -- | sendHTTP hStream httpRequest transmits httpRequest -- (after normalization) over hStream, but does not alter the -- status of the connection, nor request it to be closed upon receiving -- the response. sendHTTP :: HStream ty => HandleStream ty -> Request ty -> IO (Result (Response ty)) -- | sendHTTP_notify hStream httpRequest action behaves like -- sendHTTP, but lets you supply an IO action to execute -- once the request has been successfully transmitted over the -- connection. Useful when you want to set up tracing of request -- transmission and its performance. sendHTTP_notify :: HStream ty => HandleStream ty -> Request ty -> IO () -> IO (Result (Response ty)) -- | receiveHTTP hStream reads a Request from the -- HandleStream hStream receiveHTTP :: HStream ty => HandleStream ty -> IO (Result (Request ty)) -- | respondHTTP hStream httpResponse transmits an HTTP -- Response over the HandleStream hStream. It -- could be used to implement simple web server interactions, performing -- the dual role to sendHTTP. respondHTTP :: HStream ty => HandleStream ty -> Response ty -> IO () -- | A convenience constructor for a GET Request. -- -- If the URL isn't syntactically valid, the function raises an error. getRequest :: String -> Request_String -- | A convenience constructor for a HEAD Request. -- -- If the URL isn't syntactically valid, the function raises an error. headRequest :: String -> Request_String -- | A convenience constructor for a POST Request. -- -- If the URL isn't syntactically valid, the function raises an error. postRequest :: String -> Request_String -- | A convenience constructor for a POST Request. -- -- It constructs a request and sets the body as well as the Content-Type -- and Content-Length headers. The contents of the body are forced to -- calculate the value for the Content-Length header. -- -- If the URL isn't syntactically valid, the function raises an error. postRequestWithBody :: String -> String -> String -> Request_String -- | getResponseBody response takes the response of a HTTP -- requesting action and tries to extricate the body of the -- Response response. If the request action returned an -- error, an IO exception is raised. getResponseBody :: Result (Response ty) -> IO ty -- | getResponseBody response takes the response of a HTTP -- requesting action and tries to extricate the status code of the -- Response response. If the request action returned an -- error, an IO exception is raised. getResponseCode :: Result (Response ty) -> IO ResponseCode -- | Transmitting HTTP requests and responses holding String in -- their payload bodies. This is one of the implementation modules for -- the Network.HTTP interface, representing request and response -- content as Strings and transmitting them in non-packed form -- (cf. Network.HTTP.HandleStream and its use of -- ByteStrings.) over Stream handles. It is mostly here -- for backwards compatibility, representing how requests and responses -- were transmitted up until the 4.x releases of the HTTP package. -- -- For more detailed information about what the individual exports do, -- please consult the documentation for Network.HTTP. -- Notice however that the functions here do not perform any kind -- of normalization prior to transmission (or receipt); you are -- responsible for doing any such yourself, or, if you prefer, just -- switch to using Network.HTTP function instead. module Network.HTTP.Stream -- | Simple way to transmit a resource across a non-persistent connection. simpleHTTP :: Request_String -> IO (Result Response_String) -- | Like simpleHTTP, but acting on an already opened stream. simpleHTTP_ :: Stream s => s -> Request_String -> IO (Result Response_String) sendHTTP :: Stream s => s -> Request_String -> IO (Result Response_String) sendHTTP_notify :: Stream s => s -> Request_String -> IO () -> IO (Result Response_String) -- | Receive and parse a HTTP request from the given Stream. Should be used -- for server side interactions. receiveHTTP :: Stream s => s -> IO (Result Request_String) -- | Very simple function, send a HTTP response over the given stream. This -- could be improved on to use different transfer types. respondHTTP :: Stream s => s -> Response_String -> IO () -- | Session-level interactions over HTTP. -- -- The Network.Browser goes beyond the basic Network.HTTP -- functionality in providing support for more involved, and real, -- request/response interactions over HTTP. Additional features supported -- are: -- -- -- -- Example use: -- --
--   do
--     (_, rsp)
--        <- Network.Browser.browse $ do
--              setAllowRedirects True -- handle HTTP redirects
--              request $ getRequest "http://www.haskell.org/"
--     return (take 100 (rspBody rsp))
--   
module Network.Browser -- | BrowserState is the (large) record type tracking the current -- settings of the browser. data BrowserState connection -- | BrowserAction is the IO monad, but carrying along a -- BrowserState. data BrowserAction conn a -- | HTTP proxies (or not) are represented via Proxy, specifying if -- a proxy should be used for the request (see setProxy) data Proxy -- | Don't use a proxy. NoProxy :: Proxy -- | Use the proxy given. Should be of the form "http://host:port", "host", -- "host:port", or "http://host". Additionally, an optional -- Authority for authentication with the proxy. Proxy :: String -> (Maybe Authority) -> Proxy -- | browse act is the toplevel action to perform a -- BrowserAction. Example use: browse (request (getRequest -- yourURL)). browse :: BrowserAction conn a -> IO a -- | request httpRequest tries to submit the Request -- httpRequest to some HTTP server (possibly going via a -- proxy, see setProxy.) Upon successful delivery, the URL -- where the response was fetched from is returned along with the -- Response itself. request :: HStream ty => Request ty -> BrowserAction (HandleStream ty) (URI, Response ty) -- | getBrowserState returns the current browser config. Useful -- for restoring state across BrowserActions. -- | Deprecated: Use Control.Monad.State.get instead. getBrowserState :: BrowserAction t (BrowserState t) -- | withBrowserAction st act performs act with -- BrowserState st. withBrowserState :: BrowserState t -> BrowserAction t a -> BrowserAction t a -- | setAllowRedirects onOff toggles the willingness to follow -- redirects (HTTP responses with 3xx status codes). setAllowRedirects :: Bool -> BrowserAction t () -- | getAllowRedirects returns current setting of the -- do-chase-redirects flag. getAllowRedirects :: BrowserAction t Bool -- | setMaxRedirects maxCount sets the maxiumum number of -- forwarding hops we are willing to jump through. A no-op if the count -- is negative; if zero, the max is set to whatever default applies. -- Notice that setting the max redirects count does not enable -- following of redirects itself; use setAllowRedirects to do so. setMaxRedirects :: Maybe Int -> BrowserAction t () -- | getMaxRedirects returns the current setting for the -- max-redirect count. If Nothing, the Network.Browser's -- default is used. getMaxRedirects :: BrowserAction t (Maybe Int) -- | Authority specifies the HTTP Authentication method to use for -- a given domain/realm; Basic or Digest. data Authority AuthBasic :: String -> String -> String -> URI -> Authority [auRealm] :: Authority -> String [auUsername] :: Authority -> String [auPassword] :: Authority -> String [auSite] :: Authority -> URI AuthDigest :: String -> String -> String -> String -> Maybe Algorithm -> [URI] -> Maybe String -> [Qop] -> Authority [auRealm] :: Authority -> String [auUsername] :: Authority -> String [auPassword] :: Authority -> String [auNonce] :: Authority -> String [auAlgorithm] :: Authority -> Maybe Algorithm [auDomain] :: Authority -> [URI] [auOpaque] :: Authority -> Maybe String [auQop] :: Authority -> [Qop] -- | getAuthorities return the current set of Authoritys -- known to the browser. getAuthorities :: BrowserAction t [Authority] setAuthorities :: [Authority] -> BrowserAction t () addAuthority :: Authority -> BrowserAction t () data Challenge ChalBasic :: String -> Challenge [chRealm] :: Challenge -> String ChalDigest :: String -> [URI] -> String -> Maybe String -> Bool -> Maybe Algorithm -> [Qop] -> Challenge [chRealm] :: Challenge -> String [chDomain] :: Challenge -> [URI] [chNonce] :: Challenge -> String [chOpaque] :: Challenge -> Maybe String [chStale] :: Challenge -> Bool [chAlgorithm] :: Challenge -> Maybe Algorithm [chQop] :: Challenge -> [Qop] data Qop QopAuth :: Qop QopAuthInt :: Qop -- | Algorithm controls the digest algorithm to, MD5 or -- MD5Session. data Algorithm AlgMD5 :: Algorithm AlgMD5sess :: Algorithm -- | getAuthorityGen returns the current authority generator getAuthorityGen :: BrowserAction t (URI -> String -> IO (Maybe (String, String))) -- | setAuthorityGen genAct sets the auth generator to -- genAct. setAuthorityGen :: (URI -> String -> IO (Maybe (String, String))) -> BrowserAction t () -- | setAllowBasicAuth onOff enables/disables HTTP Basic -- Authentication. setAllowBasicAuth :: Bool -> BrowserAction t () getAllowBasicAuth :: BrowserAction t Bool -- | setMaxErrorRetries mbMax sets the maximum number of attempts -- at transmitting a request. If Nothing, rever to default max. setMaxErrorRetries :: Maybe Int -> BrowserAction t () -- | getMaxErrorRetries returns the current max number of error -- retries. getMaxErrorRetries :: BrowserAction t (Maybe Int) -- | setMaxPoolSize maxCount sets the maximum size of the -- connection pool that is used to cache connections between requests setMaxPoolSize :: Maybe Int -> BrowserAction t () -- | getMaxPoolSize gets the maximum size of the connection pool -- that is used to cache connections between requests. If -- Nothing, the Network.Browser's default is used. getMaxPoolSize :: BrowserAction t (Maybe Int) -- | setMaxAuthAttempts mbMax sets the maximum number of -- authentication attempts to do. If Nothing, rever to default -- max. setMaxAuthAttempts :: Maybe Int -> BrowserAction t () -- | getMaxAuthAttempts returns the current max auth attempts. If -- Nothing, the browser's default is used. getMaxAuthAttempts :: BrowserAction t (Maybe Int) -- | setCookieFilter fn sets the cookie acceptance filter to -- fn. setCookieFilter :: (URI -> Cookie -> IO Bool) -> BrowserAction t () -- | getCookieFilter returns the current cookie acceptance filter. getCookieFilter :: BrowserAction t (URI -> Cookie -> IO Bool) -- | defaultCookieFilter is the initial cookie acceptance filter. -- It welcomes them all into the store :-) defaultCookieFilter :: URI -> Cookie -> IO Bool -- | userCookieFilter is a handy acceptance filter, asking the -- user if he/she is willing to accept an incoming cookie before adding -- it to the store. userCookieFilter :: URI -> Cookie -> IO Bool -- | Cookie is the Haskell representation of HTTP cookie values. -- See its relevant specs for authoritative details. data Cookie MkCookie :: String -> String -> String -> Maybe String -> Maybe String -> Maybe String -> Cookie [ckDomain] :: Cookie -> String [ckName] :: Cookie -> String [ckValue] :: Cookie -> String [ckPath] :: Cookie -> Maybe String [ckComment] :: Cookie -> Maybe String [ckVersion] :: Cookie -> Maybe String -- | getCookies returns the current set of cookies known to the -- browser. getCookies :: BrowserAction t [Cookie] -- | setCookies cookies replaces the set of cookies known to the -- browser to cookies. Useful when wanting to restore cookies -- used across browse invocations. setCookies :: [Cookie] -> BrowserAction t () -- | addCookie c adds a cookie to the browser state, removing -- duplicates. addCookie :: Cookie -> BrowserAction t () -- | setErrHandler sets the IO action to call when the browser -- reports running errors. To disable any such, set it to const -- (return ()). setErrHandler :: (String -> IO ()) -> BrowserAction t () -- | setOutHandler sets the IO action to call when the browser -- chatters info on its running. To disable any such, set it to const -- (return ()). setOutHandler :: (String -> IO ()) -> BrowserAction t () -- | setEventHandler onBrowserEvent configures event handling. If -- onBrowserEvent is Nothing, event handling is turned -- off; setting it to Just onEv causes the onEv IO -- action to be notified of browser events during the processing of a -- request by the Browser pipeline. setEventHandler :: Maybe (BrowserEvent -> BrowserAction ty ()) -> BrowserAction ty () -- | BrowserEvent is the event record type that a user-defined -- handler, set via setEventHandler, will be passed. It indicates -- various state changes encountered in the processing of a given -- RequestID, along with timestamps at which they occurred. data BrowserEvent BrowserEvent :: UTCTime -> RequestID -> String -> BrowserEventType -> BrowserEvent [browserTimestamp] :: BrowserEvent -> UTCTime [browserRequestID] :: BrowserEvent -> RequestID [browserRequestURI] :: BrowserEvent -> String [browserEventType] :: BrowserEvent -> BrowserEventType -- | BrowserEventType is the enumerated list of events that the -- browser internals will report to a user-defined event handler. data BrowserEventType OpenConnection :: BrowserEventType ReuseConnection :: BrowserEventType RequestSent :: BrowserEventType ResponseEnd :: ResponseData -> BrowserEventType ResponseFinish :: BrowserEventType type RequestID = Int -- | setProxy p will disable proxy usage if p is -- NoProxy. If p is Proxy proxyURL mbAuth, -- then proxyURL is interpreted as the URL of the proxy to use, -- possibly authenticating via Authority information in -- mbAuth. setProxy :: Proxy -> BrowserAction t () -- | getProxy returns the current proxy settings. If the -- auto-proxy flag is set to True, getProxy will -- perform the necessary getProxy :: BrowserAction t Proxy -- | setCheckForProxy flg sets the one-time check for proxy flag -- to flg. If True, the session will try to determine -- the proxy server is locally configured. See fetchProxy for -- details of how this done. setCheckForProxy :: Bool -> BrowserAction t () -- | getCheckForProxy returns the current check-proxy setting. -- Notice that this may not be equal to True if the session has -- set it to that via setCheckForProxy and subsequently performed -- some HTTP protocol interactions. i.e., the flag return represents -- whether a proxy will be checked for again before any future protocol -- interactions. getCheckForProxy :: BrowserAction t Bool -- | setDebugLog mbFile turns off debug logging iff -- mbFile is Nothing. If set to Just fStem, -- logs of browser activity is appended to files of the form -- fStem-url-authority, i.e., fStem is just the prefix -- for a set of log files, one per host/authority. setDebugLog :: Maybe String -> BrowserAction t () -- | getUserAgent returns the current User-Agent: default -- string. getUserAgent :: BrowserAction t String -- | setUserAgent ua sets the current User-Agent: string -- to ua. It will be used if no explicit user agent header is -- found in subsequent requests. -- -- A common form of user agent string is "name/version -- (details)". For example "cabal-install/0.10.2 (HTTP -- 4000.1.2)". Including the version of this HTTP package can be -- helpful if you ever need to track down HTTP compatability quirks. This -- version is available via httpPackageVersion. For more info see -- http://en.wikipedia.org/wiki/User_agent. setUserAgent :: String -> BrowserAction t () out :: String -> BrowserAction t () err :: String -> BrowserAction t () -- | Lifts an IO action into the BrowserAction monad. -- | Deprecated: Use Control.Monad.Trans.liftIO instead. ioAction :: IO a -> BrowserAction t a defaultGETRequest :: URI -> Request_String defaultGETRequest_ :: BufferType a => URI -> Request a formToRequest :: Form -> Request_String -- | uriDefaultTo a b returns a URI that is consistent with the -- first argument URI a when read in the context of the second -- URI b. If the second argument is not sufficient context for -- determining a full URI then anarchy reins. uriDefaultTo :: URI -> URI -> URI data Form Form :: RequestMethod -> URI -> [FormVar] -> Form type FormVar = (String, String) instance Control.Monad.State.Class.MonadState (Network.Browser.BrowserState conn) (Network.Browser.BrowserAction conn) instance Control.Monad.IO.Class.MonadIO (Network.Browser.BrowserAction conn) instance GHC.Base.Monad (Network.Browser.BrowserAction conn) instance GHC.Base.Applicative (Network.Browser.BrowserAction conn) instance GHC.Base.Functor (Network.Browser.BrowserAction conn) instance GHC.Show.Show (Network.Browser.BrowserState t)