def getUserDataPathWrapper(name):
    # Return the fully qualified user path and file name
    if generateVPNs():
        return "/storage/.kodi/userdata/addon_data/service.vpn.manager/" + name
    else:
        if getPlatform() == platforms.WINDOWS:
            return getUserDataPath(name).replace("\\", "\\\\")
        else:
            return getUserDataPath(name)
def getUserDataPathWrapper(path):
    # This function resets the VPN profiles to the standard VPN Manager install
    # location as per OpenELEC, or to the platform install location
    force_default_install = fakeConnection()
    if force_default_install:
        return "/storage/.kodi/userdata/addon_data/service.vpn.manager/" + path        
    else:
        if getPlatform() == platforms.WINDOWS:
            return getUserDataPath(path).replace("\\", "\\\\")
        else:
            return getUserDataPath(path)
def getUserDataPathWrapper(path):
    # This function resets the VPN profiles to the standard VPN Manager install
    # location as per OpenELEC, or to the platform install location
    force_default_install = fakeConnection()
    if force_default_install:
        return "/storage/.kodi/userdata/addon_data/service.vpn.manager/" + path
    else:
        if getPlatform() == platforms.WINDOWS:
            return getUserDataPath(path).replace("\\", "\\\\")
        else:
            return getUserDataPath(path)
Beispiel #4
0
def gotKeys(vpn_provider, ovpn_name):
    # Check to see if we have the key for this connection.  If this provider just uses
    # a single key then the getKey/CertName piece will work this out.  If no key is passed
    # in then we'll just report whether or not any keys exist for this provider
    if not ovpn_name == "":
        key_name = getUserDataPath(vpn_provider + "/" + getKeyName(vpn_provider, ovpn_name))
        cert_name = getUserDataPath(vpn_provider + "/" + getCertName(vpn_provider, ovpn_name))
        debugTrace("Checking for user key " + key_name)
        debugTrace("Checking for user cert " + cert_name)
        if xbmcvfs.exists(key_name) and xbmcvfs.exists(cert_name): return True
        debugTrace("One of the user key and cert files did not exist")
        return False
    else:
        return False
def gotKeys(vpn_provider, ovpn_name):
    # Check to see if we have the key for this connection.  If this provider just uses
    # a single key then the getKey/CertName piece will work this out.  If no key is passed
    # in then we'll just report whether or not any keys exist for this provider
    if not ovpn_name == "":
        key_name = getUserDataPath(vpn_provider + "/" + getKeyName(vpn_provider, ovpn_name))
        cert_name = getUserDataPath(vpn_provider + "/" + getCertName(vpn_provider, ovpn_name))
        debugTrace("Checking for user key " + key_name)
        debugTrace("Checking for user cert " + cert_name)
        if xbmcvfs.exists(key_name) and xbmcvfs.exists(cert_name): return True
        debugTrace("One of the user key and cert files did not exist")
        return False
    else:
        return False
Beispiel #6
0
def generateVyprVPN():
    # Data is stored in a flat text file
    # There appear to be a regular set of servers, which are either goldenfrog or vyprvpn
    # And an alternative set of servers that are available via some giganews hook up.
    # Both use the same certificate.
    location_file_vypr = getLocations("VyprVPN", "VyprVPN Account")
    location_file_giga = getLocations("VyprVPN", "Giganews Account")
    source_file = open(getUserDataPath("providers/VyprVPN/Servers.txt"), 'r')
    source = source_file.readlines()
    source_file.close()
    for line in source:
        tokens = line.split()
        for t in tokens:
            if ".goldenfrog.com" in t:
                server = t.strip(' \t\n\r')
                geo = line.replace(server, "")
                geo = geo.strip(' \t\n\r')
                server = server.replace("vpn.goldenfrog.com", "vyprvpn.com")
                if "," in geo: geo = "USA - " + geo[:geo.index(",")]
                output_line_vypr = geo + " (UDP)," + server + "," + "udp,1194" + "\n"
                server = server.replace("vyprvpn.com", "vpn.giganews.com")
                output_line_giga = geo + " (UDP)," + server + "," + "udp,1194" + "\n"
                location_file_vypr.write(output_line_vypr)
                location_file_giga.write(output_line_giga)
    location_file_vypr.close()
    location_file_giga.close()
Beispiel #7
0
def generateVPNht():
    # Data is stored in a flat text file
    # Location on one line, then server on the next
    location_file_smartdns = getLocations("VPN.ht", "With SmartDNS")
    location_file_without = getLocations("VPN.ht", "Without SmartDNS")
    location_file_all = getLocations("VPN.ht", "All Connections")
    source_file = open(getUserDataPath("providers/VPN.ht/Servers.txt"), 'r')
    source = source_file.readlines()
    source_file.close()
    i = 0
    for line in source:
        if i == 0:
            i = 1
            geo = line.strip(' \t\n\r')
        else:
            i = 0
            server = line.strip(' \t\n\r')
            serverudp = server
            for j in range(1, 7):
                serverudp = serverudp + " " + server
            output_line_udp = geo + " (UDP)," + serverudp + "," + "udp,1194 1195 1196 1197 1198 1199 1200" + "\n"
            output_line_udp_no = geo + " (UDP SmartDNS)," + serverudp + "," + "udp,1194 1195 1196 1197 1198 1199 1200" + ",#REMOVE=1\n"
            output_line_tcp_no = geo + " (TCP)," + server + "," + "tcp,443" + ",#REMOVE=1\n"
            output_line_tcp = geo + " (TCP SmartDNS)," + server + "," + "tcp,443" + "\n"
            location_file_smartdns.write(output_line_udp)
            location_file_smartdns.write(output_line_tcp)
            location_file_without.write(output_line_udp_no)
            location_file_without.write(output_line_tcp_no)
            location_file_all.write(output_line_udp)
            location_file_all.write(output_line_tcp)
            location_file_all.write(output_line_udp_no)
            location_file_all.write(output_line_tcp_no)
    location_file_smartdns.close()
    location_file_without.close()
    location_file_all.close()
Beispiel #8
0
def generateSecureVPN():
    # Can't use a template as SecureVPN use multiple everything.
    # Copy the file to the target directory and strip it of user keys
    existing_profiles = glob.glob(
        getUserDataPath("providers/SecureVPN" + "/*.ovpn"))
    for connection in existing_profiles:
        xbmcvfs.delete(connection)
    # Get the list from the provider data directory
    profiles = getProfileList("SecureVPN")
    destination_path = getAddonPath(True, "SecureVPN" + "/")
    for profile in profiles:
        shortname = profile[profile.index("SecureVPN") + 10:]
        shortname = shortname[:shortname.index(".")]
        proto = "(UDP)"
        filename = shortname + " " + proto + ".ovpn"
        profile_file = open(profile, 'r')
        output_file = open(destination_path + filename, 'w')
        profile_contents = profile_file.readlines()
        profile_file.close()
        output = ""
        i = 0
        write = True
        for line in profile_contents:
            line = line.strip(' \t\n\r')
            if not (line == "" or line.startswith("#")):
                if "<key>" in line or "<cert>" in line: write = False
                if "</key>" in line:
                    write = True
                    line = "key #USERKEY"
                if "</cert>" in line:
                    write = True
                    line = "cert #USERCERT"
                if write: output_file.write(line + "\n")
            i = i + 1
        output_file.close()
Beispiel #9
0
def generateWiTopia():
    # Data is stored in a flat text file
    # City name followed by server name, or just server name (starts with vpn.)
    location_file = getLocations("WiTopia", "")
    source_file = open(getUserDataPath("providers/WiTopia/Servers.txt"), 'r')
    source = source_file.readlines()
    source_file.close()
    city = ""
    cont = ""
    for line in source:
        line = line.strip(" \t\n\r")
        if not line.startswith("vpn."):
            if line.startswith("-"):
                cont = line.replace("-", "")
                if not cont == "": cont = cont + " - "
            else:
                city = line
        else:
            if city == "":
                city = line.replace("vpn.", "").replace(".witopia.net", "")
                city = string.capwords(city)
            geo = cont + city
            server = line
            output_line_udp = geo + " (UDP)," + server + "," + "udp,1194" + "\n"
            city = ""
            location_file.write(output_line_udp)
    location_file.close()
Beispiel #10
0
def generateproXPN():
    # Data is stored in a flat text file
    # Location, tab, server - free locations are marked with a leading *
    location_file_full = getLocations("proXPN", "Full Account")
    location_file_free = getLocations("proXPN", "Free Account")
    source_file = open(getUserDataPath("providers/proXPN/Servers.txt"), 'r')
    source = source_file.readlines()
    source_file.close()
    for line in source:
        line = line.strip(" \t\n\r")
        if not ("UDP" in line or "TCP" in line):
            geo = line.strip(" \t\n\r")
            geo = geo.replace(",", " -")
        else:
            if "Free" in geo:
                server = line[line.index("IP:") + 3:]
            else:
                server = line[line.index("  "):line.index(".com") + 4]
            server = server.strip(" \t\n\r")
            if "UDP" in line:
                output_line = geo + " (UDP)," + server + "," + "udp,443" + "\n"
            if "TCP" in line:
                output_line = geo + " (TCP)," + server + "," + "tcp,443" + "\n"
            if "Free" in geo:
                location_file_free.write(output_line)
            else:
                location_file_full.write(output_line)
    location_file_full.close()
    location_file_free.close()
def getLocationFiles(vpn_provider):
    # Return the locations files, add any user version to the end of the list
    locations = glob.glob(getAddonPath(True, vpn_provider + "/LOCATIONS*.txt"))
    user_locations = getUserDataPath(vpn_provider + "/LOCATIONS.txt")
    if xbmcvfs.exists(user_locations):
        locations.append(user_locations.replace(".txt", " User.txt"))
    return locations
def copyUserDefinedFiles():
    # Copy everything in the user directory to the addon directory
    infoTrace("vpnproviders.py",
              "Copying user defined files from userdata directory")
    source_path = getUserDataPath((user_def_str) + "/")
    dest_path = getAddonPath(True, user_def_str + "/")
    # Get the list of connection profiles and another list of strings to abuse for the selection screen
    try:
        files = getUserDataList(user_def_str, "*")
        if len(files) == 0:
            errorTrace(
                "vpnproviders.py",
                "No User Defined files available to copy from " + source_path)
            return False
        for file in files:
            name = file[file.rfind(getSeparator()) + 1:]
            dest_file = dest_path + getSeparator() + name
            xbmcvfs.copy(file, dest_file)
        return True
    except Exception as e:
        errorTrace(
            "vpnproviders.py",
            "Error copying files from " + source_path + " to " + dest_path)
        errorTrace("vpnproviders.py", str(e))
        return False
def getTemplateFile(vpn_provider):
    def_temp = getAddonPath(True, vpn_provider + "/TEMPLATE.txt")
    user_temp = getUserDataPath(vpn_provider + "/TEMPLATE.txt")
    if xbmcvfs.exists(user_temp):
        return user_temp
    else:
        return def_temp
Beispiel #14
0
def getUserDataPathWrapper(path):
    # This function resets the VPN profiles to the standard VPN Manager install
    # location as per OpenELEC, or to the platform install location
    force_default_install = fakeConnection()    
    if force_default_install:
        return "/storage/.kodi/userdata/addon_data/service.purevpn.monitor/" + path        
    else:
        return getUserDataPath(path)        
def copyKeyAndCert(vpn_provider, ovpn_name, user_key, user_cert):
    # Copy the user key and cert to the userdata directory
    key_dest = getUserDataPath(vpn_provider + "/" + getKeyName(vpn_provider, ovpn_name))
    key_source = user_key
    cert_dest = getUserDataPath(vpn_provider + "/" + getCertName(vpn_provider, ovpn_name))
    cert_source = user_cert
    try:
        debugTrace("Copying key " + key_source + " to " + key_dest)
        if xbmcvfs.exists(key_dest): xbmcvfs.delete(key_dest)
        xbmcvfs.copy(key_source, key_dest)
        debugTrace("Copying cert " + cert_source + " to " + cert_dest)
        if xbmcvfs.exists(cert_dest): xbmcvfs.delete(cert_dest)
        xbmcvfs.copy(cert_source, cert_dest)
        return True
    except:
        errorTrace("vpnproviders.py", "Failed to copy user key or cert file to userdata")
        return False
Beispiel #16
0
def copyKeyAndCert(vpn_provider, ovpn_name, user_key, user_cert):
    # Copy the user key and cert to the userdata directory
    key_dest = getUserDataPath(vpn_provider + "/" + getKeyName(vpn_provider, ovpn_name))
    key_source = user_key
    cert_dest = getUserDataPath(vpn_provider + "/" + getCertName(vpn_provider, ovpn_name))
    cert_source = user_cert
    try:
        debugTrace("Copying key " + key_source + " to " + key_dest)
        if xbmcvfs.exists(key_dest): xbmcvfs.delete(key_dest)
        xbmcvfs.copy(key_source, key_dest)
        debugTrace("Copying cert " + cert_source + " to " + cert_dest)
        if xbmcvfs.exists(cert_dest): xbmcvfs.delete(cert_dest)
        xbmcvfs.copy(cert_source, cert_dest)
        return True
    except:
        errorTrace("vpnproviders.py", "Failed to copy user key or cert file to userdata")
        return False
Beispiel #17
0
def generateVPNUnlim():
    # Data is stored in ovpn files with location info in Servers.txt
    location_file = getLocations("VPNUnlimited", "")
    source_file = open(getUserDataPath("providers/VPNUnlimited/Servers.txt"),
                       'r')
    servers = source_file.readlines()
    source_file.close()
    for entry in servers:
        geo = entry[:entry.index(",")].strip()
        server = entry[entry.index(",") + 1:].strip()
        output_line_udp = geo + " (UDP)," + server + ",udp,443\n"
        output_line_tcp = geo + " (TCP)," + server + ",tcp,80\n"
        location_file.write(output_line_udp)
        location_file.write(output_line_tcp)
    location_file.close()
def clearUserData():
    # Deleting everything here, but not deleting 'DEFAULT.txt' as 
    # any existing user and password info will get deleted
    path = getUserDataPath("UserDefined" + "/*.*")
    debugTrace("Deleting contents of User Defined directory" + path)
    files = glob.glob(path)
    try:
        for file in files:
            if not file.endswith("DEFAULT.txt") and xbmcvfs.exists(file): 
                debugTrace("Deleting " + file)
                xbmcvfs.delete(file)
    except Exception as e:
        errorTrace("import.py", "Couldn't clear the UserDefined directory")
        errorTrace("import.py", str(e))
        return False
    return True
def getBestPathWrapper(name):
    # This function will return the path to the user version of a given file
    # if it exists, otherwise it'll return the path the default add-on version

    # This is just about resetting the ovpn documents if neccesary
    if generateVPNs():
        return "/storage/.kodi/addons/service.vpn.manager/" + path
    else:
        filename = getUserDataPath(name)
        if not xbmcvfs.exists(filename):
            filename = getAddonPath(True, name)
        else:
            infoTrace("vpnprovider.py", "Using userdata override " + filename)
        if getPlatform() == platforms.WINDOWS:
            return filename.replace("\\", "\\\\")
        else:
            return filename
def copyUserDefinedFiles():    
    # Copy everything in the user directory to the addon directory
    infoTrace("vpnproviders.py", "Copying user defined files from userdata directory")
    source_path = getUserDataPath((user_def_str)+"/")
    dest_path = getAddonPath(True, user_def_str + "/")
    # Get the list of connection profiles and another list of strings to abuse for the selection screen    
    try:
        files = getUserDataList(user_def_str, "*")
        if len(files) == 0:
            errorTrace("vpnproviders.py", "No User Defined files available to copy from " + source_path)
            return False
        for file in files:
            name = file[file.rfind(getSeparator())+1:]
            dest_file = dest_path + getSeparator() + name
            xbmcvfs.copy(file, dest_file)
        return True
    except:
        errorTrace("vpnproviders.py", "Error copying files from " + source_path + " to " + dest_path)
        return False
Beispiel #21
0
def generatetigerVPN():
    # Data is stored in a flat text file, each line representing a connection
    # valid for UDP and TCP using the standard ports
    location_file_full = getLocations("tigerVPN", "tigerVPN Full Account")
    location_file_lite = getLocations("tigerVPN", "tigerVPN Lite Account")
    source_file = open(getUserDataPath("providers/tigerVPN/tigerVPN.csv"), 'r')
    source = source_file.readlines()
    source_file.close()
    for line in source:
        server = line.split(',')
        output_line_udp = server[1] + " " + server[0] + " (UDP)," + server[
            2] + "," + "udp,1194" + "\n"
        output_line_tcp = server[1] + " " + server[0] + " (TCP)," + server[
            2] + "," + "tcp,443" + "\n"
        location_file_full.write(output_line_udp)
        location_file_full.write(output_line_tcp)
        if server[4].startswith("Lite"):
            location_file_lite.write(output_line_udp)
            location_file_lite.write(output_line_tcp)
    location_file_full.close()
    location_file_lite.close()
Beispiel #22
0
def generateTotalVPN():
    # Data is stored in a flat text file
    # Location, tab, server - free locations are marked with a leading *
    location_file_full = getLocations("TotalVPN", "Full Account")
    location_file_free = getLocations("TotalVPN", "Free Account")
    source_file = open(getUserDataPath("providers/TotalVPN/Servers.txt"), 'r')
    source = source_file.readlines()
    source_file.close()
    for line in source:
        line = line.strip(" \t\n\r")
        geo, server = line.split("\t")
        geo = geo.strip(" *\t\n\r")
        geo = geo.replace(",", " -")
        output_line_udp = geo + " (UDP)," + server + "," + "udp,1194" + "\n"
        output_line_tcp = geo + " (TCP)," + server + "," + "tcp,443" + "\n"
        location_file_full.write(output_line_udp)
        location_file_full.write(output_line_tcp)
        if "*" in line:
            location_file_free.write(output_line_udp)
            location_file_free.write(output_line_tcp)
    location_file_full.close()
    location_file_free.close()
Beispiel #23
0
def generateHMA():
    # Data is stored in a flat text file
    # <Continent> - <Country>  xx.yy.rocks  random.xx.yy.rocks
    location_file = getLocations("HMA", "")
    source_file = open(getUserDataPath("providers/HMA/Servers.txt"), 'r')
    source = source_file.readlines()
    source_file.close()
    for line in source:
        tokens = line.split()
        for t in tokens:
            if ".rocks" in t and not "random." in t:
                server = t.strip(' \t\n\r')
                geo = line.replace(server, "")
                geo = geo.replace("random.", "")
                geo = geo.strip(' \t\n\r')
                geo = geo.replace("USA,", "USA -")
                geo = geo.replace("UK,", "UK -")
                output_line_udp = geo + " (UDP)," + server + "," + "udp,53" + "\n"
                output_line_tcp = geo + " (TCP)," + server + "," + "tcp,443" + "\n"
                location_file.write(output_line_udp)
                location_file.write(output_line_tcp)
    location_file.close()
     
 # Add in a finished option
 finished_item = "[I]Finished[/I]"
 all_user.append(finished_item)
 
 # Get the pair to delete
 index = xbmcgui.Dialog().select("Select key and certificate to delete, or [I]Finished[/I]", all_user)
 if all_user[index] == finished_item:
     still_deleting = False
 else:
     if all_user[index] == single_pair : all_user[index] = "user"
     if all_user[index] == all_item:                        
         if xbmcgui.Dialog().yesno(addon_name, "Are you sure you want to delete all key and certificate files for " + provider_display + "?"):
             for item in all_user:
                 if not item == all_item and not item == finished_item: 
                     path = getUserDataPath(provider + "/" + item)
                     try:
                         if xbmcvfs.exists(path+".key"):
                             xbmcvfs.delete(path + ".key")
                         if xbmcvfs.exists(path + ".crt"):
                             xbmcvfs.delete(path + ".crt")
                     except:
                         xbmcgui.Dialog().ok(addon_name, "Couldn't delete one of the key or certificate files:\n" + path)
     else:
         path = getUserDataPath(provider + "/" + all_user[index])
         try:
             if xbmcvfs.exists(path+".key"):
                 xbmcvfs.delete(path + ".key")
             if xbmcvfs.exists(path + ".crt"):
                 xbmcvfs.delete(path + ".crt")
         except:
Beispiel #25
0
def getProfileList(vpn_provider):
    path = getUserDataPath("providers/" + vpn_provider + "/*.ovpn")
    return glob.glob(path)
def generateOVPNFiles(vpn_provider, alternative_locations_name):
    # Generate the OVPN files for a VPN provider using the template and update with location info
    
    infoTrace("vpnproviders.py", "Generating OVPN files for " + vpn_provider + " using list " + alternative_locations_name)

    # See if there's a port override going on
    addon = xbmcaddon.Addon("service.vpn.manager")
    if addon.getSetting("default_udp") == "true":
        portUDP = ""
    else:
        portUDP = addon.getSetting("alternative_udp_port")
        
    if addon.getSetting("default_tcp") == "true":
        portTCP = ""
    else:
        portTCP = addon.getSetting("alternative_tcp_port")

    # Get the logging level
    verb_value = addon.getSetting("openvpn_verb")
    if verb_value == "":
        verb_value = "1"
        addon.setSetting("openvpn_verb", verb_value)
        
    # Load ovpn template
    try:
        debugTrace("Opening template file for " + vpn_provider)
        template_file = open(getAddonPath(True, vpn_provider + "/TEMPLATE.txt"), 'r')
        debugTrace("Opened template file for " + vpn_provider)
        template = template_file.readlines()
        template_file.close()
    except:
        errorTrace("vpnproviders.py", "Couldn't open the template file for " + vpn_provider)
        return False
    
    # Load locations file
    if not alternative_locations_name == "":
        if alternative_locations_name == "User":
            locations_name = getUserDataPath(vpn_provider + "/LOCATIONS.txt")
        else:
            locations_name = getAddonPath(True, vpn_provider + "/LOCATIONS " + alternative_locations_name + ".txt")
    else:
        locations_name = getAddonPath(True, vpn_provider + "/LOCATIONS.txt")

    try:
        debugTrace("Opening locations file for " + vpn_provider + "\n" + locations_name)
        locations_file = open(locations_name, 'r')
        debugTrace("Opened locations file for " + vpn_provider)
        locations = locations_file.readlines()
        locations_file.close()
    except:
        errorTrace("vpnproviders.py", "Couldn't open the locations file for " + vpn_provider + "\n" + locations_name)
        return False

    # For each location, generate an OVPN file using the template
    for location in locations:
        try:
            location_values = location.split(",")
            geo = location_values[0]
            servers = location_values[1].split()
            proto = location_values[2]
            ports = (location_values[3].strip(' \t\n\r')).split()
            port = ""

            # Initialise the set of values that can be modified by the location file tuples
            ca_cert = "ca.crt"
            ta_key = "ta.key"
            user_key = getUserDataPathWrapper(vpn_provider + "/" + getKeyName(vpn_provider, geo))
            user_cert = getUserDataPathWrapper(vpn_provider + "/" + getCertName(vpn_provider, geo))
            remove_flags = ""
            
            if len(location_values) > 4: 
                # The final location value is a list of multiple x=y declarations.
                # These need to be parsed out and modified.
                modifier_tuples = (location_values[4].strip(' \t\n\r')).split()
                # Loop through all of the values splitting them into name value pairs
                for modifier in modifier_tuples:
                    pair = modifier.split("=")
                    if "#CERT" in pair[0]: ca_cert = pair[1].strip()
                    if "#REMOVE" in pair[0]: remove_flags = pair[1].strip()
                    if "#TLSKEY" in pair[0]: ta_key = pair[1].strip()
                    if "#USERKEY" in pair[0]: user_key = pair[1].strip()
                    if "#USERCERT" in pair[0]: user_cert = pair[1].strip()
            if proto == "udp" and not portUDP == "": port = portUDP
            if proto == "tcp" and not portTCP == "": port = portTCP
            if port == "" and len(ports) == 1: port = ports[0]
        except:
            errorTrace("vpnproviders.py", "Location file for " + vpn_provider + " invalid on line\n" + location)
            return False
            
        try:
            ovpn_file = open(getAddonPath(True, vpn_provider + "/" + geo + ".ovpn"), 'w')
            if proto == "tcp":
                servprot = "tcp-client"
            else:
                servprot = proto

            # Do a replace on the tags in the template with data from the location file
            for line in template:
                output_line = line.strip(' \t\n\r')
                # Must check to see if there's a remove tag on the line before looking for other tags
                if "#REMOVE" in output_line:
                    if output_line[output_line.index("#REMOVE")+7] in remove_flags:
                        # Remove the line if it's a flag this location doesn't care about
                        output_line = ""
                    else:
                        # Delete the tag if this location doesn't want this line removed
                        output_line = output_line.replace("#REMOVE" + output_line[output_line.index("#REMOVE")+7], "")
                output_line = output_line.replace("#PROTO", proto)
                output_line = output_line.replace("#SERVPROT", servprot)
                # If there are multiple servers then we'll need to duplicate the server
                # line (which starts with 'remote ') and fix the server.  The rest of the
                # code will deal with the port which is the same for all lines (although
                # this assumption might not be true for all VPN providers...)
                if output_line.startswith("remote "):
                    server_template = output_line
                    server_lines = ""
                    i = 0
                    for server in servers:
                        if not server_lines == "" : server_lines = server_lines + "\n"
                        server_lines = server_lines + server_template.replace("#SERVER", server)
                        if port == "":
                            server_lines = server_lines.replace("#PORT", ports[i])
                        i = i + 1
                    output_line = server_lines
                # There might be other places we use server and port, so still the do the replace
                output_line = output_line.replace("#SERVER", servers[0])
                output_line = output_line.replace("#PORT", port)
                output_line = output_line.replace("#PASS", getAddonPathWrapper(vpn_provider + "/" + "pass.txt"))
                output_line = output_line.replace("#CERT", getAddonPathWrapper(vpn_provider + "/" + ca_cert))
                output_line = output_line.replace("#TLSKEY", getAddonPathWrapper(vpn_provider + "/" + ta_key))
                output_line = output_line.replace("#CRLVERIFY", getAddonPathWrapper(vpn_provider + "/" + "crl.pem"))
                output_line = output_line.replace("#USERKEY", user_key)
                output_line = output_line.replace("#USERCERT", user_cert)
                # Overwrite the verb value with the one in the settings
                if output_line.startswith("verb "):
                    output_line = "verb " + verb_value
                # This is a little hack to remove a tag that doesn't work with TCP but is needed for UDP
                # Could do this with a #REMOVE, but doing it here is less error prone.
                if "explicit-exit-notify" in line and proto == "tcp": output_line = ""
                if not output_line == "" : ovpn_file.write(output_line + "\n")
            ovpn_file.close()
            debugTrace("Wrote location " + geo + " " + proto)
        except:
            errorTrace("vpnproviders.py", "Can't write a location file for " + vpn_provider + " failed on line\n" + location)
            return False
    
    # Flag that the files have been generated
    writeGeneratedFile(vpn_provider)

    return True
def getLocationFiles(vpn_provider):
    # Return the locations files, add any user version to the end of the list
    locations = glob.glob(getAddonPath(True, vpn_provider + "/LOCATIONS*.txt"))
    user_locations = getUserDataPath(vpn_provider + "/LOCATIONS.txt")
    if xbmcvfs.exists(user_locations): locations.append(user_locations.replace(".txt", " User.txt"))
    return locations
Beispiel #28
0
def generateOVPNFiles(vpn_provider, alternative_locations_name):
    # Generate the OVPN files for a VPN provider using the template and update with location info
    
    infoTrace("vpnproviders.py", "Generating OVPN files for " + vpn_provider + " using list " + alternative_locations_name)

    # Set ports as default
    portUDP = ""
    portTCP = ""
        
    # Load ovpn template
    try:
        debugTrace("Opening template file for " + vpn_provider)
        template_file = open(getAddonPath(True, vpn_provider + "/TEMPLATE.txt"), 'r')
        debugTrace("Opened template file for " + vpn_provider)
        template = template_file.readlines()
        template_file.close()
    except:
        errorTrace("vpnproviders.py", "Couldn't open the template file for " + vpn_provider)
        return False
    
    # Load locations file
    if not alternative_locations_name == "":
        if alternative_locations_name == "User":
            locations_name = getUserDataPath(vpn_provider + "/LOCATIONS.txt")
        else:
            locations_name = getAddonPath(True, vpn_provider + "/LOCATIONS " + alternative_locations_name + ".txt")
    else:
        locations_name = getAddonPath(True, vpn_provider + "/LOCATIONS.txt")

    try:
        debugTrace("Opening locations file for " + vpn_provider + "/n" + locations_name)
        locations_file = open(locations_name, 'r')
        debugTrace("Opened locations file for " + vpn_provider)
        locations = locations_file.readlines()
        locations_file.close()
    except:
        errorTrace("vpnproviders.py", "Couldn't open the locations file for " + vpn_provider + "\n" + locations_name)
        return False

    # For each location, generate an OVPN file using the template
    for location in locations:
        try:
            location_values = location.split(",")
            geo = location_values[0]
            servers = location_values[1].split()
            proto = location_values[2]
            ports = (location_values[3].strip(' \t\n\r')).split()
            port = ""

            # Initialise the set of values that can be modified by the location file tuples
            ca_cert = "ca.crt"
            ta_key = "ta.key"
            user_key = getUserDataPathWrapper(vpn_provider + "/" + getKeyName(vpn_provider, geo))
            user_cert = getUserDataPathWrapper(vpn_provider + "/" + getCertName(vpn_provider, geo))
            remove_flags = ""
            
            if len(location_values) > 4: 
                # The final location value is a list of multiple x=y declarations.
                # These need to be parsed out and modified.
                modifier_tuples = (location_values[4].strip(' \t\n\r')).split()
                # Loop through all of the values splitting them into name value pairs
                for modifier in modifier_tuples:
                    pair = modifier.split("=")
                    if "#CERT" in pair[0]: ca_cert = pair[1].strip()
                    if "#REMOVE" in pair[0]: remove_flags = pair[1].strip()
                    if "#TLSKEY" in pair[0]: ta_key = pair[1].strip()
                    if "#USERKEY" in pair[0]: user_key = pair[1].strip()
                    if "#USERCERT" in pair[0]: user_cert = pair[1].strip()
            if proto == "udp" and not portUDP == "": port = portUDP
            if proto == "tcp" and not portTCP == "": port = portTCP
            if port == "" and len(ports) == 1: port = ports[0]
        except:
            errorTrace("vpnproviders.py", "Location file for " + vpn_provider + " invalid on line\n" + location)
            return False
            
        try:
            ovpn_file = open(getAddonPath(True, vpn_provider + "/" + geo + ".ovpn"), 'w')
            if proto == "tcp":
                servprot = "tcp-client"
            else:
                servprot = proto

            # Do a replace on the tags in the template with data from the location file
            for line in template:
                output_line = line.strip(' \t\n\r')
                # Must check to see if there's a remove tag on the line before looking for other tags
                if "#REMOVE" in output_line:
                    if output_line[output_line.index("#REMOVE")+7] in remove_flags:
                        # Remove the line if it's a flag this location doesn't care about
                        output_line = ""
                    else:
                        # Delete the tag if this location doesn't want this line removed
                        output_line = output_line.replace("#REMOVE" + output_line[output_line.index("#REMOVE")+7], "")
                output_line = output_line.replace("#PROTO", proto)
                output_line = output_line.replace("#SERVPROT", servprot)
                # If there are multiple servers then we'll need to duplicate the server
                # line (which starts with 'remote ') and fix the server.  The rest of the
                # code will deal with the port which is the same for all lines (although
                # this assumption might not be true for all VPN providers...)
                if output_line.startswith("remote "):
                    server_template = output_line
                    server_lines = ""
                    i = 0
                    for server in servers:
                        if not server_lines == "" : server_lines = server_lines + "\n"
                        server_lines = server_lines + server_template.replace("#SERVER", server)
                        if port == "":
                            server_lines = server_lines.replace("#PORT", ports[i])
                        i = i + 1
                    output_line = server_lines
                # There might be other places we use server and port, so still the do the replace
                output_line = output_line.replace("#SERVER", servers[0])
                output_line = output_line.replace("#PORT", port)
                output_line = output_line.replace("#PASS", getAddonPathWrapper(vpn_provider + "/" + "pass.txt"))
                #output_line = output_line.replace("#RESOLVE", getAddonPathWrapper(vpn_provider + "/" + "dnsLeak.py"))
                output_line = output_line.replace("#RESOLVE", ' \'/bin/bash -c \"python ' + getAddonPathWrapper(vpn_provider + "/" + "dnsLeak.py") +'"\'')
                output_line = output_line.replace("#CERT", getAddonPathWrapper(vpn_provider + "/" + ca_cert))
                output_line = output_line.replace("#TLSKEY", getAddonPathWrapper(vpn_provider + "/" + ta_key))
                output_line = output_line.replace("#CRLVERIFY", getAddonPathWrapper(vpn_provider + "/" + "crl.pem"))
                output_line = output_line.replace("#USERKEY", user_key)
                output_line = output_line.replace("#USERCERT", user_cert)
                # This is a little hack to remove a tag that doesn't work with TCP but is needed for UDP
                # Could do this with a #REMOVE, but doing it here is less error prone.
                if "explicit-exit-notify" in line and proto == "tcp": output_line = ""
                if not output_line == "" : ovpn_file.write(output_line + "\n")
            ovpn_file.close()
            debugTrace("Wrote location " + geo + " " + proto)
        except:
            errorTrace("vpnproviders.py", "Can't write a location file for " + vpn_provider + " failed on line\n" + location)
            return False
    
    # Write a file to indicate successful generation of the ovpn files
    ovpn_file = open(getAddonPath(True, vpn_provider + "/GENERATED.txt"), 'w')
    ovpn_file.close()
    
    return True
Beispiel #29
0
def connectVPN(connection_order, vpn_profile):

    # Don't know where this was called from so using plugin name to get addon handle
    addon = xbmcaddon.Addon("service.vpn.manager")
    addon_name = addon.getAddonInfo("name")

    # If we've not arrived here though the addon (because we've used the add-on setting
    # on the option menu), we want to surpress running the wizard as there's no need.
    addon.setSetting("vpn_wizard_run", "true")

    # Check openvpn installed and runs
    if not addon.getSetting("checked_openvpn") == "true":        
        if checkVPNInstall(addon): addon.setSetting("checked_openvpn", "true")
        else: return

    if not addon.getSetting("ran_openvpn") == "true":
        stopVPN()    
        if checkVPNCommand(addon): addon.setSetting("ran_openvpn", "true")
        else: return
    
    # The VPN protocol can be blank if this is a new run and the wizard is being used.
    # Force it to UDP as that's the most optimal and let them change in the settings.
    vpn_protocol = addon.getSetting("vpn_protocol")
    if vpn_protocol == "":
        addon.setSetting("vpn_protocol", "UDP")
        vpn_protocol = "UDP"
    
    # Do some stuff to set up text used in dialog windows
    connection_title = ""
    
    # Adjust strings below if changing number of conn_max
    if connection_order == "0" : connection_title = ""
    if connection_order == "1" : connection_title = " first"
    if connection_order == "2" : connection_title = " second"
    if connection_order == "3" : connection_title = " third"
    if connection_order == "4" : connection_title = " fourth"
    if connection_order == "5" : connection_title = " fifth"
    if connection_order == "6" : connection_title = " sixth"
    if connection_order == "7" : connection_title = " seventh"
    if connection_order == "8" : connection_title = " eighth"
    if connection_order == "9" : connection_title = " ninth"
    if connection_order == "10" : connection_title = " tenth"
    
    state = ""
    
    forceCycleLock()
    
    # Display a progress dialog box (put this on the screen quickly before doing other stuff)
    progress = xbmcgui.DialogProgress()
    progress_title = "Connecting to" + connection_title + " VPN."
    progress.create(addon_name,progress_title) 

    debugTrace(progress_title)
        
    # Pause the monitor service
    progress_message = "Pausing VPN monitor."
    progress.update(1, progress_title, progress_message)
    if not stopService():
        progress.close()
        # Display error result in an ok dialog
        errorTrace("common.py", "VPN monitor service is not running, can't start VPN")
        xbmcgui.Dialog().ok(progress_title, "Error, Service not running.\nCheck log and re-enable.")
        return

    if not progress.iscanceled():
        progress_message = "VPN monitor paused."
        debugTrace(progress_message)
        progress.update(5, progress_title, progress_message)
        xbmc.sleep(500)
        
    # Stop any active VPN connection
    if not progress.iscanceled():
        progress_message = "Stopping any active VPN connection."    
        progress.update(6, progress_title, progress_message)
        stopVPNConnection()

    if not progress.iscanceled():
        progress_message = "Disconnected from VPN."
        progress.update(10, progress_title, progress_message)
        xbmc.sleep(500)
        
    # Install the VPN provider    
    existing_connection = ""
    if not progress.iscanceled():
    
        vpn_provider = addon.getSetting("vpn_provider")
    
        # This is some code to copy the user name from a default file rather than use the user entered values.
        # It exists to help development where swapping between providers constantly is tedious.
        default_path = getUserDataPath(getVPNLocation(vpn_provider) + "/DEFAULT.txt")
        if connection_order == "1" and xbmcvfs.exists(default_path):
            default_file = open(default_path, 'r')
            default = default_file.readlines()
            default_file.close()
            default_value = default[0].strip(' \t\n\r')
            addon.setSetting("vpn_username", default_value)
            default_value = default[1].strip(' \t\n\r')
            addon.setSetting("vpn_password", default_value)  

        # Reset the username/password if it's not being used
        if not usesPassAuth(vpn_provider):
            addon.setSetting("vpn_username", "")
            addon.setSetting("vpn_password", "")  
                
        vpn_username = addon.getSetting("vpn_username")
        vpn_password = addon.getSetting("vpn_password")
        
        # Reset the setting indicating we've a good configuration for just this connection
        if not connection_order == "0":
            existing_connection = addon.getSetting(connection_order + "_vpn_validated")
            addon.setSetting(connection_order + "_vpn_validated", "")
            addon.setSetting(connection_order + "_vpn_validated_friendly", "")
        last_provider = addon.getSetting("vpn_provider_validated")
        last_credentials = addon.getSetting("vpn_username_validated") + " " + addon.getSetting("vpn_password_validated")
        if last_provider == "" : last_provider = "?"
        
        # Provider or credentials we've used previously have changed so we need to reset all validated connections
        vpn_credentials = vpn_username + " " + vpn_password
        if not last_provider == vpn_provider:
            last_credentials = "?"
        if not last_credentials == vpn_credentials:
            debugTrace("Credentials have changed since last time lthrough so need to revalidate")
            resetVPNConfig(addon, 1)   
    
    # Generate or fix the OVPN files if we've not done this previously
    provider_gen = True
    if not progress.iscanceled():
        if not ovpnFilesAvailable(getVPNLocation(vpn_provider)):

            # Fetch the list of locations available.  If there are multiple, the user can select
            locations = getLocationFiles(getVPNLocation(vpn_provider))            
            default_label = "Default"
            i = 0            
            for location in locations:
                locations[i] = location[location.index("LOCATIONS")+10:location.index(".txt")]
                if locations[i] == "" : locations[i] = default_label
                i = i + 1
            selected_profile = ""
            if len(locations) == 0: errorTrace("common.py", "No LOCATIONS.txt files found in VPN directory.  Cannot generate ovpn files.")
            if len(locations) > 1:
                selected_location = xbmcgui.Dialog().select("Select connections profile", locations)
                selected_profile = locations[selected_location]
                if selected_profile == default_label : selected_profile = ""
            
            addon.setSetting("vpn_locations_list", selected_profile)
            progress_message = "Setting up VPN provider " + vpn_provider + "."
            progress.update(11, progress_title, progress_message)
            # Delete any old files in other directories
            debugTrace("Deleting all generated ovpn files")
            removeGeneratedFiles()
            # Generate new ones
            try:
                provider_gen = fixOVPNFiles(getVPNLocation(vpn_provider), selected_profile)
            except:
                errorTrace("Couldn't generate new .ovpn files")
                provider_gen = False
            xbmc.sleep(500)

    if provider_gen:
        if not progress.iscanceled():
            progress_message = "Using VPN provider " + vpn_provider
            progress.update(15, progress_title, progress_message)
            xbmc.sleep(500)
                            
        # Set up user credentials file
        if not progress.iscanceled() and usesPassAuth(vpn_provider):
            credentials_path = getCredentialsPath(addon)
            debugTrace("Attempting to use the credentials in " + credentials_path)
            if (not last_credentials == vpn_credentials) or (not xbmcvfs.exists(credentials_path)) or (not connectionValidated(addon)):
                progress_message = "Configuring authentication settings for user " + vpn_username + "."
                progress.update(16, progress_title, progress_message)
                provider_gen = writeCredentials(addon)

    got_keys = True
    keys_copied = True
    cancel_attempt = False
    cancel_clear = False
    if provider_gen:
        ovpn_name = ""
        if not progress.iscanceled():
            if usesPassAuth(vpn_provider):
                progress_message = "Using authentication settings for user " + vpn_username + "."
            else:
                progress_message = "User authentication not used with " + vpn_provider + "."
            progress.update(19, progress_title, progress_message)
            xbmc.sleep(500)

        # Display the list of connections
        if not progress.iscanceled():

            if not connection_order == "0":
                debugTrace("Displaying list of connections")
                all_connections = getProfileList(vpn_provider)
                ovpn_connections = getFilteredProfileList(all_connections, vpn_protocol, addon)
                ovpn_connections.sort()
                connections = getFriendlyProfileList(vpn_provider, ovpn_connections)
                
                if len(connections) > 0:
                    if existing_connection == "":
                        cancel_text = "[I]Cancel connection attempt[/I]"
                    else:
                        cancel_text = "[I]Cancel connection attempt and clear connection[/I]"
                        cancel_clear = True
                    connections.append(cancel_text)
                    selected_connection = xbmcgui.Dialog().select("Select " + connection_title + " VPN profile", connections)                  
                
                    # Based on the value selected, get the path name to the ovpn file
                    ovpn_name = connections[selected_connection]
                    if ovpn_name == cancel_text:
                        ovpn_name = ""
                        cancel_attempt = True
                    else:
                        ovpn_connection = ovpn_connections[selected_connection]
            else:
                ovpn_name = getFriendlyProfileName(vpn_provider, vpn_profile)
                ovpn_connection = vpn_profile

        if not progress.iscanceled() and not ovpn_name == "":
            # Fetch the key from the user if one is needed
            if usesUserKeys(getVPNLocation(vpn_provider)):                
                # If a key already exists, skip asking for it
                if not (gotKeys(getVPNLocation(vpn_provider), ovpn_name)):
                    # Stick out a helpful message if this is first time through
                    if not gotKeys(getVPNLocation(vpn_provider), ""):
                        xbmcgui.Dialog().ok(addon_name, vpn_provider + " provides unique key and certificate files to authenticate, typically called [I]client.key and client.crt[/I] or [I]user.key and user.crt[/I].  Make these files available on an accessable drive or USB key.")                
                    # Get the last directory browsed to avoid starting from the top
                    start_dir = xbmcgui.Window(10000).getProperty("VPN_Manager_User_Directory")
                    if usesSingleKey(getVPNLocation(vpn_provider)): select_title = "Select the user key file to use for all connections"
                    else: select_title = "Select the user key file to use for this individual connection"
                    key_file = xbmcgui.Dialog().browse(1, select_title, "files", ".key", False, False, start_dir, False)
                    if key_file.endswith(".key"):
                        start_dir = os.path.dirname(key_file) + getSeparator()
                        if usesSingleKey(getVPNLocation(vpn_provider)): select_title = "Select the user certificate file to use for all connections"
                        else: select_title = "Select the user certificate file to use for this individual connection"
                        crt_file = xbmcgui.Dialog().browse(1, select_title, "files", ".crt", False, False, start_dir, False)                    
                        if crt_file.endswith(".crt"):
                            start_dir = os.path.dirname(crt_file) + getSeparator()
                            xbmcgui.Window(10000).setProperty("VPN_Manager_User_Directory", start_dir)
                            keys_copied = copyKeyAndCert(getVPNLocation(vpn_provider), ovpn_name, key_file, crt_file)
                            got_keys = keys_copied
                        else:
                            got_keys = False
                    else:
                        got_keys = False

        # Try and connect to the VPN provider using the entered credentials        
        if not progress.iscanceled() and not ovpn_name == "" and got_keys:    
            progress_message = "Connecting using profile " + ovpn_name + "."
            debugTrace(progress_message)
            
            # Start the connection and wait a second before starting to check the state
            startVPN(ovpn_connection)
            
            i = 0
            # Bad network takes over a minute to spot so loop for a bit longer (each loop is 2 seconds)
            loop_max = 38
            if fakeConnection(): loop_max = 2
            percent = 20
            while i <= loop_max:
                progress.update(percent, progress_title, progress_message)
                xbmc.sleep(2000)
                state = getVPNConnectionStatus()
                if not (state == connection_status.UNKNOWN or state == connection_status.TIMEOUT) : break
                if progress.iscanceled(): break
                i = i + 1
                percent = percent + 2

    # Mess with the state to make it look as if we've connected to a VPN
    if fakeConnection() and not progress.iscanceled() and provider_gen and not ovpn_name == "" and got_keys: state = connection_status.CONNECTED
    
    # Determine what happened during the connection attempt        
    if state == connection_status.CONNECTED :
        # Success, VPN connected! Display an updated progress window whilst we work out where we're connected to
        progress_message = "Connected, restarting VPN monitor."
        progress.update(97, progress_title, progress_message)
        # Set the final message to indicate success
        progress_message = "Connected, VPN monitor restarted."
        _, ip, country, isp = getIPInfo(addon)
        dialog_message = "Connected to a VPN in " + country + ".\nUsing profile " + ovpn_name + ".\nExternal IP address is " + ip + ".\nService Provider is " + isp + "."
        infoTrace("common.py", dialog_message)
        if ifDebug(): writeVPNLog()
        # Store that setup has been validated and the credentials used
        setVPNProfile(ovpn_connection)
        setVPNProfileFriendly(ovpn_name)
        if not connection_order == "0":
            addon.setSetting("vpn_provider_validated", vpn_provider)
            addon.setSetting("vpn_username_validated", vpn_username)
            addon.setSetting("vpn_password_validated", vpn_password)
            addon.setSetting(connection_order + "_vpn_validated", ovpn_connection)
            addon.setSetting(connection_order + "_vpn_validated_friendly", ovpn_name)
        setVPNState("started")
        setVPNRequestedProfile("")
        setVPNRequestedProfileFriendly("")
        setVPNLastConnectedProfile("")
        setVPNLastConnectedProfileFriendly("")
        setConnectionErrorCount(0)
        # Indicate to the service that it should update its settings
        updateService()        
    elif progress.iscanceled() or cancel_attempt:
        # User pressed cancel.  Don't change any of the settings as we've no idea how far we got
        # down the path of installing the VPN, configuring the credentials or selecting the connection
        # We're assuming here that if the VPN or user ID has been changed, then the connections are invalid
        # already.  If the cancel happens during the connection validation, we can just use the existing one.
        # Set the final message to indicate user cancelled operation
        progress_message = "Cancelling connection attempt, restarting VPN monitor."
        progress.update(97, progress_title, progress_message)
        # Set the final message to indicate cancellation
        progress_message = "Cancelling connection attempt, VPN monitor restarted."
        # Restore the previous connection info 
        dialog_message = "Cancelled connection attempt.\n"
        if not connection_order == "0":
            if not isVPNConnected():
                if cancel_clear:
                    dialog_message = dialog_message + "This connection has been removed from the list of valid connections."
                else:
                    dialog_message = dialog_message + "This connection has not been validated."
                resetVPNConfig(addon, int(connection_order))
        else:
            dialog_message = dialog_message + "Please reconnect."
        
        # Don't know how far we got, if we were trying to connect and then got cancelled,
        # there might still be an instance of openvpn running we need to kill
        stopVPN()
    else:
        # An error occurred, The current connection is already invalidated.  The VPN credentials might 
        # be ok, but if they need re-entering, the user must update them which will force a reset.  
        progress_message = "Error connecting to VPN, restarting VPN monitor."
        progress.update(97, progress_title, progress_message)
        xbmc.sleep(500)
        # Set the final message to show an error occurred
        progress_message = "Error connecting to VPN, VPN monitor restarted."
        # First set of errors happened prior to trying to connect
        if not provider_gen:
            dialog_message = "Error creating OVPN or credentials file for provider.\nCheck log to determine cause of failure."
        elif not got_keys:
            if not keys_copied:
                dialog_message = "Failed to copy supplied user key and cert files.\nCheck log and retry."
            else:
                dialog_message = "User key and certificate files are required, but were not provided.  Locate the files and try again."
        elif ovpn_name == "":
            dialog_message = "No unused VPN profiles were available for " + vpn_protocol + " protocol.\nChange VPN provider settings."
        else:
            # This second set of errors happened because we tried to connect and failed
            if state == connection_status.AUTH_FAILED: 
                dialog_message = "Error connecting to VPN, authentication failed.\nCheck your username and password."
                credentials_path = getCredentialsPath(addon)
                if not connection_order == "0":
                    addon.setSetting("vpn_username_validated", "")
                    addon.setSetting("vpn_password_validated", "")
            elif state == connection_status.NETWORK_FAILED: 
                dialog_message = "Error connecting to VPN, could not estabilish connection.\nCheck your username, password and network connectivity and retry."
            elif state == connection_status.TIMEOUT:
                dialog_message = "Error connecting to VPN, connection has timed out.\nTry using a different VPN profile or retry."
            else:
                dialog_message = "Error connecting to VPN, something unexpected happened.\nRetry to check openvpn operation and then check log."
                addon.setSetting("ran_openvpn", "false")
            
            # Output what when wrong with the VPN to the log
            writeVPNLog()

        if not connection_order == "0" :
            resetVPNConfig(addon, int(connection_order))
        
        errorTrace("common.py", dialog_message)

        # The VPN might be having a spaz still so we want to ensure it's stopped
        stopVPN()

    # Restart service
    if not startService():
        progress.close()
        errorTrace("common.py", "VPN monitor service is not running, VPN has started")
        dialog_message = "Error, Service not running.\nCheck log and reboot."        
    else:
        # Close out the final progress dialog
        progress.update(100, progress_title, progress_message)
        xbmc.sleep(500)
        progress.close()
    
    freeCycleLock()

    # Display connection result in an ok dialog
    xbmcgui.Dialog().ok(progress_title, dialog_message)
    
    # Refresh the screen if this is not being done on settings screen
    if connection_order == "0" : xbmc.executebuiltin('Container.Refresh')
def getUserCerts(vpn_provider):
    # Return the list of key and cert files for a given provider (aka directory name...)
    path = getUserDataPath(getVPNLocation(vpn_provider)+"/*.crt")
    debugTrace("Getting certificate files " + path)
    return (glob.glob(path))         
def getUserDataList(vpn_provider, filter):    
    # Return all user files for a provider (aka directory name...)
    path = getUserDataPath(getVPNLocation(vpn_provider) + "/" + filter)
    debugTrace("Getting list of files in " + path)
    return sorted(glob.glob(path))  
def copyKeyAndCert(vpn_provider, ovpn_name, user_key, user_cert):
    # Copy the user key and cert to the userdata directory
    key_dest = getUserDataPath(vpn_provider + "/" +
                               getKeyName(vpn_provider, ovpn_name))
    key_source = user_key
    cert_dest = getUserDataPath(vpn_provider + "/" +
                                getCertName(vpn_provider, ovpn_name))
    cert_source = user_cert
    if key_source == cert_source:
        # This means that a .ovpn was selected
        try:
            debugTrace("Extracing key and cert from " + key_source + " to " +
                       key_dest + " and " + cert_dest)
            ovpn_file = open(key_source, 'r')
            ovpn = ovpn_file.readlines()
            ovpn_file.close()
            debugTrace("Checking directory path exists for key and cert " +
                       os.path.dirname(key_dest))
            if not os.path.exists(os.path.dirname(key_dest)):
                infoTrace("vpnprovider.py",
                          "Creating " + os.path.dirname(key_dest))
                os.makedirs(os.path.dirname(key_dest))
                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(key_dest)):
                    if t == 9:
                        errorTrace(
                            "vpnprovider.py",
                            "Waited 10 seconds to create directory but it never appeared"
                        )
                        break
                    xbmc.sleep(1000)
                    t += 1
            key_file = open(key_dest, 'w')
            cert_file = open(cert_dest, 'w')
            key = False
            cert = False
            key_count = 0
            cert_count = 0
            for line in ovpn:
                line = line.strip(' \t\n\r')
                if line.startswith("<key>"): key = True
                elif line.startswith("</key>"): key = False
                elif line.startswith("<cert>"): cert = True
                elif line.startswith("</cert>"): cert = False
                else:
                    if key:
                        key_file.write(line + "\n")
                        key_count += 1
                    if cert:
                        cert_file.write(line + "\n")
                        cert_count += 1
            key_file.close()
            cert_file.close()
            if key_count > 0 and cert_count > 0:
                return True
            else:
                # Couldn't extract key and/or cert, delete any remains and return error
                errorTrace(
                    "vpnproviders.py",
                    "Failed to extract user key or cert file from ovpn.  Key size was "
                    + str(key_count) + " and cert size was " + str(cert_count))
                if xbmcvfs.exists(key_dest): xbmcvfs.delete(key_dest)
                if xbmcvfs.exists(cert_dest): xbmcvfs.delete(cert_dest)
                return False
        except Exception as e:
            errorTrace("vpnproviders.py",
                       "Failed to copy user key or cert file to userdata")
            errorTrace("vpnproviders.py", str(e))
            return False
    else:
        # Individual key and crt files were selected
        try:
            debugTrace("Copying key " + key_source + " to " + key_dest)
            if xbmcvfs.exists(key_dest): xbmcvfs.delete(key_dest)
            xbmcvfs.copy(key_source, key_dest)
            debugTrace("Copying cert " + cert_source + " to " + cert_dest)
            if xbmcvfs.exists(cert_dest): xbmcvfs.delete(cert_dest)
            xbmcvfs.copy(cert_source, cert_dest)
            return True
        except Exception as e:
            errorTrace("vpnproviders.py",
                       "Failed to copy user key or cert file to userdata")
            errorTrace("vpnproviders.py", str(e))
            return False
def generateOVPNFiles(vpn_provider, alternative_locations_name):
    # Generate the OVPN files for a VPN provider using the template and update with location info

    infoTrace(
        "vpnproviders.py", "Generating OVPN files for " + vpn_provider +
        " using list " + alternative_locations_name)

    # See if there's a port override going on
    addon = xbmcaddon.Addon("service.vpn.manager")
    if addon.getSetting("default_udp") == "true":
        portUDP = ""
    else:
        portUDP = addon.getSetting("alternative_udp_port")

    if addon.getSetting("default_tcp") == "true":
        portTCP = ""
    else:
        portTCP = addon.getSetting("alternative_tcp_port")

    # Get the logging level
    verb_value = addon.getSetting("openvpn_verb")
    if verb_value == "":
        verb_value = "1"
        addon.setSetting("openvpn_verb", verb_value)

    # Load ovpn template
    try:
        template_path = getTemplateFile(vpn_provider)
        debugTrace("Opening template file " + template_path)
        template_file = open(template_path, 'r')
        template = template_file.readlines()
        template_file.close()
    except Exception as e:
        errorTrace("vpnproviders.py",
                   "Couldn't open the template file for " + vpn_provider)
        errorTrace("vpnproviders.py", str(e))
        return False

    # Open a translate file
    try:
        debugTrace("Opening translate file for " + vpn_provider)
        translate_file = open(
            getAddonPath(True, vpn_provider + "/TRANSLATE.txt"), 'w')
        debugTrace("Opened translate file for " + vpn_provider)
    except Exception as e:
        errorTrace("vpnproviders.py",
                   "Couldn't open the translate file for " + vpn_provider)
        errorTrace("vpnproviders.py", str(e))
        return False

    if getPlatform() == platforms.WINDOWS and addon.getSetting(
            "block_outside_dns") == "true":
        template.append("block-outside-dns")

    if addon.getSetting("force_ping") == "true":
        template.append("ping #PINGSPEED")
        template.append("ping-exit #PINGEXIT")
        template.append("ping-timer-rem")

    if addon.getSetting("up_down_script") == "true":
        template.append("script-security 2")
        template.append(getUpParam(vpn_provider))
        template.append(getDownParam(vpn_provider))

    # Load locations file
    if not alternative_locations_name == "":
        if alternative_locations_name == "User":
            locations_name = getUserDataPath(vpn_provider + "/LOCATIONS.txt")
        else:
            locations_name = getAddonPath(
                True, vpn_provider + "/LOCATIONS " +
                alternative_locations_name + ".txt")
    else:
        locations_name = getAddonPath(True, vpn_provider + "/LOCATIONS.txt")

    try:
        debugTrace("Opening locations file for " + vpn_provider + "\n" +
                   locations_name)
        locations_file = open(locations_name, 'r')
        debugTrace("Opened locations file for " + vpn_provider)
        locations = locations_file.readlines()
        locations_file.close()
    except Exception as e:
        errorTrace(
            "vpnproviders.py", "Couldn't open the locations file for " +
            vpn_provider + "\n" + locations_name)
        errorTrace("vpnproviders.py", str(e))
        translate_file.close()
        return False

    # For each location, generate an OVPN file using the template
    for location in locations:
        try:
            location_values = location.split(",")
            geo = location_values[0]
            servers = location_values[1].split()
            proto = location_values[2]
            ports = (location_values[3].strip(' \t\n\r')).split()
            port = ""

            # Initialise the set of values that can be modified by the location file tuples
            ca_cert = "ca.crt"
            ta_key = "ta.key"
            crl_pem = "crl.pem"
            dh_parm = "dh.pem"
            user1 = ""
            user2 = ""
            user_key = getUserDataPathWrapper(vpn_provider + "/" +
                                              getKeyName(vpn_provider, geo))
            user_cert = getUserDataPathWrapper(vpn_provider + "/" +
                                               getCertName(vpn_provider, geo))
            user_pass = getUserDataPathWrapper(
                vpn_provider + "/" + getKeyPassName(vpn_provider, geo))
            remove_flags = ""
            if proto == "udp":
                ping_speed = "5"
                ping_exit = "30"
            else:
                ping_speed = "10"
                ping_exit = "60"

            if len(location_values) > 4:
                # The final location value is a list of multiple x=y declarations.
                # These need to be parsed out and modified.
                modifier_tuples = (location_values[4].strip(' \t\n\r')).split()
                # Loop through all of the values splitting them into name value pairs
                for modifier in modifier_tuples:
                    pair = modifier.split("=")
                    if "#CERT" in pair[0]: ca_cert = pair[1].strip()
                    if "#REMOVE" in pair[0]: remove_flags = pair[1].strip()
                    if "#TLSKEY" in pair[0]: ta_key = pair[1].strip()
                    if "#USERKEY" in pair[0]: user_key = pair[1].strip()
                    if "#USERCERT" in pair[0]: user_cert = pair[1].strip()
                    if "#USERPASS" in pair[0]: user_pass = pair[1].strip()
                    if "#CRLVERIFY" in pair[0]: crl_pem = pair[1].strip()
                    if "#DH" in pair[0]: dh_parm = pair[1].strip()
                    if "#USER1" in pair[0]: user1 = pair[1].strip()
                    if "#USER2" in pair[0]: user2 = pair[1].strip()
                    if "#PINGSPEED" in pair[0]: ping_speed = pair[1].strip()
                    if "#PINGEXIT" in pair[0]: ping_exit = pair[1].strip()
            if proto == "udp" and not portUDP == "": port = portUDP
            if proto == "tcp" and not portTCP == "": port = portTCP
            if port == "" and len(ports) == 1: port = ports[0]
        except Exception as e:
            errorTrace(
                "vpnproviders.py", "Location file for " + vpn_provider +
                " invalid on line\n" + location)
            errorTrace("vpnproviders.py", str(e))
            translate_file.close()
            return False

        try:
            ovpn_file = open(
                getAddonPath(True, vpn_provider + "/" + geo + ".ovpn"), 'w')
            translate_location = geo
            if proto == "tcp":
                servprot = "tcp-client"
            else:
                servprot = proto

            # Do a replace on the tags in the template with data from the location file
            for line in template:
                output_line = line.strip(' \t\n\r')
                # Must check to see if there's a remove tag on the line before looking for other tags
                if "#REMOVE" in output_line:
                    if output_line[output_line.index("#REMOVE") +
                                   7] in remove_flags:
                        # Remove the line if it's a flag this location doesn't care about
                        output_line = ""
                    else:
                        # Delete the tag if this location doesn't want this line removed
                        output_line = output_line.replace(
                            "#REMOVE" +
                            output_line[output_line.index("#REMOVE") + 7], "")
                output_line = output_line.replace("#PROTO", proto)
                output_line = output_line.replace("#SERVPROT", servprot)
                # If there are multiple servers then we'll need to duplicate the server
                # line (which starts with 'remote ') and fix the server.  The rest of the
                # code will deal with the port which is the same for all lines (although
                # this assumption might not be true for all VPN providers...)
                if output_line.startswith("remote "):
                    server_template = output_line
                    server_lines = ""
                    i = 0
                    for server in servers:
                        if i == 0: translate_server = server
                        if not server_lines == "":
                            server_lines = server_lines + "\n"
                        server_lines = server_lines + server_template.replace(
                            "#SERVER", server)
                        if port == "":
                            server_lines = server_lines.replace(
                                "#PORT", ports[i])
                        i = i + 1
                    if i > 1:
                        translate_server = translate_server + " & " + str(
                            i - 1) + " more"
                    output_line = server_lines
                # There might be other places we use server and port, so still the do the replace
                output_line = output_line.replace("#SERVER", servers[0])
                output_line = output_line.replace("#PORT", port)
                # Pass is always generated by the add-on so will be in the addon directory
                if "#PASS" in output_line:
                    output_line = output_line.replace(
                        "#PASS",
                        getAddonPathWrapper(vpn_provider + "/" + "pass.txt"))
                # These flags are files that can be over ridden in the user data directory
                if "#CERT" in output_line:
                    output_line = output_line.replace(
                        "#CERT",
                        getBestPathWrapper(vpn_provider + "/" + ca_cert))
                if "#TLSKEY" in output_line:
                    output_line = output_line.replace(
                        "#TLSKEY",
                        getBestPathWrapper(vpn_provider + "/" + ta_key))
                if "#CRLVERIFY" in output_line:
                    output_line = output_line.replace(
                        "#CRLVERIFY",
                        getBestPathWrapper(vpn_provider + "/" + crl_pem))
                if "#DH" in output_line:
                    output_line = output_line.replace(
                        "#DH",
                        getBestPathWrapper(vpn_provider + "/" + dh_parm))
                # User files are managed by the add-on so will be in the user directory (set above)
                output_line = output_line.replace("#USERKEY", user_key)
                output_line = output_line.replace("#USERCERT", user_cert)
                output_line = output_line.replace("#USERPASS", user_pass)
                # Path is the add-on path, not the user directory
                if "#PATH" in output_line:
                    output_line = output_line.replace(
                        "#PATH", getAddonPathWrapper(vpn_provider + "/"))
                output_line = output_line.replace("#USER1", user1)
                output_line = output_line.replace("#USER2", user2)
                output_line = output_line.replace("#PINGSPEED", ping_speed)
                output_line = output_line.replace("#PINGEXIT", ping_exit)
                # Overwrite the verb value with the one in the settings
                if output_line.startswith("verb "):
                    output_line = "verb " + verb_value
                # This is a little hack to remove a tag that doesn't work with TCP but is needed for UDP
                # Could do this with a #REMOVE, but doing it here is less error prone.
                if "explicit-exit-notify" in line and proto == "tcp":
                    output_line = ""
                if not output_line == "": ovpn_file.write(output_line + "\n")
            ovpn_file.close()
            debugTrace("Wrote location " + geo + " " + proto)
            translate_file.write(translate_location + "," + translate_server +
                                 " (" + proto.upper() + ")\n")
        except Exception as e:
            errorTrace(
                "vpnproviders.py", "Can't write a location file for " +
                vpn_provider + " failed on line\n" + location)
            errorTrace("vpnproviders.py", str(e))
            translate_file.close()
            return False

    # Write the location to server translation file
    translate_file.close()

    # Flag that the files have been generated
    writeGeneratedFile(vpn_provider)

    return True
def importWizard():    
    addon = xbmcaddon.Addon("service.vpn.manager")
    addon_name = addon.getAddonInfo("name")

    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?", "", ""):
        cleanPassFiles()
        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?.", "", "", "Directory", "Files"):
            directory_input = False
            files = xbmcgui.Dialog().browse(1, "Select all VPN provider files", "files", "", False, False, "c:\\", True)
        else:
            directory_input = True
            dname = xbmcgui.Dialog().browse(0, "Select a directory containing VPN provider files", "files", "", False, False, "c:\\", 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 xbmcgui.Dialog().yesno(addon_name, "Update the .ovpn files to best guess values and determine the best User Defined provider settings (recommended)?", "", ""):
            update = True
            detail.append("Updating the .ovpn files to best guess settings\n")
            if xbmcgui.Dialog().yesno(addon_name, "Rename the .ovpn files to indicate either a UDP or TCP connection type to allow filtering of connections?", "", ""):
                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("import.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("vpnprovider.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("import.py", "Copying " + fname + " to " + dest_name)
                detail.append("Copying " + fname + " to " + dest_name + "\n")
                xbmcvfs.copy(fname, 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:
                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("import.py", "Copying " + oname + " to " + dest_name)
                    detail.append("Copying " + oname + " to " + dest_name + "\n")
                    xbmcvfs.copy(oname, 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("import.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"
                        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
                                            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("#"):
                                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
                            dest_file.write(line+"\n")
                        dest_file.close()
                        
                        if 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("import.py", "Failed to copy (or update) file")
            errorTrace("import.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.", "", "", "OK", "Import Log"):
            popupImportLog()
    else:
        xbmcgui.Dialog().ok(addon_name, errorMessage)
        
    return success
def getUserDataList(vpn_provider, filter):
    # Return all user files for a provider (aka directory name...)
    path = getUserDataPath(getVPNLocation(vpn_provider) + "/" + filter)
    debugTrace("Getting list of files in " + path)
    return sorted(glob.glob(path))
 index = xbmcgui.Dialog().select(
     "Select key and certificate to delete, or [I]Finished[/I]",
     all_user)
 if all_user[index] == finished_item:
     still_deleting = False
 else:
     if all_user[index] == single_pair:
         all_user[index] = "user"
     if all_user[index] == all_item:
         if xbmcgui.Dialog().yesno(
                 addon_name,
                 "Are you sure you want to delete all key and certificate files for "
                 + provider_display + "?"):
             for item in all_user:
                 if not item == all_item and not item == finished_item:
                     path = getUserDataPath(provider +
                                            "/" + item)
                     try:
                         if xbmcvfs.exists(path +
                                           ".key"):
                             xbmcvfs.delete(path +
                                            ".key")
                         if xbmcvfs.exists(path +
                                           ".txt"):
                             xbmcvfs.delete(path +
                                            ".txt")
                         if xbmcvfs.exists(path +
                                           ".crt"):
                             xbmcvfs.delete(path +
                                            ".crt")
                     except:
                         xbmcgui.Dialog().ok(
def getUserCerts(vpn_provider):
    # Return the list of key and cert files for a given provider (aka directory name...)
    path = getUserDataPath(getVPNLocation(vpn_provider) + "/*.crt")
    debugTrace("Getting certificate files " + path)
    return (glob.glob(path))