B -_@sXdZddlZddlZddlZddlZddlZddlZddlZ ddl m Z dddddd d d d d ddddddddgZ dZ dZdZdZdZdZeejjddejjDZdZdZd Zed!jZed"jZ ed#Z!d$d%d&hZ"d@d(d)Z#Gd*d+d+ej$j%Z&e&fd,d-Z'Gd.ddej(Z)Gd/ddZ*y ddl+Z+Wne,k rRYnXGd0d1d1e*Z-e .d1Gd2dde/Z0Gd3dde0Z1Gd4d d e0Z2Gd5dde0Z3Gd6d d e0Z4Gd7d d e0Z5Gd8d d e0Z6Gd9d d e0Z7Gd:dde7Z8Gd;dde7Z9Gddde0Ze0Z?dS)Aa HTTP/1.1 client library 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 Req-started-unread-response _CS_REQ_STARTED Req-sent-unread-response _CS_REQ_SENT N)urlsplit HTTPResponseHTTPConnection HTTPException NotConnectedUnknownProtocolUnknownTransferEncodingUnimplementedFileModeIncompleteRead InvalidURLImproperConnectionStateCannotSendRequestCannotSendHeaderResponseNotReady BadStatusLine LineTooLongRemoteDisconnectederror responsesPiZUNKNOWNZIdlezRequest-startedz Request-sentcCsi|] }|j|qS)phrase).0vrr!/usr/lib/python3.7/http/client.py jsriids[^:\s][^:\r\n]*s\n(?![ \t])|\r(?![ \t\n])z[- ]ZPATCHZPOSTZPUTdatac Csfy |dStk r`}z8t|j|j|j|jd|||j|j|fdWdd}~XYnXdS)zd?Z Z!S)FrrNcCsR|d|_||_||_d|_|_t|_t|_t|_ t|_ t|_ t|_ t|_ dS)Nrb)ZmakefilerA debuglevel_methodrBmsg_UNKNOWNversionstatusreasonchunked chunk_leftlength will_close)r0sockrEmethodurlrrr__init__s  zHTTPResponse.__init__c Cst|jtdd}t|tkr*td|jdkrBtdt||sNt dy| dd\}}}WnFt k ry| dd\}}d}Wnt k rd}YnXYnX| d s| t|y$t|}|d ks|d krt|Wnt k rt|YnX|||fS) Nr*z iso-8859-1z status linerzreply:z-Remote end closed connection without responsezHTTP/ri)strrAr:r;r,rrEprintreprrsplit ValueError startswith _close_connrint)r0r2rIrJrKrrr _read_status s2    zHTTPResponse._read_statuscCs|jdk rdSxh|\}}}|tkr(PxJ|jtd}t|tkrNtd|}|s\P|j dkr*t d|q*WqW||_ |_ ||_ |dkrd|_n|drd|_nt|t|j|_|_|j dkrx&|jD]}t d|d |j|qW|jd }|r*|d kr*d |_d|_nd |_||_d|_|jd}|jd }|r|jsyt||_Wntk rd|_YnX|jdkrd|_nd|_|tks|tksd|krdksn|jdkrd|_|js|js|jdkrd |_dS)Nr*z header linerzheader:)zHTTP/1.0zHTTP/0.9 zHTTP/1. r)ztransfer-encodingrLTFzcontent-lengthrHEAD)rBr^ZCONTINUErAr:r;r,rstriprErWcoderJrKrIr[rrCrGgetr+rLrM _check_closerOrNr]rZZ NO_CONTENTZ NOT_MODIFIEDrF)r0rIrJrKskiphdrZtr_encrNrrrbegin+sf                zHTTPResponse.begincCsv|jd}|jdkr.|r*d|kr*dSdS|jdr>dS|rRd|krRdS|jd}|rrd|krrdSdS)NZ connectionr`closeTFz keep-alivezproxy-connection)rBrerIr+)r0ZconnZpconnrrrrf{s    zHTTPResponse._check_closecCs|j}d|_|dS)N)rArj)r0rArrrr\szHTTPResponse._close_conncs$ztWd|jr|XdS)N)superrjrAr\)r0) __class__rrrjszHTTPResponse.closecst|jr|jdS)N)rkflushrA)r0)rlrrrms zHTTPResponse.flushcCsdS)zAlways returns TrueTr)r0rrrreadableszHTTPResponse.readablecCs |jdkS)z!True if the connection is closed.N)rA)r0rrrisclosedszHTTPResponse.isclosedcCs|jdkrdS|jdkr$|dS|dk rRt|}||}t|d|S|jr`|S|j dkrv|j }n6y| |j }Wnt k r|YnXd|_ ||SdS)Nr8rbr) rArFr\ bytearrayreadinto memoryviewtobytesrL_readall_chunkedrNread _safe_readr )r0amtbr1srrrrus*     zHTTPResponse.readcCs|jdkrdS|jdkr$|dS|jr4||S|jdk r^t||jkr^t|d|j}|j|}|s||r||n&|jdk r|j|8_|js||S)z^Read up to len(b) bytes into bytearray b and return the number of bytes read. Nrrb) rArFr\rL_readinto_chunkedrNr,rrrq)r0rxr1rrrrqs$       zHTTPResponse.readintocCsp|jtd}t|tkr$td|d}|dkrB|d|}y t|dStk rj|YnXdS)Nr*z chunk size;r) rAr:r;r,rfindr]rZr\)r0r2irrr_read_next_chunk_sizes    z"HTTPResponse._read_next_chunk_sizecCs>x8|jtd}t|tkr&td|s,P|dkrPqWdS)Nr*z trailer line)s r7r8)rAr:r;r,r)r0r2rrr_read_and_discard_trailers z&HTTPResponse._read_and_discard_trailercCsl|j}|sh|dk r|dy |}Wntk rDtdYnX|dkrb||d}||_|S)NrTr8r)rMrvrrZr rr\)r0rMrrr_get_chunk_lefts  zHTTPResponse._get_chunk_leftcCsr|jtkstg}y8x,|}|dkr(P|||d|_qWd|Stk rltd|YnXdS)Nrr8) rLrHAssertionErrorrr/rvrMr=r )r0valuerMrrrrt6s  zHTTPResponse._readall_chunkedcCs|jtkstd}t|}yvxp|}|dkr2|St||krZ||}|||_||S|d|}||}||d}||7}d|_qWWn(tk rtt |d|YnXdS)Nr) rLrHrrrrr,_safe_readintorMr bytes)r0rx total_bytesmvbrMr1temp_mvbrrrrzDs&      zHTTPResponse._readinto_chunkedcCsXg}xH|dkrL|jt|t}|s4td|||||t|8}qWd|S)aVRead the number of bytes requested, compensating for partial reads. Normally, we have a blocking socket, but a read() can be interrupted by a signal (resulting in a partial read). Note that we cannot distinguish between EOF and an interrupt when zero bytes have been read. IncompleteRead() will be raised in this situation. This function should be used when bytes "should" be present for reading. If the bytes are truly not available (due to EOF), then the IncompleteRead exception can be used to detect the problem. rr8)rArumin MAXAMOUNTr r=r/r,)r0rwrychunkrrrrv\s  zHTTPResponse._safe_readcCsd}t|}xt|t|krtt|kr@|dt}|j|}n |j|}|sjtt|d|t|||d}||7}qW|S)z2Same as _safe_read, but for reading into a buffer.rN)rrr,rrArqr r)r0rxrrrr1rrrrss     zHTTPResponse._safe_readintocCs|jdks|jdkrdS|jr(||S|jdk rJ|dksD||jkrJ|j}|j|}|sh|rh|n|jdk r|jt|8_|S)zvRead with at most one underlying system call. If at least one byte is buffered, return that instead. Nrbr8r)rArFrL_read1_chunkedrNread1r\r,)r0r1resultrrrrs    zHTTPResponse.read1cCs4|jdks|jdkrdS|jr(||S|j|S)Nrbr8)rArFrL _peek_chunkedpeek)r0r1rrrrs  zHTTPResponse.peekcs|jdks|jdkrdS|jr*t|S|jdk rL|dksF||jkrL|j}|j|}|sj|rj|n|jdk r|jt|8_|S)Nrbr8r)rArFrLrkr:rNr\r,)r0limitr)rlrrr:s    zHTTPResponse.readlinecCsd|}|dks|dkrdSd|kr0|ks6n|}|j|}|jt|8_|s`td|S)Nrr8)rrArrMr,r )r0r1rMrurrrrs zHTTPResponse._read1_chunkedcCsBy |}Wntk r dSX|dkr.dS|j|d|S)Nr8)rr rAr)r0r1rMrrrrs zHTTPResponse._peek_chunkedcCs |jS)N)rAfileno)r0rrrrszHTTPResponse.filenocCsF|jdkrt|j|p|}t|ts4t|ds8|Sd|SdS)axReturns 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. N__iter__z, )rBrZget_all isinstancerVhasattrr=)r0r%defaultrBrrr getheaders zHTTPResponse.getheadercCs|jdkrtt|jS)z&Return list of (header, value) tuples.N)rBrlistitems)r0rrr getheaderss zHTTPResponse.getheaderscCs|S)Nr)r0rrrrszHTTPResponse.__iter__cCs|jS)ajReturns 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. )rB)r0rrrinfoszHTTPResponse.infocCs|jS)aZReturn 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. )rR)r0rrrgeturls zHTTPResponse.geturlcCs|jS)zuReturn the HTTP status code that was sent with the response, or None if the URL is not an HTTP URL. )rJ)r0rrrgetcodeszHTTPResponse.getcode)rNN)N)r)r)r)N)"r4r5r6rSr^rirfr\rjrmrnrorurqrrrrtrzrvrrrr:rrrrrrrrr __classcell__rr)rlrrs< !P  "     c@seZdZdZdZeZeZdZ dZ e ddZ e ddZ d ejd d fd d Zd/d dZddZddZddZddZddZddZddZddZd0d d!Zd1d"d#Zd$d%Zd2dd&d'd(Zd ifdd&d)d*Zd+d,Zd-d.Z d S)3rr`zHTTP/1.1r*rcCs t|tjS)zFTest whether a file-like object is a text or a binary stream. )rio TextIOBase)streamrrr _is_textIOszHTTPConnection._is_textIOcCsd|dkr|tkrdSdSt|dr*dSyt|}|jStk rLYnXt|tr`t|SdS)aGet the content-length based on the body. If the body is None, we set Content-Length: 0 for methods that expect a body (RFC 7230, Section 3.3.2). We also set the Content-Length for any method if the body is a str or bytes-like object and not a file. Nrru) upper_METHODS_EXPECTING_BODYrrrnbytes TypeErrorrrVr,)bodyrQZmvrrr_get_content_length%s   z"HTTPConnection._get_content_lengthNi cCsb||_||_||_d|_g|_d|_t|_d|_d|_ d|_ i|_ | ||\|_ |_tj|_dS)N)timeoutsource_address blocksizerP_buffer_HTTPConnection__response_CS_IDLE_HTTPConnection__staterF _tunnel_host _tunnel_port_tunnel_headers _get_hostporthostportsocketZcreate_connection_create_connection)r0rrrrrrrrrSEszHTTPConnection.__init__cCs<|jrtd|||\|_|_|r.||_n |jdS)aDSet 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. z.Can't set up tunnel for established connectionN)rP RuntimeErrorrrrrclear)r0rrrBrrr set_tunnelYs zHTTPConnection.set_tunnelcCs|dkr|d}|d}||kryt||dd}WnHtk r||dddkrh|j}ntd||ddYnX|d|}n|j}|r|ddkr|ddkr|dd}||fS) Nr)]r*rUznonnumeric port: '%s'r[r)rfindr]rZ default_portr )r0rrr~jrrrrqs   zHTTPConnection._get_hostportcCs ||_dS)N)rE)r0levelrrrset_debuglevelszHTTPConnection.set_debuglevelc Csd|j|jf}|d}||x6|jD](\}}d||f}|d}||q0W|d|j|j|jd}| \}} } | t j j kr| td| | fxP|jtd} t| tkrtd | sP| d krP|jd krtd | qWdS) NzCONNECT %s:%d HTTP/1.0 asciiz%s: %s zlatin-1s )rQzTunnel connection failed: %d %sr*z header line)s r7r8rzheader:)rrrsendrrresponse_classrPrFr^http HTTPStatusZOKrjOSErrorrcrAr:r;r,rrErWr>) r0Z connect_strZ connect_bytesheaderrZ header_strZ header_bytesresponserIrdmessager2rrr_tunnels2         zHTTPConnection._tunnelcCsB||j|jf|j|j|_|jtjtj d|j r>| dS)z3Connect to the host and port specified in __init__.r*N) rrrrrrPZ setsockoptrZ IPPROTO_TCPZ TCP_NODELAYrr)r0rrrconnects zHTTPConnection.connectcCsBt|_z|j}|r d|_|Wd|j}|r) r0rQrR skip_hostskip_accept_encodingmatchrequestZnetlocZnilZ netloc_encrrZhost_encrrr putrequest/sT           zHTTPConnection.putrequestcGs|jtkrtt|dr$|d}t|s:td|ft|}xht|D]\\}}t|drn|d||<nt |t rt |d||<t ||rLtd||fqLWd |}|d|}||dS) zkSend a request header line to the server. For example: h.putheader('Accept', 'text/html') rrzInvalid header name %rzlatin-1zInvalid header value %rs s: N)rrrrr_is_legal_header_namerZr enumeraterr]rV_is_illegal_header_valuer=r)r0rvaluesr~Z one_valuerrrrrs"        zHTTPConnection.putheader)rcCs*|jtkrt|_nt|j||ddS)zIndicate 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. )rN)rr _CS_REQ_SENTrr)r0rrrrr endheaderss zHTTPConnection.endheaderscCs||||||dS)z&Send a complete request to the server.N) _send_request)r0rQrRrrBrrrrrszHTTPConnection.requestc Cstdd|D}i}d|kr&d|d<d|kr6d|d<|j||f|d|krd |krd }|||}|dkr|dk r|jd krtd |d }|ddq|dt|nd }x |D]\} } || | qWt|trt |d}|j ||ddS)Ncss|]}|VqdS)N)r+)rkrrr sz/HTTPConnection._send_request..rr*rzaccept-encodingrzcontent-lengthztransfer-encodingFrzUnable to determine size of %rTzTransfer-EncodingrLzContent-Lengthr)r) frozensetrrrErWrrVrrr'r) r0rQrRrrBrZ header_namesZskipsZcontent_lengthrhrrrrrs0      zHTTPConnection._send_requestcCs|jr|jrd|_|jtks&|jr0t|j|jdkrR|j|j|j|jd}n|j|j|jd}yZy | Wnt k r| YnX|j t kstt|_|j r| n||_|S| YnXdS)a)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. Nr)rQ)rrorrrrErrPrFriConnectionErrorrjrOrHrr)r0rrrr getresponse s.      zHTTPConnection.getresponse)NN)NF)FF)N)!r4r5r6rrrr HTTP_PORTrrrE staticmethodrrr_GLOBAL_DEFAULT_TIMEOUTrSrrrrrrjrrrrrrrrrrrrrrrs:    & 6  .csHeZdZdZeZdddejdfddddfdd ZfddZ Z S) HTTPSConnectionz(This class allows communication via SSL.Ni )contextcheck_hostnamerc stt|j||||| d|dk s2|dk s2|dk rHddl} | dtd||_||_|dkrdt }|j tj k} |dkr~|j }|r| st d|s|r|||||_|dk r||j_ dS)N)rrzTkey_file, cert_file and check_hostname are deprecated, use a custom context instead.rTzMcheck_hostname needs a SSL context with either CERT_OPTIONAL or CERT_REQUIRED)rkrrSwarningswarnDeprecationWarningkey_file cert_filesslZ_create_default_https_contextZ verify_modeZ CERT_NONErrZZload_cert_chain_context) r0rrrrrrrrrrZ will_verify)rlrrrSWs,  zHTTPSConnection.__init__cs6t|jr|j}n|j}|jj|j|d|_dS)z(Connect to a host on a given (SSL) port.)server_hostnameN)rkrrrrZ wrap_socketrP)r0r)rlrrrts   zHTTPSConnection.connect) r4r5r6__doc__ HTTPS_PORTrrrrSrrrr)rlrrPsrc@s eZdZdS)rN)r4r5r6rrrrrsc@s eZdZdS)rN)r4r5r6rrrrrsc@s eZdZdS)r N)r4r5r6rrrrr sc@seZdZddZdS)rcCs|f|_||_dS)N)argsrI)r0rIrrrrSszUnknownProtocol.__init__N)r4r5r6rSrrrrrsc@s eZdZdS)rN)r4r5r6rrrrrsc@s eZdZdS)r N)r4r5r6rrrrr sc@s&eZdZdddZddZddZdS) r NcCs|f|_||_||_dS)N)r partialexpected)r0r r rrrrSszIncompleteRead.__init__cCs2|jdk rd|j}nd}d|jjt|j|fS)Nz, %i more expectedrUz%s(%i bytes read%s))r rlr4r,r )r0errr__repr__s   zIncompleteRead.__repr__cCst|S)N)rX)r0rrr__str__szIncompleteRead.__str__)N)r4r5r6rSr rrrrrr s c@s eZdZdS)r N)r4r5r6rrrrr sc@s eZdZdS)r N)r4r5r6rrrrr sc@s eZdZdS)rN)r4r5r6rrrrrsc@s eZdZdS)rN)r4r5r6rrrrrsc@seZdZddZdS)rcCs|s t|}|f|_||_dS)N)rXr r2)r0r2rrrrSszBadStatusLine.__init__N)r4r5r6rSrrrrrsc@seZdZddZdS)rcCst|dt|fdS)Nz&got more than %d bytes when reading %s)rrSr;)r0Z line_typerrrrSszLineTooLong.__init__N)r4r5r6rSrrrrrsc@seZdZddZdS)rcOs"t|dtj|f||dS)NrU)rrSConnectionResetError)r0poskwrrrrSs zRemoteDisconnected.__init__N)r4r5r6rSrrrrrs)r)@rZ email.parserr?Z email.messagerrrerZcollections.abcrZ urllib.parser__all__rrrHrrrglobalsupdater __members__rrrr;r<compile fullmatchrrrrrr'rZMessager(rCBufferedIOBaserrr ImportErrorrr/ Exceptionrrr rrr r r r rrrrrrrrrrrEs       6: 1