�`^c@s dZdZddgZddlZddlZddlZddlmZmZe��ej rxedde
�nddlZWdQXddlZd Z
d
Zd�Zdejfd��YZdejfd
��YZeedd�Zedkre�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�N(tfilterwarningstcatch_warningstignores.*mimetools has been removeds�<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>
s text/htmlcCs(|jdd�jdd�jdd�S(Nt&s&t<s<t>s>(treplace(thtml((s$/sys/lib/python2.7/BaseHTTPServer.pyt_quote_htmlcscBseZdZd�ZRS(icCsHtjj|�|jj�d \}}tj|�|_||_dS(s.Override server_bind to store the server name.iN(tSocketServert TCPServertserver_bindtsockettgetsocknametgetfqdntserver_nametserver_port(tselfthosttport((s$/sys/lib/python2.7/BaseHTTPServer.pyR
js(t__name__t
__module__tallow_reuse_addressR
(((s$/sys/lib/python2.7/BaseHTTPServer.pyRfsc
BsCeZdZdejj�dZdeZdZ d�Z
d�Zd�Zd�d�ZeZeZd�d �Zd
�Zd�Zddd
�Zd�Zd�Zd�Zd�d�Zd�ZdddddddgZd�ddddddd d!d"d#d$d%g
Zd&�Zd'Ze j!Z"i(d�d*6d�d-6d�d06d�d36d�d66d�d96d�d<6d�d?6d�dB6d�dE6d�dH6d�dK6d�dN6d�dQ6d�dT6d�dV6d�dY6d�d\6d�d_6d�db6d�de6d�dh6d�dk6d�dn6d�dq6d�dt6d�dw6d�dz6d�d}6d�d�6d�d�6d�d�6d�d�6d�d�6d�d�6d�d�6d�d�6d�d�6d�d�6d�d�6Z#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/sHTTP/0.9c Cs�d|_|j|_}d|_|j}|jd�}||_|j�}t |�dkry|\}}}|d dkr�|j
dd|�tSyd|jdd�d}|jd �}t |�d
kr�t�nt
|d�t
|d�f}Wn,ttfk
r*|j
dd|�tSX|dkrR|jdkrRd|_n|dkr�j
d
d|�tSnpt |�d
kr�|\}}d|_|dkr�j
dd|�tSn"|s�tS|j
dd|�tS||||_|_|_|j|jd�|_|jjdd�}|j�dkrQd|_n-|j�dkr~|jdkr~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.
is
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(tNonetcommandtdefault_request_versiontrequest_versiontclose_connectiontraw_requestlinetrstriptrequestlinetsplittlent
send_errortFalset
ValueErrortintt
IndexErrortprotocol_versiontpathtMessageClasstrfiletheaderstgettlowertTrue( RtversionR&twordsR R/tbase_version_numbertversion_numbertconntype((s$/sys/lib/python2.7/BaseHTTPServer.pyt
parse_request�s^ $ cCsy�|jjd�|_t|j�dkrYd|_d|_d|_|jd�dS|jsod|_dS|j �sdSd|j}t
||�s�|jdd |j�dSt||�}|�|jj
�Wn0tjk
r}|jd
|�d|_dSXdS(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.
iiRi�Nitdo_i�sUnsupported method (%r)sRequest timed out: %r(R1treadlineR$R(R&R"R R)R#R;thasattrtgetattrtwfiletflushRttimeoutt log_error(Rtmnametmethodte((s$/sys/lib/python2.7/BaseHTTPServer.pythandle_one_request-s0
cCs1d|_|j�x|js,|j�qWdS(s&Handle multiple requests if necessary.iN(R#RG(R((s$/sys/lib/python2.7/BaseHTTPServer.pythandlePs
cCsy|j|\}}Wntk
r6d\}}nX|d
krL|}n|}|jd||�|ji|d6t|�d6|d6}|j||�|jd|j�|jdd�|j �|j
d kr|d
kr|dkr|jj|�nd
S(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-TypeRRtHEADi�i�i0N(s???s???(i�i0(
t responsestKeyErrorRRCterror_message_formatR
t
send_responsetsend_headerterror_content_typetend_headersR R@twrite(RRIRJtshorttlongRKtcontent((s$/sys/lib/python2.7/BaseHTTPServer.pyR)Xs
"
'cCs�|j|�|dkrE||jkr<|j|d}qEd}n|jdkrw|jjd|j||f�n|jd|j��|jd|j ��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_requestRRMR"[email protected]version_stringtdate_time_string(RRIRJ((s$/sys/lib/python2.7/BaseHTTPServer.pyRPzs
cCs�|jdkr,|jjd||f�n|j�dkr}|j�dkr\d|_q}|j�dkr}d|_q}ndS( sSend a MIME header.sHTTP/0.9s%s: %s
t
connectionRis
keep-aliveiN(R"R@RTR4R#(Rtkeywordtvalue((s$/sys/lib/python2.7/BaseHTTPServer.pyRQ�scCs&|jdkr"|jjd�ndS(s,Send the blank line ending the MIME headers.sHTTP/0.9s
N(R"R@RT(R((s$/sys/lib/python2.7/BaseHTTPServer.pyRS�st-cCs)|jd|jt|�t|��dS(sNLog an accepted request.
This is called by send_response().
s
"%s" %s %sN(tlog_messageR&tstr(RRItsize((s$/sys/lib/python2.7/BaseHTTPServer.pyRZ�s cGs|j||�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(Ra(Rtformattargs((s$/sys/lib/python2.7/BaseHTTPServer.pyRC�scGs2tjjd|jd|j�||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 ip address and current date/time are prefixed to every
message.
s%s - - [%s] %s
iN(tsyststderrRTtclient_addresstlog_date_time_string(RRdRe((s$/sys/lib/python2.7/BaseHTTPServer.pyRa�s
cCs|jd|jS(s*Return the server software version string.t (tserver_versiontsys_version(R((s$/sys/lib/python2.7/BaseHTTPServer.pyR[�sc Csv|dkrtj�}ntj|�\ }}}}}}}} }
d|j|||j|||||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/python2.7/BaseHTTPServer.pyR\�s*
c Cs]tj�}tj|�\ }}}}}}}} }
d||j|||||f}|S(s.Return the current time formatted for logging.s%02d/%3s/%04d %02d:%02d:%02d(Rmt localtimeRp(RtnowRrRsRtRuRvRwtxRyRzR{((s$/sys/lib/python2.7/BaseHTTPServer.pyRi�s
* tMontTuetWedtThutFritSattSuntJantFebtMartAprtMaytJuntJultAugtSeptOcttNovtDeccCs |jd \}}tj|�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(RhRR(RRR((s$/sys/lib/python2.7/BaseHTTPServer.pytaddress_string�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 resource.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(R�s!Request received, please continue(sSwitching Protocolss.Switching to new protocol; obey Upgrade header(R�s#Request fulfilled, document follows(R�sDocument created, URL follows(R�s/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(R�s(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(R�s*No permission -- see authorization schemes(sPayment Requireds"No payment -- see charging schemes(R�s0Request forbidden -- authorization will not help(s Not FoundsNothing matches the given URI(sMethod Not Alloweds.Specified method is invalid for this resource.(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.(R�sRequest conflict.(R�s6URI 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__RfR6R'Rlt__version__RkR!R;RGRHRR)tDEFAULT_ERROR_MESSAGEROtDEFAULT_ERROR_CONTENT_TYPERRRPRQRSRZRCRaR[R\RiRoRpR�R.t mimetoolstMessageR0RM(((s$/sys/lib/python2.7/BaseHTTPServer.pyRrs�f
E #
sHTTP/1.0cCs�tjdr#ttjd�}nd}d|f}||_|||�}|jj�}dG|dGdG|dGdGH|j�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(RftargvR,R.RRt
serve_forever(tHandlerClasstServerClasstprotocolRtserver_addressthttpdtsa((s$/sys/lib/python2.7/BaseHTTPServer.pyttestCs
t__main__(R�R�t__all__RfRmRtwarningsRRtpy3kwarningtDeprecationWarningR�RR�R�R
RRtStreamRequestHandlerRR�R(((s$/sys/lib/python2.7/BaseHTTPServer.pyt<module>s,3
�
|