/ lib / http / server.pyc
server.pyc
  1  o

  2  ���cj��@s�dZdZgd�ZddlZddlZddlZddlZddlZ	ddl
  3  Z
  4  ddlZddlZddl
Z
ddlZddlZddlZddlZddlZddlZddlZddlZddl	mZdZdZGdd	�d	ej�ZGd
  5  d�deje�ZGdd
�d
ej�ZGdd�de�Z dd�Z!da"dd�Z#dd�Z$Gdd�de �Z%dd�Z&eedddfdd�Z'e(dkr�ddl)Z)ddl*Z*e)�+�Z,e,j-dd d!d"�e,j-d#d$d%d&d'�e,j-d(d)e
�.�d*d+�e,j-d,d-de/d.d/d0�e,�0�Z1e1j2r�e%Z3ne Z3Gd1d2�d2e�Z4e'e3e4e1j5e1j6d3�dSdS)4a@HTTP server classes.
  6  
  7  Note: BaseHTTPRequestHandler doesn't implement any HTTP request; see
  8  SimpleHTTPRequestHandler for simple implementations of GET, HEAD and POST,
  9  and CGIHTTPRequestHandler for CGI scripts.
 10  
 11  It does, however, optionally implement HTTP/1.1 persistent connections,
 12  as of version 0.3.
 13  
 14  Notes on CGIHTTPRequestHandler
 15  ------------------------------
 16  
 17  This class implements GET and POST requests to cgi-bin scripts.
 18  
 19  If the os.fork() function is not present (e.g. on Windows),
 20  subprocess.Popen() is used as a fallback, with slightly altered semantics.
 21  
 22  In all cases, the implementation is intentionally naive -- all
 23  requests are executed synchronously.
 24  
 25  SECURITY WARNING: DON'T USE THIS CODE UNLESS YOU ARE INSIDE A FIREWALL
 26  -- it may execute arbitrary Python code or external programs.
 27  
 28  Note that status code 200 is sent prior to execution of a CGI script, so
 29  scripts cannot send other status codes such as 302 (redirect).
 30  
 31  XXX To do:
 32  
 33  - log requests even later (to capture byte count)
 34  - log user-agent header and other interesting goodies
 35  - send error log to separate file
 36  z0.6)�
 37  HTTPServer�ThreadingHTTPServer�BaseHTTPRequestHandler�SimpleHTTPRequestHandler�CGIHTTPRequestHandler�N)�
 38  HTTPStatusa�<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
 39          "http://www.w3.org/TR/html4/strict.dtd">
 40  <html>
 41      <head>
 42          <meta http-equiv="Content-Type" content="text/html;charset=utf-8">
 43          <title>Error response</title>
 44      </head>
 45      <body>
 46          <h1>Error response</h1>
 47          <p>Error code: %(code)d</p>
 48          <p>Message: %(message)s.</p>
 49          <p>Error code explanation: %(code)s - %(explain)s.</p>
 50      </body>
 51  </html>
 52  ztext/html;charset=utf-8c@seZdZdZdd�ZdS)r�cCs4tj�|�|jdd�\}}t�|�|_||_dS)z.Override server_bind to store the server name.N�)�socketserver�	TCPServer�server_bind�server_address�socket�getfqdn�server_name�server_port)�self�host�port�r�sC:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.10_3.10.2800.0_x64__qbz5n2kfra8p0\lib\http\server.pyr�s
 53  zHTTPServer.server_bindN)�__name__�
 54  __module__�__qualname__�allow_reuse_addressrrrrrr�src@seZdZdZdS)rTN)rrr�daemon_threadsrrrrr�src	@s*eZdZdZdej��dZdeZ	e
 55  ZeZ
dZdd�Zdd	�Zd
 56  d�Zdd
�Zd5dd�Zd6dd�Zd6dd�Zdd�Zdd�Zdd�Zd7dd�Zdd�Ze�d d!�e�ed"�ed#d$��D��Z d%e e!d&�<d'd(�Z"d)d*�Z#d6d+d,�Z$d-d.�Z%gd/�Z&gd0�Z'd1d2�Z(d3Z)e*j+j,Z-d4d!�e.j/�0�D�Z1dS)8ra�HTTP request handler base class.
 57  
 58      The following explanation of HTTP serves to guide you through the
 59      code as well as to expose any misunderstandings I may have about
 60      HTTP (so you don't need to read the code to figure out I'm wrong
 61      :-).
 62  
 63      HTTP (HyperText Transfer Protocol) is an extensible protocol on
 64      top of a reliable stream transport (e.g. TCP/IP).  The protocol
 65      recognizes three parts to a request:
 66  
 67      1. One line identifying the request type and path
 68      2. An optional set of RFC-822-style headers
 69      3. An optional data part
 70  
 71      The headers and data are separated by a blank line.
 72  
 73      The first line of the request has the form
 74  
 75      <command> <path> <version>
 76  
 77      where <command> is a (case-sensitive) keyword such as GET or POST,
 78      <path> is a string containing path information for the request,
 79      and <version> should be the string "HTTP/1.0" or "HTTP/1.1".
 80      <path> is encoded using the URL encoding scheme (using %xx to signify
 81      the ASCII character with hex code xx).
 82  
 83      The specification specifies that lines are separated by CRLF but
 84      for compatibility with the widest range of clients recommends
 85      servers also handle LF.  Similarly, whitespace in the request line
 86      is treated sensibly (allowing multiple spaces between components
 87      and allowing trailing whitespace).
 88  
 89      Similarly, for output, lines ought to be separated by CRLF pairs
 90      but most clients grok LF characters just fine.
 91  
 92      If the first line of the request has the form
 93  
 94      <command> <path>
 95  
 96      (i.e. <version> is left out) then this is assumed to be an HTTP
 97      0.9 request; this form has no optional headers and data part and
 98      the reply consists of just the data.
 99  
100      The reply form of the HTTP 1.x protocol again has three parts:
101  
102      1. One line giving the response code
103      2. An optional set of RFC-822-style headers
104      3. The data
105  
106      Again, the headers and data are separated by a blank line.
107  
108      The response code line has the form
109  
110      <version> <responsecode> <responsestring>
111  
112      where <version> is the protocol version ("HTTP/1.0" or "HTTP/1.1"),
113      <responsecode> is a 3-digit response code indicating success or
114      failure of the request, and <responsestring> is an optional
115      human-readable string explaining what the response code means.
116  
117      This server parses the request and the headers, and then calls a
118      function specific to the request type (<command>).  Specifically,
119      a request SPAM will be handled by a method do_SPAM().  If no
120      such method exists the server sends an error response to the
121      client.  If it exists, it is called with no arguments:
122  
123      do_SPAM()
124  
125      Note that the request name is case sensitive (i.e. SPAM and spam
126      are different requests).
127  
128      The various request details are stored in instance variables:
129  
130      - client_address is the client IP address in the form (host,
131      port);
132  
133      - command, path and version are the broken-down request line;
134  
135      - headers is an instance of email.message.Message (or a derived
136      class) containing the header information;
137  
138      - rfile is a file object open for reading positioned at the
139      start of the optional input data part;
140  
141      - wfile is a file object open for writing.
142  
143      IT IS IMPORTANT TO ADHERE TO THE PROTOCOL FOR WRITING!
144  
145      The first thing to be written must be the response line.  Then
146      follow 0 or more header lines, then a blank line, and then the
147      actual data (if any).  The meaning of the header lines depends on
148      the command executed by the server; in most cases, when data is
149      returned, there should be at least one header line of the form
150  
151      Content-type: <type>/<subtype>
152  
153      where <type> and <subtype> should be registered MIME types,
154      e.g. "text/html" or "text/plain".
155  
156      zPython/rz	BaseHTTP/�HTTP/0.9c
157  Cs�d|_|j|_}d|_t|jd�}|�d�}||_|��}t	|�dkr&dSt	|�dkr�|d}z*|�
158  d	�s8t�|�d
159  d�d}|�d�}t	|�d
krMt�t|d�t|d�f}Wntt
fyo|�tjd|�YdSw|dkr||jdkr|d|_|dkr�|�tjd|�dS||_d
t	|�kr�dks�n|�tjd|�dS|dd
�\}}t	|�d
kr�d|_|dkr�|�tjd|�dS|||_|_|j�
160  d�r�d
161  |j�d
162  �|_z
tjj|j|jd�|_Wn?tjj�y	}z|�tjdt|��WYd}~dSd}~wtjj�y(}z|�tjdt|��WYd}~dSd}~ww|j�dd�}	|	��dk�r;d|_n|	��dk�rK|jdk�rKd|_|j�dd�}
163  |
164  ��dk�rl|jdk�rl|jdk�rl|� ��sldSdS) aHParse a request (internal).
165  
166          The request should be stored in self.raw_requestline; the results
167          are in self.command, self.path, self.request_version and
168          self.headers.
169  
170          Return True for success, False for failure; on failure, any relevant
171          error response has already been sent back.
172  
173          NTz
174  iso-8859-1z
175  rF������zHTTP/�/r�.r	zBad request version (%r))rrzHTTP/1.1)r	rzInvalid HTTP version (%s)zBad request syntax (%r)�GETzBad HTTP/0.9 request type (%r)z//)�_classz
Line too longzToo many headers�
176  Connection��close�
177  keep-alive�Expectz100-continue)!�command�default_request_version�request_version�close_connection�str�raw_requestline�rstrip�requestline�split�len�
178  startswith�
179  ValueError�int�
180  IndexError�
181  send_errorr�BAD_REQUEST�protocol_version�HTTP_VERSION_NOT_SUPPORTED�path�lstrip�http�client�
parse_headers�rfile�MessageClass�headers�LineTooLong�REQUEST_HEADER_FIELDS_TOO_LARGE�
HTTPException�get�lower�handle_expect_100)r�versionr/�wordsZbase_version_numberZversion_numberr(r:�errZconntype�expectrrr�
parse_requests�
182  
183  
184  �����
185  ������
186  z$BaseHTTPRequestHandler.parse_requestcCs|�tj�|��dS)a7Decide what to do with an "Expect: 100-continue" header.
187  
188          If the client is expecting a 100 Continue response, we must
189          respond with either a 100 Continue or a final response before
190          waiting for the request body. The default is to always respond
191          with a 100 Continue. You can behave differently (for example,
192          reject unauthorized requests) by overriding this method.
193  
194          This method should either return True (possibly after sending
195          a 100 Continue response) or send an error response and return
196          False.
197  
198          T)�send_response_onlyr�CONTINUE�end_headers�rrrrrGvsz(BaseHTTPRequestHandler.handle_expect_100c
199  Cs�zW|j�d�|_t|j�dkr!d|_d|_d|_|�tj	�WdS|js*d|_
200  WdS|��s1WdSd|j}t||�sH|�tj
d|j�WdSt||�}|�|j��WdStys}z|�d|�d|_
201  WYd}~dSd}~ww)	z�Handle a single HTTP request.
202  
203          You normally don't need to override this method; see the class
204          __doc__ string for information on how to handle specific HTTP
205          commands such as GET and POST.
206  
207          iir$NT�do_zUnsupported method (%r)zRequest timed out: %r)r?�readliner-r1r/r*r(r6r�REQUEST_URI_TOO_LONGr+rL�hasattr�NOT_IMPLEMENTED�getattr�wfile�flush�TimeoutError�	log_error)r�mname�method�errr�handle_one_request�s:
208  
209  �
210  ��z)BaseHTTPRequestHandler.handle_one_requestcCs*d|_|��|js|��|jr
211  dSdS)z&Handle multiple requests if necessary.TN)r+r^rPrrr�handle�s
212  �zBaseHTTPRequestHandler.handleNcCsz	|j|\}}Wn
tyd\}}Ynw|dur|}|dur#|}|�d||�|�||�|�dd�d}|dkrp|tjtjtjfvrp|j	|t
213  j|dd�t
214  j|dd�d	�}|�d
215  d�}|�d|j
�|�d
tt|���|��|jdkr�|r�|j�|�dSdSdS)akSend and log an error reply.
216  
217          Arguments are
218          * code:    an HTTP error code
219                     3 digits
220          * message: a simple optional 1 line reason phrase.
221                     *( HTAB / SP / VCHAR / %x80-FF )
222                     defaults to short entry matching the response code
223          * explain: a detailed message defaults to the long entry
224                     matching the response code.
225  
226          This sends an error response (so it must be called before any
227          output has been generated), logs the error, and finally sends
228          a piece of HTML explaining the error to the user.
229  
230          )�???r`Nzcode %d, message %sr#r%��F��quote)�code�message�explainzUTF-8�replacezContent-Type�Content-Length�HEAD)�	responses�KeyErrorrZ�
send_response�send_headerr�
231  NO_CONTENT�
RESET_CONTENT�NOT_MODIFIED�error_message_format�html�escape�encode�error_content_typer,r1rOr(rW�write)rrdrerfZshortmsgZlongmsg�body�contentrrrr6�s<����z!BaseHTTPRequestHandler.send_errorcCs:|�|�|�||�|�d|���|�d|���dS)z�Add the response header to the headers buffer and log the
232          response code.
233  
234          Also send two standard headers with the server software
235          version and the current date.
236  
237          �Server�DateN)�log_requestrMrm�version_string�date_time_string�rrdrerrrrl�s
238  z$BaseHTTPRequestHandler.send_responsecCsh|jdkr2|dur||jvr|j|d}nd}t|d�s g|_|j�d|j||f�dd��dSdS)	zSend the response header only.rNrr$�_headers_bufferz
239  %s %d %s
240  �latin-1�strict)r*rjrTr�appendr8rtr~rrrrM�s
241  
242  
243  
244  ����z)BaseHTTPRequestHandler.send_response_onlycCsv|jdkrt|d�s
g|_|j�d||f�dd��|��dkr7|��dkr,d|_dS|��d	kr9d
245  |_dSdSdS)z)Send a MIME header to the headers buffer.rrz%s: %s
246  r�r��
247  connectionr%Tr&FN)r*rTrr�rtrFr+)r�keyword�valuerrrrms
248  
249  �
250  
251  �z"BaseHTTPRequestHandler.send_headercCs&|jdkr|j�d�|��dSdS)z,Send the blank line ending the MIME headers.rs
252  N)r*rr��
flush_headersrPrrrrOs
253  �z"BaseHTTPRequestHandler.end_headerscCs,t|d�r|j�d�|j��g|_dSdS)Nr�)rTrWrv�joinrrPrrrr�s
254  
255  �z$BaseHTTPRequestHandler.flush_headers�-cCs.t|t�r|j}|�d|jt|�t|��dS)zNLog an accepted request.
256  
257          This is called by send_response().
258  
259          z
260  "%s" %s %sN)�
261  isinstancerr��log_messager/r,)rrd�sizerrrr{s
262  
263  �z"BaseHTTPRequestHandler.log_requestcGs|j|g|�R�dS)z�Log an error.
264  
265          This is called when a request cannot be fulfilled.  By
266          default it passes the message on to log_message().
267  
268          Arguments are the same as for log_message().
269  
270          XXX This should go to the separate error log.
271  
272          N)r�)r�format�argsrrrrZ)sz BaseHTTPRequestHandler.log_errorcCsi|]	}|d|d���qS)z\x�02xr)�.0�crrr�
273  <dictcomp>9sz!BaseHTTPRequestHandler.<dictcomp>� ��z\\�\cGs2||}tj�d|��|��|�|j�f�dS)aZLog an arbitrary message.
274  
275          This is used by all other logging functions.  Override
276          it if you have specific logging wishes.
277  
278          The first argument, FORMAT, is a format string for the
279          message to be logged.  If the format string contains
280          any % escapes requiring parameters, they should be
281          specified as subsequent arguments (it's just like
282          printf!).
283  
284          The client ip and current date/time are prefixed to
285          every message.
286  
287          Unicode control characters are replaced with escaped hex
288          before writing the output to stderr.
289  
290          z%s - - [%s] %s
291  N)�sys�stderrrv�address_string�log_date_time_string�	translate�_control_char_table)rr�r�rerrrr�<s
292  �
293  �z"BaseHTTPRequestHandler.log_messagecCs|jd|jS)z*Return the server software version string.� )�server_version�sys_versionrPrrrr|Vsz%BaseHTTPRequestHandler.version_stringcCs |durt��}tjj|dd�S)z@Return the current date and time formatted for a message header.NT)�usegmt)�time�email�utils�
294  formatdate)r�	timestamprrrr}Zsz'BaseHTTPRequestHandler.date_time_stringc	CsBt��}t�|�\	}}}}}}}}	}
295  d||j|||||f}|S)z.Return the current time formatted for logging.z%02d/%3s/%04d %02d:%02d:%02d)r��	localtime�	monthname)r�now�year�month�day�hh�mm�ss�x�y�z�srrrr�`s�z+BaseHTTPRequestHandler.log_date_time_string)�Mon�Tue�Wed�Thu�Fri�Sat�Sun)
N�Jan�Feb�Mar�Apr�May�Jun�Jul�Aug�Sep�Oct�Nov�DeccCs
296  |jdS)zReturn the client address.r)�client_addressrPrrrr�ns
297  z%BaseHTTPRequestHandler.address_string�HTTP/1.0cCsi|]	}||j|jf�qSr)�phrase�description)r��vrrrr�}s��)NN�N)r�r�)2rrr�__doc__r�rHr0r��__version__r��DEFAULT_ERROR_MESSAGErq�DEFAULT_ERROR_CONTENT_TYPErur)rLrGr^r_r6rlrMrmrOr�r{rZr,�	maketrans�	itertools�chain�ranger��ordr�r|r}r��weekdaynamer�r�r8r<r=�HTTPMessager@r�__members__�valuesrjrrrrr�sFgj%
298  
299  5
300  

301  �
302  	
303  �rcsxeZdZdZdeZddddd�ZZdd	��fd
304  d�
305  Zdd
�Z	dd�Z
306  dd�Zdd�Zdd�Z
dd�Zdd�Z�ZS)raWSimple HTTP request handler with GET and HEAD commands.
307  
308      This serves files from the current directory and any of its
309      subdirectories.  The MIME type for files is determined by
310      calling the .guess_type() method.
311  
312      The GET and HEAD requests are identical except that the HEAD
313      request omits the actual contents of the file.
314  
315      zSimpleHTTP/zapplication/gzip�application/octet-streamzapplication/x-bzip2zapplication/x-xz)z.gzz.Zz.bz2z.xzN��	directorycs2|durt��}t�|�|_t�j|i|��dSr�)�os�getcwd�fspathr��super�__init__)rr�r��kwargs��	__class__rrr��sz!SimpleHTTPRequestHandler.__init__cCs8|��}|rz|�||j�W|��dS|��wdS)zServe a GET request.N)�	send_head�copyfilerWr%�r�frrr�do_GET�s�zSimpleHTTPRequestHandler.do_GETcCs|��}|r|��dSdS)zServe a HEAD request.N)r�r%r�rrr�do_HEAD�s�z SimpleHTTPRequestHandler.do_HEADcCsL|�|j�}d}tj�|�rgtj�|j�}|j�d�sL|�t	j
316  �|d|d|dd|d|df}tj�|�}|�d|�|�d	d
317  �|�
�dSdD]}tj�||�}tj�|�ra|}nqN|�|�S|�|�}|�d�rz|�t	jd�dSzt|d
�}Wnty�|�t	jd�YdSwz�t�|���}d|jvr�d|jvr�ztj�|jd�}	Wn
ttttfy�Yn:w|	j dur�|	j!t"j#j$d�}	|	j t"j#j$ur�t"j"�%|j&t"j#j$�}
318  |
319  j!dd�}
320  |
321  |	kr�|�t	j'�|�
�|�(�WdS|�t	j)�|�d|�|�d	t*|d��|�d|�+|j&��|�
�|WS|�(��)a{Common code for GET and HEAD commands.
322  
323          This sends the response code and MIME headers.
324  
325          Return value is either a file object (which has to be copied
326          to the outputfile by the caller unless the command was HEAD,
327          and must be closed by the caller under all circumstances), or
328          None, in which case the caller has nothing further to do.
329  
330          Nrrrr	r��Locationrh�0)z
331  index.htmlz	index.htmzFile not found�rbzIf-Modified-Sincez
If-None-Match)�tzinfo)�microsecond�Content-type�z
Last-Modified),�translate_pathr:r��isdir�urllib�parse�urlsplit�endswithrlr�MOVED_PERMANENTLY�
332  urlunsplitrmrOr��isfile�list_directory�
333  guess_typer6�	NOT_FOUND�open�OSError�fstat�filenorAr�r��parsedate_to_datetime�	TypeErrorr5�
OverflowErrorr3r�rg�datetime�timezone�utc�
fromtimestamp�st_mtimerpr%�OKr,r})rr:r��partsZ	new_parts�new_url�index�ctype�fs�imsZ
334  last_modifrrrr��s���
335  
336  
337  �
338  
339  ��
340  
341  �
342  �z"SimpleHTTPRequestHandler.send_headc
	Cs�zt�|�}Wnty|�tjd�YdSw|jdd�d�g}ztjj	|j
343  dd�}Wnty=tj�	|�}Ynwtj
|dd	�}t��}d
344  |}|�d�|�d�|�d
|�|�d|�|�d|�|�d�|D]9}tj
345  �||�}|}	}
346  tj
347  �|�r�|d}	|d}
348  tj
349  �|�r�|d}	|�dtjj|
350  dd�tj
|	dd	�f�qs|�d�d�|��|d�}t��}|�|�|�d�|�tj�|�dd|�|�dtt|���|��|S)z�Helper to produce a directory listing (absent index.html).
351  
352          Return value is either a file object, or None (indicating an
353          error).  In either case, the headers are sent, making the
354          interface the same as for send_head().
355  
356          zNo permission to list directoryNcSs|��Sr�)rF)�arrr�<lambda>sz9SimpleHTTPRequestHandler.list_directory.<locals>.<lambda>)�key�
surrogatepass��errorsFrbzDirectory listing for %szZ<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">z
<html>
357  <head>z@<meta http-equiv="Content-Type" content="text/html; charset=%s">z<title>%s</title>
358  </head>z<body>
359  <h1>%s</h1>z	<hr>
360  <ul>r�@z<li><a href="%s">%s</a></li>z</ul>
361  <hr>
362  </body>
363  </html>
364  �
365  �surrogateescaperr�ztext/html; charset=%srh) r��listdirr�r6rr��sortr�r��unquoter:�UnicodeDecodeErrorrrrsr��getfilesystemencodingr�r�r��islinkrcrt�io�BytesIOrv�seekrlr
366  rmr,r1rO)
rr:�list�rZdisplaypath�enc�title�name�fullname�displayname�linkname�encodedr�rrrr�sl��
367  
368  ��
369  
370  �
371  ���
372  
373  
374  z'SimpleHTTPRequestHandler.list_directorycCs�|�dd�d}|�dd�d}|���d�}z
375  tjj|dd�}Wnty0tj�|�}Ynwt�|�}|�d�}t	d|�}|j
376  }|D]}tj�
|�sU|tjtjfvrVqEtj�||�}qE|rd|d7}|S)	z�Translate a /-separated PATH to the local filename syntax.
377  
378          Components that mean special things to the local file system
379          (e.g. drive or directory names) are ignored.  (XXX They should
380          probably be diagnosed.)
381  
382          �?rr�#rrrN)r0r.r�r�r�rr�	posixpath�normpath�filterr�r�r:�dirname�curdir�pardirr�)rr:Ztrailing_slashrI�wordrrrr�?s&	�
383  
384  
385  z'SimpleHTTPRequestHandler.translate_pathcCst�||�dS)a�Copy all data between two file objects.
386  
387          The SOURCE argument is a file object open for reading
388          (or anything with a read() method) and the DESTINATION
389          argument is a file object open for writing (or
390          anything with a write() method).
391  
392          The only reason for overriding this would be to change
393          the block size or perhaps to replace newlines by CRLF
394          -- note however that this the default server uses this
395          to copy binary data as well.
396  
397          N)�shutil�copyfileobj)r�sourceZ
398  outputfilerrrr�]sz!SimpleHTTPRequestHandler.copyfilecCsXt�|�\}}||jvr|j|S|��}||jvr|j|St�|�\}}|r*|SdS)a�Guess the type of a file.
399  
400          Argument is a PATH (a filename).
401  
402          Return value is a string of the form type/subtype,
403          usable for a MIME Content-type header.
404  
405          The default implementation looks the file's extension
406          up in the table self.extensions_map, using application/octet-stream
407          as a default; however it would be permissible (if
408          slow) to look inside the data to make a better guess.
409  
410          r�)r.�splitext�extensions_maprF�	mimetypesr�)rr:�base�ext�guess�_rrrr�ms
411  
412  
413  
414  z#SimpleHTTPRequestHandler.guess_type)rrrr�r�r�r9�_encodings_map_defaultr�r�r�r�r�r�r�r��
__classcell__rrr�rr�s 
415  �	X:rc	Cs�|�d�\}}}tj�|�}|�d�}g}|dd�D]}|dkr&|��q|r1|dkr1|�|�q|rL|��}|rK|dkrE|��d}n	|dkrKd}nd}|rWd�||f�}dd�|�|f}d�|�}|S)a�
416      Given a URL path, remove extra '/'s and '.' path elements and collapse
417      any '..' references and returns a collapsed path.
418  
419      Implements something akin to RFC-2396 5.2 step 6 to parse relative paths.
420      The utility of this function is limited to is_cgi method and helps
421      preventing some security attacks.
422  
423      Returns: The reconstituted URL, which will always start with a '/'.
424  
425      Raises: IndexError if too many '..' occur within the path.
426  
427      r,rNrz..r r$)�	partitionr�r�rr0�popr�r�)	r:r>�query�
428  path_partsZ
429  head_parts�partZ	tail_part�	splitpath�collapsed_pathrrr�_url_collapse_path�s2
430  
431  
432  ��
433  rHcCsntrtSzddl}Wn
434  tyYdSwz
435  |�d�daWtSty6dtdd�|��D��aYtSw)	z$Internal routine to get nobody's uidrNr�nobodyr	rcss�|]}|dVqdS)r	Nr)r�r�rrr�	<genexpr>�s�znobody_uid.<locals>.<genexpr>)rI�pwd�ImportError�getpwnamrk�maxZgetpwall)rKrrr�
436  nobody_uid�s���rOcCst�|tj�S)zTest for executable file.)r��access�X_OK)r:rrr�
437  executable�srRc@sVeZdZdZeed�ZdZdd�Zdd�Z	dd	�Z
438  d
439  dgZdd
�Zdd�Z
dd�ZdS)rz�Complete HTTP server with GET, HEAD and POST commands.
440  
441      GET and HEAD also support running CGI scripts.
442  
443      The POST command is *only* implemented for CGI scripts.
444  
445      �forkrcCs&|��r
446  |��dS|�tjd�dS)zRServe a POST request.
447  
448          This is only implemented for CGI scripts.
449  
450          zCan only POST to CGI scriptsN)�is_cgi�run_cgir6rrUrPrrr�do_POST�s�zCGIHTTPRequestHandler.do_POSTcCs|��r|��St�|�S)z-Version of send_head that support CGI scripts)rTrUrr�rPrrrr��s
451  zCGIHTTPRequestHandler.send_headcCs�t|j�}|�dd�}|dkr-|d|�|jvr-|�d|d�}|dkr-|d|�|jvs|dkrG|d|�||dd�}}||f|_dSdS)a3Test whether self.path corresponds to a CGI script.
452  
453          Returns True and updates the cgi_info attribute to the tuple
454          (dir, rest) if self.path requires running a CGI script.
455          Returns False otherwise.
456  
457          If any exception is raised, the caller should assume that
458          self.path was rejected as invalid and act accordingly.
459  
460          The default implementation tests whether the normalized url
461          path begins with one of the strings in self.cgi_directories
462          (and the next character is a '/' or the end of the string).
463  
464          rrrNTF)rHr:�find�cgi_directories�cgi_info)rrGZdir_sep�head�tailrrrrT�s
465  �
466  zCGIHTTPRequestHandler.is_cgiz/cgi-binz/htbincCst|�S)z1Test whether argument path is an executable file.)rR)rr:rrr�
is_executablesz#CGIHTTPRequestHandler.is_executablecCstj�|�\}}|��dvS)z.Test whether argument path is a Python script.)z.pyz.pyw)r�r:r8rF)rr:rZr[rrr�	is_pythonszCGIHTTPRequestHandler.is_pythonc)	Cs�|j\}}|d|}|�dt|�d�}|dkrG|d|�}||dd�}|�|�}tj�|�rB||}}|�dt|�d�}nn|dks|�d�\}}}	|�d�}|dkrf|d|�||d�}
467  }n|d}
468  }|d|
469  }|�|�}tj�|�s�|�	t
470  jd|�dStj�|�s�|�	t
471  j
d|�dS|�|�}
|js�|
s�|�|�s�|�	t
472  j
d	|�dSt�tj�}|��|d
473  <|jj|d<d|d
<|j|d<t|jj�|d<|j|d<tj�|�}||d<|�|�|d<||d<|	|d<|jd|d<|j� d�}|�rV|�!�}t|�dk�rVddl"}ddl#}|d|d<|d�$�dk�rVz|d�%d�}|�&|��'d�}Wn
|j(t)f�yCYnw|�!d�}t|�dk�rV|d|d<|j� d�du�rg|j�*�|d<n|jd|d<|j� d�}|�r{||d <|j� d!�}|�r�||d"<|j�+d#d$�}d%�,|�|d&<|j� d'�}|�r�||d(<t-d|j�+d)g��}d*�,|�}|�r�||d+<d,D]	}|�.|d��q�|�/t
474  j0d-�|�1�|	�2d.d/�}|j�rw|
475  g}d0|v�r�|�3|�t4�}|j5�6�t�7�}|dk�r4t�8|d�\}}t9�9|j:gggd�d�r"|j:�;d��sn
t9�9|j:gggd�d�s
t�<|�}|�r2|�=d1|���dSz.zt�>|�Wn
476  t?�yFYnwt�@|j:�A�d�t�@|j5�A�d�t�B|||�WdS|j�C|jD|j�t�Ed2�YdSddlF} |g}!|�|��r�tGjH}"|"�$��Id3��r�|"dd4�|"d5d�}"|"d6g|!}!d0|	v�r�|!�3|	�|�Jd7| �K|!��ztL|�}#WntMtNf�y�d}#Ynw| jO|!| jP| jP| jP|d8�}$|j�$�d9k�r�|#dk�r�|j:�;|#�}%nd}%t9�9|j:jQgggd�d�r|j:jQ�Rd��snt9�9|j:jQgggd�d�s�|$�S|%�\}&}'|j5�T|&�|'�r'|�=d:|'�|$jU�V�|$jW�V�|$jX}(|(�r?|�=d;|(�dS|�Jd<�dS)=zExecute a CGI script.rrrNr,r$zNo such CGI script (%r)z#CGI script is not a plain file (%r)z!CGI script is not executable (%r)�SERVER_SOFTWARE�SERVER_NAMEzCGI/1.1ZGATEWAY_INTERFACEZSERVER_PROTOCOLZSERVER_PORT�REQUEST_METHODZ	PATH_INFOZPATH_TRANSLATEDZSCRIPT_NAME�QUERY_STRINGZREMOTE_ADDR�
authorizationr	Z	AUTH_TYPE�basic�ascii�:ZREMOTE_USERzcontent-type�CONTENT_TYPEzcontent-length�CONTENT_LENGTH�referer�HTTP_REFERER�acceptr�,ZHTTP_ACCEPTz
477  user-agent�HTTP_USER_AGENT�cookiez, �HTTP_COOKIE)raZREMOTE_HOSTrgrlrnrizScript output follows�+r��=zCGI script exit code r�zw.exe����������z-uzcommand: %s)�stdin�stdoutr��env�postz%szCGI script exit status %#xzCGI script exited OK)YrYrWr1r�r�r:r�rA�existsr6rr�r��	FORBIDDENr]�	have_forkr\�copy�deepcopy�environr|�serverrr8r,rr(r�r�rr�rArEr0�base64�binasciirFrt�decodebytes�decode�Error�UnicodeError�get_content_type�get_allr�r0�
478  setdefaultrlr
479  r�rgr�rOrWrXrS�waitpid�selectr?�read�waitstatus_to_exitcoderZ�setuidr��dup2r�execve�handle_error�request�_exit�
480  subprocessr�rRr�r��list2cmdliner4rr3�Popen�PIPE�_sock�recv�communicatervr�r%rt�
481  returncode))r�dir�restr:�iZnextdirZnextrestZ	scriptdirr>rC�script�
482  scriptnameZ
483  scriptfileZispyruZuqrestrbr~r�lengthrhrj�ua�coZ
484  cookie_str�kZ
decoded_queryr�rI�pid�sts�exitcoder��cmdline�interp�nbytes�p�datartr��statusrrrrUs@
485  
486  
487  �
488  
489  
490  ��
491  
492  
493  �
494  
495  ��
496  
497  
498  
499  
500  
501  �
502  �
503  
504  ���
505  
506  zCGIHTTPRequestHandler.run_cgiN)rrrr�rTr�ry�rbufsizerVr�rTrXr\r]rUrrrrr�s
507  	rcGs4tj|tjtjd��}tt|��\}}}}}||fS)N)�type�flags)r�getaddrinfo�SOCK_STREAM�
508  AI_PASSIVE�next�iter)�address�infos�familyr��proto�	canonname�sockaddrrrr�_get_best_family�s�r�r�i@c	Cs�t||�\|_}||_|||��R}|j��dd�\}}d|vr&d|�d�n|}td|�d|�d|�d|�d	�	�z|��WntyQtd
509  �t�	d�Yn	wWd�dSWd�dS1sewYdS)zmTest the HTTP request handler class.
510  
511      This runs an HTTP server on port 8000 (or the port argument).
512  
513      Nr	re�[�]zServing HTTP on z port z	 (http://z/) ...z&
514  Keyboard interrupt received, exiting.r)
515  r��address_familyr8r�getsockname�print�
serve_forever�KeyboardInterruptr��exit)	�HandlerClass�ServerClass�protocolr�bind�addrZhttpdrZurl_hostrrr�test�s,������"�r��__main__z--cgi�
516  store_truezrun as CGI server)�action�helpz--bindz-b�ADDRESSz8specify alternate bind address (default: all interfaces))�metavarr�z--directoryz-dz8specify alternate directory (default: current directory))�defaultr�r�storer,z&specify alternate port (default: 8000))r�r�r��nargsr�cs$eZdZ�fdd�Zdd�Z�ZS)�DualStackServercsHt�t��|j�tjtjd�Wd�n1swYt���S)Nr)	�
517  contextlib�suppress�	Exceptionr�
518  setsockopt�IPPROTO_IPV6�IPV6_V6ONLYr�rrPr�rrrs
519  ��
520  zDualStackServer.server_bindcCs|j|||tjd�dS)Nr�)�RequestHandlerClassr�r�)rr�r�rrr�finish_requests
521  
522  �zDualStackServer.finish_request)rrrrr�r@rrr�rr�sr�)r�r�rr�)7r�r��__all__rzr�email.utilsr�rr�http.clientr<r r�r:r�r.r�r5rr
523  r�r��urllib.parser�rr�r�rr�ThreadingMixInr�StreamRequestHandlerrrrHrIrOrRrr�r�r�argparser��ArgumentParser�parser�add_argumentr�r4�
524  parse_argsr��cgi�
handler_classr�rr�rrrr�<module>s�Rs0
525  
526  ��
527  ���

528  ��