�
��c @s�dZdZddgZddkZddkZddkZddkZddkZdZd�Z dei
fd��YZdeifd ��YZ
e
ed
d�Zedjoe�ndS(
s
HTTP server base class.
Note: the class in this module doesn't implement any HTTP request; see
SimpleHTTPServer for simple implementations of GET, HEAD and POST
(including CGI scripts). It does, however, optionally implement HTTP/1.1
persistent connections, as of version 0.3.
Contents:
- BaseHTTPRequestHandler: HTTP request handler base class
- test: test function
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
s0.3t
HTTPServertBaseHTTPRequestHandleri�Ns�<head>
<title>Error response</title>
</head>
<body>
<h1>Error response</h1>
<p>Error code %(code)d.
<p>Message: %(message)s.
<p>Error code explanation: %(code)s = %(explain)s.
</body>
cCs(|idd�idd�idd�S(Nt&s&t<s<t>s>(treplace(thtml((s!/sys/lib/python/BaseHTTPServer.pyt_quote_html\scBseZdZd�ZRS(icCsHtii|�|ii�d \}}ti|�|_||_dS(s.Override server_bind to store the server name.iN(tSocketServert TCPServertserver_bindtsockettgetsocknametgetfqdntserver_nametserver_port(tselfthosttport((s!/sys/lib/python/BaseHTTPServer.pyR
cs(t__name__t
__module__tallow_reuse_addressR
(((s!/sys/lib/python/BaseHTTPServer.pyR_sc
Bs�eZdZdeii�dZdeZd�Z d�Z
d�Zd�d�Z
eZd�d�Zd �Zd
�Zddd�Zd
�Zd�Zd�Zd�d�Zd�ZdddddddgZd�dddddddd d!d"d#d$g
Zd%�Zd&ZeiZhd�d)<d�d,<d�d/<d�d2<d�d5<d�d8<d�d;<d�d><d�dA<d�dD<d�dG<d�dJ<d�dM<d�dP<d�dS<d�dU<d�dX<d�d[<d�d^<d�da<d�dd<d�dg<d�dj<d�dm<d�dp<d�ds<d�dv<d�dy<d�d|<d�d<d�d�<d�d�<d�d�<d�d�<d�d�<d�d�<d�d�<d�d�<d�d�<d�d�<Z RS(�s�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 mimetools.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".
sPython/is BaseHTTP/c Cs�d|_d|_}d|_|i}|ddjo|d }n |ddjo|d }n||_|i�}t|�djo-|\}}}|d d jo|id
d|�t Snyf|idd�d}|id
�}t|�djo
t
�nt|d�t|d�f}Wn1t
tfj
o|id
d|�t SnX|djo|i
djo
d|_n|djo|idd|�t Sq7n}t|�djoB|\}}d|_|djo|id
d|�t Sq7n(|pt Sn|id
d|�t S||||_|_|_|i|id�|_|iidd�}|i�djo
d|_n1|i�djo|i
djo
d|_ntS(s'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.
sHTTP/0.9ii�s
i�s
iisHTTP/i�sBad request version (%r)t/t.iisHTTP/1.1i�sInvalid HTTP Version (%s)tGETsBad HTTP/0.9 request type (%r)sBad request syntax (%r)t
Connectionttcloses
keep-aliveN(ii(ii(tNonetcommandtrequest_versiontclose_connectiontraw_requestlinetrequestlinetsplittlent
send_errortFalset
ValueErrortintt
IndexErrortprotocol_versiontpathtMessageClasstrfiletheaderstgettlowertTrue( RtversionR!twordsRR*tbase_version_numbertversion_numbertconntype((s!/sys/lib/python/BaseHTTPServer.pyt
parse_request�sd
$
cCs�|ii�|_|ipd|_dSn|i�pdSnd|i}t||�p|idd|i�dSnt||�}|�dS(s�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.
iNtdo_i�sUnsupported method (%r)( R,treadlineR RR6RthasattrR$tgetattr(Rtmnametmethod((s!/sys/lib/python/BaseHTTPServer.pythandle_one_request#s
cCs3d|_|i�x|ip|i�qWdS(s&Handle multiple requests if necessary.iN(RR=(R((s!/sys/lib/python/BaseHTTPServer.pythandle8s
cCsy|i|\}}Wntj
od\}}nX|djo
|}n|}|id||�|ih|d<t|�d<|d<}|i||�|idd�|idd �|i�|i d
jo.|djo!|djo|i
i|�ndS(s�Send and log an error reply.
Arguments are the error code, and a detailed message.
The detailed message defaults to the short 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.
s???scode %d, message %stcodetmessagetexplainsContent-Types text/htmlRRtHEADi�i�i0N(s???s???(i�i0(t responsestKeyErrorRt log_errorterror_message_formatRt
send_responsetsend_headertend_headersRtwfiletwrite(RR?R@tshorttlongRAtcontent((s!/sys/lib/python/BaseHTTPServer.pyR$@s
(
*cCs�|i|�|djo/||ijo|i|d}qId}n|idjo$|iid|i||f�n|id|i��|id|i ��dS(s�Send the response header and log the response code.
Also send two standard headers with the server software
version and the current date.
iRsHTTP/0.9s
%s %d %s
tServertDateN(
tlog_requestRRCRRJRKR)RHtversion_stringtdate_time_string(RR?R@((s!/sys/lib/python/BaseHTTPServer.pyRGas
cCs�|idjo|iid||f�n|i�djoD|i�djo
d|_q�|i�djo
d|_q�ndS( sSend a MIME header.sHTTP/0.9s%s: %s
t
connectionRis
keep-aliveiN(RRJRKR/R(Rtkeywordtvalue((s!/sys/lib/python/BaseHTTPServer.pyRHus
cCs(|idjo|iid�ndS(s,Send the blank line ending the MIME headers.sHTTP/0.9s
N(RRJRK(R((s!/sys/lib/python/BaseHTTPServer.pyRI�st-cCs)|id|it|�t|��dS(sNLog an accepted request.
This is called by send_response().
s
"%s" %s %sN(tlog_messageR!tstr(RR?tsize((s!/sys/lib/python/BaseHTTPServer.pyRQ�s cGs|i|�dS(s�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.
N(RX(Rtargs((s!/sys/lib/python/BaseHTTPServer.pyRE�scGs1tiid|i�|i�||f�dS(s�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 host and current date/time are prefixed to
every message.
s%s - - [%s] %s
N(tsyststderrRKtaddress_stringtlog_date_time_string(RtformatR[((s!/sys/lib/python/BaseHTTPServer.pyRX�s cCs|id|iS(s*Return the server software version string.t (tserver_versiontsys_version(R((s!/sys/lib/python/BaseHTTPServer.pyRR�sc Csx|djoti�}nti|�\ }}}}}}}} }
d|i|||i|||||f}|S(s@Return the current date and time formatted for a message header.s#%s, %02d %3s %4d %02d:%02d:%02d GMTN(Rttimetgmtimetweekdaynamet monthname(Rt timestamptyeartmonthtdaythhtmmtsstwdtytzts((s!/sys/lib/python/BaseHTTPServer.pyRS�s
*
c Cs]ti�}ti|�\ }}}}}}}} }
d||i|||||f}|S(s.Return the current time formatted for logging.s%02d/%3s/%04d %02d:%02d:%02d(Rdt localtimeRg(RtnowRiRjRkRlRmRntxRpRqRr((s!/sys/lib/python/BaseHTTPServer.pyR_�s
* tMontTuetWedtThutFritSattSuntJantFebtMartAprtMaytJuntJultAugtSeptOcttNovtDeccCs |id \}}ti|�S(s�Return the client address formatted for logging.
This version looks up the full hostname using gethostbyaddr(),
and tries to find a name that contains at least one dot.
i(tclient_addressRR
(RRR((s!/sys/lib/python/BaseHTTPServer.pyR^�ssHTTP/1.0tContinues!Request received, please continueidsSwitching Protocolss.Switching to new protocol; obey Upgrade headerietOKs#Request fulfilled, document followsi�tCreatedsDocument created, URL followsi�tAccepteds/Request accepted, processing continues off-linei�sNon-Authoritative InformationsRequest fulfilled from cachei�s
No Contents"Request fulfilled, nothing followsi�s
Reset Contents#Clear input form for further input.i�sPartial ContentsPartial content follows.i�sMultiple Choicess,Object has several resources -- see URI listi,sMoved Permanentlys(Object moved permanently -- see URI listi-tFounds(Object moved temporarily -- see URI listi.s See Others'Object moved -- see Method and URL listi/sNot Modifieds)Document has not changed since given timei0s Use ProxysAYou must use proxy specified in Location to access this resource.i1sTemporary Redirecti3sBad Requests(Bad request syntax or unsupported methodi�tUnauthorizeds*No permission -- see authorization schemesi�sPayment Requireds"No payment -- see charging schemesi�t Forbiddens0Request forbidden -- authorization will not helpi�s Not FoundsNothing matches the given URIi�sMethod Not Alloweds,Specified method is invalid for this server.i�sNot Acceptables&URI not available in preferred format.i�sProxy Authentication Requireds8You must authenticate with this proxy before proceeding.i�sRequest Timeouts#Request timed out; try again later.i�tConflictsRequest conflict.i�tGones6URI no longer exists and has been permanently removed.i�sLength Requireds#Client must specify Content-Length.i�sPrecondition Faileds!Precondition in headers is false.i�sRequest Entity Too LargesEntity is too large.i�sRequest-URI Too LongsURI is too long.i�sUnsupported Media Types"Entity body in unsupported format.i�sRequested Range Not SatisfiablesCannot satisfy request range.i�sExpectation Faileds(Expect condition could not be satisfied.i�sInternal Server ErrorsServer got itself in troublei�sNot Implementeds&Server does not support this operationi�sBad Gateways,Invalid responses from another server/proxy.i�sService Unavailables8The server cannot process the request due to a high loadi�sGateway Timeouts4The gateway server did not receive a timely responsei�sHTTP Version Not SupportedsCannot fulfill request.i�N(sContinues!Request received, please continue(sSwitching Protocolss.Switching to new protocol; obey Upgrade header(sOKs#Request fulfilled, document follows(sCreatedsDocument created, URL follows(sAccepteds/Request accepted, processing continues off-line(sNon-Authoritative InformationsRequest fulfilled from cache(s
No Contents"Request fulfilled, nothing follows(s
Reset Contents#Clear input form for further input.(sPartial ContentsPartial content follows.(sMultiple Choicess,Object has several resources -- see URI list(sMoved Permanentlys(Object moved permanently -- see URI list(sFounds(Object moved temporarily -- see URI list(s See Others'Object moved -- see Method and URL list(sNot Modifieds)Document has not changed since given time(s Use ProxysAYou must use proxy specified in Location to access this resource.(sTemporary Redirects(Object moved temporarily -- see URI list(sBad Requests(Bad request syntax or unsupported method(sUnauthorizeds*No permission -- see authorization schemes(sPayment Requireds"No payment -- see charging schemes(s Forbiddens0Request forbidden -- authorization will not help(s Not FoundsNothing matches the given URI(sMethod Not Alloweds,Specified method is invalid for this server.(sNot Acceptables&URI not available in preferred format.(sProxy Authentication Requireds8You must authenticate with this proxy before proceeding.(sRequest Timeouts#Request timed out; try again later.(sConflictsRequest conflict.(sGones6URI no longer exists and has been permanently removed.(sLength Requireds#Client must specify Content-Length.(sPrecondition Faileds!Precondition in headers is false.(sRequest Entity Too LargesEntity is too large.(sRequest-URI Too LongsURI is too long.(sUnsupported Media Types"Entity body in unsupported format.(sRequested Range Not SatisfiablesCannot satisfy request range.(sExpectation Faileds(Expect condition could not be satisfied.(sInternal Server ErrorsServer got itself in trouble(sNot Implementeds&Server does not support this operation(sBad Gateways,Invalid responses from another server/proxy.(sService Unavailables8The server cannot process the request due to a high load(sGateway Timeouts4The gateway server did not receive a timely response(sHTTP Version Not SupportedsCannot fulfill request.(!RRt__doc__R\R1R"Rct__version__RbR6R=R>RR$tDEFAULT_ERROR_MESSAGERFRGRHRIRQRERXRRRSR_RfRgR^R)t mimetoolstMessageR+RC(((s!/sys/lib/python/BaseHTTPServer.pyRks�f
H
sHTTP/1.0cCs�tidottid�}nd}d|f}||_|||�}|ii�}dG|dGdG|dGdGH|i�dS( sTest the HTTP request handler class.
This runs an HTTP server on port 8000 (or the first command line
argument).
ii@RsServing HTTP oniRs...N(R\targvR'R)RRt
serve_forever(tHandlerClasstServerClasstprotocolRtserver_addressthttpdtsa((s!/sys/lib/python/BaseHTTPServer.pyttest*s t__main__(R�R�t__all__R\RdRR�RR�RR RtStreamRequestHandlerRR�R(((s!/sys/lib/python/BaseHTTPServer.pys<module>s 3
�
|