o w[e@sPdZddlZddlZddlZddlZddlZddlZddlZddl Z ddl Z ddl m Z gdZdZdZdZdZd Zd Zeejjd d ejjDZd ZdZedjZedj Z!edZ"edZ#hdZ$d?ddZ%Gdddej&j'Z(ddZ)e(fddZ*Gdddej+Z,Gdd d Z-zddl.Z.Wn e/yYnwGd!d"d"e-Z0e1d"Gd#d$d$e2Z3Gd%d&d&e3Z4Gd'd(d(e3Z5Gd)d*d*e3Z6Gd+d,d,e3Z7Gd-d.d.e3Z8Gd/d0d0e3Z9Gd1d2d2e3Z:Gd3d4d4e:Z;Gd5d6d6e:ZGd;d<dd>e@e>ZAe3ZBdS)@a 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 responsesPiUNKNOWNIdlezRequest-startedz Request-sentcCsi|]}||jqS)phrase).0vrr"/usr/lib/python3.10/http/client.py lsrids[^:\s][^:\r\n]*s\n(?![ \t])|\r(?![ \t\n])z[- ]z[-]>PUTPOSTPATCHdatac CsZz|dWSty,}zt|j|j|j|jd|||j|j|fdd}~ww)zd?Z Z!S)CrrNcCsR|d|_||_||_d|_|_t|_t|_t|_ t|_ t|_ t|_ t|_ dS)Nrb)makefilerH debuglevel_methodrImsg_UNKNOWNversionstatusreasonchunked chunk_leftlength will_close)r7sockrWmethodurlrrr__init__s   zHTTPResponse.__init__c Cst|jtdd}t|tkrtd|jdkr!tdt||s't dz | dd\}}}Wn!t ySz | dd\}}d}Wn t yPd}YnwYnw| d sa| t|zt|}|d ksn|d krrt|Wn t y~t|w|||fS) Nr1rKz status linerzreply:z-Remote end closed connection without responsezHTTP/ri)strrHrErFr3rrWprintreprrsplit ValueError startswith _close_connrint)r7r;r[r\r]rrr _read_statuss<       zHTTPResponse._read_statusc Cs|jdurdS |\}}}|tkrnt|j}|jdkr#td|~q||_|_| |_ |dvr8d|_ n | drAd|_ nt |t|j|_|_|jdkre|jD] \}}td|d |qX|jd }|rz|d krzd|_d|_nd |_||_d|_|jd }|r|jszt||_Wn tyd|_Yn w|jdkrd|_nd|_|tks|tksd|krdksn|jdkrd|_|js|js|jdurd|_dSdSdSdS)NTrzheaders:)zHTTP/1.0zHTTP/0.9 zHTTP/1. header:r0transfer-encodingr^Fcontent-lengthrHEAD)rIrpCONTINUErJrHrWricoder\stripr]r[rmrrTrYitemsgetr2r^r_ _check_closerar`rorl NO_CONTENT NOT_MODIFIEDrX) r7r[r\r]skipped_headershdrvaltr_encr`rrrbegin7sf                 zHTTPResponse.begincCsv|jd}|jdkr|rd|vrdSdS|jdrdS|r)d|vr)dS|jd}|r9d|vr9dSdS)N connectionrrcloseTFz keep-alivezproxy-connection)rIr|r[r2)r7connpconnrrrr}s    zHTTPResponse._check_closecCs|j}d|_|dSN)rHr)r7rHrrrrns zHTTPResponse._close_conncs6ztW|jr|dSdS|jr|wwr)superrrHrnr7 __class__rrrs   zHTTPResponse.closecs"t|jr|jdSdSr)rflushrHrrrrrs zHTTPResponse.flushcCsdS)zAlways returns TrueTrrrrrreadableszHTTPResponse.readablecCs |jduS)z!True if the connection is closed.N)rHrrrriscloseds zHTTPResponse.isclosedcCs|jdurdS|jdkr|dS|jr||S|durR|jdur+||jkr+|j}|j|}|s;|r;||S|jdurP|jt|8_|jsP||S|jdur]|j}nz||j}Wn t yq|wd|_||S)z?Read and return the response body, or up to the next amt bytes.NrDrwr) rHrXrnr^ _read_chunkedr`readr3 _safe_readr )r7amtsrrrrs<        zHTTPResponse.readcCs|jdurdS|jdkr|dS|jr||S|jdur/t||jkr/t|d|j}|j|}|s?|r?||S|jdurR|j|8_|jsR||S)z^Read up to len(b) bytes into bytearray b and return the number of bytes read. Nrrw) rHrXrnr^_readinto_chunkedr`r3 memoryviewreadinto)r7br8rrrrs&      zHTTPResponse.readintocCsh|jtd}t|tkrtd|d}|dkr!|d|}zt|dWSty3|w)Nr1z chunk size;r) rHrErFr3rfindrorlrn)r7r;irrr_read_next_chunk_size s     z"HTTPResponse._read_next_chunk_sizecCs< |jtd}t|tkrtd|sdS|dvrdSq)NTr1z trailer linerA)rHrErFr3rr7r;rrr_read_and_discard_trailers z&HTTPResponse._read_and_discard_trailercCsf|j}|s1|dur|dz|}Wn tytdw|dkr.||d}||_|S)NrfrDr)r_rrrlr rrn)r7r_rrr_get_chunk_left*s   zHTTPResponse._get_chunk_leftcCs|jtksJg}z: |}|durn*|dur*||kr*||||||_n||||dur:||8}d|_q d|WStyQtd|w)NTrrD)r^rZrr6rr_rMr )r7rvaluer_rrrrBs(   zHTTPResponse._read_chunkedcCs|jtksJd}t|}z: |}|dur|WSt||kr/||}|||_||WS|d|}||}||d}||7}d|_qtyXtt|d|w)Nr) r^rZrrr3_safe_readintor_r bytes)r7r total_bytesmvbr_r8temp_mvbrrrrXs*        zHTTPResponse._readinto_chunkedcCs.|j|}t||krt||t||S)a Read the number of bytes requested. 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. )rHrr3r )r7rr"rrrrps  zHTTPResponse._safe_readcCs:t|}|j|}||krtt|d||||S)z2Same as _safe_read, but for reading into a buffer.N)r3rHrr r)r7rrr8rrrr|s  zHTTPResponse._safe_readintocCs|jdus |jdkr dS|jr||S|jdur%|dks"||jkr%|j}|j|}|s5|r5||S|jdurC|jt|8_|S)zvRead with at most one underlying system call. If at least one byte is buffered, return that instead. NrwrDr)rHrXr^_read1_chunkedr`read1rnr3)r7r8resultrrrrs   zHTTPResponse.read1cCs4|jdus |jdkr dS|jr||S|j|S)NrwrD)rHrXr^ _peek_chunkedpeek)r7r8rrrrs   zHTTPResponse.peekcs|jdus |jdkr dS|jrt|S|jdur&|dks#||jkr&|j}|j|}|s6|r6||S|jdurD|jt|8_|S)NrwrDr)rHrXr^rrEr`rnr3)r7limitrrrrrEs   zHTTPResponse.readlinecCsd|}|dus |dkrdSd|kr|ksn|}|j|}|jt|8_|s0td|S)NrrD)rrHrr_r3r )r7r8r_rrrrrs zHTTPResponse._read1_chunkedcCsBz|}Wn tyYdSw|durdS|j|d|S)NrD)rr rHr)r7r8r_rrrrs  zHTTPResponse._peek_chunkedcCs |jSr)rHfilenorrrrr zHTTPResponse.filenocCsB|jdurt|j|p|}t|tst|ds|Sd|S)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, )rIrget_all isinstancerhhasattrrM)r7r+defaultrIrrr getheaders  zHTTPResponse.getheadercCs|jdurtt|jS)z&Return list of (header, value) tuples.N)rIrlistr{rrrr getheaderss zHTTPResponse.getheaderscCs|SrrrrrrrszHTTPResponse.__iter__cC|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. )rIrrrrinfoszHTTPResponse.infocCr)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. )rdrrrrgeturls zHTTPResponse.geturlcCr)zuReturn the HTTP status code that was sent with the response, or None if the URL is not an HTTP URL. )r\rrrrgetcodeszHTTPResponse.getcode)rNNr)r)"r=r>r?rerprr}rnrrrrrrrrrrrrrrrrErrrrrrrrr __classcell__rrrrrs> !H   ("      rc@seZdZdZdZeZeZdZ dZ e ddZ e ddZ d ejd d fd d Zd7d dZddZddZddZddZddZddZddZddZd8d d!Z  d9d"d#Zd$d%Zd&d'Zd(d)Zd*d+Zd,d-Z d:dd.d/d0Z!d ifdd.d1d2Z"d3d4Z#d5d6Z$d S);rrrzHTTP/1.1r1rcCs t|tjS)zFTest whether a file-like object is a text or a binary stream. )rio TextIOBase)streamrrr _is_textIO s zHTTPConnection._is_textIOcCsd|dur|tvr dSdSt|drdSzt|}|jWSty&Ynwt|tr0t|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. Nrr) upper_METHODS_EXPECTING_BODYrrnbytes TypeErrorrrhr3)bodyrcmvrrr_get_content_length&s    z"HTTPConnection._get_content_lengthN cCsn||_||_||_d|_g|_d|_t|_d|_d|_ d|_ i|_ | ||\|_ |_||j tj|_dSr)timeoutsource_address blocksizerb_buffer_HTTPConnection__response_CS_IDLE_HTTPConnection__staterX _tunnel_host _tunnel_port_tunnel_headers _get_hostporthostport_validate_hostsocketcreate_connection_create_connection)r7rrrrrrrrreFs  zHTTPConnection.__init__cCs>|jrtd|||\|_|_|r||_dS|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 HTTP 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)rb RuntimeErrorrrrrclear)r7rrrIrrr set_tunnel\s  zHTTPConnection.set_tunnelcCs|dur`|d}|d}||krIz t||dd}Wn#tyA||dddkr3|j}n td||ddYnw|d|}n|j}|r`|ddkr`|ddkr`|dd}||fS) Nr0]r1rgznonnumeric port: '%s'r[r)rfindrorl default_portr )r7rrrjrrrrts"    zHTTPConnection._get_hostportcCs ||_dSr)rW)r7levelrrrset_debuglevelrzHTTPConnection.set_debuglevelc Csd|jd|jf}|g}|jD]\}}||d|ddq|d|d|~|j|j |j d}| \}}}|t j jkrZ|td |d | |jtd } t| tkrmtd | sqdS| dvrwdS|jdkrtd| q[)NsCONNECT %s:%d HTTP/1.0 asciiz:  r#rBrDrczTunnel connection failed:  Tr1r@rArrs)rr$rrr{r6sendrMresponse_classrbrXrphttp HTTPStatusOKrOSErrorrzrHrErFr3rrWrirN) r7connectrIheaderrresponser[rymessager;rrr_tunnels2    zHTTPConnection._tunnelc Cstd||j|j||j|jf|j|j|_z |jt j t j dWnt y=}z |j t jkr3WYd}~nd}~ww|jrG|dSdS)z3Connect to the host and port specified in __init__.zhttp.client.connectr1N)sysauditrrrrrrb setsockoptr IPPROTO_TCP TCP_NODELAYrerrno ENOPROTOOPTrrr7errrrs   zHTTPConnection.connectcCs^t|_z|j}|rd|_|W|j}|rd|_|dSdS|j}|r.d|_|ww)z(Close the connection to the HTTP server.N)rrrbrr)r7rbrrrrrs"  zHTTPConnection.closecCs |jdur|jr |nt|jdkrtdt|t|dr[|jdkr*td||}|r:|jdkr:td | |j }|sF dS|rM| d}t d |||j|q;t d ||z |j|WdStyt|tjjr|D]}|j|q{YdStd t|w) zSend `data' to the server. ``data`` can be a string object, a bytes object, an array object, a file-like object that supports a .read() method, or an iterable object. Nrzsend:rsendIng a read()ableencoding file using iso-8859-1r1rKzhttp.client.sendz9data should be a bytes-like object or an iterable, got %r)rb auto_openrrrWrirjrrrrr$rrsendallrr collectionsabcIterabletype)r7r"r$ datablockdrrrrsD           zHTTPConnection.sendcCs|j|dS)zuAdd a line of output to the current request buffer. Assumes that the line does *not* end with \r\n. N)rr6)r7rrrr_outputszHTTPConnection._outputccs`|jdkr td||}|r|jdkrtd ||j}|s%dS|r,|d}|Vq)NrrrTrK)rWrirrrr$)r7rr$rrrr_read_readables    zHTTPConnection._read_readableFc Cs|jdd|j}|jdd=|||durt|dr&||}n)zt|WntyKzt|}WntyHtdt |wYnw|f}|D])}|s_|j dkr^t dqQ|ru|j dkrut |d d d |d}||qQ|r|j dkr|d dSdSdSdS) zSend the currently buffered request and clear the buffer. Appends an extra \r\n to the buffer. A message_body may be specified, to be appended to the request. )rDrDrBNrzAmessage_body should be a bytes-like object or an iterable, got %rrzZero length chunk ignoredrrXrrs0 )rextendrMrrrrriterrrWri _http_vsnr3r$)r7 message_bodyencode_chunkedrYchunkschunkrrr _send_outputsD             'zHTTPConnection._send_outputc Cs|jr |jr d|_|jtkrt|_nt|j||||_|p$d}||d|||j f}| | ||j dkr|sd}| drQt|\}}}}}|rpz|d}Wntyh|d}Ynw|d |nN|jrz|j} |j} n|j} |j} z| d} Wnty| d} Ynw| d d krd | d } | |jkr|d | n| d} |d d| | f|s|dddSdS dS)a`Send a request to the server. `method' specifies an HTTP request method, e.g. 'GET'. `url' specifies the object being requested, e.g. '/index.html'. `skip_host' if True does not add automatically a 'Host:' header `skip_accept_encoding' if True does not add automatically an 'Accept-Encoding:' header N/z%s %s %srrrgrridnaHostr0r[]z%s:%szAccept-Encodingidentity)rrrr_CS_REQ_STARTEDr _validate_methodrX_validate_path _http_vsn_strr_encode_requestr rmrr$r% putheaderrrrrrrrN) r7rcrd skip_hostskip_accept_encodingrequestnetlocnil netloc_encrrhost_encrrr putrequest;sV              zHTTPConnection.putrequestcCs |dS)Nr)r$)r7r rrrrs zHTTPConnection._encode_requestcC,t|}|rtd|d|ddS)z&Validate a method name for putrequest.z)method can't contain control characters.  (found at least )N)$_contains_disallowed_method_pchar_researchrlgroup)r7rcmatchrrrrs zHTTPConnection._validate_methodcCr&)zValidate a url for putrequest.&URL can't contain control characters. r'r(N!_contains_disallowed_url_pchar_rer*r r+)r7rdr,rrrr   zHTTPConnection._validate_pathcCr&)z9Validate a host so it doesn't contain control characters.r-r'r(Nr.)r7rr,rrrrr0zHTTPConnection._validate_hostcGs|jtkrtt|dr|d}t|std|ft|}t|D].\}}t|dr6|d||<nt |t rDt |d||<t ||rStd||fq%d |}|d|}||dS) zkSend a request header line to the server. For example: h.putheader('Accept', 'text/html') r$rzInvalid header name %rr#zInvalid header value %rs s: N)rrrrr$_is_legal_header_namerlr enumeraterrorh_is_illegal_header_valuerMr)r7rvaluesr one_valuerrrrrs$        zHTTPConnection.putheaderrcCs*|jtkr t|_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. r6N)rr _CS_REQ_SENTrr)r7r rrrr endheaderss zHTTPConnection.endheaderscCs||||||dS)z&Send a complete request to the server.N) _send_request)r7rcrdrrIrrrrr szHTTPConnection.requestc Cstdd|D}i}d|vrd|d<d|vrd|d<|j||fi|d|vrZd |vrYd }|||}|durQ|durP|jd krHtd |d }|ddn |dt|nd }|D] \} } || | q`t|trut |d}|j ||ddS)Ncss|]}|VqdSr)r2)rkrrr sz/HTTPConnection._send_request..rr1rzaccept-encodingrrurtFrzUnable to determine size of %rTzTransfer-Encodingr^zContent-Lengthrr6) frozensetr%rrWrirrhr{rr-r8) r7rcrdrrIr header_namesskipscontent_lengthrrrrrr9s4       zHTTPConnection._send_requestcCs|jr |jr d|_|jtks|jrt|j|jdkr)|j|j|j|jd}n |j|j|jd}z-z| Wn t yE| w|j t ksMJt|_|j rZ| |WS||_|WS| )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. Nrr)rrrr7rrWrrbrXrConnectionErrorrrarZr)r7rrrr getresponse3s4     zHTTPConnection.getresponse)NN)NF)FFr)%r=r>r?r rrr HTTP_PORTrrrW staticmethodrrr_GLOBAL_DEFAULT_TIMEOUTrerrrrrrrrrrr%rrrrrr8r r9rArrrrrsL    ( 6     .rcsHeZdZdZeZdddejdfddddfdd ZfddZ Z S) HTTPSConnectionz(This class allows communication via SSL.Nr)contextcheck_hostnamerc stt|j||||| d|dus|dus|dur$ddl} | dtd||_||_|durEt }|j dkr=| dg|j durEd|_ |j tjk} |durR|j}|rZ| sZtd|s^|rl||||j durld|_ ||_|dury||j_dSdS) N)rrzTkey_file, cert_file and check_hostname are deprecated, use a custom context instead.rfrrzhttp/1.1TzMcheck_hostname needs a SSL context with either CERT_OPTIONAL or CERT_REQUIRED)rrErewarningswarnDeprecationWarningkey_file cert_filessl_create_default_https_contextr set_alpn_protocolspost_handshake_auth verify_mode CERT_NONErGrlload_cert_chain_context) r7rrrKrLrrrFrGrrH will_verifyrrrre~s>       zHTTPSConnection.__init__cs6t|jr |j}n|j}|jj|j|d|_dS)z(Connect to a host on a given (SSL) port.)server_hostnameN)rrrrrT wrap_socketrb)r7rVrrrrs   zHTTPSConnection.connect) r=r>r?__doc__ HTTPS_PORTrrrDrerrrrrrrEws'rEc@ eZdZdS)rNr=r>r?rrrrrsrc@rZ)rNr[rrrrrrc@rZ)r Nr[rrrrr r\r c@r.)rcCs|f|_||_dSr)argsr[)r7r[rrrres zUnknownProtocol.__init__Nr=r>r?rerrrrr rc@rZ)rNr[rrrrrr\rc@rZ)r Nr[rrrrr r\r c@s$eZdZdddZddZejZdS)r NcCs|f|_||_||_dSr)r]partialexpected)r7r`rarrrres zIncompleteRead.__init__cCs2|jdur d|j}nd}d|jjt|j|fS)Nz, %i more expectedrgz%s(%i bytes read%s))rarr=r3r`rrrr__repr__s   zIncompleteRead.__repr__r)r=r>r?rerbr'__str__rrrrr s  r c@rZ)r Nr[rrrrr r\r c@rZ)r Nr[rrrrr r\r c@rZ)rNr[rrrrrr\rc@rZ)rNr[rrrrrr\rc@r.)rcCs|st|}|f|_||_dSr)rjr]r;rrrrres zBadStatusLine.__init__Nr^rrrrrr_rc@r.)rcCst|dt|fdS)Nz&got more than %d bytes when reading %s)rrerF)r7 line_typerrrres zLineTooLong.__init__Nr^rrrrrr_rc@r.)rcOs(t|dtj|g|Ri|dS)Nrg)rreConnectionResetError)r7poskwrrrres zRemoteDisconnected.__init__Nr^rrrrrr_r)r")CrX email.parserrO email.messagerrrrerrcollections.abcr urllib.parser__all__rBrYrZrrr7globalsupdater __members__r4rrFrGcompile fullmatchr1r*r3r/r)rr-rMessager/rJrTBufferedIOBaserrrM ImportErrorrEr6 Exceptionrrr rrr r r r rrrrrerrrrrrs~F       +`   ;