Custom HTTPSConnection to support source_address across Python 2.4 - Python 3
| 450 | |
| 451 | if HTTPSConnection: |
| 452 | class SpeedtestHTTPSConnection(HTTPSConnection): |
| 453 | """Custom HTTPSConnection to support source_address across |
| 454 | Python 2.4 - Python 3 |
| 455 | """ |
| 456 | default_port = 443 |
| 457 | |
| 458 | def __init__(self, *args, **kwargs): |
| 459 | source_address = kwargs.pop('source_address', None) |
| 460 | timeout = kwargs.pop('timeout', 10) |
| 461 | |
| 462 | self._tunnel_host = None |
| 463 | |
| 464 | HTTPSConnection.__init__(self, *args, **kwargs) |
| 465 | |
| 466 | self.timeout = timeout |
| 467 | self.source_address = source_address |
| 468 | |
| 469 | def connect(self): |
| 470 | "Connect to a host on a given (SSL) port." |
| 471 | try: |
| 472 | self.sock = socket.create_connection( |
| 473 | (self.host, self.port), |
| 474 | self.timeout, |
| 475 | self.source_address |
| 476 | ) |
| 477 | except (AttributeError, TypeError): |
| 478 | self.sock = create_connection( |
| 479 | (self.host, self.port), |
| 480 | self.timeout, |
| 481 | self.source_address |
| 482 | ) |
| 483 | |
| 484 | if self._tunnel_host: |
| 485 | self._tunnel() |
| 486 | |
| 487 | if ssl: |
| 488 | try: |
| 489 | kwargs = {} |
| 490 | if hasattr(ssl, 'SSLContext'): |
| 491 | if self._tunnel_host: |
| 492 | kwargs['server_hostname'] = self._tunnel_host |
| 493 | else: |
| 494 | kwargs['server_hostname'] = self.host |
| 495 | self.sock = self._context.wrap_socket(self.sock, **kwargs) |
| 496 | except AttributeError: |
| 497 | self.sock = ssl.wrap_socket(self.sock) |
| 498 | try: |
| 499 | self.sock.server_hostname = self.host |
| 500 | except AttributeError: |
| 501 | pass |
| 502 | elif FakeSocket: |
| 503 | # Python 2.4/2.5 support |
| 504 | try: |
| 505 | self.sock = FakeSocket(self.sock, socket.ssl(self.sock)) |
| 506 | except AttributeError: |
| 507 | raise SpeedtestException( |
| 508 | 'This version of Python does not support HTTPS/SSL ' |
| 509 | 'functionality' |