3 \ R� @sdZddlmZmZmZddlmZddlZddlZddl Z dddd d d gZ d d dddddgZ dddddddddddddg Z dd �Z d!d"d#d$d%d&d'd(d)d*h jZd+d,�Zd-d �ZGd.d�d�ZGd/d�de�ZGd0d�de�ZGd1d �d e�ZGd2d �d e�ZdS)3z/Base classes for server/gateway implementations�)� FileWrapper� guess_scheme� is_hop_by_hop)�Headers�N� BaseHandler� SimpleHandler�BaseCGIHandler� CGIHandler� IISCGIHandler� read_environZMonZTueZWedZThuZFriZSatZSunZJanZFebZMarZAprZMayZJunZJulZAugZSepZOctZNovZDecc Cs:tj|�\ }}}}}}}}} dt||t|||||fS)Nz#%s, %02d %3s %4d %02d:%02d:%02d GMT)�timeZgmtime� _weekdayname� _monthname) Z timestampZyearZmonthZdayZhhZmmZssZwd�y�z�r�(/usr/lib64/python3.6/wsgiref/handlers.py�format_date_timesr� SCRIPT_NAME� PATH_INFOZ QUERY_STRINGZREQUEST_METHODZ AUTH_TYPEZ CONTENT_TYPEZCONTENT_LENGTHZHTTPSZ REMOTE_USERZ REMOTE_IDENTcCs6t|�p4|jd�p4|jd�p4|jd�o4t|dd��S)NZHTTP_ZSSL_Z REDIRECT_� )� _is_request� startswith�_needs_transcode)�krrrrsrc Cs�tj�}d}ydjd|�Wntk r4d}YnXi}x�tjj�D]�\}}t|�r�tjdkr�tjj dd�j �}|j d�r�|jd�j d�}q�|j d �r�q�|j d �r�d |kr�|jd�j d�}q�|j|d�j d�}n|j||�j d�}|||<qFW|S) z'Read environment, fixing HTTP variables�surrogateescape�zutf-8�replaceZwin32�SERVER_SOFTWAREzmicrosoft-iis/z iso-8859-1zapache/z simplehttp/zpython/3) �sys�getfilesystemencoding�encode� LookupError�os�environ�itemsr�platform�get�lowerr�decode)�enc�escr%r�vZsoftwarerrrr "s,      c@s"eZdZdZd<ZdZdZdZdZdZ dZ e �Z e ZeZdZdZd=gZd ZdZZdZdZdZd d �Zdd�Zdd�Zdd�Zdd�Zdd�Zd>dd�Z dd�Z!dd�Z"dd�Z#d d!�Z$d"d#�Z%d$d%�Z&d&d'�Z'd(d)�Z(d*d+�Z)d,d-�Z*d.d/�Z+d0d1�Z,d2d3�Z-d4d5�Z.d6d7�Z/d8d9�Z0d:d;�Z1dS)?rz+Manage the invocation of a WSGI applicationrrTFz1.0Nz500 Internal Server Error� Content-Type� text/plains;A server error occurred. Please contact the administrator.cCsZy$|j�||j|j�|_|j�Wn0y |j�Wn|j��YnXYnXdS)zInvoke the applicationN)� setup_environr%�start_response�result�finish_response� handle_error�close)�selfZ applicationrrr�run�s  zBaseHandler.runcCs�|jj�}|_|j�|j�|d<|j�|d<|j|d<|j|d<|j�|d<|j |d<|j |d<|j dk rx|j |d <|j r�|j r�|jd |j �dS) z&Set up the environment for one requestz wsgi.inputz wsgi.errorsz wsgi.versionz wsgi.run_oncezwsgi.url_schemezwsgi.multithreadzwsgi.multiprocessNzwsgi.file_wrapperr)� os_environ�copyr%� add_cgi_vars� get_stdin� get_stderr� wsgi_version� wsgi_run_once� get_scheme�wsgi_multithread�wsgi_multiprocess�wsgi_file_wrapper� origin_server�server_software� setdefault)r6�envrrrr0�s          zBaseHandler.setup_environc CsJz:|j� s|j� r8x|jD]}|j|�qW|j�Wd|j�XdS)a>Send any iterable data, then close self and the iterable Subclasses intended for use in asynchronous servers will want to redefine this method, such that it sets up callbacks in the event loop to iterate over the data, and to call 'self.close()' once the response is finished. N)�result_is_file�sendfiler2�write�finish_contentr5)r6�datarrrr3�s   zBaseHandler.finish_responsecCs t|j�S)z Return the URL scheme being used)rr%)r6rrrr?�szBaseHandler.get_schemec CsJyt|j�}Wntttfk r(YnX|dkrFt|j�|jd<dSdS)z@Compute Content-Length or switch to chunked encoding if possiblerzContent-LengthN)�lenr2� TypeError�AttributeError�NotImplementedError�str� bytes_sent�headers)r6Zblocksrrr�set_content_length�szBaseHandler.set_content_lengthcCsd|jkr|j�dS)zqMake any necessary header changes or defaults Subclasses can extend this to add other defaults. zContent-LengthN)rRrS)r6rrr�cleanup_headers�s zBaseHandler.cleanup_headersc Cs�|r2z$|jr&|d|d�j|d��Wdd}Xn|jdk rDtd��||_|j|�|_|j|d�}t|�dksvtd��|dd �j�s�td ��|d d ks�td ��x:|D]2\}}|j|d �}|j|d�}t |� s�td��q�W|j S)z4'start_response()' callable as specified by PEP 3333rr�NzHeaders already set!ZStatus�z$Status must be at least 4 characters�z(Status message must begin w/3-digit code� z+Status message must have a space after codez Header namez Header valuezHop-by-hop headers not allowed) � headers_sent�with_tracebackrR�AssertionError�status� headers_class�_convert_string_typerL�isdigitrrI)r6r\rR�exc_info�name�valrrrr1�s$     zBaseHandler.start_responsecCs(t|�tkr|Stdj|t|����dS)zConvert/check value type.z!{0} must be of type str (got {1})N)�typerPr[�format�repr)r6�value�titlerrrr^�s z BaseHandler._convert_string_typecCs�|jrx|j�r�|jd|j|jfjd��d|jkrP|jdttj��jd��|j r�d|jkr�|jd|j jd��n|jd|jjd��dS) z6Transmit version/status/date/server, via self._write()z HTTP/%s %s z iso-8859-1ZDatez Date: %s ZServerz Server: %s z Status: %s N) rC�client_is_modern�_write� http_versionr\r"rRrr rD)r6rrr� send_preamble�s zBaseHandler.send_preamblecCsft|�tkstd��|js$td��n,|js>t|�|_|j�n|jt|�7_|j|�|j �dS)z+'write()' callable as specified by PEP 3333z)write() argument must be a bytes instancezwrite() before start_response()N) rc�bytesr[r\rYrLrQ� send_headersri�_flush)r6rKrrrrIs    zBaseHandler.writecCsdS)aPlatform-specific file transmission Override this method in subclasses to support platform-specific file transmission. It is only called if the application's return iterable ('self.result') is an instance of 'self.wsgi_file_wrapper'. This method should return a true value if it was able to actually transmit the wrapped file-like object using a platform-specific approach. It should return a false value if normal iteration should be used instead. An exception can be raised to indicate that transmission was attempted, but failed. NOTE: this method should call 'self.send_headers()' if 'self.headers_sent' is false and it is going to attempt direct transmission of the file. Fr)r6rrrrHszBaseHandler.sendfilecCs"|js|jjdd�|j�ndS)z.Ensure headers and content have both been sentzContent-Length�0N)rYrRrErm)r6rrrrJ0s zBaseHandler.finish_contentc CsFzt|jd�r|jj�Wdd|_|_|_|_d|_d|_XdS)z�Close the iterable (if needed) and reset all instance vars Subclasses may want to also drop the client connection. r5NrF)�hasattrr2r5rRr\r%rQrY)r6rrrr5:s  zBaseHandler.closecCs:|j�d|_|j s|j�r6|j�|jt|j��dS)z1Transmit headers to the client, via self._write()TN)rTrYrCrhrkrirlrR)r6rrrrmGs zBaseHandler.send_headerscCs|j}|dk ot|j|�S)z@True if 'self.result' is an instance of 'self.wsgi_file_wrapper'N)rB� isinstancer2)r6�wrapperrrrrGPszBaseHandler.result_is_filecCs|jdj�dkS)z,True if client can accept status and headersZSERVER_PROTOCOLzHTTP/0.9)r%�upper)r6rrrrhVszBaseHandler.client_is_modernc CsJz>ddlm}|j�}||d|d|d|j|�|j�Wdd}XdS)z�Log the 'exc_info' tuple in the server log Subclasses may override to retarget the output or change its format. r)�print_exceptionrrUN)� tracebackrtr<�traceback_limit�flush)r6r`rt�stderrrrr� log_exception[s   zBaseHandler.log_exceptioncCs2|jtj��|js.|j|j|j�|_|j�dS)z>Log current error, and send error output to client if possibleN) ryr r`rY� error_outputr%r1r2r3)r6rrrr4kszBaseHandler.handle_errorcCs$||j|jdd�tj��|jgS)aZWSGI mini-app to create error output By default, this just uses the 'error_status', 'error_headers', and 'error_body' attributes to generate an output page. It can be overridden in a subclass to dynamically generate diagnostics, choose an appropriate message for the user's preferred language, etc. Note, however, that it's not recommended from a security perspective to spit out diagnostics to any old user; ideally, you should have to do something special to enable diagnostic output, which is why we don't include any here! N)� error_status� error_headersr r`� error_body)r6r%r1rrrrzss zBaseHandler.error_outputcCst�dS)aOverride in subclass to buffer data for send to client It's okay if this method actually transmits the data; BaseHandler just separates write and flush operations for greater efficiency when the underlying system actually has such a distinction. N)rO)r6rKrrrri�szBaseHandler._writecCst�dS)z�Override in subclass to force sending of recent '_write()' calls It's okay if this method is a no-op (i.e., if '_write()' actually sends the data. N)rO)r6rrrrn�szBaseHandler._flushcCst�dS)z4Override in subclass to return suitable 'wsgi.input'N)rO)r6rrrr;�szBaseHandler.get_stdincCst�dS)z5Override in subclass to return suitable 'wsgi.errors'N)rO)r6rrrr<�szBaseHandler.get_stderrcCst�dS)z>Override in subclass to insert CGI variables in 'self.environ'N)rO)r6rrrr:�szBaseHandler.add_cgi_vars)rr)r.r/)N)2�__name__� __module__� __qualname__�__doc__r=r@rAr>rCrjrDr r8rrBrr]rvr{r|r}r\r2rYrRrQr7r0r3r?rSrTr1r^rkrIrHrJr5rmrGrhryr4rzrirnr;r<r:rrrrr^sV      c@sBeZdZdZddd�Zdd�Zdd �Zd d �Zd d �Zdd�Z dS)raqHandler that's just initialized with streams, environment, etc. This handler subclass is intended for synchronous HTTP/1.0 origin servers, and handles sending the entire response output, given the correct inputs. Usage:: handler = SimpleHandler( inp,out,err,env, multithread=False, multiprocess=True ) handler.run(app)TFcCs(||_||_||_||_||_||_dS)N)�stdin�stdoutrx�base_envr@rA)r6r�r�rxr%� multithread� multiprocessrrr�__init__�s zSimpleHandler.__init__cCs|jS)N)r�)r6rrrr;�szSimpleHandler.get_stdincCs|jS)N)rx)r6rrrr<�szSimpleHandler.get_stderrcCs|jj|j�dS)N)r%�updater�)r6rrrr:�szSimpleHandler.add_cgi_varscCsb|jj|�}|dks |t|�kr$dSddlm}|dt�x"||d�}|sNP|jj|�}q<WdS)Nr)�warnz9SimpleHandler.stdout.write() should not do partial writes)r�rIrL�warningsr��DeprecationWarning)r6rKr2r�rrrri�s   zSimpleHandler._writecCs|jj�|jj|_dS)N)r�rwrn)r6rrrrn�s zSimpleHandler._flushN)TF) r~rr�r�r�r;r<r:rirnrrrrr�s   c@seZdZdZdZdS)r a�CGI-like systems using input/output/error streams and environ mapping Usage:: handler = BaseCGIHandler(inp,out,err,env) handler.run(app) This handler class is useful for gateway protocols like ReadyExec and FastCGI, that have usable input/output/error streams and an environment mapping. It's also the base class for CGIHandler, which just uses sys.stdin, os.environ, and so on. The constructor also takes keyword arguments 'multithread' and 'multiprocess' (defaulting to 'True' and 'False' respectively) to control the configuration sent to the application. It sets 'origin_server' to False (to enable CGI-like output), and assumes that 'wsgi.run_once' is False. FN)r~rr�r�rCrrrrr �sc@s eZdZdZdZiZdd�ZdS)r a�CGI-based invocation via sys.stdin/stdout/stderr and os.environ Usage:: CGIHandler().run(app) The difference between this class and BaseCGIHandler is that it always uses 'wsgi.run_once' of 'True', 'wsgi.multithread' of 'False', and 'wsgi.multiprocess' of 'True'. It does not take any initialization parameters, but always uses 'sys.stdin', 'os.environ', and friends. If you need to override any of these parameters, use BaseCGIHandler instead. Tc Cs(tj|tjjtjjtjt�ddd�dS)NFT)r�r�)r r�r r��bufferr�rxr )r6rrrr�szCGIHandler.__init__N)r~rr�r�r>r8r�rrrrr �sc@s eZdZdZdZiZdd�ZdS)r aCGI-based invocation with workaround for IIS path bug This handler should be used in preference to CGIHandler when deploying on Microsoft IIS without having set the config allowPathInfo option (IIS>=7) or metabase allowPathInfoForScriptMappings (IIS<7). Tc Csjt�}|jdd�}|jdd�}|dj|d�rD|t|�d�|d<tj|tjjtj jtj |ddd�dS)Nrrr�/FT)r�r�) r r(rrLr r�r r�r�r�rx)r6r%�pathZscriptrrrr�$s  zIISCGIHandler.__init__N)r~rr�r�r>r8r�rrrrr s)r��utilrrrrRrr r$r �__all__rrr� __contains__rrr rrr r r rrrr�<module>s*   <H2