Example #1
0
def setErrorValue(index, value):
    index -= 1
    errors = xbmcaddon.Addon(getID()).getSetting("ip_service_errors")    
    if errors == "": errors = LIST_DEFAULT
    list = errors.split(",")
    i = 0
    output = ""
    while i < (len(list)):
        if i > 0: output = output + ","
        if i == index: output = output + str(value)
        else: output = output + str(list[i])
        i += 1
    xbmcaddon.Addon(getID()).setSetting("ip_service_errors", output)
Example #2
0
def changeConnection():
    # Connect, or display status if we're already using selected VPN profile
    # If there is no profile, then skip this as the user has selected something non-selectable
    debugTrace("Changing connection to " + params + " from " +
               getVPNProfile() + ", connected:" + str(isVPNConnected()))
    addon = xbmcaddon.Addon(getID())
    ignore = False
    user_text = ""
    vpn_provider = addon.getSetting("vpn_provider")
    if isAlternative(vpn_provider):
        # Convert the friendly name to a file name, or an error message
        _, ovpn_connection, user_text, ignore = getAlternativeLocation(
            vpn_provider, params, 0, True)
    else:
        # Just extract the ovpn name from the URL for regular providers
        ovpn_connection = params
    # Try and connect if we've got a connection name.  If we're already connection, display the status
    if not ignore:
        if not user_text == "":
            xbmcgui.Dialog().ok(addon_name, user_text)
        elif isVPNConnected() and ovpn_connection == getVPNProfile(
        ) and not allowReconnection(vpn_provider) and not addon.getSetting(
                "allow_cycle_reconnect") == "true":
            displayStatus()
        else:
            connectVPN("0", ovpn_connection)
    return
Example #3
0
def getTokenNordVPN():
    # Return a token that can be used on API calls
    token, renew, expiry, _ = getTokens()

    # If the expiry time is passed, renew the token
    if expiry.isdigit() and int(expiry) < now():
        if renewNordVPN(renew):
            token, _, _, _ = getTokens()
            return token
        else:
            # Force an authenticate to happen
            token = ""

    # The authentication call is made during connection validation, which will validate everything and fetch
    # the tokens.  If a reboot happens and the tokens disappear, then we need to force an authenticate again
    if token == "":
        addon = xbmcaddon.Addon(getID())
        if authenticateNordVPN(addon.getSetting("vpn_provider_validated"),
                               addon.getSetting("vpn_username_validated"),
                               addon.getSetting("vpn_password_validated")):
            token, _, _, _ = getTokens()
            return token
        else:
            errorTrace("alternativeNord.py",
                       "Couldn't authenticate or renew the user ID")
            resetTokens()
            raise RuntimeError("Couldn't get a user ID token")

    debugTrace("Using existing user ID token")
    return token
Example #4
0
def copySystemdFiles():
    # Delete any existing openvpn.service and copy openvpn service file to config directory
    service_source = getAddonPath(True, "openvpn.service")
    service_dest = getSystemdPath("system.d/openvpn.service")
    debugTrace("Copying openvpn.service " + service_source + " to " +
               service_dest)
    if not fakeSystemd():
        if xbmcvfs.exists(service_dest): xbmcvfs.delete(service_dest)
        xbmcvfs.copy(service_source, service_dest)
        if not xbmcvfs.exists(service_dest):
            raise IOError('Failed to copy service ' + service_source + " to " +
                          service_dest)

    # Delete any existing openvpn.config and copy first VPN to openvpn.config
    config_source = sudo_setting = xbmcaddon.Addon(
        getID()).getSetting("1_vpn_validated")
    if service_source == "":
        errorTrace("vpnplatform.py", "Nothing has been validated")
    config_dest = getSystemdPath("openvpn.config")
    debugTrace("Copying openvpn.config " + config_source + " to " +
               config_dest)
    if not fakeSystemd():
        if xbmcvfs.exists(config_dest): xbmcvfs.delete(config_dest)
        xbmcvfs.copy(config_source, config_dest)
        if not xbmcvfs.exists(config_dest):
            raise IOError('Failed to copy service ovpn ' + config_source +
                          " to " + config_dest)
Example #5
0
def popupSysBox():
    if not getID() == "":
        addon = xbmcaddon.Addon(getID())
        dialog_text_l = ""
        dialog_text_r = ""
        data_left = getSystemData(addon, True, True, False, False)
        data_right = getSystemData(addon, False, False, False, True)
        for line in data_left:
            if line.startswith("[B]") and not dialog_text_l == "": dialog_text_l = dialog_text_l + "\n"
            dialog_text_l = dialog_text_l + line + "\n"
        for line in data_right:
            if line.startswith("[B]") and not dialog_text_r == "": dialog_text_r = dialog_text_r + "\n"
            dialog_text_r = dialog_text_r + line + "\n"    
        showInfoBox("System Information", dialog_text_l, dialog_text_r)
    else:
        errorTrace("sysbox.py", "VPN service is not ready")
Example #6
0
def postConnectNordVPN(vpn_provider):
    # Post connect, might need to update the systemd config
    addon = xbmcaddon.Addon(getID())
    if ((addon.getSetting("1_vpn_validated") == getVPNProfile()) and (addon.getSetting("vpn_connect_before_boot") == "true")):
        if xbmcvfs.exists(getSystemdPath("openvpn.config")) or fakeSystemd():
            copySystemdFiles()
    return    
Example #7
0
def getErrorValue(index):
    index -= 1
    errors = xbmcaddon.Addon(getID()).getSetting("ip_service_errors")
    if not errors == "":
        list = errors.split(",")
        if not index > len(list):
            return int(list[index])
    return 0
Example #8
0
def getWorkingValue(index):
    index -= 1
    values = xbmcaddon.Addon(getID()).getSetting("ip_service_values")
    if not values == "":
        list = values.split(",")
        if not index > len(list):
            return int(list[index])
    return 0
Example #9
0
def useSudo():
    sudo_setting = xbmcaddon.Addon(getID()).getSetting("openvpn_sudo")
    if sudo_setting == "Always": return True
    if sudo_setting == "Never": return False
    if getPlatform() == platforms.LINUX:
        # For non-LE/OE Linux (based on the path name...) we don't need to use sudo
        if not getAddonPath(True, "").startswith("/storage/.kodi/"): return True
    return False
def showInfoBox(caption, text_l, text_r):
    path = xbmcaddon.Addon(getID()).getAddonInfo("path")
    win = InfoBox("infotextbox.xml",
                  path,
                  caption=caption,
                  text_left=text_l,
                  text_right=text_r)
    win.doModal()
    del win
def sendAPI(command, command_text, api_data, check_response):
    # Common routine to send an API command
    try:
        response = ""
        rc = True
        rest_url = REQUEST_URL + command
        
        auth_token,_,_,_ = getTokens()
        # Login again if the token is blank and the command is not login anyway
        if auth_token == "" and not "=login" in command:
            debugTrace("Logging in again because auth token not valid")
            addon = xbmcaddon.Addon(getID())
            rc = authenticateShellfire(addon.getSetting("vpn_provider"), addon.getSetting("vpn_username"), addon.getSetting("vpn_password"))
            auth_token,_,_,_ = getTokens()
            if auth_token == "" or not rc:
                raise Exception(command_text + " was not authorized")
        
        if ifHTTPTrace(): infoTrace("alternativeShellfire.py", command_text + " " + rest_url)     
        else: debugTrace(command_text)
        
        req = urllib2.Request(rest_url, api_data, REQUEST_HEADERS)
        if not auth_token == "": req.add_header("x-authorization-token", auth_token)
        t_before = now()
        response = urllib2.urlopen(req)
        api_data = json.load(response)   
        t_after = now()    
        response.close()

        # Trace if the command took a long time
        if ifJSONTrace(): infoTrace("alternativeShellfire.py", "JSON received is \n" + json.dumps(api_data, indent=4))
        if t_after - t_before > TIME_WARN: infoTrace("alternativeShellfire.py", command_text + " took " + str(t_after - t_before) + " seconds")
        
        # Check the response and fail if it's bad
        if check_response:
            if not api_data["status"] == "success":
                raise Exception(command_text + " returned bad response, " + api_data["status"])
        
    except urllib2.HTTPError as e:
        errorTrace("alternativeShellfire.py", command_text + " failed")
        errorTrace("alternativeShellfire.py", "API call was " + rest_url)
        if not api_data == "": errorTrace("alternativeShellfire.py", "Data returned was \n" + json.dumps(api_data, indent=4))
        errorTrace("alternativeShellfire.py", "Response was " + str(e.code) + " " + e.reason)
        errorTrace("alternativeShellfire.py", e.read())
        rc = False
    except Exception as e:
        errorTrace("alternativeShellfire.py", command_text + " failed")
        errorTrace("alternativeShellfire.py", "API call was " + rest_url)
        if not api_data == "": errorTrace("alternativeShellfire.py", "Data returned was \n" + json.dumps(api_data, indent=4))
        errorTrace("alternativeShellfire.py", "Response was " + str(type(e)) + " " + str(e))
        rc = False
    
    return rc, api_data
Example #12
0
def getOpenVPNPath():
    # Return the path to openvpn
    p = getPlatform()
    if p == platforms.RPI:
        return getAddonPath(False, "network.openvpn/bin/openvpn")
    if p == platforms.LINUX or p == platforms.WINDOWS:
        addon = xbmcaddon.Addon(getID())
        if addon.getSetting("openvpn_no_path") == "true" or addon.getSetting("openvpn_path") == "": return "openvpn"
        return '"' + addon.getSetting("openvpn_path") + "openvpn" + '"'
        
    # **** ADD MORE PLATFORMS HERE ****
    
    return
Example #13
0
def getTestFilePath():
    # Return the full filename for the VPN log file
    # It's platform dependent, but can be forced to the Kodi log location
    use_kodi_dir = xbmcaddon.Addon(getID()).getSetting("openvpn_log_location")
    p = getPlatform()
    if p == platforms.WINDOWS or use_kodi_dir == "true":
        # Putting this with the other logs on Windows
        return translatePath("special://logpath/command_test.txt")
    if p == platforms.LINUX or p == platforms.RPI:
        # This should be a RAM drive so doesn't wear the media
        return "/run/command_text.txt"

    # **** ADD MORE PLATFORMS HERE ****

    return ""
Example #14
0
def getNordVPNLocationsCommon(vpn_provider, exclude_used, friendly):
    # Return a list of all of the locations or location .ovpn files
    addon = xbmcaddon.Addon(getID())
    # Get the list of used, validated location file names
    used = []
    if exclude_used:
        # Adjust the 11 below to change conn_max
        for i in range(1, 11):
            s = addon.getSetting(str(i) + "_vpn_validated_friendly")
            if not s == "": used.append(s)

    filename = getAddonPath(True, vpn_provider + "/" + NORD_LOCATIONS)
    # If the list of countries doesn't exist (this can happen after a reinstall)
    # then go and do the pre-fetch first.  Otherwise this shouldn't be necessary
    try:
        if not xbmcvfs.exists(filename):
            getNordVPNPreFetch(vpn_provider)
    except Exception as e:
        errorTrace(
            "alternativeNord.py",
            "Couldn't download the list of countries for " + vpn_provider +
            " from " + filename)
        errorTrace("alternativeNord.py", str(e))
        return []

    # Read the locations file and generate the location file name, excluding any that are used
    try:

        locations_file = open(filename, 'r')
        locations = locations_file.readlines()
        locations_file.close()
        return_locations = []
        for l in locations:
            country, id = l.split(",")
            if not exclude_used or not country in used:
                if friendly:
                    return_locations.append(country)
                else:
                    return_locations.append(
                        getNordVPNLocationName(vpn_provider, country))
        return return_locations
    except Exception as e:
        errorTrace(
            "alternativeNord.py", "Couldn't read the list of countries for " +
            vpn_provider + " from " + filename)
        errorTrace("alternativeNord.py", str(e))
        return []
def checkForShellfireUpdates(vpn_provider):
    # See if the current stored tokens have changed
    addon = xbmcaddon.Addon(getID())
    current = addon.getSetting("vpn_locations_list")
    # If nothing has been selected/validated, then it doesn't matter if there's updates or not
    if current == "": return False
    # Likewise, if nothing is connected, then it doesn't matter yet
    if addon.getSetting("1_vpn_validated") == "": return False
    debugTrace("Checking for updates for " + current)
    # Get the list of services and see if the current ID is still the same
    services = getServices()
    if services == None: return False
    for s in services:
        # Look for the current service/id. If it's found nothing has been updated
        if s == current: return False
    # If we didn't find the service/id, then it's changed, so there are updates
    return True
def checkForShellfireUpdates(vpn_provider):
    # See if the current stored tokens have changed
    addon = xbmcaddon.Addon(getID())
    current = addon.getSetting("vpn_locations_list")
    # If nothing has been selected/validated, then it doesn't matter if there's updates or not
    if current == "": return False
    # Likewise, if nothing is connected, then it doesn't matter yet
    if addon.getSetting("1_vpn_validated") == "": return False
    debugTrace("Checking for updates for " + current)
    # Get the list of services and see if the current ID is still the same
    services = getServices()
    if services == None: return False
    for s in services:
        # Look for the current service/id. If it's found nothing has been updated
        if s == current: return False
    # If we didn't find the service/id, then it's changed, so there are updates
    return True
Example #17
0
def isVPNTaskRunning():
    # Return True if the VPN task is still running, or the VPN connection is still active
    # Return False if the VPN task is no longer running and the connection is not active

    if fakeConnection(): return True

    p = getPlatform()
    if p == platforms.LINUX or p == platforms.RPI:
        try:
            command = getPidofPath() + " openvpn"
            if useSudo(): command = "sudo " + command
            debugTrace("(Linux) Checking VPN task with " + command)
            pid = os.system(command)
            # This horrible call returns 0 if it finds a process, it's not returning the PID number
            if xbmcaddon.Addon(getID()).getSetting("alt_pid_check") == "true":
                if pid > 0: return True
            else:
                if pid == 0: return True
            debugTrace("(Linux) Didn't find a running process")
            return False
        except Exception as e:
            errorTrace("vpnplatform.py", "VPN task list failed")
            errorTrace("vpnplatform.py", str(e))
            return False
    if p == platforms.WINDOWS:
        try:
            command = 'tasklist /FI "IMAGENAME eq OPENVPN.EXE"'
            debugTrace("(Windows) Checking VPN task with " + command)
            args = shlex.split(command)
            out = str(
                subprocess.check_output(args,
                                        creationflags=subprocess.SW_HIDE,
                                        shell=True).strip())
            if "openvpn.exe" in out:
                return True
            else:
                debugTrace("(Windows) Didn't find a running process")
                return False
        except Exception as e:
            errorTrace("vpnplatform.py", "VPN task list failed")
            errorTrace("vpnplatform.py", str(e))
            return False

    # **** ADD MORE PLATFORMS HERE ****

    return False
Example #18
0
def getAutoSource():
    # If the VPN has changed, then reset all the numbers        
    addon = xbmcaddon.Addon(getID())
    last_vpn = addon.getSetting("ip_service_last_vpn")
    current_vpn = addon.getSetting("vpn_provider_validated")
    if (not last_vpn == current_vpn):
        addon.setSetting("ip_service_last_vpn", current_vpn)
        resetIPServices()

    # Get the last source we tried to use from the home window or use the first if this is first time through
    source = xbmcgui.Window(10000).getProperty("VPN_Manager_Last_IP_Service")
    if source == "":
        # Record that we're using the first one
        xbmcgui.Window(10000).setProperty("VPN_Manager_Last_IP_Service", ip_sources[1])
        return ip_sources[1]
    else:
        index = ip_sources.index(source)
        if index > 1:
            if getWorkingValue(index) >= getErrorValue(index - 1):
                setWorkingValue(index, 0)
                index = index - 1
        return ip_sources[index]
Example #19
0
def apiConnect(connection):
    if connection.isdigit():
        c = int(connection)
        addon = xbmcaddon.Addon(getID())
        # Adjust the 11 below to change conn_max
        if c > 0 and c < 11:
            connection = addon.getSetting(str(c) + "_vpn_validated")
            if not connection == "":
                setAPICommand(connection)
            else:
                errorTrace(
                    "api.py", "Connection requested, " + str(c) +
                    " has not been validated")
        else:
            errorTrace("api.py",
                       "Invalid connection, " + str(c) + " requested")
    else:
        if xbmcvfs.exists(connection):
            setAPICommand(connection)
        else:
            errorTrace(
                "api.py",
                "Requested connection, " + connection + " does not exist")
def getShellfireUserPass(vpn_provider):
    # Use the user ID and password entered into the GUI
    addon = xbmcaddon.Addon(getID())
    return addon.getSetting("vpn_username"), addon.getSetting("vpn_password")
def getShellfireLocation(vpn_provider, location, server_count, just_name):
    # Return the friendly and .ovpn name
    addon = xbmcaddon.Addon(getID())
    # Just return if this is a title that's been passed in
    if location.startswith(TITLE_START):
        return "", "", "Select a location or server", True
    # Remove all of the tagging
    # There's some escaping of the UPGRADE_END characters when passed in via the add-on menu
    # This is why the command below searches for the end of the upgrade and strips it
    location = location.replace(UPGRADE_START, "")
    if "I]" in location: location = location[:(location.index("I]") - 2)]
    location = location.strip(" ")

    filename = getAddonPath(True, vpn_provider + "/" + SHELLFIRE_LOCATIONS)
    try:
        if not xbmcvfs.exists(filename):
            getShellfirePreFetch(vpn_provider)
    except Exception as e:
        errorTrace(
            "alternativeShellfire.py",
            "Couldn't download the list of locations for " + vpn_provider +
            " from " + filename)
        errorTrace("alternativeShellfire.py", str(e))
        return "", "", "", False

    try:
        # Read the locations from the file and list by account type
        locations_file = open(filename, 'r')
        locations = locations_file.readlines()
        locations_file.close()
        for l in locations:
            if location in l:
                country, server, type, server_id = l.split(",")
                server_id = server_id.strip(" \n")
                break
        # Return an upgrade message if this server is not available to the user
        if ACCOUNT_TYPES.index(type) > ACCOUNT_TYPES.index(getAccountType()):
            _, message = getShellfireMessages(vpn_provider, 0, "")
            if message == "":
                message = "Get access to servers in over 30 countries with unlimited speed at shellfire.net/kodi"
            return "", "", "Upgrade to use this [B]" + type + "[/B] location.\n" + message, False

        # Generate the file name from the location
        location_filename = getShellfireLocationName(vpn_provider, country)

        if just_name: return location, location_filename, "", False

    except Exception as e:
        errorTrace(
            "alternativeShellfire.py",
            "Couldn't read the list of locations for " + vpn_provider +
            " from " + filename)
        errorTrace("alternativeShellfire.py", str(e))
        return "", "", "", False

    # Set the selected server for the VPN being used
    try:
        setShellfireServer(getAccountID(), server_id)

        # Set the protocol.  If it's "UDP and TCP", choose UDP
        proto = addon.getSetting("vpn_protocol")
        if "UDP" in proto: proto = "UDP"
        if not setShellfireProtocol(getAccountID(), proto):
            raise Exception("Couldn't set the protocol")

        # Get the parameters associated with this server and put them in a file
        if not getShellfireOvpn(getAccountID(), vpn_provider, country):
            raise Exception("Couldn't create an OVPN file")

        # Get the certs associated with this server and put them in a file
        if not getShellfireCerts(getAccountID(), vpn_provider, country):
            raise Exception("Couldn't create the certificates")

        return country, location_filename, "", False
    except Exception as e:
        errorTrace(
            "alternativeShellfire.py",
            "Couldn't read the list of locations for " + vpn_provider +
            " from " + filename)
        errorTrace("alternativeShellfire.py", str(e))
        return "", "", "", False
def getShellfireLocationsCommon(vpn_provider, exclude_used, friendly, servers):
    # Return a list of all of the locations
    addon = xbmcaddon.Addon(getID())
    # Get the list of used, validated location file names
    used = []
    if exclude_used:
        # Adjust the 11 below to change conn_max
        for i in range(1, 11):
            s = addon.getSetting(str(i) + "_vpn_validated_friendly")
            if not s == "": used.append(s)

    filename = getAddonPath(True, vpn_provider + "/" + SHELLFIRE_LOCATIONS)
    # If the list of locations doesn't exist (this can happen after a reinstall)
    # then go and do the pre-fetch first.  Otherwise this shouldn't be necessary
    try:
        if not xbmcvfs.exists(filename):
            getShellfirePreFetch(vpn_provider)
    except Exception as e:
        errorTrace(
            "alternativeShellfire.py",
            "Couldn't download the list of locations for " + vpn_provider +
            " from " + filename)
        errorTrace("alternativeShellfire.py", str(e))
        return []

    try:
        service = ACCOUNT_TYPES.index(getAccountType())
    except Exception as e:
        errorTrace("alternativeShellfire.py",
                   "Don't have an account for " + vpn_provider)
        errorTrace("alternativeShellfire.py", str(e))
        return []

    try:

        # Read the locations from the file and list by account type
        locations_file = open(filename, 'r')
        locations = locations_file.readlines()
        locations_file.close()
        return_locations = []

        # List the free servers
        return_locations.append(TITLE_START + "Free Locations" + TITLE_END)
        for l in locations:
            country, server, type, server_id = l.split(",")
            server_id = server_id.strip(" \n")
            if type == ACCOUNT_TYPES[0]:
                if not exclude_used or not country in used:
                    if friendly:
                        return_locations.append(SERVER_START + country +
                                                SERVER_END)
                    elif servers:
                        return_locations.append(SERVER_START + server +
                                                SERVER_END)
                    else:
                        return_locations.append(
                            type +
                            getShellfireLocationName(vpn_provider, country))

        # List the paid servers
        return_locations.append(TITLE_START + "Paid Locations" + TITLE_END)
        for l in locations:
            country, server, type, server_id = l.split(",")
            server_id = server_id.strip(" \n")
            if not type == ACCOUNT_TYPES[0]:
                if ACCOUNT_TYPES.index(type) > service:
                    start = UPGRADE_START
                    end = UPGRADE_END
                else:
                    start = SERVER_START
                    end = SERVER_END
                if not exclude_used or not country in used:
                    if friendly:
                        return_locations.append(start + country + end)
                    elif servers:
                        return_locations.append(start + server + end)
                    else:
                        return_locations.append(
                            type +
                            getShellfireLocationName(vpn_provider, country))

        return return_locations
    except Exception as e:
        errorTrace(
            "alternativeShellfire.py",
            "Couldn't read the list of locations for " + vpn_provider +
            " from " + filename)
        errorTrace("alternativeShellfire.py", str(e))
        return []

    return []
Example #23
0
#    This module allows some limited interaction with the service via
#    a set of commands

import xbmcaddon
import xbmcvfs
import string
from libs.common import setAPICommand, clearAPICommand, getAPICommand
from libs.utility import debugTrace, errorTrace, infoTrace, newPrint, getID

# Get the first argument which will indicate the connection that's being dealt with
command = sys.argv[1]
lcommand = command.lower()

debugTrace("Entered api.py with parameter " + command)

if not getID() == "":
    if lcommand == "disconnect": 
        setAPICommand("Disconnect")
    elif lcommand == "cycle":
        setAPICommand("Cycle")
    elif lcommand == "fake":
        setAPICommand("Fake")
    elif lcommand == "real":
        setAPICommand("Real")
    elif lcommand == "pause":
        setAPICommand("Pause")
    elif lcommand == "restart":
        setAPICommand("Restart")
    elif lcommand == "reconnect":
        setAPICommand("Reconnect")
    elif lcommand == "getip":
def getAccountID():
    # This returns the ID of the account that was selected
    addon = xbmcaddon.Addon(getID())
    service = addon.getSetting("vpn_locations_list")
    type, id = service.split(";")
    return id
Example #25
0
        
def editSingle(default):
    new_filter = xbmcgui.Dialog().numeric(0, "Enter window ID", default)
    if (not new_filter == "") and int(new_filter) > 9999 and int(new_filter) < 100000:
        return new_filter
    else:
        xbmcgui.Dialog().ok(addon_name, "ID is invalid.  IDs should be 5 characters")
        return ""
       
       
vpn = sys.argv[1]

debugTrace("-- Entered windowfilter.py with parameter " + vpn + " --")       

if not getID() == "":

    id_range = "[I]Add range of IDs[/I]"
    id_single = "[I]Add single ID[/I]"
    id_reset = "[I]Delete all[/I]"
    id_cancel = "[I]Cancel changes[/I]"
    id_done = "[I]Done[/I]"

    addon = xbmcaddon.Addon(getID())
    addon_name = getName()

    show_filters = True

    # Build the list of filters
    if vpn == "0":
        filter_string = addon.getSetting("vpn_excluded_windows")
Example #26
0
def getNordVPNLocation(vpn_provider, location, server_count, just_name):
    # Return friendly name and .ovpn file name
    # Given the location, find the country ID of the servers
    addon = xbmcaddon.Addon(getID())

    filename = getAddonPath(True, vpn_provider + "/" + NORD_LOCATIONS)
    # If the list of countries doesn't exist (this can happen after a reinstall)
    # then go and do the pre-fetch first.  Otherwise this shouldn't be necessary
    try:
        if not xbmcvfs.exists(filename):
            getNordVPNPreFetch(vpn_provider)
    except Exception as e:
        errorTrace(
            "alternativeNord.py",
            "Couldn't download the list of countries to get ID for " +
            vpn_provider + " from " + filename)
        errorTrace("alternativeNord.py", str(e))
        return "", "", "", False

    try:
        locations_file = open(filename, 'r')
        locations = locations_file.readlines()
        locations_file.close()
        id = ""
        for l in locations:
            country, id = l.split(",")
            id = id.strip(' \t\n\r')
            if location == country:
                break
        if id == "":
            errorTrace(
                "alternativeNord.py", "Couldn't retrieve location " +
                location + " for " + vpn_provider + " from " + filename)
            return "", "", "", False
    except Exception as e:
        errorTrace(
            "alternativeNord.py",
            "Couldn't read the list of countries to get ID for " +
            vpn_provider + " from " + filename)
        errorTrace("alternativeNord.py", str(e))
        return "", "", "", False

    # Generate the file name from the location
    location_filename = getNordVPNLocationName(vpn_provider, location)

    if just_name: return location, location_filename, "", False

    # Download the JSON object of servers
    response = ""
    error = True
    try:
        if "UDP" in addon.getSetting("vpn_protocol"): protocol = "udp"
        else: protocol = "tcp"
        download_url = "https://api.nordvpn.com/v1/servers/recommendations?filters[servers_technologies][identifier]=openvpn_" + protocol + "&filters[country_id]=" + id + "&filters[servers_groups][identifier]=legacy_standard"
        if ifHTTPTrace():
            infoTrace(
                "alternativeNord.py",
                "Downloading server info for " + location + " with ID " + id +
                " and protocol " + protocol + " using " + download_url)
        else:
            debugTrace("Downloading server info for " + location +
                       " with ID " + id + " and protocol " + protocol)
        token = getTokenNordVPN()
        req = urllib2.Request(download_url)
        req.add_header("Authorization", "token:" + token)
        t_before = now()
        response = urllib2.urlopen(req, timeout=10)
        server_data = json.load(response)
        t_after = now()
        response.close()
        error = False
        if ifJSONTrace():
            infoTrace(
                "alternativeNord.py",
                "JSON received is \n" + json.dumps(server_data, indent=4))
        if t_after - t_before > TIME_WARN:
            infoTrace(
                "alternativeNord.py", "Downloading server info for " +
                location + " with ID " + id + " and protocol " + protocol +
                " took " + str(t_after - t_before) + " seconds")
    except urllib2.HTTPError as e:
        errorTrace(
            "alternativeNord.py", "Couldn't retrieve the server info for " +
            vpn_provider + " location " + location + ", ID " + id)
        errorTrace("alternativeNord.py", "API call was " + download_url)
        errorTrace("alternativeNord.py",
                   "Response was " + str(e.code) + " " + e.reason)
        errorTrace("alternativeNord.py", e.read())
    except Exception as e:
        errorTrace(
            "alternativeNord.py", "Couldn't retrieve the server info for " +
            vpn_provider + " location " + location + ", ID " + id)
        errorTrace("alternativeNord.py", "API call was " + download_url)
        errorTrace("alternativeNord.py",
                   "Response was " + str(type(e)) + " " + str(e))

    if error:
        # If there's an API connectivity issue but a location file exists then use that
        # Won't have the latest best location in it though
        if xbmcvfs.exists(location_filename):
            infoTrace("alternativeNord.py",
                      "Using existing " + location + " file")
            return location, location_filename, "", False
        else:
            return "", "", "", False

    # First server is the best one, but if it didn't connect last time then skip it.  The last attempted server
    # will be cleared on a restart, or a successful connection.  If there are no more connections to try, then
    # it will try the first connection again.  However, if this is > 4th attempt to connect outside of the
    # validation then it'll always default to the best as it's likely there's a network rather than server problem
    last = getVPNRequestedServer()
    if not last == "" and server_count < 5:
        debugTrace(
            "Server " + last +
            " didn't connect last time so will be skipping to the next server."
        )
        last_found = False
    else:
        last = ""
        last_found = True
    first_server = ""
    for item in server_data:
        name = item["name"]
        server = item["hostname"]
        status = item["status"]
        load = str(item["load"])
        #debugTrace("Next is " + name + ", " + server + ", " + status + ". Load is " + load)
        if status == "online":
            if first_server == "": first_server = server
            if last_found:
                debugTrace("Using " + name + ", " + server +
                           ", online. Load is " + load)
                break
            if server == last: last_found = True
        server = ""
    if server == "": server = first_server
    setVPNRequestedServer(server)
    setVPNURL(server)

    # Fetch the ovpn file for the server
    if not server == "":
        if not getNordVPNOvpnFile(server, protocol, location_filename):
            if not xbmcvfs.exists(location_filename):
                return "", "", "", False
        return location, location_filename, "", False
    else:
        return "", "", "", False
def getShellfireLocationsCommon(vpn_provider, exclude_used, friendly, servers):
    # Return a list of all of the locations
    addon = xbmcaddon.Addon(getID())
    # Get the list of used, validated location file names
    used = []
    if exclude_used:
        # Adjust the 11 below to change conn_max
        for i in range(1, 11):
            s = addon.getSetting(str(i) + "_vpn_validated_friendly")
            if not s == "" : used.append(s)

    filename = getAddonPath(True, vpn_provider + "/" + SHELLFIRE_LOCATIONS)
    # If the list of locations doesn't exist (this can happen after a reinstall)
    # then go and do the pre-fetch first.  Otherwise this shouldn't be necessary
    try:
        if not xbmcvfs.exists(filename):
            getShellfirePreFetch(vpn_provider)
    except Exception as e:
        errorTrace("alternativeShellfire.py", "Couldn't download the list of locations for " + vpn_provider + " from " + filename)
        errorTrace("alternativeShellfire.py", str(e))
        return [] 

    try:
        service = ACCOUNT_TYPES.index(getAccountType())
    except Exception as e:
        errorTrace("alternativeShellfire.py", "Don't have an account for " + vpn_provider)
        errorTrace("alternativeShellfire.py", str(e))
        return []
        
    try:
            
        # Read the locations from the file and list by account type
        locations_file = open(filename, 'r')
        locations = locations_file.readlines()
        locations_file.close()
        return_locations = []
        
        # List the free servers
        return_locations.append(TITLE_START + "Free Locations" + TITLE_END)
        for l in locations:
            country, server, type, server_id = l.split(",")
            server_id = server_id.strip(" \n")    
            if type == ACCOUNT_TYPES[0]:
                if not exclude_used or not country in used:
                    if friendly:
                        return_locations.append(SERVER_START + country + SERVER_END)
                    elif servers:
                        return_locations.append(SERVER_START + server + SERVER_END)
                    else:
                        return_locations.append(type + getShellfireLocationName(vpn_provider, country))

        # List the paid servers
        return_locations.append(TITLE_START + "Paid Locations" + TITLE_END)
        for l in locations:
            country, server, type, server_id = l.split(",")
            server_id = server_id.strip(" \n")
            if not type == ACCOUNT_TYPES[0]:
                if ACCOUNT_TYPES.index(type) > service:
                    start = UPGRADE_START
                    end = UPGRADE_END
                else:
                    start = SERVER_START
                    end = SERVER_END
                if not exclude_used or not country in used:
                    if friendly:
                        return_locations.append(start + country + end)
                    elif servers:
                        return_locations.append(start + server + end)
                    else:
                        return_locations.append(type + getShellfireLocationName(vpn_provider, country))

        return return_locations    
    except Exception as e:
        errorTrace("alternativeShellfire.py", "Couldn't read the list of locations for " + vpn_provider + " from " + filename)
        errorTrace("alternativeShellfire.py", str(e))
        return []
        
    return []
Example #28
0
#    it under the terms of the GNU General Public License as published by
#    the Free Software Foundation, either version 3 of the License, or
#    (at your option) any later version.
#
#    This program is distributed in the hope that it will be useful,
#    but WITHOUT ANY WARRANTY; without even the implied warranty of
#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#    GNU General Public License for more details.
#
#    You should have received a copy of the GNU General Public License
#    along with this program. If not, see <http://www.gnu.org/licenses/>.
#
#    This module assists with the import of a user defined VPN provider

import xbmc
from libs.utility import debugTrace, errorTrace, infoTrace, newPrint, getID
from libs.userdefined import importWizard

debugTrace("Entered import.py")

if not getID() == "":     
    importWizard()        

    # Return to the settings screen
    command = "Addon.OpenSettings(" + getID() + ")"
    xbmc.executebuiltin(command)
else:
    errorTrace("import.py", "VPN service is not ready")

debugTrace("Exit import.py")
Example #29
0
def showLogBox(caption, text):
    path = xbmcaddon.Addon(getID()).getAddonInfo("path")
    win = LogBox("logtextbox.xml", path, caption=caption, text=text)
    win.doModal()
    del win
Example #30
0
def importWizard():    
    addon = xbmcaddon.Addon(getID())
    addon_name = getName()

    errorMessage = ""
    success = False
    cancel = False

    xbmcgui.Dialog().ok(addon_name, "The User Defined import wizard helps you set up an unsupported VPN provider.  It may not work without additional user intervention.  You should review the import log and subsequent VPN logs to debug any problems.")

    # Warn the user that files will be deleted and kittens will be harmed
    if xbmcgui.Dialog().yesno(addon_name, "Any existing User Defined settings and files will be deleted. Do you want to continue?"):
        removeGeneratedFiles()
        success = clearUserData()
        addon.setSetting("vpn_provider", "User Defined")
        if not success: errorMessage = "Could not clear the UserDefined directory. Check the log."
    else:
        success = False
        errorMessage = "Import wizard has not been run, no settings or files have been changed."

    # Get the list of files to be used
    if success:
        if xbmcgui.Dialog().yesno(addon_name, "Select ALL files needed to connect to the VPN provider, including .ovpn, .key and .crt files.  Select a directory (sub directories are ignored) or select multiple files within a directory?.", nolabel="Directory", yeslabel="Files"):
            directory_input = False
            files = xbmcgui.Dialog().browse(1, "Select all VPN provider files", "files", "", False, False, "", True)
        else:
            directory_input = True
            dname = xbmcgui.Dialog().browse(0, "Select a directory containing VPN provider files", "files", "", False, False, "", False)
            debugTrace("Import from directory " + dname)
            dirs, files = xbmcvfs.listdir(dname)
            
        # Separate the selected files into ovpn files and other files
        ovpn_files = []
        other_files = []
        for name in files:
            if directory_input:
                name = dname + name
            debugTrace("Found file " + name)
            if name.endswith(".ovpn"):
                ovpn_files.append(name)
            else:
                other_files.append(name)
        if len(ovpn_files) == 0:
            success = False
            errorMessage = "No .ovpn files found.  You must provide at least one .ovpn file."
            
    # Copy and modify the ovpn files
    if success:
        
        # Create some logs to write out later
        summary = []
        detail = []
       
        summary.append("Importing selected files to User Defined directory, " + getUserDataPath("UserDefined/") + "\n")
        summary.append("at " + time.strftime('%Y-%m-%d %H:%M:%S') + "\n")
        detail.append("\n=== Import details ===\n\n")
        
        update = False
        rename = False
        if not xbmcgui.Dialog().yesno(addon_name, "Update the .ovpn files to best guess values and determine the best User Defined provider settings [I](recommended)[/I]?", nolabel="Yes", yeslabel="No"):
            update = True
            detail.append("Updating the .ovpn files to best guess settings\n")
            if not xbmcgui.Dialog().yesno(addon_name, "Rename the .ovpn files to indicate either a UDP or TCP connection type to allow filtering of connections [I](recommended)[/I]?", nolabel="Yes", yeslabel="No"):
                rename = True
                detail.append("Files will be renamed to indicate UDP or TCP\n")        
            
        # Display dialog to show progress of copying files
        dialog_step = 100/(len(ovpn_files) + len(other_files))
        progress = xbmcgui.DialogProgress()
        progress_title = "Copying User Defined files."
        progress.create(addon_name,progress_title) 
        prog_step = 0
        xbmc.sleep(500)
        try:
            dest_path = getUserDataPath("UserDefined/")
            debugTrace("Checking directory path exists before copying " + dest_path)
            if not os.path.exists(dest_path):
                infoTrace("userdefined.py", "Creating " + dest_path)
                os.makedirs(os.path.dirname(dest_path))
                xbmc.sleep(500)
                # Loop around waiting for the directory to be created.  After 10 seconds we'll carry 
                # on and let he open file calls fail and throw an exception
                t = 0
                while not os.path.exists(os.path.dirname(dest_path)):
                    if t == 9:
                        errorTrace("userdefined.py", "Waited 10 seconds to create directory but it never appeared")
                        break
                    xbmc.sleep(1000)
                    t += 1
            other_files_count = []
            for fname in other_files:
                path, dest_name = os.path.split(fname)
                dest_name = getUserDataPath("UserDefined/" + dest_name)
                # Report file being copied, then do it
                progress_message = "Copying " + fname
                progress.update(prog_step, progress_title, progress_message)
                xbmc.sleep(100)
                prog_step += dialog_step
                infoTrace("userdefined.py", "Copying " + fname + " to " + dest_name)
                detail.append("Copying " + fname + " to " + dest_name + "\n")
                xbmcvfs.copy(fname, dest_name)
                if not xbmcvfs.exists(dest_name): raise IOError('Failed to copy user def file ' + fname + " to " + dest_name)
                other_files_count.append(0)
                if progress.iscanceled():
                    cancel = True
                    break
            auth_count = 0
            auth_found = 0
            cert_count = 0
            cert_found = 0
            multiple_certs = False
            last_cert_found = ""
            ecert_count = 0
            key_count = 0
            key_found = 0
            key_pass_found = 0
            key_pass_count = 0
            multiple_keys = False
            last_key_found = ""
            ekey_count = 0
            if not cancel:
                metadata = getGitMetaData("UserDefined")
                mods = []
                if not metadata == None:
                    for line in metadata:
                        line = line.strip(' \t\n\r')
                        mods.append(line)
                for oname in ovpn_files:
                    path, dest_name = os.path.split(oname)
                    dest_name = getUserDataPath("UserDefined/" + dest_name)

                    # Update dialog to saywhat's happening
                    if update:
                        progress_message = "Copying and updating " + oname
                    else:
                        progress_message = "Copying " + oname
                    progress.update(prog_step, progress_title, progress_message)
                    xbmc.sleep(100)
                    prog_step += dialog_step

                    # Copy the ovpn file
                    infoTrace("userdefined.py", "Copying " + oname + " to " + dest_name)
                    detail.append("Copying " + oname + " to " + dest_name + "\n")
                    xbmcvfs.copy(oname, dest_name)
                    if not xbmcvfs.exists(dest_name): raise IOError('Failed to copy user def ovpn ' + oname + " to " + dest_name)
                    
                    if update:
                        # Read the copied file in and then overwrite it with any updates needed
                        # Was doing a read from source and write here but this failed on Linux over an smb mount (file not found)
                        auth = False
                        keypass = False
                        infoTrace("userdefined.py", "Updating " + dest_name)
                        detail.append("Updating " + dest_name + "\n")
                        source_file = open(dest_name, 'r')
                        source = source_file.readlines()
                        source_file.close()
                        dest_file = open(dest_name, 'w')
                        proto = "UDP"
                        flags = [False, False, False, False, False]
                        for line in source:
                            line = line.strip(' \t\n\r')
                            old_line = line
                            i = 0
                            # Look for each non ovpn file uploaded and update it to make sure the path is good
                            for fname in other_files:
                                path, name = os.path.split(fname)
                                if not line.startswith("#"):
                                    params = line.split()
                                    if len(params) > 2:
                                        # Remove the separator in order to get any fully qualified filename as space delimited
                                        params[1].replace(getSeparator(), " ")
                                        # Add in a leading space for unqualified filenames
                                        params[1] = " " + params[1]
                                        if params[1].endswith(" " + name):
                                            old_line = line
                                            line = params[0] + " " + "#PATH" + getSeparatorOutput() + name
                                            # Add any trailing parameters back in
                                            if len(params) > 2:
                                                for i in range(2, len(params)):
                                                    line = line + " " + params[i]
                                            detail.append("  Found " + name + ", old line was : " + old_line + "\n")
                                            detail.append("  New line is " + line + "\n")
                                            other_files_count[i] += 1
                                            if line.startswith("auth-user-pass"):
                                                auth_found += 1
                                                auth = True
                                            if line.startswith("cert "):
                                                cert_found += 1
                                            if line.startswith("key "):
                                                key_found += 1
                                            if line.startswith("askpass "):
                                                key_pass_found += 1
                                                keypass = True
                                i += 1
                            # Do some tag counting to determine authentication methods to use
                            if not line.startswith("#"):
                                for mod in mods:
                                    flag, verb, parms = mod.split(",")
                                    if flag == "1" and line.startswith(verb) and parms in line: flags[0] = True
                                    if flag == "3" and line.startswith(verb): flags[2] = True
                                    if flag == "4" and line.startswith(verb): line = verb + " " + parms
                                    if flag == "5" and not flags[4] and verb in line: 
                                        detail.append("  WARNING, " + parms + "\n")
                                        flags[4] = True
                                if line.startswith("auth-user-pass"):
                                    auth_count += 1
                                    if not auth: line = "auth-user-pass #PATH" + getSeparatorOutput() + "pass.txt"
                                if line.startswith("cert "):
                                    cert_count += 1
                                    if not last_cert_found == old_line:
                                        if not last_cert_found == "":
                                            multiple_certs = True
                                        last_cert_found = old_line
                                if line.startswith("key "):
                                    key_count += 1
                                    if not last_key_found == old_line:
                                        if not last_key_found == "":
                                            multiple_keys = True
                                        last_key_found = old_line
                                if line.startswith("askpass"):
                                    key_pass_count += 1
                                    if not keypass: line = "askpass #PATH" + getSeparatorOutput() + "key.txt"
                                if line.startswith("proto "):
                                    if "tcp" in (line.lower()): proto = "TCP"
                                if line.startswith("<cert>"):
                                    ecert_count += 1
                                if line.startswith("<key>"):
                                    ekey_count += 1
                            if not flags[2]: dest_file.write(line+"\n")
                            flags[2] = False
                        for mod in mods:
                            flag, verb, parms = mod.split(",")
                            if flag == "2":
                                dest_file.write(verb+"\n")
                        dest_file.close()
                        flags[4] = False
                        if flags[0]:
                            if xbmcvfs.exists(dest_name):
                                xbmcvfs.delete(dest_name)
                            detail.append("  wARNING, couldn't import file as it contains errors or is unsupported\n")
                        elif rename:
                            proto = " (" + proto + ").ovpn"
                            new_name = dest_name.replace(".ovpn", proto)   
                            if not xbmcvfs.exists(new_name):
                                xbmcvfs.rename(dest_name, new_name)
                                detail.append("  Renamed to " + new_name + "\n")
                            else:
                                detail.append("  WARNING, couldn't rename file to " + new_name + " as a file with that name already exists\n")

                    if progress.iscanceled():
                        cancel = True
                        break
                        
        except Exception as e:
            errorTrace("userdefined.py", "Failed to copy (or update) file")
            errorTrace("userdefined.py", str(e))
            success = False
            errorMessage = "Failed to copy (or update) selected files.  Check the log."
            
        progress_message = "Outputting results of import wizard"
        progress.update(100, progress_title, progress_message)
        xbmc.sleep(500)   
        
        # General import results
        summary.append("\n=== Summary of import ===\n\n")
        if cancel:
            summary.append("Import was cancelled\n")
        else:
            summary.append("Imported " + str(len(ovpn_files)) + " .ovpn files and " + str(len(other_files)) + " other files.\n")
            summary.append("\nYou should understand any WARNINGs below, and validate that the .ovpn files imported have been updated correctly.\n\n")
            summary.append("If the VPN connection fails view the VPN log to determine why, using Google to understand the errors if necessary.\n")
            summary.append("You can fix problems either by editing your local files and re-importing, or by editing the contents of the User Defined directory.\n\n")
            
            if update:
                # Report on how user names and passwords will be handled
                if auth_count > 0:
                    if auth_found > 0:
                        # Not using a password as resolved by file
                        addon.setSetting("user_def_credentials", "false")
                        summary.append("The auth-user-pass tag was found " + str(auth_count) + " times, but was resolved using a supplied file so user name and password don't need to be entered.\n")
                        if not auth_found == auth_count:
                            summary.append("  WARNING : The auth-user-pass tag was found " + str(auth_count) + " times, but only resolved using a supplied file " + str(auth_found) + " times. Some connections may not work.\n")
                    else:
                        # Using a password as auth-user-pass tag was found
                        addon.setSetting("user_def_credentials", "true")
                        summary.append("The auth-user-pass tag was found " + str(auth_count) + " times so assuming user name and password authentication is used.\n")
                    if auth_count < len(ovpn_files):
                        summary.append("  WARNING : The auth-user-pass tag was only found in " + str(auth_count) + " .ovpn files, out of " + str(len(ovpn_files)) + ". Some connections may not work.\n")
                else:
                    # Not using a password as no auth-user-pass tag was found
                    addon.setSetting("user_def_credentials", "false")
                    summary.append("No auth-user-pass tag was found, so assuming user name and password is not needed.\n")
                
                # Report on how keys and certs will be handled
                if (cert_count > 0 or key_count > 0):
                    summary.append("The key tag was found " + str(key_count) + " times, and the cert tag was found " + str(cert_count) + " times.\n")
                    if cert_found > 0 or key_found > 0:
                        # Key and cert resolved by file so not asking user for them
                        addon.setSetting("user_def_keys", "None")
                        summary.append("The key and certificate don't need to be requested as the key tags were resolved using a supplied file " + str(key_found) + " times, and the cert tags were resolved using a supplied file " + str(cert_found) + " times.\n")
                        if (not cert_found == cert_count) or (not key_found == key_count):
                            summary.append("  WARNING : The key or cert tags were not resolved by a supplied file for all occurrences. Some connections may not work.\n")
                    else:
                        if multiple_certs or multiple_keys:
                            # Key and cert tags found with different file names, but no files supplied.  Assume multiple files, user supplied
                            addon.setSetting("user_def_keys", "Multiple")
                            summary.append("Found key and cert tags with multiple filenames, but no key or certificate files were supplied. These will be requested during connection.\n")
                        else:
                            # Key and cert tags found with same file names, but no files supplied.  Assume single file, user supplied
                            addon.setSetting("user_def_keys", "Single")
                            summary.append("Found key and cert tags all with the same filename, but no key or certificate files were supplied. These will be requested during connection.\n")
                    if cert_count < len(ovpn_files) or key_count < len(ovpn_files):
                        summary.append("  WARNING : The key tag was found " + str(key_count) + " times, and the cert tag was found " + str(cert_count) + " times. Expected to find one of each in all " + str(len(ovpn_files)) + " .ovpn files. Some connections may not work.\n") 
                else:
                    # Embedded key and certs found, so not asking user for them
                    addon.setSetting("user_def_keys", "None")
                    if (ekey_count > 0 or ecert_count > 0):
                        if ekey_count == ecert_count and key_count == len(ovpn_files):
                            summary.append("Using embedded user keys and certificates so keys and certs don't need to be entered.\n")
                        else:
                            summary.append("  WARNING : Using embedded user keys and certificates, but found " + str(ekey_count) + " keys and " + str(ecert_count) + " certificates in " + str(len(ovpn_files)) + " .ovpn files. There should be one of each in all .ovpn files otherwise some connections may not work.\n")
                    else:
                        summary.append("No user key or cert tags were found so assuming this type of authentication is not used.\n")
                
                # Report on how key passwords will be handled
                if key_pass_count > 0:
                    if key_pass_found > 0:
                        # Not using a password as resolved by file
                        addon.setSetting("user_def_key_password", "false")
                        summary.append("The askpass tag was found " + str(auth_count) + " times, but was resolved using a supplied file so the key password doesn't need to be entered.\n")
                        if not key_pass_found == key_pass_count:
                            summary.append("  WARNING : The askpass tag was found " + str(key_pass_count) + " times, but only resolved using a supplied file " + str(key_pass_found) + " times. Some connections may not work.\n")
                    else:
                        # Using a password as auth-user-pass tag was found
                        addon.setSetting("user_def_key_password", "true")
                        summary.append("The askpass tag was found " + str(key_pass_count) + " times so assuming key password authentication is used.\n")
                    if key_pass_count < len(ovpn_files):
                        summary.append("  WARNING : The askpass tag was only found in " + str(key_pass_count) + " .ovpn files, out of " + str(len(ovpn_files)) + ". Some connections may not work, or you may be asked to enter a password when it's not necessary.\n")
                else:
                    # Not using a password as no askpass tag was found
                    addon.setSetting("user_def_key_password", "false")
                    summary.append("No askpass tag was found, so assuming key password is not needed.\n")

                
                # Report how many times each of the non .ovpn files were used
                i = 0
                for oname in other_files:
                    summary.append("File " + oname + " was found and used in .ovpn files " + str(other_files_count[i]) + " times.\n")
                    if not other_files_count[i] == len(ovpn_files):
                        if other_files_count[i] == 0:
                            summary.append("  WARNING : " + oname + " was not used to update any .ovpn files and could be unused.\n")
                        else:
                            summary.append("  WARNING : The number of updates for " + oname + " was different to the number of .ovpn files, " + str(len(ovpn_files)) + ", which could be a problem.\n")
                    i += 1
            else:
                summary.append("None of the files were updated during import.\n")
        
        # Open a log file so all changes can be recorded without fouling up the kodi log       
        log_name = getImportLogPath()
        if xbmcvfs.exists(log_name): xbmcvfs.delete(log_name) 
        log_file = open(log_name, 'w') 
        for line in summary:
            log_file.write(line)
        for line in detail:
            log_file.write(line)
        log_file.close()
        
        progress.close()
        xbmc.sleep(100)
        
    if success:
        if xbmcgui.Dialog().yesno(addon_name, "Import wizard finished.  You should view the import log to review any issues, enter your user ID and password (if necessary) and then try and validate a VPN connection.", nolabel="OK", yeslabel="Import Log"):
            popupImportLog()
    else:
        xbmcgui.Dialog().ok(addon_name, errorMessage)
        
    return success
def sendAPI(command, command_text, api_data, check_response):
    # Common routine to send an API command
    try:
        response = ""
        rc = True
        rest_url = REQUEST_URL + command

        auth_token, _, _, _ = getTokens()
        # Login again if the token is blank and the command is not login anyway
        if auth_token == "" and not "=login" in command:
            debugTrace("Logging in again because auth token not valid")
            addon = xbmcaddon.Addon(getID())
            rc = authenticateShellfire(addon.getSetting("vpn_provider"),
                                       addon.getSetting("vpn_username"),
                                       addon.getSetting("vpn_password"))
            auth_token, _, _, _ = getTokens()
            if auth_token == "" or not rc:
                raise Exception(command_text + " was not authorized")

        if ifHTTPTrace():
            infoTrace("alternativeShellfire.py", command_text + " " + rest_url)
        else:
            debugTrace(command_text)

        req = urllib2.Request(rest_url, api_data, REQUEST_HEADERS)
        if not auth_token == "":
            req.add_header("x-authorization-token", auth_token)
        t_before = now()
        response = urllib2.urlopen(req)
        api_data = json.load(response)
        t_after = now()
        response.close()

        # Trace if the command took a long time
        if ifJSONTrace():
            infoTrace("alternativeShellfire.py",
                      "JSON received is \n" + json.dumps(api_data, indent=4))
        if t_after - t_before > TIME_WARN:
            infoTrace(
                "alternativeShellfire.py",
                command_text + " took " + str(t_after - t_before) + " seconds")

        # Check the response and fail if it's bad
        if check_response:
            if not api_data["status"] == "success":
                raise Exception(command_text + " returned bad response, " +
                                api_data["status"])

    except urllib2.HTTPError as e:
        errorTrace("alternativeShellfire.py", command_text + " failed")
        errorTrace("alternativeShellfire.py", "API call was " + rest_url)
        if not api_data == "":
            errorTrace("alternativeShellfire.py",
                       "Data returned was \n" + json.dumps(api_data, indent=4))
        errorTrace("alternativeShellfire.py",
                   "Response was " + str(e.code) + " " + e.reason)
        errorTrace("alternativeShellfire.py", e.read())
        rc = False
    except Exception as e:
        errorTrace("alternativeShellfire.py", command_text + " failed")
        errorTrace("alternativeShellfire.py", "API call was " + rest_url)
        if not api_data == "":
            errorTrace("alternativeShellfire.py",
                       "Data returned was \n" + json.dumps(api_data, indent=4))
        errorTrace("alternativeShellfire.py",
                   "Response was " + str(type(e)) + " " + str(e))
        rc = False

    return rc, api_data
def getAccountID():
    # This returns the ID of the account that was selected
    addon = xbmcaddon.Addon(getID())
    service = addon.getSetting("vpn_locations_list")
    type, id = service.split(";")
    return id
def getShellfireUserPass(vpn_provider):
    # Use the user ID and password entered into the GUI
    addon = xbmcaddon.Addon(getID())
    return addon.getSetting("vpn_username"), addon.getSetting("vpn_password")
def getShellfireLocation(vpn_provider, location, server_count, just_name):
    # Return the friendly and .ovpn name
    addon = xbmcaddon.Addon(getID())
    # Just return if this is a title that's been passed in
    if location.startswith(TITLE_START): return "", "", "Select a location or server", True
    # Remove all of the tagging
    # There's some escaping of the UPGRADE_END characters when passed in via the add-on menu
    # This is why the command below searches for the end of the upgrade and strips it
    location = location.replace(UPGRADE_START, "")
    if "I]" in location: location = location[:(location.index("I]")-2)]
    location = location.strip(" ")
    
    filename = getAddonPath(True, vpn_provider + "/" + SHELLFIRE_LOCATIONS)
    try:
        if not xbmcvfs.exists(filename):
            getShellfirePreFetch(vpn_provider)
    except Exception as e:
        errorTrace("alternativeShellfire.py", "Couldn't download the list of locations for " + vpn_provider + " from " + filename)
        errorTrace("alternativeShellfire.py", str(e))
        return "", "", "", False
           
    try:
        # Read the locations from the file and list by account type
        locations_file = open(filename, 'r')
        locations = locations_file.readlines()
        locations_file.close()
        for l in locations:
            if location in l:
                country, server, type, server_id = l.split(",")
                server_id = server_id.strip(" \n")
                break
        # Return an upgrade message if this server is not available to the user
        if ACCOUNT_TYPES.index(type) > ACCOUNT_TYPES.index(getAccountType()):
            _, message = getShellfireMessages(vpn_provider, 0, "")
            if message == "": message = "Get access to servers in over 30 countries with unlimited speed at shellfire.net/kodi"
            return "", "", "Upgrade to use this [B]" + type + "[/B] location.\n" + message, False
        
        # Generate the file name from the location
        location_filename = getShellfireLocationName(vpn_provider, country)
        
        if just_name: return location, location_filename, "", False
        
    except Exception as e:
        errorTrace("alternativeShellfire.py", "Couldn't read the list of locations for " + vpn_provider + " from " + filename)
        errorTrace("alternativeShellfire.py", str(e))
        return "", "", "", False
        
    # Set the selected server for the VPN being used
    try:
        setShellfireServer(getAccountID(), server_id)
        
        # Set the protocol.  If it's "UDP and TCP", choose UDP
        proto = addon.getSetting("vpn_protocol")
        if "UDP" in proto: proto = "UDP"
        if not setShellfireProtocol(getAccountID(), proto):
           raise Exception("Couldn't set the protocol") 
        
        # Get the parameters associated with this server and put them in a file
        if not getShellfireOvpn(getAccountID(), vpn_provider, country):
            raise Exception("Couldn't create an OVPN file") 
        
        # Get the certs associated with this server and put them in a file
        if not getShellfireCerts(getAccountID(), vpn_provider, country):
            raise Exception("Couldn't create the certificates") 

        return country, location_filename, "", False
    except Exception as e:
        errorTrace("alternativeShellfire.py", "Couldn't read the list of locations for " + vpn_provider + " from " + filename)
        errorTrace("alternativeShellfire.py", str(e))
        return "", "", "", False
Example #35
0
def resetIPServices():
    addon = xbmcaddon.Addon(getID())
    addon.setSetting("ip_service_errors", LIST_DEFAULT)
    addon.setSetting("ip_service_values", LIST_DEFAULT)
    xbmcgui.Window(10000).setProperty("VPN_Manager_Last_IP_Service", ip_sources[1])
Example #36
0
# -*- coding: utf-8 -*-
#
#    Copyright (C) 2016 Zomboided
#
#    This program is free software: you can redistribute it and/or modify
#    it under the terms of the GNU General Public License as published by
#    the Free Software Foundation, either version 3 of the License, or
#    (at your option) any later version.
#
#    This program is distributed in the hope that it will be useful,
#    but WITHOUT ANY WARRANTY; without even the implied warranty of
#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#    GNU General Public License for more details.
#
#    You should have received a copy of the GNU General Public License
#    along with this program. If not, see <http://www.gnu.org/licenses/>.
#
#    This module does the same as calling the cycle function from the add-on
#    menu screen but allows a user to configure it to a button on a remote, etc

from libs.common import requestVPNCycle
from libs.utility import debugTrace, errorTrace, infoTrace, newPrint, getID

# Call the common cycle routine
debugTrace("-- Entered cycle.py --")
if not getID() == "":
    requestVPNCycle(False)
else:
    errorTrace("cycle.py", "VPN service is not ready")
debugTrace("-- Exit cycle.py --")
Example #37
0
 def onInit(self):
     self.getControl(400).setImage(getAddonPath(True, "/resources/map.png"))
     self.getControl(401).addLabel(
         xbmcaddon.Addon(getID()).getAddonInfo("name"))
     self.getControl(402).addLabel("Press a key to map or wait to clear.")
from libs.vpnproviders import removeGeneratedFiles, cleanPassFiles, providers, usesUserKeys, usesMultipleKeys, getUserKeys
from libs.vpnproviders import getUserCerts, getVPNDisplay, getVPNLocation, refreshFromGit, removeDownloadedFiles, isAlternative, resetAlternative
from libs.utility import debugTrace, errorTrace, infoTrace, newPrint, getID, getName
from libs.platform import getLogPath, getUserDataPath, writeVPNLog, copySystemdFiles, addSystemd, removeSystemd, generateVPNs
from libs.common import resetVPNConnections, isVPNConnected, disconnectVPN, suspendConfigUpdate, resumeConfigUpdate, dnsFix
from libs.ipinfo import resetIPServices
try:
    from libs.generation import generateAll
except:
    pass

action = sys.argv[1]

debugTrace("-- Entered managefiles.py with parameter " + action + " --")

if not getID() == "":
    addon = xbmcaddon.Addon(getID())
    addon_name = getName()

    # Reset the ovpn files
    if action == "ovpn":
        if addon.getSetting("1_vpn_validated") == "" or xbmcgui.Dialog().yesno(
                addon_name,
                "Resetting the VPN provider will disconnect and reset all VPN connections, and then remove any files that have been created. Continue?"
        ):
            suspendConfigUpdate()
            # Disconnect so that live files are not being modified
            if isVPNConnected(): resetVPNConnections(addon)
            debugTrace("Deleting all generated files")
            # Delete the generated files, and reset the locations so it can be selected again
            removeGeneratedFiles()
Example #39
0
#    along with this program. If not, see <http://www.gnu.org/licenses/>.
#
#    This module displays a list of connections on the screen and allows a
#    user to select one to connect to.  It can be called from a remote button.

import xbmcgui
import xbmcaddon
from libs.vpnproviders import getAddonList, isAlternative, getAlternativeLocations, getAlternativeFriendlyLocations
from libs.vpnproviders import getAlternativeLocationName, allowReconnection, getAlternativeLocation
from libs.common import requestVPNCycle, getFilteredProfileList, getFriendlyProfileList, setAPICommand, connectionValidated, getValidatedList
from libs.common import getVPNProfile, getVPNProfileFriendly, getVPNState, clearVPNCycle, getCycleLock, freeCycleLock, getAlternativeFriendlyProfileList
from libs.utility import debugTrace, errorTrace, infoTrace, newPrint, getID, getName

debugTrace("-- Entered table.py --")

if not getID() == "":
    # Get info about the addon that this script is pretending to be attached to
    addon = xbmcaddon.Addon(getID())
    addon_name = getName()

    cancel_text = "[I][COLOR grey]Cancel[/COLOR][/I]"
    disconnect_text = "[COLOR ffff0000]Disconnect[/COLOR]"
    disconnected_text = "[COLOR ffff0000](Disconnected)[/COLOR]"

    # Don't display the table if there's nothing been set up
    if connectionValidated(addon):
        if getCycleLock():
        
            vpn_provider = addon.getSetting("vpn_provider_validated")
        
            # Want to stop cycling whilst this menu is displayed, and clear any active cycle