| 1 |
""" |
| 2 |
Copyright (c) 2023 Proton AG |
| 3 |
|
| 4 |
This file is part of Proton. |
| 5 |
|
| 6 |
Proton is free software: you can redistribute it and/or modify |
| 7 |
it under the terms of the GNU General Public License as published by |
| 8 |
the Free Software Foundation, either version 3 of the License, or |
| 9 |
(at your option) any later version. |
| 10 |
|
| 11 |
Proton is distributed in the hope that it will be useful, |
| 12 |
but WITHOUT ANY WARRANTY; without even the implied warranty of |
| 13 |
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the |
| 14 |
GNU General Public License for more details. |
| 15 |
|
| 16 |
You should have received a copy of the GNU General Public License |
| 17 |
along with ProtonVPN. If not, see <https://www.gnu.org/licenses/>. |
| 18 |
""" |
| 19 |
from asyncio import transports, TimeoutError |
| 20 |
from typing import List |
| 21 |
from unittest.mock import Mock |
| 22 |
from urllib.parse import urlparse |
| 23 |
import json, base64, struct, time, asyncio, random, itertools |
| 24 |
|
| 25 |
from ..exceptions import * |
| 26 |
from .base import Transport |
| 27 |
from .aiohttp import AiohttpTransport |
| 28 |
from .alternativerouting import AlternativeRoutingTransport |
| 29 |
from ..api import sync_wrapper |
| 30 |
|
| 31 |
|
| 32 |
class AutoTransport(Transport): |
| 33 |
# We assume that a given transport fails after that number of seconds |
| 34 |
TRANSPORT_TIMEOUT = 15 |
| 35 |
|
| 36 |
@classmethod |
| 37 |
def _get_priority(cls): |
| 38 |
return 100 |
| 39 |
|
| 40 |
def __init__(self, session, transport_choices: List[Transport] = None, transport_timeout: int = None): |
| 41 |
super().__init__(session) |
| 42 |
|
| 43 |
self._current_transport = None |
| 44 |
self._transport_choices = transport_choices or [ |
| 45 |
(0, AiohttpTransport), |
| 46 |
(5, AlternativeRoutingTransport) |
| 47 |
] |
| 48 |
self._transport_timeout = transport_timeout or self.TRANSPORT_TIMEOUT |
| 49 |
|
| 50 |
@property |
| 51 |
def is_available(self) -> bool: |
| 52 |
return self._current_transport is not None |
| 53 |
|
| 54 |
@property |
| 55 |
def transport_choices(self): |
| 56 |
return self._transport_choices |
| 57 |
|
| 58 |
@transport_choices.setter |
| 59 |
def transport_choices(self, newvalue): |
| 60 |
self._transport_choices = [] |
| 61 |
|
| 62 |
for timeout, cls in newvalue: |
| 63 |
if not isinstance(cls, Transport): |
| 64 |
raise TypeError("Transports should be a subclass of Transport") |
| 65 |
self._transport_choices.append((timeout, cls)) |
| 66 |
self._transport_choices.sort(key=lambda x: x[0]) |
| 67 |
|
| 68 |
async def _ping_via_transport(self, timeout, transport): |
| 69 |
await asyncio.sleep(timeout) |
| 70 |
ping_url = "/tests/ping" |
| 71 |
try: |
| 72 |
result = await asyncio.wait_for(transport.async_api_request(ping_url), self._transport_timeout) |
| 73 |
except TimeoutError as error: |
| 74 |
raise ProtonAPINotReachable( |
| 75 |
f"{type(transport).__name__} transport not available: unable to reach {ping_url}" |
| 76 |
) from error |
| 77 |
if result != {"Code": 1000}: |
| 78 |
raise ProtonAPINotAvailable( |
| 79 |
f"{type(transport).__name__} transport received unexpected response from {ping_url}:\n" |
| 80 |
f"{result}" |
| 81 |
) |
| 82 |
return transport |
| 83 |
|
| 84 |
async def find_available_transport(self): |
| 85 |
pending = [] |
| 86 |
for timeout, cls in self._transport_choices: |
| 87 |
transport = cls(self._session) |
| 88 |
pending.append(asyncio.create_task(self._ping_via_transport(timeout, transport))) |
| 89 |
|
| 90 |
results_ok = [] |
| 91 |
results_fail = [] |
| 92 |
final_timestamp = time.time() + self._transport_timeout |
| 93 |
while len(pending) > 0 and len(results_ok) == 0: |
| 94 |
done, pending = await asyncio.wait(pending, timeout=max(0.1, final_timestamp - time.time()), return_when=asyncio.FIRST_COMPLETED) |
| 95 |
for task in done: |
| 96 |
try: |
| 97 |
results_ok.append(task.result()) |
| 98 |
except (ProtonAPINotAvailable, ProtonAPINotReachable) as e: |
| 99 |
# That means that we were able to get to the API (wasn't reachable or was mitm'ed) |
| 100 |
results_fail.append(e) |
| 101 |
except Exception as e: |
| 102 |
# Unhandled exception, we might want to understand what is going on |
| 103 |
for task in pending: |
| 104 |
task.cancel() |
| 105 |
raise |
| 106 |
|
| 107 |
for task in pending: |
| 108 |
task.cancel() |
| 109 |
|
| 110 |
if not results_ok: |
| 111 |
raise ProtonAPINotReachable("No working transports found") |
| 112 |
|
| 113 |
self._current_transport = results_ok[0] |
| 114 |
|
| 115 |
async def async_api_request( |
| 116 |
self, endpoint, |
| 117 |
jsondata=None, data=None, additional_headers=None, method=None, params=None, |
| 118 |
return_raw=False |
| 119 |
): |
| 120 |
tries_left = 3 |
| 121 |
while tries_left > 0: |
| 122 |
tries_left -= 1 |
| 123 |
if self._current_transport is None: |
| 124 |
await self.find_available_transport() |
| 125 |
|
| 126 |
try: |
| 127 |
return await asyncio.wait_for(self._current_transport.async_api_request(endpoint, jsondata, data, additional_headers, method, params, return_raw=return_raw), self._transport_timeout) |
| 128 |
except asyncio.TimeoutError: |
| 129 |
# Reset transport |
| 130 |
self._current_transport = None |
| 131 |
|
| 132 |
raise ProtonAPINotReachable("Timeout accessing the API") # we should not reach that point except in case of Timeout |