|
105 | 105 | # Mapping status codes to official W3C names |
106 | 106 | responses = {v: v.phrase for v in http.HTTPStatus.__members__.values()} |
107 | 107 |
|
| 108 | +# maximal amount of data to read at one time in _safe_read |
| 109 | +MAXAMOUNT = 1048576 |
| 110 | + |
108 | 111 | # maximal line length when calling readline(). |
109 | 112 | _MAXLINE = 65536 |
110 | 113 | _MAXHEADERS = 100 |
@@ -604,24 +607,43 @@ def _readinto_chunked(self, b): |
604 | 607 | raise IncompleteRead(bytes(b[0:total_bytes])) |
605 | 608 |
|
606 | 609 | def _safe_read(self, amt): |
607 | | - """Read the number of bytes requested. |
| 610 | + """Read the number of bytes requested, compensating for partial reads. |
| 611 | +
|
| 612 | + Normally, we have a blocking socket, but a read() can be interrupted |
| 613 | + by a signal (resulting in a partial read). |
| 614 | +
|
| 615 | + Note that we cannot distinguish between EOF and an interrupt when zero |
| 616 | + bytes have been read. IncompleteRead() will be raised in this |
| 617 | + situation. |
608 | 618 |
|
609 | 619 | This function should be used when <amt> bytes "should" be present for |
610 | 620 | reading. If the bytes are truly not available (due to EOF), then the |
611 | 621 | IncompleteRead exception can be used to detect the problem. |
612 | 622 | """ |
613 | | - data = self.fp.read(amt) |
614 | | - if len(data) < amt: |
615 | | - raise IncompleteRead(data, amt-len(data)) |
616 | | - return data |
| 623 | + s = [] |
| 624 | + while amt > 0: |
| 625 | + chunk = self.fp.read(min(amt, MAXAMOUNT)) |
| 626 | + if not chunk: |
| 627 | + raise IncompleteRead(b''.join(s), amt) |
| 628 | + s.append(chunk) |
| 629 | + amt -= len(chunk) |
| 630 | + return b"".join(s) |
617 | 631 |
|
618 | 632 | def _safe_readinto(self, b): |
619 | 633 | """Same as _safe_read, but for reading into a buffer.""" |
620 | | - amt = len(b) |
621 | | - n = self.fp.readinto(b) |
622 | | - if n < amt: |
623 | | - raise IncompleteRead(bytes(b[:n]), amt-n) |
624 | | - return n |
| 634 | + total_bytes = 0 |
| 635 | + mvb = memoryview(b) |
| 636 | + while total_bytes < len(b): |
| 637 | + if MAXAMOUNT < len(mvb): |
| 638 | + temp_mvb = mvb[0:MAXAMOUNT] |
| 639 | + n = self.fp.readinto(temp_mvb) |
| 640 | + else: |
| 641 | + n = self.fp.readinto(mvb) |
| 642 | + if not n: |
| 643 | + raise IncompleteRead(bytes(mvb[0:total_bytes]), len(b)) |
| 644 | + mvb = mvb[n:] |
| 645 | + total_bytes += n |
| 646 | + return total_bytes |
625 | 647 |
|
626 | 648 | def read1(self, n=-1): |
627 | 649 | """Read with at most one underlying system call. If at least one |
|
0 commit comments