eventlet.green.http package
***************************


Submodules
==========


eventlet.green.http.client module
=================================

HTTP/1.1 client library

<intro stuff goes here> <other stuff, too>

HTTPConnection goes through a number of "states", which define when a
client may legally make another request or fetch the response for a
particular request. This diagram details these state transitions:

      (null)

            HTTPConnection()

         v

      Idle

            putrequest()

         v

      Request-started

            ( putheader() )*  endheaders()

         v

      Request-sent
         >>|<<_____________________________ |
         | getresponse() raises | response = getresponse()     |
         ConnectionError v                              v

      Unread-response                Idle [Response-headers-read]

         >>|<<____________________ |                     | |
         response.read()     | putrequest() v                     v

      Idle                  Req-started-unread-response
            ______/|

         /        |

   response.read() |        | ( putheader() )*  endheaders()
         v        v

      Request-started    Req-sent-unread-response

               response.read()

            v

         Request-sent

This diagram presents the following rules:
   -- a second request may not be started until {response-headers-
   read} -- a response [object] cannot be retrieved until {request-
   sent} -- there is no differentiation between an unread response
   body and a

      partially read response body

Note: this enforcement is applied by the HTTPConnection class. The
   HTTPResponse class does not enforce this state machine, which
   implies sophisticated clients may accelerate the request/response
   pipeline. Caution should be taken, though: accelerating the states
   beyond the above pattern may imply knowledge of the server's
   connection-close behavior for certain requests. For example, it is
   impossible to tell whether the server will close the connection
   UNTIL the response headers have been read; this means that further
   requests cannot be placed into the pipeline until it is known that
   the server will NOT be closing the connection.

Logical State                  __state            __response
-------------                  -------            ---------- Idle
_CS_IDLE           None Request-started                _CS_REQ_STARTED
None Request-sent                   _CS_REQ_SENT       None Unread-
response                _CS_IDLE           <response_class> Req-
started-unread-response    _CS_REQ_STARTED    <response_class> Req-
sent-unread-response       _CS_REQ_SENT       <response_class>

exception eventlet.green.http.client.BadStatusLine(line)

   Bases: "HTTPException"

exception eventlet.green.http.client.CannotSendHeader

   Bases: "ImproperConnectionState"

exception eventlet.green.http.client.CannotSendRequest

   Bases: "ImproperConnectionState"

class eventlet.green.http.client.HTTPConnection(host, port=None, timeout=<object object>, source_address=None)

   Bases: "object"

   auto_open = 1

   close()

      Close the connection to the HTTP server.

   connect()

      Connect to the host and port specified in __init__.

   debuglevel = 0

   default_port = 80

   endheaders(message_body=None, **kwds)

      Indicate that the last header line has been sent to the server.

      This method sends the request to the server.  The optional
      message_body argument can be used to pass a message body
      associated with the request.

   getresponse()

      Get the response from the server.

      If the HTTPConnection is in the correct state, returns an
      instance of HTTPResponse or of whatever object is returned by
      the response_class variable.

      If a request has not been sent or if a previous response has not
      be handled, ResponseNotReady is raised.  If the HTTP response
      indicates that the connection should be closed, then it will be
      closed before the response is returned.  When the connection is
      closed, the underlying socket is closed.

   putheader(header, *values)

      Send a request header line to the server.

      For example: h.putheader('Accept', 'text/html')

   putrequest(method, url, skip_host=0, skip_accept_encoding=0)

      Send a request to the server.

      >>`<<method' specifies an HTTP request method, e.g. 'GET'.
      >>`<<url' specifies the object being requested, e.g.
      '/index.html'. >>`<<skip_host' if True does not add
      automatically a 'Host:' header >>`<<skip_accept_encoding' if
      True does not add automatically an

         'Accept-Encoding:' header

   request(method, url, body=None, headers={}, **kwds)

      Send a complete request to the server.

   response_class

      alias of "HTTPResponse"

   send(data)

      Send *data' to the server. ``data`* can be a string object, a
      bytes object, an array object, a file-like object that supports
      a .read() method, or an iterable object.

   set_debuglevel(level)

   set_tunnel(host, port=None, headers=None)

      Set up host and port for HTTP CONNECT tunnelling.

      In a connection that uses HTTP CONNECT tunneling, the host
      passed to the constructor is used as a proxy server that relays
      all communication to the endpoint passed to *set_tunnel*. This
      done by sending an HTTP CONNECT request to the proxy server when
      the connection is established.

      This method must be called before the HTML connection has been
      established.

      The headers argument should be a mapping of extra HTTP headers
      to send with the CONNECT request.

exception eventlet.green.http.client.HTTPException

   Bases: "Exception"

class eventlet.green.http.client.HTTPResponse(sock, debuglevel=0, method=None, url=None)

   Bases: "BufferedIOBase"

   begin()

   close()

      Flush and close the IO object.

      This method has no effect if the file is already closed.

   fileno()

      Return underlying file descriptor if one exists.

      Raise OSError if the IO object does not use a file descriptor.

   flush()

      Flush write buffers, if applicable.

      This is not implemented for read-only and non-blocking streams.

   getcode()

      Return the HTTP status code that was sent with the response, or
      None if the URL is not an HTTP URL.

   getheader(name, default=None)

      Returns the value of the header matching *name*.

      If there are multiple matching headers, the values are combined
      into a single string separated by commas and spaces.

      If no matching header is found, returns *default* or None if the
      *default* is not specified.

      If the headers are unknown, raises http.client.ResponseNotReady.

   getheaders()

      Return list of (header, value) tuples.

   geturl()

      Return the real URL of the page.

      In some cases, the HTTP server redirects a client to another
      URL. The urlopen() function handles this transparently, but in
      some cases the caller needs to know which URL the client was
      redirected to. The geturl() method can be used to get at this
      redirected URL.

   info()

      Returns an instance of the class mimetools.Message containing
      meta-information associated with the URL.

      When the method is HTTP, these headers are those returned by the
      server at the head of the retrieved HTML page (including
      Content-Length and Content-Type).

      When the method is FTP, a Content-Length header will be present
      if (as is now usual) the server passed back a file length in
      response to the FTP retrieval request. A Content-Type header
      will be present if the MIME type can be guessed.

      When the method is local-file, returned headers will include a
      Date representing the file's last-modified time, a Content-
      Length giving file size, and a Content-Type containing a guess
      at the file's type. See also the description of the mimetools
      module.

   isclosed()

      True if the connection is closed.

   peek(n=-1)

   read(amt=None)

      Read and return up to n bytes.

      If the size argument is omitted, None, or negative, read and
      return all data until EOF.

      If the size argument is positive, and the underlying raw stream
      is not 'interactive', multiple raw reads may be issued to
      satisfy the byte count (unless EOF is reached first). However,
      for interactive raw streams (as well as sockets and pipes), at
      most one raw read will be issued, and a short result does not
      imply that EOF is imminent.

      Return an empty bytes object on EOF.

      Return None if the underlying raw stream was open in non-
      blocking mode and no data is available at the moment.

   read1(n=-1)

      Read with at most one underlying system call.  If at least one
      byte is buffered, return that instead.

   readable()

      Always returns True

   readinto(b)

      Read up to len(b) bytes into bytearray b and return the number
      of bytes read.

   readline(limit=-1)

      Read and return a line from the stream.

      If size is specified, at most size bytes will be read.

      The line terminator is always b'n' for binary files; for text
      files, the newlines argument to open can be used to select the
      line terminator(s) recognized.

class eventlet.green.http.client.HTTPSConnection(host, port=None, key_file=None, cert_file=None, timeout=<object object>, source_address=None, *, context=None, check_hostname=None)

   Bases: "HTTPConnection"

   This class allows communication via SSL.

   connect()

      Connect to a host on a given (SSL) port.

   default_port = 443

exception eventlet.green.http.client.ImproperConnectionState

   Bases: "HTTPException"

exception eventlet.green.http.client.IncompleteRead(partial, expected=None)

   Bases: "HTTPException"

exception eventlet.green.http.client.InvalidURL

   Bases: "HTTPException"

exception eventlet.green.http.client.LineTooLong(line_type)

   Bases: "HTTPException"

exception eventlet.green.http.client.NotConnected

   Bases: "HTTPException"

exception eventlet.green.http.client.RemoteDisconnected(*pos, **kw)

   Bases: "ConnectionResetError", "BadStatusLine"

exception eventlet.green.http.client.ResponseNotReady

   Bases: "ImproperConnectionState"

exception eventlet.green.http.client.UnimplementedFileMode

   Bases: "HTTPException"

exception eventlet.green.http.client.UnknownProtocol(version)

   Bases: "HTTPException"

exception eventlet.green.http.client.UnknownTransferEncoding

   Bases: "HTTPException"

eventlet.green.http.client.error

   alias of "HTTPException"


eventlet.green.http.cookiejar module
====================================

HTTP cookie handling for web clients.

This module has (now fairly distant) origins in Gisle Aas' Perl module
HTTP::Cookies, from the libwww-perl library.

Docstrings, comments and debug strings in this code refer to the
attributes of the HTTP cookie system as cookie-attributes, to
distinguish them clearly from Python attributes.

Class diagram (note that BSDDBCookieJar and the MSIE* classes are not
distributed with the Python standard library, but are available from
http://wwwsearch.sf.net/):

         CookieJar____ /

      FileCookieJar
         /    |

   MozillaCookieJar | LWPCookieJar
                     |      
                  ---MSIEBase |       
               /      |     |        
            /   MSIEDBCookieJar BSDDBCookieJar

         >>|<</

      MSIECookieJar

class eventlet.green.http.cookiejar.Cookie(version, name, value, port, port_specified, domain, domain_specified, domain_initial_dot, path, path_specified, secure, expires, discard, comment, comment_url, rest, rfc2109=False)

   Bases: "object"

   HTTP Cookie.

   This class represents both Netscape and RFC 2965 cookies.

   This is deliberately a very simple class.  It just holds
   attributes.  It's possible to construct Cookie instances that don't
   comply with the cookie standards.  CookieJar.make_cookies is the
   factory function for Cookie objects -- it deals with cookie
   parsing, supplying defaults, and normalising to the representation
   used in this class.  CookiePolicy is responsible for checking them
   to see whether they should be accepted from and returned to the
   server.

   Note that the port may be present in the headers, but unspecified
   ("Port" rather than"Port=80", for example); if this is the case,
   port is None.

   get_nonstandard_attr(name, default=None)

   has_nonstandard_attr(name)

   is_expired(now=None)

   set_nonstandard_attr(name, value)

class eventlet.green.http.cookiejar.CookieJar(policy=None)

   Bases: "object"

   Collection of HTTP cookies.

   You may not need to know about this class: try
   urllib.request.build_opener(HTTPCookieProcessor).open(url).

   add_cookie_header(request)

      Add correct Cookie: header to request (urllib.request.Request
      object).

      The Cookie2 header is also added unless policy.hide_cookie2 is
      true.

   clear(domain=None, path=None, name=None)

      Clear some cookies.

      Invoking this method without arguments will clear all cookies.
      If given a single argument, only cookies belonging to that
      domain will be removed.  If given two arguments, cookies
      belonging to the specified path within that domain are removed.
      If given three arguments, then the cookie with the specified
      name, path and domain is removed.

      Raises KeyError if no matching cookie exists.

   clear_expired_cookies()

      Discard all expired cookies.

      You probably don't need to call this method: expired cookies are
      never sent back to the server (provided you're using
      DefaultCookiePolicy), this method is called by CookieJar itself
      every so often, and the .save() method won't save expired
      cookies anyway (unless you ask otherwise by passing a true
      ignore_expires argument).

   clear_session_cookies()

      Discard all session cookies.

      Note that the .save() method won't save session cookies anyway,
      unless you ask otherwise by passing a true ignore_discard
      argument.

   domain_re = re.compile('[^.]*')

   dots_re = re.compile('^\\.+')

   extract_cookies(response, request)

      Extract cookies from response, where allowable given the
      request.

   magic_re = re.compile('^\\#LWP-Cookies-(\\d+\\.\\d+)', re.ASCII)

   make_cookies(response, request)

      Return sequence of Cookie objects extracted from response
      object.

   non_word_re = re.compile('\\W')

   quote_re = re.compile('([\\"\\\\])')

   set_cookie(cookie)

      Set a cookie, without checking whether or not it should be set.

   set_cookie_if_ok(cookie, request)

      Set a cookie if policy says it's OK to do so.

   set_policy(policy)

   strict_domain_re = re.compile('\\.?[^.]*')

class eventlet.green.http.cookiejar.CookiePolicy

   Bases: "object"

   Defines which cookies get accepted from and returned to server.

   May also modify cookies, though this is probably a bad idea.

   The subclass DefaultCookiePolicy defines the standard rules for
   Netscape and RFC 2965 cookies -- override that if you want a
   customised policy.

   domain_return_ok(domain, request)

      Return false if cookies should not be returned, given cookie
      domain.

   path_return_ok(path, request)

      Return false if cookies should not be returned, given cookie
      path.

   return_ok(cookie, request)

      Return true if (and only if) cookie should be returned to
      server.

   set_ok(cookie, request)

      Return true if (and only if) cookie should be accepted from
      server.

      Currently, pre-expired cookies never get this far -- the
      CookieJar class deletes such cookies itself.

class eventlet.green.http.cookiejar.DefaultCookiePolicy(blocked_domains=None, allowed_domains=None, netscape=True, rfc2965=False, rfc2109_as_netscape=None, hide_cookie2=False, strict_domain=False, strict_rfc2965_unverifiable=True, strict_ns_unverifiable=False, strict_ns_domain=0, strict_ns_set_initial_dollar=False, strict_ns_set_path=False)

   Bases: "CookiePolicy"

   Implements the standard rules for accepting and returning cookies.

   DomainLiberal = 0

   DomainRFC2965Match = 4

   DomainStrict = 3

   DomainStrictNoDots = 1

   DomainStrictNonDomain = 2

   allowed_domains()

      Return None, or the sequence of allowed domains (as a tuple).

   blocked_domains()

      Return the sequence of blocked domains (as a tuple).

   domain_return_ok(domain, request)

      Return false if cookies should not be returned, given cookie
      domain.

   is_blocked(domain)

   is_not_allowed(domain)

   path_return_ok(path, request)

      Return false if cookies should not be returned, given cookie
      path.

   return_ok(cookie, request)

      If you override .return_ok(), be sure to call this method.  If
      it returns false, so should your subclass (assuming your
      subclass wants to be more strict about which cookies to return).

   return_ok_domain(cookie, request)

   return_ok_expires(cookie, request)

   return_ok_port(cookie, request)

   return_ok_secure(cookie, request)

   return_ok_verifiability(cookie, request)

   return_ok_version(cookie, request)

   set_allowed_domains(allowed_domains)

      Set the sequence of allowed domains, or None.

   set_blocked_domains(blocked_domains)

      Set the sequence of blocked domains.

   set_ok(cookie, request)

      If you override .set_ok(), be sure to call this method.  If it
      returns false, so should your subclass (assuming your subclass
      wants to be more strict about which cookies to accept).

   set_ok_domain(cookie, request)

   set_ok_name(cookie, request)

   set_ok_path(cookie, request)

   set_ok_port(cookie, request)

   set_ok_verifiability(cookie, request)

   set_ok_version(cookie, request)

class eventlet.green.http.cookiejar.FileCookieJar(filename=None, delayload=False, policy=None)

   Bases: "CookieJar"

   CookieJar that can be loaded from and saved to a file.

   load(filename=None, ignore_discard=False, ignore_expires=False)

      Load cookies from a file.

   revert(filename=None, ignore_discard=False, ignore_expires=False)

      Clear all cookies and reload cookies from a saved file.

      Raises LoadError (or OSError) if reversion is not successful;
      the object's state will not be altered if this happens.

   save(filename=None, ignore_discard=False, ignore_expires=False)

      Save cookies to a file.

class eventlet.green.http.cookiejar.LWPCookieJar(filename=None, delayload=False, policy=None)

   Bases: "FileCookieJar"

   The LWPCookieJar saves a sequence of "Set-Cookie3" lines. "Set-
   Cookie3" is the format used by the libwww-perl library, not known
   to be compatible with any browser, but which is easy to read and
   doesn't lose information about RFC 2965 cookies.

   Additional methods

   as_lwp_str(ignore_discard=True, ignore_expired=True)

   as_lwp_str(ignore_discard=True, ignore_expires=True)

      Return cookies as a string of "n"-separated "Set-Cookie3"
      headers.

      ignore_discard and ignore_expires: see docstring for
      FileCookieJar.save

   save(filename=None, ignore_discard=False, ignore_expires=False)

      Save cookies to a file.

exception eventlet.green.http.cookiejar.LoadError

   Bases: "OSError"

class eventlet.green.http.cookiejar.MozillaCookieJar(filename=None, delayload=False, policy=None)

   Bases: "FileCookieJar"

   WARNING: you may want to backup your browser's cookies file if you
   use this class to save cookies.  I *think* it works, but there have
   been bugs in the past!

   This class differs from CookieJar only in the format it uses to
   save and load cookies to and from a file.  This class uses the
   Mozilla/Netscape >>`<<cookies.txt' format.  lynx uses this file
   format, too.

   Don't expect cookies saved while the browser is running to be
   noticed by the browser (in fact, Mozilla on unix will overwrite
   your saved cookies if you change them on disk while it's running;
   on Windows, you probably can't save at all while the browser is
   running).

   Note that the Mozilla/Netscape format will downgrade RFC2965
   cookies to Netscape cookies on saving.

   In particular, the cookie version and port number information is
   lost, together with information about whether or not Path, Port and
   Discard were specified by the Set-Cookie2 (or Set-Cookie) header,
   and whether or not the domain as set in the HTTP header started
   with a dot (yes, I'm aware some domains in Netscape files start
   with a dot and some don't -- trust me, you really don't want to
   know any more about this).

   Note that though Mozilla and Netscape use the same format, they use
   slightly different headers.  The class saves cookies using the
   Netscape header by default (Mozilla can cope with that).

   header = '# Netscape HTTP Cookie File\n# http://curl.haxx.se/rfc/cookie_spec.html\n# This is a generated file!  Do not edit.\n\n'

   magic_re = re.compile('#( Netscape)? HTTP Cookie File')

   save(filename=None, ignore_discard=False, ignore_expires=False)

      Save cookies to a file.


eventlet.green.http.cookies module
==================================


eventlet.green.http.server module
=================================

HTTP server classes.

Note: BaseHTTPRequestHandler doesn't implement any HTTP request; see
SimpleHTTPRequestHandler for simple implementations of GET, HEAD and
POST, and CGIHTTPRequestHandler for CGI scripts.

It does, however, optionally implement HTTP/1.1 persistent
connections, as of version 0.3.


Notes on CGIHTTPRequestHandler
------------------------------

This class implements GET and POST requests to cgi-bin scripts.

If the os.fork() function is not present (e.g. on Windows),
subprocess.Popen() is used as a fallback, with slightly altered
semantics.

In all cases, the implementation is intentionally naive -- all
requests are executed synchronously.

SECURITY WARNING: DON'T USE THIS CODE UNLESS YOU ARE INSIDE A FIREWALL
-- it may execute arbitrary Python code or external programs.

Note that status code 200 is sent prior to execution of a CGI script,
so scripts cannot send other status codes such as 302 (redirect).

XXX To do:

* log requests even later (to capture byte count)

* log user-agent header and other interesting goodies

* send error log to separate file

class eventlet.green.http.server.BaseHTTPRequestHandler(request, client_address, server)

   Bases: "StreamRequestHandler"

   HTTP request handler base class.

   The following explanation of HTTP serves to guide you through the
   code as well as to expose any misunderstandings I may have about
   HTTP (so you don't need to read the code to figure out I'm wrong
   :-).

   HTTP (HyperText Transfer Protocol) is an extensible protocol on top
   of a reliable stream transport (e.g. TCP/IP).  The protocol
   recognizes three parts to a request:

   1. One line identifying the request type and path

   2. An optional set of RFC-822-style headers

   3. An optional data part

   The headers and data are separated by a blank line.

   The first line of the request has the form

   <command> <path> <version>

   where <command> is a (case-sensitive) keyword such as GET or POST,
   <path> is a string containing path information for the request, and
   <version> should be the string "HTTP/1.0" or "HTTP/1.1". <path> is
   encoded using the URL encoding scheme (using %xx to signify the
   ASCII character with hex code xx).

   The specification specifies that lines are separated by CRLF but
   for compatibility with the widest range of clients recommends
   servers also handle LF.  Similarly, whitespace in the request line
   is treated sensibly (allowing multiple spaces between components
   and allowing trailing whitespace).

   Similarly, for output, lines ought to be separated by CRLF pairs
   but most clients grok LF characters just fine.

   If the first line of the request has the form

   <command> <path>

   (i.e. <version> is left out) then this is assumed to be an HTTP 0.9
   request; this form has no optional headers and data part and the
   reply consists of just the data.

   The reply form of the HTTP 1.x protocol again has three parts:

   1. One line giving the response code

   2. An optional set of RFC-822-style headers

   3. The data

   Again, the headers and data are separated by a blank line.

   The response code line has the form

   <version> <responsecode> <responsestring>

   where <version> is the protocol version ("HTTP/1.0" or "HTTP/1.1"),
   <responsecode> is a 3-digit response code indicating success or
   failure of the request, and <responsestring> is an optional human-
   readable string explaining what the response code means.

   This server parses the request and the headers, and then calls a
   function specific to the request type (<command>).  Specifically, a
   request SPAM will be handled by a method do_SPAM().  If no such
   method exists the server sends an error response to the client.  If
   it exists, it is called with no arguments:

   do_SPAM()

   Note that the request name is case sensitive (i.e. SPAM and spam
   are different requests).

   The various request details are stored in instance variables:

   * client_address is the client IP address in the form (host,

   port);

   * command, path and version are the broken-down request line;

   * headers is an instance of email.message.Message (or a derived

   class) containing the header information;

   * rfile is a file object open for reading positioned at the

   start of the optional input data part;

   * wfile is a file object open for writing.

   IT IS IMPORTANT TO ADHERE TO THE PROTOCOL FOR WRITING!

   The first thing to be written must be the response line.  Then
   follow 0 or more header lines, then a blank line, and then the
   actual data (if any).  The meaning of the header lines depends on
   the command executed by the server; in most cases, when data is
   returned, there should be at least one header line of the form

   Content-type: <type>/<subtype>

   where <type> and <subtype> should be registered MIME types, e.g.
   "text/html" or "text/plain".

   MessageClass

      alias of "HTTPMessage"

   address_string()

      Return the client address.

   date_time_string(timestamp=None)

      Return the current date and time formatted for a message header.

   default_request_version = 'HTTP/0.9'

   end_headers()

      Send the blank line ending the MIME headers.

   error_content_type = 'text/html;charset=utf-8'

   error_message_format = '<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"\n        "http://www.w3.org/TR/html4/strict.dtd">\n<html>\n    <head>\n        <meta http-equiv="Content-Type" content="text/html;charset=utf-8">\n        <title>Error response</title>\n    </head>\n    <body>\n        <h1>Error response</h1>\n        <p>Error code: %(code)d</p>\n        <p>Message: %(message)s.</p>\n        <p>Error code explanation: %(code)s - %(explain)s.</p>\n    </body>\n</html>\n'

   flush_headers()

   handle()

      Handle multiple requests if necessary.

   handle_expect_100()

      Decide what to do with an "Expect: 100-continue" header.

      If the client is expecting a 100 Continue response, we must
      respond with either a 100 Continue or a final response before
      waiting for the request body. The default is to always respond
      with a 100 Continue. You can behave differently (for example,
      reject unauthorized requests) by overriding this method.

      This method should either return True (possibly after sending a
      100 Continue response) or send an error response and return
      False.

   handle_one_request()

      Handle a single HTTP request.

      You normally don't need to override this method; see the class
      __doc__ string for information on how to handle specific HTTP
      commands such as GET and POST.

   log_date_time_string()

      Return the current time formatted for logging.

   log_error(format, *args)

      Log an error.

      This is called when a request cannot be fulfilled.  By default
      it passes the message on to log_message().

      Arguments are the same as for log_message().

      XXX This should go to the separate error log.

   log_message(format, *args)

      Log an arbitrary message.

      This is used by all other logging functions.  Override it if you
      have specific logging wishes.

      The first argument, FORMAT, is a format string for the message
      to be logged.  If the format string contains any % escapes
      requiring parameters, they should be specified as subsequent
      arguments (it's just like printf!).

      The client ip and current date/time are prefixed to every
      message.

   log_request(code='-', size='-')

      Log an accepted request.

      This is called by send_response().

   monthname = [None, 'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']

   parse_request()

      Parse a request (internal).

      The request should be stored in self.raw_requestline; the
      results are in self.command, self.path, self.request_version and
      self.headers.

      Return True for success, False for failure; on failure, an error
      is sent back.

   protocol_version = 'HTTP/1.0'

   responses = {HTTPStatus.CONTINUE: ('Continue', 'Request received, please continue'), HTTPStatus.SWITCHING_PROTOCOLS: ('Switching Protocols', 'Switching to new protocol; obey Upgrade header'), HTTPStatus.PROCESSING: ('Processing', ''), HTTPStatus.OK: ('OK', 'Request fulfilled, document follows'), HTTPStatus.CREATED: ('Created', 'Document created, URL follows'), HTTPStatus.ACCEPTED: ('Accepted', 'Request accepted, processing continues off-line'), HTTPStatus.NON_AUTHORITATIVE_INFORMATION: ('Non-Authoritative Information', 'Request fulfilled from cache'), HTTPStatus.NO_CONTENT: ('No Content', 'Request fulfilled, nothing follows'), HTTPStatus.RESET_CONTENT: ('Reset Content', 'Clear input form for further input'), HTTPStatus.PARTIAL_CONTENT: ('Partial Content', 'Partial content follows'), HTTPStatus.MULTI_STATUS: ('Multi-Status', ''), HTTPStatus.ALREADY_REPORTED: ('Already Reported', ''), HTTPStatus.IM_USED: ('IM Used', ''), HTTPStatus.MULTIPLE_CHOICES: ('Multiple Choices', 'Object has several resources -- see URI list'), HTTPStatus.MOVED_PERMANENTLY: ('Moved Permanently', 'Object moved permanently -- see URI list'), HTTPStatus.FOUND: ('Found', 'Object moved temporarily -- see URI list'), HTTPStatus.SEE_OTHER: ('See Other', 'Object moved -- see Method and URL list'), HTTPStatus.NOT_MODIFIED: ('Not Modified', 'Document has not changed since given time'), HTTPStatus.USE_PROXY: ('Use Proxy', 'You must use proxy specified in Location to access this resource'), HTTPStatus.TEMPORARY_REDIRECT: ('Temporary Redirect', 'Object moved temporarily -- see URI list'), HTTPStatus.PERMANENT_REDIRECT: ('Permanent Redirect', 'Object moved temporarily -- see URI list'), HTTPStatus.BAD_REQUEST: ('Bad Request', 'Bad request syntax or unsupported method'), HTTPStatus.UNAUTHORIZED: ('Unauthorized', 'No permission -- see authorization schemes'), HTTPStatus.PAYMENT_REQUIRED: ('Payment Required', 'No payment -- see charging schemes'), HTTPStatus.FORBIDDEN: ('Forbidden', 'Request forbidden -- authorization will not help'), HTTPStatus.NOT_FOUND: ('Not Found', 'Nothing matches the given URI'), HTTPStatus.METHOD_NOT_ALLOWED: ('Method Not Allowed', 'Specified method is invalid for this resource'), HTTPStatus.NOT_ACCEPTABLE: ('Not Acceptable', 'URI not available in preferred format'), HTTPStatus.PROXY_AUTHENTICATION_REQUIRED: ('Proxy Authentication Required', 'You must authenticate with this proxy before proceeding'), HTTPStatus.REQUEST_TIMEOUT: ('Request Timeout', 'Request timed out; try again later'), HTTPStatus.CONFLICT: ('Conflict', 'Request conflict'), HTTPStatus.GONE: ('Gone', 'URI no longer exists and has been permanently removed'), HTTPStatus.LENGTH_REQUIRED: ('Length Required', 'Client must specify Content-Length'), HTTPStatus.PRECONDITION_FAILED: ('Precondition Failed', 'Precondition in headers is false'), HTTPStatus.REQUEST_ENTITY_TOO_LARGE: ('Request Entity Too Large', 'Entity is too large'), HTTPStatus.REQUEST_URI_TOO_LONG: ('Request-URI Too Long', 'URI is too long'), HTTPStatus.UNSUPPORTED_MEDIA_TYPE: ('Unsupported Media Type', 'Entity body in unsupported format'), HTTPStatus.REQUESTED_RANGE_NOT_SATISFIABLE: ('Requested Range Not Satisfiable', 'Cannot satisfy request range'), HTTPStatus.EXPECTATION_FAILED: ('Expectation Failed', 'Expect condition could not be satisfied'), HTTPStatus.UNPROCESSABLE_ENTITY: ('Unprocessable Entity', ''), HTTPStatus.LOCKED: ('Locked', ''), HTTPStatus.FAILED_DEPENDENCY: ('Failed Dependency', ''), HTTPStatus.UPGRADE_REQUIRED: ('Upgrade Required', ''), HTTPStatus.PRECONDITION_REQUIRED: ('Precondition Required', 'The origin server requires the request to be conditional'), HTTPStatus.TOO_MANY_REQUESTS: ('Too Many Requests', 'The user has sent too many requests in a given amount of time ("rate limiting")'), HTTPStatus.REQUEST_HEADER_FIELDS_TOO_LARGE: ('Request Header Fields Too Large', 'The server is unwilling to process the request because its header fields are too large'), HTTPStatus.INTERNAL_SERVER_ERROR: ('Internal Server Error', 'Server got itself in trouble'), HTTPStatus.NOT_IMPLEMENTED: ('Not Implemented', 'Server does not support this operation'), HTTPStatus.BAD_GATEWAY: ('Bad Gateway', 'Invalid responses from another server/proxy'), HTTPStatus.SERVICE_UNAVAILABLE: ('Service Unavailable', 'The server cannot process the request due to a high load'), HTTPStatus.GATEWAY_TIMEOUT: ('Gateway Timeout', 'The gateway server did not receive a timely response'), HTTPStatus.HTTP_VERSION_NOT_SUPPORTED: ('HTTP Version Not Supported', 'Cannot fulfill request'), HTTPStatus.VARIANT_ALSO_NEGOTIATES: ('Variant Also Negotiates', ''), HTTPStatus.INSUFFICIENT_STORAGE: ('Insufficient Storage', ''), HTTPStatus.LOOP_DETECTED: ('Loop Detected', ''), HTTPStatus.NOT_EXTENDED: ('Not Extended', ''), HTTPStatus.NETWORK_AUTHENTICATION_REQUIRED: ('Network Authentication Required', 'The client needs to authenticate to gain network access')}

   send_error(code, message=None, explain=None)

      Send and log an error reply.

      Arguments are * code:    an HTTP error code

         3 digits

      * message: a simple optional 1 line reason phrase.
           >>*<<( HTAB / SP / VCHAR / %x80-FF ) defaults to short
           entry matching the response code

      * explain: a detailed message defaults to the long entry
           matching the response code.

      This sends an error response (so it must be called before any
      output has been generated), logs the error, and finally sends a
      piece of HTML explaining the error to the user.

   send_header(keyword, value)

      Send a MIME header to the headers buffer.

   send_response(code, message=None)

      Add the response header to the headers buffer and log the
      response code.

      Also send two standard headers with the server software version
      and the current date.

   send_response_only(code, message=None)

      Send the response header only.

   server_version = 'BaseHTTP/0.6'

   sys_version = 'Python/3.13.3'

   version_string()

      Return the server software version string.

   weekdayname = ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun']

class eventlet.green.http.server.CGIHTTPRequestHandler(request, client_address, server)

   Bases: "SimpleHTTPRequestHandler"

   Complete HTTP server with GET, HEAD and POST commands.

   GET and HEAD also support running CGI scripts.

   The POST command is *only* implemented for CGI scripts.

   cgi_directories = ['/cgi-bin', '/htbin']

   do_POST()

      Serve a POST request.

      This is only implemented for CGI scripts.

   have_fork = True

   is_cgi()

      Test whether self.path corresponds to a CGI script.

      Returns True and updates the cgi_info attribute to the tuple
      (dir, rest) if self.path requires running a CGI script. Returns
      False otherwise.

      If any exception is raised, the caller should assume that
      self.path was rejected as invalid and act accordingly.

      The default implementation tests whether the normalized url path
      begins with one of the strings in self.cgi_directories (and the
      next character is a '/' or the end of the string).

   is_executable(path)

      Test whether argument path is an executable file.

   is_python(path)

      Test whether argument path is a Python script.

   rbufsize = 0

   run_cgi()

      Execute a CGI script.

   send_head()

      Version of send_head that support CGI scripts

class eventlet.green.http.server.HTTPServer(server_address, RequestHandlerClass, bind_and_activate=True)

   Bases: "TCPServer"

   allow_reuse_address = 1

   server_bind()

      Override server_bind to store the server name.

class eventlet.green.http.server.SimpleHTTPRequestHandler(request, client_address, server)

   Bases: "BaseHTTPRequestHandler"

   Simple HTTP request handler with GET and HEAD commands.

   This serves files from the current directory and any of its
   subdirectories.  The MIME type for files is determined by calling
   the .guess_type() method.

   The GET and HEAD requests are identical except that the HEAD
   request omits the actual contents of the file.

   copyfile(source, outputfile)

      Copy all data between two file objects.

      The SOURCE argument is a file object open for reading (or
      anything with a read() method) and the DESTINATION argument is a
      file object open for writing (or anything with a write()
      method).

      The only reason for overriding this would be to change the block
      size or perhaps to replace newlines by CRLF -- note however that
      this the default server uses this to copy binary data as well.

   do_GET()

      Serve a GET request.

   do_HEAD()

      Serve a HEAD request.

   extensions_map = {'': 'application/octet-stream', '.3g2': 'audio/3gpp2', '.3gp': 'audio/3gpp', '.3gpp': 'audio/3gpp', '.3gpp2': 'audio/3gpp2', '.a': 'application/octet-stream', '.aac': 'audio/aac', '.adts': 'audio/aac', '.ai': 'application/postscript', '.aif': 'audio/x-aiff', '.aifc': 'audio/x-aiff', '.aiff': 'audio/x-aiff', '.ass': 'audio/aac', '.au': 'audio/basic', '.avi': 'video/x-msvideo', '.avif': 'image/avif', '.bat': 'text/plain', '.bcpio': 'application/x-bcpio', '.bin': 'application/octet-stream', '.bmp': 'image/bmp', '.c': 'text/plain', '.cdf': 'application/x-netcdf', '.cpio': 'application/x-cpio', '.csh': 'application/x-csh', '.css': 'text/css', '.csv': 'text/csv', '.dll': 'application/octet-stream', '.doc': 'application/msword', '.dot': 'application/msword', '.dvi': 'application/x-dvi', '.eml': 'message/rfc822', '.eps': 'application/postscript', '.etx': 'text/x-setext', '.exe': 'application/octet-stream', '.gif': 'image/gif', '.gtar': 'application/x-gtar', '.h': 'text/plain', '.h5': 'application/x-hdf5', '.hdf': 'application/x-hdf', '.heic': 'image/heic', '.heif': 'image/heif', '.htm': 'text/html', '.html': 'text/html', '.ico': 'image/vnd.microsoft.icon', '.ief': 'image/ief', '.jpe': 'image/jpeg', '.jpeg': 'image/jpeg', '.jpg': 'image/jpeg', '.js': 'text/javascript', '.json': 'application/json', '.ksh': 'text/plain', '.latex': 'application/x-latex', '.loas': 'audio/aac', '.m1v': 'video/mpeg', '.m3u': 'application/vnd.apple.mpegurl', '.m3u8': 'application/vnd.apple.mpegurl', '.man': 'application/x-troff-man', '.markdown': 'text/markdown', '.md': 'text/markdown', '.me': 'application/x-troff-me', '.mht': 'message/rfc822', '.mhtml': 'message/rfc822', '.mif': 'application/x-mif', '.mjs': 'text/javascript', '.mov': 'video/quicktime', '.movie': 'video/x-sgi-movie', '.mp2': 'audio/mpeg', '.mp3': 'audio/mpeg', '.mp4': 'video/mp4', '.mpa': 'video/mpeg', '.mpe': 'video/mpeg', '.mpeg': 'video/mpeg', '.mpg': 'video/mpeg', '.ms': 'application/x-troff-ms', '.n3': 'text/n3', '.nc': 'application/x-netcdf', '.nq': 'application/n-quads', '.nt': 'application/n-triples', '.nws': 'message/rfc822', '.o': 'application/octet-stream', '.obj': 'application/octet-stream', '.oda': 'application/oda', '.opus': 'audio/opus', '.p12': 'application/x-pkcs12', '.p7c': 'application/pkcs7-mime', '.pbm': 'image/x-portable-bitmap', '.pdf': 'application/pdf', '.pfx': 'application/x-pkcs12', '.pgm': 'image/x-portable-graymap', '.pl': 'text/plain', '.png': 'image/png', '.pnm': 'image/x-portable-anymap', '.pot': 'application/vnd.ms-powerpoint', '.ppa': 'application/vnd.ms-powerpoint', '.ppm': 'image/x-portable-pixmap', '.pps': 'application/vnd.ms-powerpoint', '.ppt': 'application/vnd.ms-powerpoint', '.ps': 'application/postscript', '.pwz': 'application/vnd.ms-powerpoint', '.py': 'text/plain', '.pyc': 'application/x-python-code', '.pyo': 'application/x-python-code', '.qt': 'video/quicktime', '.ra': 'audio/x-pn-realaudio', '.ram': 'application/x-pn-realaudio', '.ras': 'image/x-cmu-raster', '.rdf': 'application/xml', '.rgb': 'image/x-rgb', '.roff': 'application/x-troff', '.rst': 'text/x-rst', '.rtf': 'text/rtf', '.rtx': 'text/richtext', '.sgm': 'text/x-sgml', '.sgml': 'text/x-sgml', '.sh': 'application/x-sh', '.shar': 'application/x-shar', '.snd': 'audio/basic', '.so': 'application/octet-stream', '.src': 'application/x-wais-source', '.srt': 'text/plain', '.sv4cpio': 'application/x-sv4cpio', '.sv4crc': 'application/x-sv4crc', '.svg': 'image/svg+xml', '.swf': 'application/x-shockwave-flash', '.t': 'application/x-troff', '.tar': 'application/x-tar', '.tcl': 'application/x-tcl', '.tex': 'application/x-tex', '.texi': 'application/x-texinfo', '.texinfo': 'application/x-texinfo', '.tif': 'image/tiff', '.tiff': 'image/tiff', '.tr': 'application/x-troff', '.trig': 'application/trig', '.tsv': 'text/tab-separated-values', '.txt': 'text/plain', '.ustar': 'application/x-ustar', '.vcf': 'text/x-vcard', '.vtt': 'text/vtt', '.wasm': 'application/wasm', '.wav': 'audio/x-wav', '.webm': 'video/webm', '.webmanifest': 'application/manifest+json', '.webp': 'image/webp', '.wiz': 'application/msword', '.wsdl': 'application/xml', '.xbm': 'image/x-xbitmap', '.xlb': 'application/vnd.ms-excel', '.xls': 'application/vnd.ms-excel', '.xml': 'text/xml', '.xpdl': 'application/xml', '.xpm': 'image/x-xpixmap', '.xsl': 'application/xml', '.xwd': 'image/x-xwindowdump', '.zip': 'application/zip'}

   guess_type(path)

      Guess the type of a file.

      Argument is a PATH (a filename).

      Return value is a string of the form type/subtype, usable for a
      MIME Content-type header.

      The default implementation looks the file's extension up in the
      table self.extensions_map, using application/octet-stream as a
      default; however it would be permissible (if slow) to look
      inside the data to make a better guess.

   list_directory(path)

      Helper to produce a directory listing (absent index.html).

      Return value is either a file object, or None (indicating an
      error).  In either case, the headers are sent, making the
      interface the same as for send_head().

   send_head()

      Common code for GET and HEAD commands.

      This sends the response code and MIME headers.

      Return value is either a file object (which has to be copied to
      the outputfile by the caller unless the command was HEAD, and
      must be closed by the caller under all circumstances), or None,
      in which case the caller has nothing further to do.

   server_version = 'SimpleHTTP/0.6'

   translate_path(path)

      Translate a /-separated PATH to the local filename syntax.

      Components that mean special things to the local file system
      (e.g. drive or directory names) are ignored.  (XXX They should
      probably be diagnosed.)


Module contents
===============

class eventlet.green.http.HTTPStatus(*values)

   Bases: "IntEnum"

   HTTP status codes and reason phrases

   Status codes from the following RFCs are all observed:

      * RFC 7231: Hypertext Transfer Protocol (HTTP/1.1), obsoletes
        2616

      * RFC 6585: Additional HTTP Status Codes

      * RFC 3229: Delta encoding in HTTP

      * RFC 4918: HTTP Extensions for WebDAV, obsoletes 2518

      * RFC 5842: Binding Extensions to WebDAV

      * RFC 7238: Permanent Redirect

      * RFC 2295: Transparent Content Negotiation in HTTP

      * RFC 2774: An HTTP Extension Framework

   ACCEPTED = 202

   ALREADY_REPORTED = 208

   BAD_GATEWAY = 502

   BAD_REQUEST = 400

   CONFLICT = 409

   CONTINUE = 100

   CREATED = 201

   EXPECTATION_FAILED = 417

   FAILED_DEPENDENCY = 424

   FORBIDDEN = 403

   FOUND = 302

   GATEWAY_TIMEOUT = 504

   GONE = 410

   HTTP_VERSION_NOT_SUPPORTED = 505

   IM_USED = 226

   INSUFFICIENT_STORAGE = 507

   INTERNAL_SERVER_ERROR = 500

   LENGTH_REQUIRED = 411

   LOCKED = 423

   LOOP_DETECTED = 508

   METHOD_NOT_ALLOWED = 405

   MOVED_PERMANENTLY = 301

   MULTIPLE_CHOICES = 300

   MULTI_STATUS = 207

   NETWORK_AUTHENTICATION_REQUIRED = 511

   NON_AUTHORITATIVE_INFORMATION = 203

   NOT_ACCEPTABLE = 406

   NOT_EXTENDED = 510

   NOT_FOUND = 404

   NOT_IMPLEMENTED = 501

   NOT_MODIFIED = 304

   NO_CONTENT = 204

   OK = 200

   PARTIAL_CONTENT = 206

   PAYMENT_REQUIRED = 402

   PERMANENT_REDIRECT = 308

   PRECONDITION_FAILED = 412

   PRECONDITION_REQUIRED = 428

   PROCESSING = 102

   PROXY_AUTHENTICATION_REQUIRED = 407

   REQUESTED_RANGE_NOT_SATISFIABLE = 416

   REQUEST_ENTITY_TOO_LARGE = 413

   REQUEST_HEADER_FIELDS_TOO_LARGE = 431

   REQUEST_TIMEOUT = 408

   REQUEST_URI_TOO_LONG = 414

   RESET_CONTENT = 205

   SEE_OTHER = 303

   SERVICE_UNAVAILABLE = 503

   SWITCHING_PROTOCOLS = 101

   TEMPORARY_REDIRECT = 307

   TOO_MANY_REQUESTS = 429

   UNAUTHORIZED = 401

   UNPROCESSABLE_ENTITY = 422

   UNSUPPORTED_MEDIA_TYPE = 415

   UPGRADE_REQUIRED = 426

   USE_PROXY = 305

   VARIANT_ALSO_NEGOTIATES = 506
