Skip to content

Commit

Permalink
New Feature: Wait for connection
Browse files Browse the repository at this point in the history
This fixes the issues described in #10
  • Loading branch information
Rafficer committed Nov 28, 2019
1 parent d8c5e3a commit 0c803bd
Show file tree
Hide file tree
Showing 2 changed files with 40 additions and 2 deletions.
11 changes: 10 additions & 1 deletion protonvpn_cli/cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -58,7 +58,8 @@
from .logger import logger
from .utils import (
check_root, change_file_owner, pull_server_data, make_ovpn_template,
check_init, set_config_value, get_config_value, is_valid_ip
check_init, set_config_value, get_config_value, is_valid_ip,
wait_for_network
)
# Constants
from .constants import (
Expand Down Expand Up @@ -96,6 +97,14 @@ def cli():
check_root()
check_init()

# Wait until a connection to the ProtonVPN API can be made
# As this is mainly for automatically connecting on boot, it only
# activates when the environment variable PVPN_WAIT is 1
# Otherwise it wouldn't connect when a VPN process without
# internet access exists or the Kill Switch is active
if os.environ.get("PVPN_WAIT", 0) == "1":
wait_for_network()

protocol = args.get("-p")
if protocol is not None and protocol.lower().strip() in ["tcp", "udp"]:
protocol = protocol.lower().strip()
Expand Down
31 changes: 30 additions & 1 deletion protonvpn_cli/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@
)


def call_api(endpoint, json_format=True):
def call_api(endpoint, json_format=True, handle_errors=True):
"""Call to the ProtonVPN API."""

api_domain = "https://api.protonmail.ch"
Expand All @@ -33,6 +33,11 @@ def call_api(endpoint, json_format=True):

logger.debug("Initiating API Call: {0}".format(url))

# For manual error handling, such as in wait_for_network()
if not handle_errors:
response = requests.get(url, headers=headers)
return response

try:
response = requests.get(url, headers=headers)
except (requests.exceptions.ConnectionError,
Expand Down Expand Up @@ -184,6 +189,30 @@ def is_connected():
return True if ovpn_processes != [] else False


def wait_for_network():
"""Check if internet access is working"""

print("Waiting for connection...")
max_waiting_time = 20 * 60 # 20 Minutes
start = time.time()

while True:
if time.time() - start > max_waiting_time:
logger.debug("Max waiting time reached.")
print("Max waiting time reached.")
sys.exit(1)
logger.debug("Waiting for connection...")
try:
call_api("/test/ping", handle_errors=False)
time.sleep(2)
print("Connection working!")
logger.debug("Connection working!")
break
except (requests.exceptions.ConnectionError,
requests.exceptions.ConnectTimeout):
time.sleep(2)


def cidr_to_netmask(cidr):
netmask = "0"
cidr_netmask = {
Expand Down

0 comments on commit 0c803bd

Please sign in to comment.