Socket(CS-Notes)

本文详细解析了I/O模型,包括阻塞式、非阻塞式、I/O复用、信号驱动和异步I/O,对比了select、poll和epoll的优缺点及适用场景。

1  I/O 模型

一个输入操作通常包括两个阶段:

  • 等待数据准备好
  • 从内核向进程复制数据

 

对于一个套接字上的输入操作第一步通常涉及等待数据从网络中到达。当所等待数据到达时,它被复制到内核中的某个缓冲区第二步就是把数据从内核缓冲区复制到应用进程缓冲区

 

Unix 有五种 I/O 模型:

  • 阻塞式 I/O
  • 非阻塞式 I/O
  • I/O 复用(select poll
  • 信号驱动式 I/O(SIGIO)
  • 异步 I/O(AIO)

 

1.1  阻塞式 I/O

应用进程被阻塞,直到数据从内核缓冲区复制到应用进程缓冲区中才返回。

应该注意到,在阻塞的过程中,其它应用进程还可以执行,因此阻塞 不意味着 整个操作系统都被阻塞。因为其它应用进程还可以执行,所以不消耗 CPU 时间,阻塞式 I/O的 CPU 利用率 会比较高

下图中,recvfrom() 用于接收 Socket 传来的数据,并复制到应用进程的缓冲区 buf 中。这里把 recvfrom() 当成系统调用

ssize_t recvfrom(int sockfd, void *buf, size_t len, int flags, struct sockaddr *src_addr, socklen_t *addrlen);

 

1.2  非阻塞式 I/O

应用进程执行系统调用之后,内核返回一个错误码。应用进程可以继续执行,但是需要不断地执行系统调用来获知 I/O 是否完成,这种方式称为轮询(polling)

由于 CPU 要处理更多的系统调用,因此非阻塞式 I/O的 CPU 利用率 比较低

1.3  I/O 复用

使用 select 或者 poll 等待数据,并且可以等待多个套接字中的任何一个变为可读。这一过程会被阻塞,当某一个套接字可读时返回,之后再使用 recvfrom 把数据从内核复制到进程中。

它可以让单个进程具有处理多个 I/O 事件的能力。又被称为 Event Driven I/O,即事件驱动 I/O

如果一个 Web 服务器没有 I/O 复用,那么每一个 Socket 连接都需要创建一个线程去处理。如果同时有几万个连接,那么就需要创建相同数量的线程。相比于多进程多线程技术I/O 复用不需要进程线程创建和切换的开销系统开销更小

 

1.4  信号驱动 I/O

应用进程 使用 sigaction 系统调用内核立即返回,应用进程可以继续执行,也就是说 等待数据阶段 应用进程是非阻塞的。内核在数据到达时 向应用进程 发送 SIGIO 信号,应用进程收到之后在信号处理程序中调用 recvfrom 将数据从内核复制到应用进程中。

recvfrom()  将数据 从内核 复制到 应用进程 中

相比于非阻塞式 I/O 的轮询方式信号驱动 I/O 的 CPU 利用率更高

1.5  异步 I/O

应用进程 执行 aio_read 系统调用 会立即返回,应用进程可以继续执行,不会被阻塞,内核会在所有操作完成之后向应用进程发送信号。

异步 I/O信号驱动 I/O 的区别在于:异步 I/O 的信号是通知 应用进程 I/O 完成,而信号驱动 I/O 的信号是通知 应用进程 可以开始 I/O

 

1.6  五大 I/O 模型比较

  • 同步 I/O:将数据从内核缓冲区复制到应用进程缓冲区的阶段(第二阶段),应用进程 会阻塞
  • 异步 I/O:第二阶段应用进程 不会阻塞

同步 I/O 包括阻塞式 I/O、非阻塞式 I/O、I/O 复用和信号驱动 I/O ,它们的主要区别在第一个阶段。

非阻塞式 I/O 、信号驱动 I/O 和异步 I/O 在第一阶段不会阻塞。

 

2  I/O 复用

select/poll/epoll 都是 I/O 多路复用的具体实现select 出现的最早,之后是 poll,再是 epoll

 

2.1  select

int select(int n, fd_set *readfds, fd_set *writefds, fd_set *exceptfds, struct timeval *timeout);

select 允许 应用程序 监视 一组文件描述符等待一个或者多个描述符成为 就绪状态,从而完成 I/O 操作。

  • fd_set 使用数组实现,数组大小使用 FD_SETSIZE 定义,所以只能监听 少于 FD_SETSIZE 数量的描述符。有三种类型的描述符类型:readsetwritesetexceptset,分别对应异常条件的描述符集合

  • timeout超时参数调用 select  会一直阻塞 直到 有描述符的事件到达 或者 等待的时间超过 timeout

  • 成功调用 返回结果大于 0出错返回结果为 -1超时返回结果为 0

fd_set fd_in, fd_out;
struct timeval tv;

// Reset the sets
FD_ZERO( &fd_in );
FD_ZERO( &fd_out );

// Monitor sock1 for input events
FD_SET( sock1, &fd_in );

// Monitor sock2 for output events
FD_SET( sock2, &fd_out );

// Find out which socket has the largest numeric value as select requires it
int largest_sock = sock1 > sock2 ? sock1 : sock2;

// Wait up to 10 seconds
tv.tv_sec = 10;
tv.tv_usec = 0;

// Call the select
int ret = select( largest_sock + 1, &fd_in, &fd_out, NULL, &tv );

// Check if select actually succeed
if ( ret == -1 )
    // report error and abort
else if ( ret == 0 )
    // timeout; no event detected
else
{
    if ( FD_ISSET( sock1, &fd_in ) )
        // input event on sock1

    if ( FD_ISSET( sock2, &fd_out ) )
        // output event on sock2
}

 

2.2  poll

int poll(struct pollfd *fds, unsigned int nfds, int timeout);

poll 的功能与 select 类似,也是等待 一组描述符中的一个 成为就绪状态。

poll 中的描述符pollfd 类型的数组,pollfd 的定义如下:

struct pollfd {
               int   fd;         /* file descriptor */
               short events;     /* requested events */
               short revents;    /* returned events */
           };
// The structure for two events
struct pollfd fds[2];

// Monitor sock1 for input
fds[0].fd = sock1;
fds[0].events = POLLIN;

// Monitor sock2 for output
fds[1].fd = sock2;
fds[1].events = POLLOUT;

// Wait 10 seconds
int ret = poll( &fds, 2, 10000 );
// Check if poll actually succeed
if ( ret == -1 )
    // report error and abort
else if ( ret == 0 )
    // timeout; no event detected
else
{
    // If we detect the event, zero it out so we can reuse the structure
    if ( fds[0].revents & POLLIN )
        fds[0].revents = 0;
        // input event on sock1

    if ( fds[1].revents & POLLOUT )
        fds[1].revents = 0;
        // output event on sock2
}

 

2.3  比较

1. 功能

select 和 poll 的功能基本相同,不过在一些实现细节上有所不同。

  • select 会修改描述符,而 poll 不会;
  • select 的描述符类型使用数组实现,FD_SETSIZE 大小默认为 1024,因此默认只能监听 1024 个描述符。如果要监听更多描述符的话,需要修改 FD_SETSIZE 之后 重新编译;而 poll 没有 描述符数量的限制
  • poll 提供了更多的事件类型,并且对描述符的重复利用上比 select 高。
  • 如果一个线程对某个描述符调用了 select 或者 poll,另一个线程关闭了该描述符,会导致调用结果不确定。

2. 速度

select 和 poll 速度都比较慢,每次调用都需要将全部描述符从应用进程缓冲区复制到内核缓冲区。

3. 可移植性

几乎所有的系统都支持 select,但是只有比较新的系统支持 poll。


 

2.4  epoll

int epoll_create(int size);
int epoll_ctl(int epfd, int op, int fd, struct epoll_event *event);
int epoll_wait(int epfd, struct epoll_event * events, int maxevents, int timeout);

epoll_ctl() 用于向内核 注册新的描述符或者是改变某个文件描述符的状态。已注册的描述符 在内核中会被维护在一棵红黑树上,通过回调函数内核会将 I/O 准备好的描述符加入到一个链表中管理,进程调用 epoll_wait() 便可以得到事件完成的描述符。

从上面的描述可以看出,epoll 只需要 将描述符 从进程缓冲区内核缓冲区 拷贝一次,并且进程不需要通过轮询来获得事件完成的描述符

epoll 仅适用于 Linux OS

epoll 比 select 和 poll 更加灵活而且没有描述符数量限制

 

epoll 对多线程编程 更加友好。一个线程调用了 epoll_wait(), 另一个线程关闭了同一个描述符,也不会产生像 select 和 poll 的不确定情况。

// Create the epoll descriptor. Only one is needed per app, and is used to monitor all sockets.
// The function argument is ignored (it was not before, but now it is), so put your favorite number here
int pollingfd = epoll_create( 0xCAFE );

if ( pollingfd < 0 )
 // report error

// Initialize the epoll structure in case more members are added in future
struct epoll_event ev = { 0 };

// Associate the connection class instance with the event. You can associate anything
// you want, epoll does not use this information. We store a connection class pointer, pConnection1
ev.data.ptr = pConnection1;

// Monitor for input, and do not automatically rearm the descriptor after the event
ev.events = EPOLLIN | EPOLLONESHOT;
// Add the descriptor into the monitoring list. We can do it even if another thread is
// waiting in epoll_wait - the descriptor will be properly added
if ( epoll_ctl( epollfd, EPOLL_CTL_ADD, pConnection1->getSocket(), &ev ) != 0 )
    // report error

// Wait for up to 20 events (assuming we have added maybe 200 sockets before that it may happen)
struct epoll_event pevents[ 20 ];

// Wait for 10 seconds, and retrieve less than 20 epoll_event and store them into epoll_event array
int ready = epoll_wait( pollingfd, pevents, 20, 10000 );
// Check if epoll actually succeed
if ( ret == -1 )
    // report error and abort
else if ( ret == 0 )
    // timeout; no event detected
else
{
    // Check if any events detected
    for ( int i = 0; i < ret; i++ )
    {
        if ( pevents[i].events & EPOLLIN )
        {
            // Get back our connection pointer
            Connection * c = (Connection*) pevents[i].data.ptr;
            c->handleReadEvent();
         }
    }
}

 

2.5  工作模式

epoll 的描述符事件有两种触发模式:LT(level trigger)ET(edge trigger)

1. LT 模式(水平触发)

epoll_wait() 检测到描述符事件 到达时,将此事件通知进程进程可以 不立即处理该事件。下次调用 epoll_wait()再次通知进程。是默认的一种模式,并且同时支持 Blocking 和 No-Blocking。

2. ET 模式(边缘触发)

和 LT 模式不同的是,通知之后 进程 必须立即处理事件。下次再调用 epoll_wait() 时 不会再得到事件到达的通知

很大程度上减少了 epoll 事件  被重复触发的次数,因此效率要比 LT 模式高只支持 No-Blocking,以避免由于一个文件句柄的阻塞读 / 阻塞写 操作 把 处理多个文件描述符的任务饿死。

 

 

2.6  应用场景

很容易产生一种错觉认为 只要用 epoll 就可以了,select 和 poll 都已经过时了,其实它们都有各自的使用场景。

 

1. select 应用场景

select 的 timeout 参数精度1ns,而 poll 和 epoll 为 1ms,因此 select 更加适用于实时性要求比较高的场景,比如核反应堆的控制

select 可移植性更好,几乎被所有主流平台所支持。

 

2. poll 应用场景

poll 没有最大描述符数量的限制,如果平台支持 并且对实时性要求不高,应该使用 poll 而不是 select。

 

3. epoll 应用场景

只需要运行在 Linux 平台上有大量的描述符需要同时轮询,并且这些连接最好是长连接

需要同时监控 小于 1000 个描述符,就没有必要使用 epoll,因为这个应用场景下并不能体现 epoll 的优势

需要监控的描述符状态变化多,而且都是非常短暂的,也没有必要使用 epoll。因为 epoll 中的所有描述符 都存储在内核中,造成每次需要对描述符的状态改变都需要通过 epoll_ctl() 进行系统调用,频繁系统调用降低效率。并且 epoll 的描述符存储在内核,不容易调试

 

参考资料

r&quot;&quot;&quot;HTTP/1.1 client library &lt;intro stuff goes here&gt; &lt;other stuff, too&gt; HTTPConnection goes through a number of &quot;states&quot;, 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&#39;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 &lt;response_class&gt; Req-started-unread-response _CS_REQ_STARTED &lt;response_class&gt; Req-sent-unread-response _CS_REQ_SENT &lt;response_class&gt; &quot;&quot;&quot; import email.parser import email.message import errno import http import io import re import socket import sys import collections.abc from urllib.parse import urlsplit # HTTPMessage, parse_headers(), and the HTTP status code constants are # intentionally omitted for simplicity __all__ = [&quot;HTTPResponse&quot;, &quot;HTTPConnection&quot;, &quot;HTTPException&quot;, &quot;NotConnected&quot;, &quot;UnknownProtocol&quot;, &quot;UnknownTransferEncoding&quot;, &quot;UnimplementedFileMode&quot;, &quot;IncompleteRead&quot;, &quot;InvalidURL&quot;, &quot;ImproperConnectionState&quot;, &quot;CannotSendRequest&quot;, &quot;CannotSendHeader&quot;, &quot;ResponseNotReady&quot;, &quot;BadStatusLine&quot;, &quot;LineTooLong&quot;, &quot;RemoteDisconnected&quot;, &quot;error&quot;, &quot;responses&quot;] HTTP_PORT = 80 HTTPS_PORT = 443 _UNKNOWN = &#39;UNKNOWN&#39; # connection states _CS_IDLE = &#39;Idle&#39; _CS_REQ_STARTED = &#39;Request-started&#39; _CS_REQ_SENT = &#39;Request-sent&#39; # hack to maintain backwards compatibility globals().update(http.HTTPStatus.__members__) # another hack to maintain backwards compatibility # Mapping status codes to official W3C names responses = {v: v.phrase for v in http.HTTPStatus.__members__.values()} # maximal line length when calling readline(). _MAXLINE = 65536 _MAXHEADERS = 100 # Header name/value ABNF (http://tools.ietf.org/html/rfc7230#section-3.2) # # VCHAR = %x21-7E # obs-text = %x80-FF # header-field = field-name &quot;:&quot; OWS field-value OWS # field-name = token # field-value = *( field-content / obs-fold ) # field-content = field-vchar [ 1*( SP / HTAB ) field-vchar ] # field-vchar = VCHAR / obs-text # # obs-fold = CRLF 1*( SP / HTAB ) # ; obsolete line folding # ; see Section 3.2.4 # token = 1*tchar # # tchar = &quot;!&quot; / &quot;#&quot; / &quot;$&quot; / &quot;%&quot; / &quot;&amp;&quot; / &quot;&#39;&quot; / &quot;*&quot; # / &quot;+&quot; / &quot;-&quot; / &quot;.&quot; / &quot;^&quot; / &quot;_&quot; / &quot;`&quot; / &quot;|&quot; / &quot;~&quot; # / DIGIT / ALPHA # ; any VCHAR, except delimiters # # VCHAR defined in http://tools.ietf.org/html/rfc5234#appendix-B.1 # the patterns for both name and value are more lenient than RFC # definitions to allow for backwards compatibility _is_legal_header_name = re.compile(rb&#39;[^:\s][^:\r\n]*&#39;).fullmatch _is_illegal_header_value = re.compile(rb&#39;\n(?![ \t])|\r(?![ \t\n])&#39;).search # These characters are not allowed within HTTP URL paths. # See https://tools.ietf.org/html/rfc3986#section-3.3 and the # https://tools.ietf.org/html/rfc3986#appendix-A pchar definition. # Prevents CVE-2019-9740. Includes control characters such as \r\n. # We don&#39;t restrict chars above \x7f as putrequest() limits us to ASCII. _contains_disallowed_url_pchar_re = re.compile(&#39;[\x00-\x20\x7f]&#39;) # Arguably only these _should_ allowed: # _is_allowed_url_pchars_re = re.compile(r&quot;^[/!$&amp;&#39;()*+,;=:@%a-zA-Z0-9._~-]+$&quot;) # We are more lenient for assumed real world compatibility purposes. # These characters are not allowed within HTTP method names # to prevent http header injection. _contains_disallowed_method_pchar_re = re.compile(&#39;[\x00-\x1f]&#39;) # We always set the Content-Length header for these methods because some # servers will otherwise respond with a 411 _METHODS_EXPECTING_BODY = {&#39;PATCH&#39;, &#39;POST&#39;, &#39;PUT&#39;} def _encode(data, name=&#39;data&#39;): &quot;&quot;&quot;Call data.encode(&quot;latin-1&quot;) but show a better error message.&quot;&quot;&quot; try: return data.encode(&quot;latin-1&quot;) except UnicodeEncodeError as err: raise UnicodeEncodeError( err.encoding, err.object, err.start, err.end, &quot;%s (%.20r) is not valid Latin-1. Use %s.encode(&#39;utf-8&#39;) &quot; &quot;if you want to send it encoded in UTF-8.&quot; % (name.title(), data[err.start:err.end], name)) from None class HTTPMessage(email.message.Message): # XXX The only usage of this method is in # http.server.CGIHTTPRequestHandler. Maybe move the code there so # that it doesn&#39;t need to be part of the public API. The API has # never been defined so this could cause backwards compatibility # issues. def getallmatchingheaders(self, name): &quot;&quot;&quot;Find all header lines matching a given header name. Look through the list of headers and find all lines matching a given header name (and their continuation lines). A list of the lines is returned, without interpretation. If the header does not occur, an empty list is returned. If the header occurs multiple times, all occurrences are returned. Case is not important in the header name. &quot;&quot;&quot; name = name.lower() + &#39;:&#39; n = len(name) lst = [] hit = 0 for line in self.keys(): if line[:n].lower() == name: hit = 1 elif not line[:1].isspace(): hit = 0 if hit: lst.append(line) return lst def _read_headers(fp): &quot;&quot;&quot;Reads potential header lines into a list from a file pointer. Length of line is limited by _MAXLINE, and number of headers is limited by _MAXHEADERS. &quot;&quot;&quot; headers = [] while True: line = fp.readline(_MAXLINE + 1) if len(line) &gt; _MAXLINE: raise LineTooLong(&quot;header line&quot;) headers.append(line) if len(headers) &gt; _MAXHEADERS: raise HTTPException(&quot;got more than %d headers&quot; % _MAXHEADERS) if line in (b&#39;\r\n&#39;, b&#39;\n&#39;, b&#39;&#39;): break return headers def parse_headers(fp, _class=HTTPMessage): &quot;&quot;&quot;Parses only RFC2822 headers from a file pointer. email Parser wants to see strings rather than bytes. But a TextIOWrapper around self.rfile would buffer too many bytes from the stream, bytes which we later need to read as bytes. So we read the correct bytes here, as bytes, for email Parser to parse. &quot;&quot;&quot; headers = _read_headers(fp) hstring = b&#39;&#39;.join(headers).decode(&#39;iso-8859-1&#39;) return email.parser.Parser(_class=_class).parsestr(hstring) class HTTPResponse(io.BufferedIOBase): # See RFC 2616 sec 19.6 and RFC 1945 sec 6 for details. # The bytes from the socket object are iso-8859-1 strings. # See RFC 2616 sec 2.2 which notes an exception for MIME-encoded # text following RFC 2047. The basic status line parsing only # accepts iso-8859-1. def __init__(self, sock, debuglevel=0, method=None, url=None): # If the response includes a content-length header, we need to # make sure that the client doesn&#39;t read more than the # specified number of bytes. If it does, it will block until # the server times out and closes the connection. This will # happen if a self.fp.read() is done (without a size) whether # self.fp is buffered or not. So, no self.fp.read() by # clients unless they know what they are doing. self.fp = sock.makefile(&quot;rb&quot;) self.debuglevel = debuglevel self._method = method # The HTTPResponse object is returned via urllib. The clients # of http and urllib expect different attributes for the # headers. headers is used here and supports urllib. msg is # provided as a backwards compatibility layer for http # clients. self.headers = self.msg = None # from the Status-Line of the response self.version = _UNKNOWN # HTTP-Version self.status = _UNKNOWN # Status-Code self.reason = _UNKNOWN # Reason-Phrase self.chunked = _UNKNOWN # is &quot;chunked&quot; being used? self.chunk_left = _UNKNOWN # bytes left to read in current chunk self.length = _UNKNOWN # number of bytes left in response self.will_close = _UNKNOWN # conn will close at end of response def _read_status(self): line = str(self.fp.readline(_MAXLINE + 1), &quot;iso-8859-1&quot;) if len(line) &gt; _MAXLINE: raise LineTooLong(&quot;status line&quot;) if self.debuglevel &gt; 0: print(&quot;reply:&quot;, repr(line)) if not line: # Presumably, the server closed the connection before # sending a valid response. raise RemoteDisconnected(&quot;Remote end closed connection without&quot; &quot; response&quot;) try: version, status, reason = line.split(None, 2) except ValueError: try: version, status = line.split(None, 1) reason = &quot;&quot; except ValueError: # empty version will cause next test to fail. version = &quot;&quot; if not version.startswith(&quot;HTTP/&quot;): self._close_conn() raise BadStatusLine(line) # The status code is a three-digit number try: status = int(status) if status &lt; 100 or status &gt; 999: raise BadStatusLine(line) except ValueError: raise BadStatusLine(line) return version, status, reason def begin(self): if self.headers is not None: # we&#39;ve already started reading the response return # read until we get a non-100 response while True: version, status, reason = self._read_status() if status != CONTINUE: break # skip the header from the 100 response skipped_headers = _read_headers(self.fp) if self.debuglevel &gt; 0: print(&quot;headers:&quot;, skipped_headers) del skipped_headers self.code = self.status = status self.reason = reason.strip() if version in (&quot;HTTP/1.0&quot;, &quot;HTTP/0.9&quot;): # Some servers might still return &quot;0.9&quot;, treat it as 1.0 anyway self.version = 10 elif version.startswith(&quot;HTTP/1.&quot;): self.version = 11 # use HTTP/1.1 code for HTTP/1.x where x&gt;=1 else: raise UnknownProtocol(version) self.headers = self.msg = parse_headers(self.fp) if self.debuglevel &gt; 0: for hdr, val in self.headers.items(): print(&quot;header:&quot;, hdr + &quot;:&quot;, val) # are we using the chunked-style of transfer encoding? tr_enc = self.headers.get(&quot;transfer-encoding&quot;) if tr_enc and tr_enc.lower() == &quot;chunked&quot;: self.chunked = True self.chunk_left = None else: self.chunked = False # will the connection close at the end of the response? self.will_close = self._check_close() # do we have a Content-Length? # NOTE: RFC 2616, S4.4, #3 says we ignore this if tr_enc is &quot;chunked&quot; self.length = None length = self.headers.get(&quot;content-length&quot;) if length and not self.chunked: try: self.length = int(length) except ValueError: self.length = None else: if self.length &lt; 0: # ignore nonsensical negative lengths self.length = None else: self.length = None # does the body have a fixed length? (of zero) if (status == NO_CONTENT or status == NOT_MODIFIED or 100 &lt;= status &lt; 200 or # 1xx codes self._method == &quot;HEAD&quot;): self.length = 0 # if the connection remains open, and we aren&#39;t using chunked, and # a content-length was not provided, then assume that the connection # WILL close. if (not self.will_close and not self.chunked and self.length is None): self.will_close = True def _check_close(self): conn = self.headers.get(&quot;connection&quot;) if self.version == 11: # An HTTP/1.1 proxy is assumed to stay open unless # explicitly closed. if conn and &quot;close&quot; in conn.lower(): return True return False # Some HTTP/1.0 implementations have support for persistent # connections, using rules different than HTTP/1.1. # For older HTTP, Keep-Alive indicates persistent connection. if self.headers.get(&quot;keep-alive&quot;): return False # At least Akamai returns a &quot;Connection: Keep-Alive&quot; header, # which was supposed to be sent by the client. if conn and &quot;keep-alive&quot; in conn.lower(): return False # Proxy-Connection is a netscape hack. pconn = self.headers.get(&quot;proxy-connection&quot;) if pconn and &quot;keep-alive&quot; in pconn.lower(): return False # otherwise, assume it will close return True def _close_conn(self): fp = self.fp self.fp = None fp.close() def close(self): try: super().close() # set &quot;closed&quot; flag finally: if self.fp: self._close_conn() # These implementations are for the benefit of io.BufferedReader. # XXX This class should probably be revised to act more like # the &quot;raw stream&quot; that BufferedReader expects. def flush(self): super().flush() if self.fp: self.fp.flush() def readable(self): &quot;&quot;&quot;Always returns True&quot;&quot;&quot; return True # End of &quot;raw stream&quot; methods def isclosed(self): &quot;&quot;&quot;True if the connection is closed.&quot;&quot;&quot; # NOTE: it is possible that we will not ever call self.close(). This # case occurs when will_close is TRUE, length is None, and we # read up to the last byte, but NOT past it. # # IMPLIES: if will_close is FALSE, then self.close() will ALWAYS be # called, meaning self.isclosed() is meaningful. return self.fp is None def read(self, amt=None): if self.fp is None: return b&quot;&quot; if self._method == &quot;HEAD&quot;: self._close_conn() return b&quot;&quot; if self.chunked: return self._read_chunked(amt) if amt is not None: if self.length is not None and amt &gt; self.length: # clip the read to the &quot;end of response&quot; amt = self.length s = self.fp.read(amt) if not s and amt: # Ideally, we would raise IncompleteRead if the content-length # wasn&#39;t satisfied, but it might break compatibility. self._close_conn() elif self.length is not None: self.length -= len(s) if not self.length: self._close_conn() return s else: # Amount is not given (unbounded read) so we must check self.length if self.length is None: s = self.fp.read() else: try: s = self._safe_read(self.length) except IncompleteRead: self._close_conn() raise self.length = 0 self._close_conn() # we read everything return s def readinto(self, b): &quot;&quot;&quot;Read up to len(b) bytes into bytearray b and return the number of bytes read. &quot;&quot;&quot; if self.fp is None: return 0 if self._method == &quot;HEAD&quot;: self._close_conn() return 0 if self.chunked: return self._readinto_chunked(b) if self.length is not None: if len(b) &gt; self.length: # clip the read to the &quot;end of response&quot; b = memoryview(b)[0:self.length] # we do not use _safe_read() here because this may be a .will_close # connection, and the user is reading more bytes than will be provided # (for example, reading in 1k chunks) n = self.fp.readinto(b) if not n and b: # Ideally, we would raise IncompleteRead if the content-length # wasn&#39;t satisfied, but it might break compatibility. self._close_conn() elif self.length is not None: self.length -= n if not self.length: self._close_conn() return n def _read_next_chunk_size(self): # Read the next chunk size from the file line = self.fp.readline(_MAXLINE + 1) if len(line) &gt; _MAXLINE: raise LineTooLong(&quot;chunk size&quot;) i = line.find(b&quot;;&quot;) if i &gt;= 0: line = line[:i] # strip chunk-extensions try: return int(line, 16) except ValueError: # close the connection as protocol synchronisation is # probably lost self._close_conn() raise def _read_and_discard_trailer(self): # read and discard trailer up to the CRLF terminator ### note: we shouldn&#39;t have any trailers! while True: line = self.fp.readline(_MAXLINE + 1) if len(line) &gt; _MAXLINE: raise LineTooLong(&quot;trailer line&quot;) if not line: # a vanishingly small number of sites EOF without # sending the trailer break if line in (b&#39;\r\n&#39;, b&#39;\n&#39;, b&#39;&#39;): break def _get_chunk_left(self): # return self.chunk_left, reading a new chunk if necessary. # chunk_left == 0: at the end of the current chunk, need to close it # chunk_left == None: No current chunk, should read next. # This function returns non-zero or None if the last chunk has # been read. chunk_left = self.chunk_left if not chunk_left: # Can be 0 or None if chunk_left is not None: # We are at the end of chunk, discard chunk end self._safe_read(2) # toss the CRLF at the end of the chunk try: chunk_left = self._read_next_chunk_size() except ValueError: raise IncompleteRead(b&#39;&#39;) if chunk_left == 0: # last chunk: 1*(&quot;0&quot;) [ chunk-extension ] CRLF self._read_and_discard_trailer() # we read everything; close the &quot;file&quot; self._close_conn() chunk_left = None self.chunk_left = chunk_left return chunk_left def _read_chunked(self, amt=None): assert self.chunked != _UNKNOWN value = [] try: while True: chunk_left = self._get_chunk_left() if chunk_left is None: break if amt is not None and amt &lt;= chunk_left: value.append(self._safe_read(amt)) self.chunk_left = chunk_left - amt break value.append(self._safe_read(chunk_left)) if amt is not None: amt -= chunk_left self.chunk_left = 0 return b&#39;&#39;.join(value) except IncompleteRead as exc: raise IncompleteRead(b&#39;&#39;.join(value)) from exc def _readinto_chunked(self, b): assert self.chunked != _UNKNOWN total_bytes = 0 mvb = memoryview(b) try: while True: chunk_left = self._get_chunk_left() if chunk_left is None: return total_bytes if len(mvb) &lt;= chunk_left: n = self._safe_readinto(mvb) self.chunk_left = chunk_left - n return total_bytes + n temp_mvb = mvb[:chunk_left] n = self._safe_readinto(temp_mvb) mvb = mvb[n:] total_bytes += n self.chunk_left = 0 except IncompleteRead: raise IncompleteRead(bytes(b[0:total_bytes])) def _safe_read(self, amt): &quot;&quot;&quot;Read the number of bytes requested. This function should be used when &lt;amt&gt; bytes &quot;should&quot; 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. &quot;&quot;&quot; data = self.fp.read(amt) if len(data) &lt; amt: raise IncompleteRead(data, amt-len(data)) return data def _safe_readinto(self, b): &quot;&quot;&quot;Same as _safe_read, but for reading into a buffer.&quot;&quot;&quot; amt = len(b) n = self.fp.readinto(b) if n &lt; amt: raise IncompleteRead(bytes(b[:n]), amt-n) return n def read1(self, n=-1): &quot;&quot;&quot;Read with at most one underlying system call. If at least one byte is buffered, return that instead. &quot;&quot;&quot; if self.fp is None or self._method == &quot;HEAD&quot;: return b&quot;&quot; if self.chunked: return self._read1_chunked(n) if self.length is not None and (n &lt; 0 or n &gt; self.length): n = self.length result = self.fp.read1(n) if not result and n: self._close_conn() elif self.length is not None: self.length -= len(result) return result def peek(self, n=-1): # Having this enables IOBase.readline() to read more than one # byte at a time if self.fp is None or self._method == &quot;HEAD&quot;: return b&quot;&quot; if self.chunked: return self._peek_chunked(n) return self.fp.peek(n) def readline(self, limit=-1): if self.fp is None or self._method == &quot;HEAD&quot;: return b&quot;&quot; if self.chunked: # Fallback to IOBase readline which uses peek() and read() return super().readline(limit) if self.length is not None and (limit &lt; 0 or limit &gt; self.length): limit = self.length result = self.fp.readline(limit) if not result and limit: self._close_conn() elif self.length is not None: self.length -= len(result) return result def _read1_chunked(self, n): # Strictly speaking, _get_chunk_left() may cause more than one read, # but that is ok, since that is to satisfy the chunked protocol. chunk_left = self._get_chunk_left() if chunk_left is None or n == 0: return b&#39;&#39; if not (0 &lt;= n &lt;= chunk_left): n = chunk_left # if n is negative or larger than chunk_left read = self.fp.read1(n) self.chunk_left -= len(read) if not read: raise IncompleteRead(b&quot;&quot;) return read def _peek_chunked(self, n): # Strictly speaking, _get_chunk_left() may cause more than one read, # but that is ok, since that is to satisfy the chunked protocol. try: chunk_left = self._get_chunk_left() except IncompleteRead: return b&#39;&#39; # peek doesn&#39;t worry about protocol if chunk_left is None: return b&#39;&#39; # eof # peek is allowed to return more than requested. Just request the # entire chunk, and truncate what we get. return self.fp.peek(chunk_left)[:chunk_left] def fileno(self): return self.fp.fileno() def getheader(self, name, default=None): &#39;&#39;&#39;Returns 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. &#39;&#39;&#39; if self.headers is None: raise ResponseNotReady() headers = self.headers.get_all(name) or default if isinstance(headers, str) or not hasattr(headers, &#39;__iter__&#39;): return headers else: return &#39;, &#39;.join(headers) def getheaders(self): &quot;&quot;&quot;Return list of (header, value) tuples.&quot;&quot;&quot; if self.headers is None: raise ResponseNotReady() return list(self.headers.items()) # We override IOBase.__iter__ so that it doesn&#39;t check for closed-ness def __iter__(self): return self # For compatibility with old-style urllib responses. def info(self): &#39;&#39;&#39;Returns 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&#39;s last-modified time, a Content-Length giving file size, and a Content-Type containing a guess at the file&#39;s type. See also the description of the mimetools module. &#39;&#39;&#39; return self.headers def geturl(self): &#39;&#39;&#39;Return 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. &#39;&#39;&#39; return self.url def getcode(self): &#39;&#39;&#39;Return the HTTP status code that was sent with the response, or None if the URL is not an HTTP URL. &#39;&#39;&#39; return self.status class HTTPConnection: _http_vsn = 11 _http_vsn_str = &#39;HTTP/1.1&#39; response_class = HTTPResponse default_port = HTTP_PORT auto_open = 1 debuglevel = 0 @staticmethod def _is_textIO(stream): &quot;&quot;&quot;Test whether a file-like object is a text or a binary stream. &quot;&quot;&quot; return isinstance(stream, io.TextIOBase) @staticmethod def _get_content_length(body, method): &quot;&quot;&quot;Get 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. &quot;&quot;&quot; if body is None: # do an explicit check for not None here to distinguish # between unset and set but empty if method.upper() in _METHODS_EXPECTING_BODY: return 0 else: return None if hasattr(body, &#39;read&#39;): # file-like object. return None try: # does it implement the buffer protocol (bytes, bytearray, array)? mv = memoryview(body) return mv.nbytes except TypeError: pass if isinstance(body, str): return len(body) return None def __init__(self, host, port=None, timeout=socket._GLOBAL_DEFAULT_TIMEOUT, source_address=None, blocksize=8192): self.timeout = timeout self.source_address = source_address self.blocksize = blocksize self.sock = None self._buffer = [] self.__response = None self.__state = _CS_IDLE self._method = None self._tunnel_host = None self._tunnel_port = None self._tunnel_headers = {} (self.host, self.port) = self._get_hostport(host, port) self._validate_host(self.host) # This is stored as an instance variable to allow unit # tests to replace it with a suitable mockup self._create_connection = socket.create_connection def set_tunnel(self, host, port=None, headers=None): &quot;&quot;&quot;Set 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. &quot;&quot;&quot; if self.sock: raise RuntimeError(&quot;Can&#39;t set up tunnel for established connection&quot;) self._tunnel_host, self._tunnel_port = self._get_hostport(host, port) if headers: self._tunnel_headers = headers else: self._tunnel_headers.clear() def _get_hostport(self, host, port): if port is None: i = host.rfind(&#39;:&#39;) j = host.rfind(&#39;]&#39;) # ipv6 addresses have [...] if i &gt; j: try: port = int(host[i+1:]) except ValueError: if host[i+1:] == &quot;&quot;: # http://foo.com:/ == http://foo.com/ port = self.default_port else: raise InvalidURL(&quot;nonnumeric port: &#39;%s&#39;&quot; % host[i+1:]) host = host[:i] else: port = self.default_port if host and host[0] == &#39;[&#39; and host[-1] == &#39;]&#39;: host = host[1:-1] return (host, port) def set_debuglevel(self, level): self.debuglevel = level def _tunnel(self): connect = b&quot;CONNECT %s:%d HTTP/1.0\r\n&quot; % ( self._tunnel_host.encode(&quot;ascii&quot;), self._tunnel_port) headers = [connect] for header, value in self._tunnel_headers.items(): headers.append(f&quot;{header}: {value}\r\n&quot;.encode(&quot;latin-1&quot;)) headers.append(b&quot;\r\n&quot;) # Making a single send() call instead of one per line encourages # the host OS to use a more optimal packet size instead of # potentially emitting a series of small packets. self.send(b&quot;&quot;.join(headers)) del headers response = self.response_class(self.sock, method=self._method) (version, code, message) = response._read_status() if code != http.HTTPStatus.OK: self.close() raise OSError(f&quot;Tunnel connection failed: {code} {message.strip()}&quot;) while True: line = response.fp.readline(_MAXLINE + 1) if len(line) &gt; _MAXLINE: raise LineTooLong(&quot;header line&quot;) if not line: # for sites which EOF without sending a trailer break if line in (b&#39;\r\n&#39;, b&#39;\n&#39;, b&#39;&#39;): break if self.debuglevel &gt; 0: print(&#39;header:&#39;, line.decode()) def connect(self): &quot;&quot;&quot;Connect to the host and port specified in __init__.&quot;&quot;&quot; sys.audit(&quot;http.client.connect&quot;, self, self.host, self.port) self.sock = self._create_connection( (self.host,self.port), self.timeout, self.source_address) # Might fail in OSs that don&#39;t implement TCP_NODELAY try: self.sock.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1) except OSError as e: if e.errno != errno.ENOPROTOOPT: raise if self._tunnel_host: self._tunnel() def close(self): &quot;&quot;&quot;Close the connection to the HTTP server.&quot;&quot;&quot; self.__state = _CS_IDLE try: sock = self.sock if sock: self.sock = None sock.close() # close it manually... there may be other refs finally: response = self.__response if response: self.__response = None response.close() def send(self, data): &quot;&quot;&quot;Send `data&#39; 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. &quot;&quot;&quot; if self.sock is None: if self.auto_open: self.connect() else: raise NotConnected() if self.debuglevel &gt; 0: print(&quot;send:&quot;, repr(data)) if hasattr(data, &quot;read&quot;) : if self.debuglevel &gt; 0: print(&quot;sendIng a read()able&quot;) encode = self._is_textIO(data) if encode and self.debuglevel &gt; 0: print(&quot;encoding file using iso-8859-1&quot;) while 1: datablock = data.read(self.blocksize) if not datablock: break if encode: datablock = datablock.encode(&quot;iso-8859-1&quot;) sys.audit(&quot;http.client.send&quot;, self, datablock) self.sock.sendall(datablock) return sys.audit(&quot;http.client.send&quot;, self, data) try: self.sock.sendall(data) except TypeError: if isinstance(data, collections.abc.Iterable): for d in data: self.sock.sendall(d) else: raise TypeError(&quot;data should be a bytes-like object &quot; &quot;or an iterable, got %r&quot; % type(data)) def _output(self, s): &quot;&quot;&quot;Add a line of output to the current request buffer. Assumes that the line does *not* end with \\r\\n. &quot;&quot;&quot; self._buffer.append(s) def _read_readable(self, readable): if self.debuglevel &gt; 0: print(&quot;sendIng a read()able&quot;) encode = self._is_textIO(readable) if encode and self.debuglevel &gt; 0: print(&quot;encoding file using iso-8859-1&quot;) while True: datablock = readable.read(self.blocksize) if not datablock: break if encode: datablock = datablock.encode(&quot;iso-8859-1&quot;) yield datablock def _send_output(self, message_body=None, encode_chunked=False): &quot;&quot;&quot;Send 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. &quot;&quot;&quot; self._buffer.extend((b&quot;&quot;, b&quot;&quot;)) msg = b&quot;\r\n&quot;.join(self._buffer) del self._buffer[:] self.send(msg) if message_body is not None: # create a consistent interface to message_body if hasattr(message_body, &#39;read&#39;): # Let file-like take precedence over byte-like. This # is needed to allow the current position of mmap&#39;ed # files to be taken into account. chunks = self._read_readable(message_body) else: try: # this is solely to check to see if message_body # implements the buffer API. it /would/ be easier # to capture if PyObject_CheckBuffer was exposed # to Python. memoryview(message_body) except TypeError: try: chunks = iter(message_body) except TypeError: raise TypeError(&quot;message_body should be a bytes-like &quot; &quot;object or an iterable, got %r&quot; % type(message_body)) else: # the object implements the buffer interface and # can be passed directly into socket methods chunks = (message_body,) for chunk in chunks: if not chunk: if self.debuglevel &gt; 0: print(&#39;Zero length chunk ignored&#39;) continue if encode_chunked and self._http_vsn == 11: # chunked encoding chunk = f&#39;{len(chunk):X}\r\n&#39;.encode(&#39;ascii&#39;) + chunk \ + b&#39;\r\n&#39; self.send(chunk) if encode_chunked and self._http_vsn == 11: # end chunked transfer self.send(b&#39;0\r\n\r\n&#39;) def putrequest(self, method, url, skip_host=False, skip_accept_encoding=False): &quot;&quot;&quot;Send a request to the server. `method&#39; specifies an HTTP request method, e.g. &#39;GET&#39;. `url&#39; specifies the object being requested, e.g. &#39;/index.html&#39;. `skip_host&#39; if True does not add automatically a &#39;Host:&#39; header `skip_accept_encoding&#39; if True does not add automatically an &#39;Accept-Encoding:&#39; header &quot;&quot;&quot; # if a prior response has been completed, then forget about it. if self.__response and self.__response.isclosed(): self.__response = None # in certain cases, we cannot issue another request on this connection. # this occurs when: # 1) we are in the process of sending a request. (_CS_REQ_STARTED) # 2) a response to a previous request has signalled that it is going # to close the connection upon completion. # 3) the headers for the previous response have not been read, thus # we cannot determine whether point (2) is true. (_CS_REQ_SENT) # # if there is no prior response, then we can request at will. # # if point (2) is true, then we will have passed the socket to the # response (effectively meaning, &quot;there is no prior response&quot;), and # will open a new one when a new request is made. # # Note: if a prior response exists, then we *can* start a new request. # We are not allowed to begin fetching the response to this new # request, however, until that prior response is complete. # if self.__state == _CS_IDLE: self.__state = _CS_REQ_STARTED else: raise CannotSendRequest(self.__state) self._validate_method(method) # Save the method for use later in the response phase self._method = method url = url or &#39;/&#39; self._validate_path(url) request = &#39;%s %s %s&#39; % (method, url, self._http_vsn_str) self._output(self._encode_request(request)) if self._http_vsn == 11: # Issue some standard headers for better HTTP/1.1 compliance if not skip_host: # this header is issued *only* for HTTP/1.1 # connections. more specifically, this means it is # only issued when the client uses the new # HTTPConnection() class. backwards-compat clients # will be using HTTP/1.0 and those clients may be # issuing this header themselves. we should NOT issue # it twice; some web servers (such as Apache) barf # when they see two Host: headers # If we need a non-standard port,include it in the # header. If the request is going through a proxy, # but the host of the actual URL, not the host of the # proxy. netloc = &#39;&#39; if url.startswith(&#39;http&#39;): nil, netloc, nil, nil, nil = urlsplit(url) if netloc: try: netloc_enc = netloc.encode(&quot;ascii&quot;) except UnicodeEncodeError: netloc_enc = netloc.encode(&quot;idna&quot;) self.putheader(&#39;Host&#39;, netloc_enc) else: if self._tunnel_host: host = self._tunnel_host port = self._tunnel_port else: host = self.host port = self.port try: host_enc = host.encode(&quot;ascii&quot;) except UnicodeEncodeError: host_enc = host.encode(&quot;idna&quot;) # As per RFC 273, IPv6 address should be wrapped with [] # when used as Host header if host.find(&#39;:&#39;) &gt;= 0: host_enc = b&#39;[&#39; + host_enc + b&#39;]&#39; if port == self.default_port: self.putheader(&#39;Host&#39;, host_enc) else: host_enc = host_enc.decode(&quot;ascii&quot;) self.putheader(&#39;Host&#39;, &quot;%s:%s&quot; % (host_enc, port)) # note: we are assuming that clients will not attempt to set these # headers since *this* library must deal with the # consequences. this also means that when the supporting # libraries are updated to recognize other forms, then this # code should be changed (removed or updated). # we only want a Content-Encoding of &quot;identity&quot; since we don&#39;t # support encodings such as x-gzip or x-deflate. if not skip_accept_encoding: self.putheader(&#39;Accept-Encoding&#39;, &#39;identity&#39;) # we can accept &quot;chunked&quot; Transfer-Encodings, but no others # NOTE: no TE header implies *only* &quot;chunked&quot; #self.putheader(&#39;TE&#39;, &#39;chunked&#39;) # if TE is supplied in the header, then it must appear in a # Connection header. #self.putheader(&#39;Connection&#39;, &#39;TE&#39;) else: # For HTTP/1.0, the server will assume &quot;not chunked&quot; pass def _encode_request(self, request): # ASCII also helps prevent CVE-2019-9740. return request.encode(&#39;ascii&#39;) def _validate_method(self, method): &quot;&quot;&quot;Validate a method name for putrequest.&quot;&quot;&quot; # prevent http header injection match = _contains_disallowed_method_pchar_re.search(method) if match: raise ValueError( f&quot;method can&#39;t contain control characters. {method!r} &quot; f&quot;(found at least {match.group()!r})&quot;) def _validate_path(self, url): &quot;&quot;&quot;Validate a url for putrequest.&quot;&quot;&quot; # Prevent CVE-2019-9740. match = _contains_disallowed_url_pchar_re.search(url) if match: raise InvalidURL(f&quot;URL can&#39;t contain control characters. {url!r} &quot; f&quot;(found at least {match.group()!r})&quot;) def _validate_host(self, host): &quot;&quot;&quot;Validate a host so it doesn&#39;t contain control characters.&quot;&quot;&quot; # Prevent CVE-2019-18348. match = _contains_disallowed_url_pchar_re.search(host) if match: raise InvalidURL(f&quot;URL can&#39;t contain control characters. {host!r} &quot; f&quot;(found at least {match.group()!r})&quot;) def putheader(self, header, *values): &quot;&quot;&quot;Send a request header line to the server. For example: h.putheader(&#39;Accept&#39;, &#39;text/html&#39;) &quot;&quot;&quot; if self.__state != _CS_REQ_STARTED: raise CannotSendHeader() if hasattr(header, &#39;encode&#39;): header = header.encode(&#39;ascii&#39;) if not _is_legal_header_name(header): raise ValueError(&#39;Invalid header name %r&#39; % (header,)) values = list(values) for i, one_value in enumerate(values): if hasattr(one_value, &#39;encode&#39;): values[i] = one_value.encode(&#39;latin-1&#39;) elif isinstance(one_value, int): values[i] = str(one_value).encode(&#39;ascii&#39;) if _is_illegal_header_value(values[i]): raise ValueError(&#39;Invalid header value %r&#39; % (values[i],)) value = b&#39;\r\n\t&#39;.join(values) header = header + b&#39;: &#39; + value self._output(header) def endheaders(self, message_body=None, *, encode_chunked=False): &quot;&quot;&quot;Indicate 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. &quot;&quot;&quot; if self.__state == _CS_REQ_STARTED: self.__state = _CS_REQ_SENT else: raise CannotSendHeader() self._send_output(message_body, encode_chunked=encode_chunked) def request(self, method, url, body=None, headers={}, *, encode_chunked=False): &quot;&quot;&quot;Send a complete request to the server.&quot;&quot;&quot; self._send_request(method, url, body, headers, encode_chunked) def _send_request(self, method, url, body, headers, encode_chunked): # Honor explicitly requested Host: and Accept-Encoding: headers. header_names = frozenset(k.lower() for k in headers) skips = {} if &#39;host&#39; in header_names: skips[&#39;skip_host&#39;] = 1 if &#39;accept-encoding&#39; in header_names: skips[&#39;skip_accept_encoding&#39;] = 1 self.putrequest(method, url, **skips) # chunked encoding will happen if HTTP/1.1 is used and either # the caller passes encode_chunked=True or the following # conditions hold: # 1. content-length has not been explicitly set # 2. the body is a file or iterable, but not a str or bytes-like # 3. Transfer-Encoding has NOT been explicitly set by the caller if &#39;content-length&#39; not in header_names: # only chunk body if not explicitly set for backwards # compatibility, assuming the client code is already handling the # chunking if &#39;transfer-encoding&#39; not in header_names: # if content-length cannot be automatically determined, fall # back to chunked encoding encode_chunked = False content_length = self._get_content_length(body, method) if content_length is None: if body is not None: if self.debuglevel &gt; 0: print(&#39;Unable to determine size of %r&#39; % body) encode_chunked = True self.putheader(&#39;Transfer-Encoding&#39;, &#39;chunked&#39;) else: self.putheader(&#39;Content-Length&#39;, str(content_length)) else: encode_chunked = False for hdr, value in headers.items(): self.putheader(hdr, value) if isinstance(body, str): # RFC 2616 Section 3.7.1 says that text default has a # default charset of iso-8859-1. body = _encode(body, &#39;body&#39;) self.endheaders(body, encode_chunked=encode_chunked) def getresponse(self): &quot;&quot;&quot;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. &quot;&quot;&quot; # if a prior response has been completed, then forget about it. if self.__response and self.__response.isclosed(): self.__response = None # if a prior response exists, then it must be completed (otherwise, we # cannot read this response&#39;s header to determine the connection-close # behavior) # # note: if a prior response existed, but was connection-close, then the # socket and response were made independent of this HTTPConnection # object since a new request requires that we open a whole new # connection # # this means the prior response had one of two states: # 1) will_close: this connection was reset and the prior socket and # response operate independently # 2) persistent: the response was retained and we await its # isclosed() status to become true. # if self.__state != _CS_REQ_SENT or self.__response: raise ResponseNotReady(self.__state) if self.debuglevel &gt; 0: response = self.response_class(self.sock, self.debuglevel, method=self._method) else: response = self.response_class(self.sock, method=self._method) try: try: response.begin() except ConnectionError: self.close() raise assert response.will_close != _UNKNOWN self.__state = _CS_IDLE if response.will_close: # this effectively passes the connection to the response self.close() else: # remember this, so we can tell when it is complete self.__response = response return response except: response.close() raise try: import ssl except ImportError: pass else: class HTTPSConnection(HTTPConnection): &quot;This class allows communication via SSL.&quot; default_port = HTTPS_PORT # XXX Should key_file and cert_file be deprecated in favour of context? def __init__(self, host, port=None, key_file=None, cert_file=None, timeout=socket._GLOBAL_DEFAULT_TIMEOUT, source_address=None, *, context=None, check_hostname=None, blocksize=8192): super(HTTPSConnection, self).__init__(host, port, timeout, source_address, blocksize=blocksize) if (key_file is not None or cert_file is not None or check_hostname is not None): import warnings warnings.warn(&quot;key_file, cert_file and check_hostname are &quot; &quot;deprecated, use a custom context instead.&quot;, DeprecationWarning, 2) self.key_file = key_file self.cert_file = cert_file if context is None: context = ssl._create_default_https_context() # send ALPN extension to indicate HTTP/1.1 protocol if self._http_vsn == 11: context.set_alpn_protocols([&#39;http/1.1&#39;]) # enable PHA for TLS 1.3 connections if available if context.post_handshake_auth is not None: context.post_handshake_auth = True will_verify = context.verify_mode != ssl.CERT_NONE if check_hostname is None: check_hostname = context.check_hostname if check_hostname and not will_verify: raise ValueError(&quot;check_hostname needs a SSL context with &quot; &quot;either CERT_OPTIONAL or CERT_REQUIRED&quot;) if key_file or cert_file: context.load_cert_chain(cert_file, key_file) # cert and key file means the user wants to authenticate. # enable TLS 1.3 PHA implicitly even for custom contexts. if context.post_handshake_auth is not None: context.post_handshake_auth = True self._context = context if check_hostname is not None: self._context.check_hostname = check_hostname def connect(self): &quot;Connect to a host on a given (SSL) port.&quot; super().connect() if self._tunnel_host: server_hostname = self._tunnel_host else: server_hostname = self.host self.sock = self._context.wrap_socket(self.sock, server_hostname=server_hostname) __all__.append(&quot;HTTPSConnection&quot;) class HTTPException(Exception): # Subclasses that define an __init__ must call Exception.__init__ # or define self.args. Otherwise, str() will fail. pass class NotConnected(HTTPException): pass class InvalidURL(HTTPException): pass class UnknownProtocol(HTTPException): def __init__(self, version): self.args = version, self.version = version class UnknownTransferEncoding(HTTPException): pass class UnimplementedFileMode(HTTPException): pass class IncompleteRead(HTTPException): def __init__(self, partial, expected=None): self.args = partial, self.partial = partial self.expected = expected def __repr__(self): if self.expected is not None: e = &#39;, %i more expected&#39; % self.expected else: e = &#39;&#39; return &#39;%s(%i bytes read%s)&#39; % (self.__class__.__name__, len(self.partial), e) __str__ = object.__str__ class ImproperConnectionState(HTTPException): pass class CannotSendRequest(ImproperConnectionState): pass class CannotSendHeader(ImproperConnectionState): pass class ResponseNotReady(ImproperConnectionState): pass class BadStatusLine(HTTPException): def __init__(self, line): if not line: line = repr(line) self.args = line, self.line = line class LineTooLong(HTTPException): def __init__(self, line_type): HTTPException.__init__(self, &quot;got more than %d bytes when reading %s&quot; % (_MAXLINE, line_type)) class RemoteDisconnected(ConnectionResetError, BadStatusLine): def __init__(self, *pos, **kw): BadStatusLine.__init__(self, &quot;&quot;) ConnectionResetError.__init__(self, *pos, **kw) # for backwards compatibility error = HTTPException 解析这些代码 怎么联接这个服务器
最新发布
06-19
### 使用HTTPConnection或HTTPSConnection类连接到服务器的方法 在Python中,`http.client`模块提供了`HTTPConnection`和`HTTPSConnection`两个类来处理HTTP和HTTPS协议的URL连接[^1]。以下是如何使用这些类连接到服务器的详细说明: #### 1. 创建连接对象 通过实例化`HTTPConnection`或`HTTPSConnection`类,可以创建一个连接对象。例如,要连接到一个HTTP服务器: ```python from http.client import HTTPConnection conn = HTTPConnection(&quot;example.com&quot;, 80) # 指定主机名和端口号 ``` 如果需要连接到HTTPS服务器,则使用`HTTPSConnection`类: ```python from http.client import HTTPSConnection conn = HTTPSConnection(&quot;example.com&quot;, 443) # 默认HTTPS端口为443 ``` #### 2. 发送请求 使用连接对象的`request`方法发送HTTP请求。该方法接受四个参数:请求方法(如`GET`、`POST`)、URL路径、请求体(可选)和头部信息(可选)。例如: ```python headers = {&quot;User-Agent&quot;: &quot;Python-Client&quot;} # 设置请求头部 conn.request(&quot;GET&quot;, &quot;/&quot;, headers=headers) # 发送GET请求 ``` #### 3. 获取响应 调用`getresponse`方法以获取服务器的响应。这将返回一个`HTTPResponse`对象: ```python response = conn.getresponse() # 获取响应对象 print(response.status, response.reason) # 输出状态码和原因短语 ``` #### 4. 读取响应内容 通过`read`方法可以从响应对象中读取返回的数据: ```python data = response.read() # 读取响应内容 print(data.decode(&quot;utf-8&quot;)) # 将字节数据解码为字符串 ``` #### 5. 关闭连接 完成请求后,应关闭连接以释放资源: ```python conn.close() ``` #### 示例代码 以下是一个完整的示例,展示如何使用`HTTPSConnection`类连接到服务器并获取网页内容: ```python from http.client import HTTPSConnection # 创建HTTPS连接 conn = HTTPSConnection(&quot;www.python.org&quot;, 443) # 设置请求头部 headers = {&quot;User-Agent&quot;: &quot;Python-Client&quot;} # 发送GET请求 conn.request(&quot;GET&quot;, &quot;/&quot;, headers=headers) # 获取响应 response = conn.getresponse() # 输出状态码和原因短语 print(f&quot;Status: {response.status}, Reason: {response.reason}&quot;) # 读取并打印响应内容 data = response.read() print(data.decode(&quot;utf-8&quot;)) # 关闭连接 conn.close() ``` ### 注意事项 - 在使用`HTTPSConnection`时,可能需要指定SSL上下文以处理证书验证问题[^1]。 - 如果服务器要求身份验证或其他特殊配置,需在请求头部中添加相应的字段。
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值