def generateAll(): infoTrace("generation.py", "Generating Location files") generatePIA() return generateWiTopia() generateVPNht() generateTotalVPN() generateCelo() generateSaferVPN() generateNordVPN() generateVyprVPN() generateBTGuard() generateVPNUnlim() generateHideMe() generateLimeVPN() generateHideIPVPN() generateVyprVPN() generateCyberGhost() generateTorGuard() generateibVPN() generatePP() generateAirVPN() generatePureVPN() generateLiquidVPN() generatetigerVPN() generateHMA() generateIPVanish() generateExpressVPN()
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 addSystemd(): # Enable the openvpn systemd service, assuming a configuration has been copied command = "systemctl enable openvpn.service" if useSudo(): command = "sudo " + command infoTrace("platform.py", "Enabling systemd service with " + command) if not fakeSystemd(): os.system(command) return
def removeSystemd(): # Disable the openvpn systemd service command = "systemctl disable openvpn.service" if useSudo(): command = "sudo " + command infoTrace("platform.py", "Disabling systemd service with " + command) if not fakeSystemd(): os.system(command) return
def checkVPNCommand(addon): # Issue the openvpn command and see if the output is a bunch of commands if not fakeConnection(): p = getPlatform() # Issue the openvpn command, expecting to get the options screen back if p == platforms.RPI or p == platforms.LINUX: # Issue Linux command command = getOpenVPNPath() + " > " + getVPNLogFilePath( ) + " 2>&1 &" if useSudo(): command = "sudo " + command infoTrace("vpnplatform.py", "Testing openvpn with : " + command) os.system(command) elif p == platforms.WINDOWS: # Issue Windows command command = getOpenVPNPath() infoTrace("vpnplatform.py", "Testing openvpn with : " + command) args = shlex.split(command) outfile = open(getVPNLogFilePath(), 'w') proc = subprocess.Popen(args, stdout=outfile, creationflags=subprocess.SW_HIDE, shell=True) else: errorTrace("vpnplatform.py", "Unsupported platform " + str(p)) # **** ADD MORE PLATFORMS HERE **** # Waiting for the log file to appear xbmc.sleep(1000) i = 0 while not xbmcvfs.exists(getVPNLogFilePath()) and i < 10: xbmc.sleep(1000) i = i + 1 # If the log file appears, check it's what we expect if xbmcvfs.exists(getVPNLogFilePath()): log_file = open(getVPNLogFilePath(), 'r') log_file_lines = log_file.readlines() log_file.close() # Look for a phrase we'd expect to see if the call # worked and the list of options was displayed for line in log_file_lines: if "General Options" in line: return True # Write the log file in case there's something in it errorTrace("vpnplatform.py", "Ran openvpn command and it failed") writeVPNLog() dialog_msg = "The OpenVPN executable isn't working. Check the log, then from a command line prompt type 'openvpn' and fix any problems reported." else: errorTrace("vpnplatform.py", "Ran openvpn command and VPN log didn't appear") dialog_msg = "The OpenVPN executable isn't writing out a log. Try changing the Kodi log directory setting in Settings-Debug menu and retry." # Display an error message xbmcgui.Dialog().ok(addon.getAddonInfo("name"), dialog_msg) return False else: return True
def getNordVPNOvpnFile(server, protocol, target_file): # Download the opvn file try: download_url = "https://downloads.nordcdn.com/configs/files/ovpn_" + protocol + "/servers/" + server + "." + protocol + ".ovpn" if ifHTTPTrace(): infoTrace( "alternativeNord.py", "Downloading ovpn for " + server + ", protocol " + protocol + " using " + download_url) else: debugTrace("Downloading ovpn for " + server + ", protocol " + protocol) token = getTokenNordVPN() req = urllib2.Request(download_url) req.add_header("Authorization", "token:" + token) t_before = now() response = urllib2.urlopen(req, timeout=10) lines = response.readlines() t_after = now() response.close() if t_after - t_before > TIME_WARN: infoTrace( "alternativeNord.py", "Downloading ovpn for " + server + ", protocol " + protocol + " took " + str(t_after - t_before) + " seconds") except urllib2.HTTPError as e: errorTrace( "alternativeNord.py", "Couldn't download the ovpn for server " + server + ", protocol " + protocol) errorTrace("alternativeNord.py", "API call was " + download_url) errorTrace("alternativeNord.py", "Response was " + str(e.code) + " " + e.reason) errorTrace("alternativeNord.py", e.read()) return False except Exception as e: errorTrace( "alternativeNord.py", "Couldn't download the ovpn for server " + server + ", protocol " + protocol) errorTrace("alternativeNord.py", "API call was " + download_url) errorTrace("alternativeNord.py", "Response was " + str(type(e)) + " " + str(e)) return False try: debugTrace("Writing ovpn file to " + target_file) f = open(target_file, 'w') for line in lines: line = line.strip(' \t\n\r') f.write(line + "\n") f.close() return True except Exception as e: errorTrace("alternativeNord.py", "Couldn't write ovpn to " + target_file) errorTrace("alternativeNord.py", str(e)) return False
def checkPlatform(addon): if not fakeConnection(): p = getPlatform() infoTrace("vpnplatform.py", "Checking platform, found " + str(p) + ", " + sys.platform) dialog_msg = "" if p == platforms.UNKNOWN or "Android" in getAddonPath(True, ""): dialog_msg = addon.getAddonInfo("name") + " is not supported on this hardware platform." xbmcgui.Dialog().ok(addon.getAddonInfo("name"), dialog_msg) return False return True
def updateVPNFiles(vpn_provider): # If the OVPN files aren't generated then they need to be updated with location info infoTrace("vpnproviders.py", "Updating VPN profiles for " + vpn_provider) # Get the list of VPN profile files ovpn_connections = getProfileList(vpn_provider) # 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") for connection in ovpn_connections: try: f = open(connection, 'r+') debugTrace("Processing file " + connection) lines = f.readlines() f.seek(0) f.truncate() # Update the necessary values in the ovpn file for line in lines: if "auth-user-pass" in line: line = "auth-user-pass " + getAddonPathWrapper(vpn_provider + "/" + "pass.txt\n") if "remote " in line: port = "" for newline in lines: if "proto " in newline: if "tcp" in newline and not portTCP == "": port = portTCP if "udp" in newline and not portUDP == "": port = portUDP if not port == "": tokens = line.split() line = "remote " + tokens[1] + " " + port + "\n" f.write(line) f.close() except: errorTrace("profileupdate.py", "Failed to update ovpn file") return False # Write a file to indicate successful update of the ovpn files ovpn_file = open(getAddonPath(True, vpn_provider + "/GENERATED.txt"), 'w') ovpn_file.close() return True
def writeVPNLog(): # Write the openvpn output log to the error file try: log_file = open(getVPNLogFilePath(), 'r') log_output = log_file.readlines() log_file.close() infoTrace("platform.py", "VPN log file start >>>") for line in log_output: print line infoTrace("platform.py", "<<< VPN log file end") except: errorTrace("platform.py", "Couldn't write VPN error log")
def writeVPNLog(): # Write the openvpn output log to the error file try: log_file = open(getVPNLogFilePath(), "r") log_output = log_file.readlines() log_file.close() infoTrace("platform.py", "VPN log file start >>>") for line in log_output: print line infoTrace("platform.py", "<<< VPN log file end") except: errorTrace("platform.py", "Couldn't write VPN error log")
def switchService(): debugTrace("Switching monitor state, current state is " + getVPNMonitorState()) if isVPNMonitorRunning(): setVPNMonitorState("Stopped") addon.setSetting("monitor_paused", "true") infoTrace("addon.py", "VPN monitor service paused") else: setVPNMonitorState("Started") addon.setSetting("monitor_paused", "false") infoTrace("addon.py", "VPN monitor service restarted") xbmc.executebuiltin('Container.Refresh') return
def checkVPNCommand(addon): # Issue the openvpn command and see if the output is a bunch of commands if not fakeConnection(): p = getPlatform() # Issue the openvpn command, expecting to get the options screen back if p == platforms.RPI or p == platforms.LINUX: # Issue Linux command command = getOpenVPNPath() + " > " + getVPNLogFilePath() + " &" if useSudo(): command = "sudo " + command infoTrace("platform.py", "Testing openvpn with : " + command) os.system(command) elif p == platforms.WINDOWS: # Issue Windows command command = getOpenVPNPath() args = shlex.split(command) outfile = open(getVPNLogFilePath(), "w") proc = subprocess.Popen(args, stdout=outfile, creationflags=subprocess.SW_HIDE, shell=True) # **** ADD MORE PLATFORMS HERE **** # Waiting for the log file to appear xbmc.sleep(1000) i = 0 while not xbmcvfs.exists(getVPNLogFilePath()) and i < 10: xbmc.sleep(1000) i = i + 1 # If the log file appears, check it's what we expect if xbmcvfs.exists(getVPNLogFilePath()): log_file = open(getVPNLogFilePath(), "r") log_file_lines = log_file.readlines() log_file.close() i = 0 # Look for a phrase we'd expect to see if the call # worked and the list of options was displayed for line in log_file_lines: if "General Options" in line: return True i = i + 1 # Write the log file in case there's something in it errorTrace("platform.py", "Ran openvpn command and it failed") writeVPNLog() else: errorTrace("platform.py", "Ran openvpn command and VPN log didn't appear") # Display an error message dialog_msg = "The OpenVPN executable isn't working. Check the log, then from a command line prompt type 'openvpn' and fix any problems reported\n" xbmcgui.Dialog().ok(addon.getAddonInfo("name"), dialog_msg) return False else: return True
def writeTestFile(): # Write the command test output to the error file try: log_file = open(getTestFilePath(), 'r') log_output = log_file.readlines() log_file.close() infoTrace("vpnplatform.py", "Command test file start >>>") for line in log_output: infoPrint(line) infoTrace("vpnplatform.py", "<<< Command test file end") except Exception as e: errorTrace("vpnplatform.py", "Couldn't write test file") errorTrace("vpnplatform.py", str(e))
def writeDefaultUpFile(): p = getPlatform() if p == platforms.LINUX or p == platforms.RPI: infoTrace("vpnproviders.py", "Writing default up script") up = open(getAddonPath(True, "up.sh"), 'w') up.write("#!/bin/bash\n") up.write("iptables -F\n") up.write( "iptables -A INPUT -i tun0 -m state --state ESTABLISHED,RELATED -j ACCEPT\n" ) up.write("iptables -A INPUT -i tun0 -j DROP\n") up.close() command = "chmod +x " + getAddonPath(True, "up.sh") if useSudo(): command = "sudo " + command infoTrace("vpnproviders.py", "Fixing default up.sh " + command) os.system(command)
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 getIPInfoFrom(source): # Generate request to find out where this IP is based # Successful return is ip, country, region, city, isp # Otherwise error strings are returned for the caller to parse try: # Determine the URL, make the call and read the response url = getIPSourceURL(source) if url == "": return "error", "error", "error", "unknown source", "" if ifHTTPTrace(): debugTrace("Using " + url) req = Request(url) req.add_header("User-Agent", "Mozilla/5.0 (Windows NT 6.1; WOW64; rv:38.0) Gecko/20100101 Firefox/38.0") response = urlopen(req, timeout = 10) json_data = json.load(response) response.close() if ifJSONTrace(): infoTrace("ipinfo.py", "JSON received is \n" + json.dumps(json_data, indent=4)) except HTTPError as e: errorTrace("ipinfo.py", "Couldn't connect to IP provider " + source) errorTrace("ipinfo.py", "API call was " + url) errorTrace("ipinfo.py", "Response was " + str(e.code) + " " + e.reason) errorTrace("ipinfo.py", e.read()) recordError(source) return "error", "unknown location", "unknown location", "call failed", "unknown ISP" except Exception as e: errorTrace("ipinfo.py", "Couldn't connect to IP provider " + source) errorTrace("ipinfo.py", "API call was " + url) errorTrace("ipinfo.py", "Response was " + str(type(e)) + " " + str(e)) recordError(source) return "no response", "error", "error", "connection failed", "unknown ISP" try: if source == "ipinfo.io": ip, country, region, city, isp = getipinfo(json_data) if source == "IP-API": ip, country, region, city, isp = getIPAPI(json_data) if source == "ipstack": ip, country, region, city, isp = getipstack(json_data) if not ip == None: recordWorking(source) return ip, country, region, city, isp else: errorTrace("ipinfo.py", "Couldn't get data from " + "source") recordError(source) return "no info", "unknown location", "unknown location", "no matches", "unknown ISP" except Exception as e: errorTrace("ipinfo.py", "Couldn't parse response from IP provider " + source) errorTrace("ipinfo.py", str(e)) recordError(source) return "error", "error", "error", "parse failed", "unknown ISP"
def updateVPNFiles(vpn_provider): # If the OVPN files aren't generated then they need to be updated with location info infoTrace("vpnproviders.py", "Updating VPN profiles for " + vpn_provider) # Get the list of VPN profile files ovpn_connections = getProfileList(vpn_provider) # Set ports as default portUDP = "" portTCP = "" for connection in ovpn_connections: try: f = open(connection, 'r+') debugTrace("Processing file " + connection) lines = f.readlines() f.seek(0) f.truncate() # Update the necessary values in the ovpn file for line in lines: if "auth-user-pass" in line: line = "auth-user-pass " + getAddonPathWrapper(vpn_provider + "/" + "pass.txt\n") if "remote " in line: port = "" for newline in lines: if "proto " in newline: if "tcp" in newline and not portTCP == "": port = portTCP if "udp" in newline and not portUDP == "": port = portUDP if not port == "": tokens = line.split() line = "remote " + tokens[1] + " " + port + "\n" f.write(line) f.close() except: errorTrace("profileupdate.py", "Failed to update ovpn file") return False # Write a file to indicate successful update of the ovpn files ovpn_file = open(getAddonPath(True, vpn_provider + "/GENERATED.txt"), 'w') ovpn_file.close() return True
def generateAll(): infoTrace("generation.py", "Generating Location files") generateIPVanish() return generateCyberGhost() generateTorGuard() generateibVPN() generatePP() generateHideMe() generateAirVPN() generatePureVPN() generateLiquidVPN() generatetigerVPN() generateHMA() generateVyprVPN() generateIvacy() generatePIA() generateNordVPN()
def checkPidofCommand(addon): # Disable this for now as kodi.bin may not exist on all systems return True # Only necessary with Linux, sees if pidof is installed/working p = getPlatform() if p == platforms.RPI or p == platforms.LINUX: # Issue Linux command command = getPidofPath() + " kodi.bin > " + getTestFilePath( ) + " 2>&1 &" if useSudo(): command = "sudo " + command infoTrace("vpnplatform.py", "Testing pidof with : " + command) os.system(command) else: return True # Waiting for the log file to appear xbmc.sleep(1000) i = 0 while not xbmcvfs.exists(getTestFilePath()) and i < 10: xbmc.sleep(1000) i = i + 1 # If the log file appears, check it's what we expect if xbmcvfs.exists(getTestFilePath()): log_file = open(getTestFilePath(), 'r') log_file_lines = log_file.readlines() log_file.close() # If this worked, the first line should be a number for line in log_file_lines: line = line.strip() if line.isdigit(): deleteTestFile() return True # Write the log file in case there's something in it errorTrace("vpnplatform.py", "Ran pidof command and it failed") writeTestFile() dialog_msg = "The command 'pidof' is required to run this add-on. Please install it and ensure it's available on the command path." else: errorTrace("vpnplatform.py", "Ran pidof command and the log didn't appear") dialog_msg = "The 'pidof' command isn't writing out a response. Try changing the Kodi log directory setting in Settings-Debug menu and retry." # Display an error message xbmcgui.Dialog().ok(addon.getAddonInfo("name"), dialog_msg) return False
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
def getGitRules(self): if self.addon.getSetting("refresh_rules") == "true": # Download RULES.txt file from Github for i in range(0, 6): try: debugTrace("Getting rules from Github") download_url = "https://raw.githubusercontent.com/Zomboided/service.zomboided.tools/master/RULES.txt" download_url = download_url.replace(" ", "%20") download_rules = urllib2.urlopen(download_url) break except urllib2.HTTPError as e: errorTrace("rules.py", "Can't get the rules from Github") errorTrace("rules.py", "API call was " + download_url) errorTrace("rules.py", "Response was " + str(e.code) + " " + e.reason) errorTrace("rules.py", e.read()) except Exception as e: errorTrace("rules.py", "Can't get the rules from Github") errorTrace("rules.py", "API call was " + download_url) errorTrace("rules.py", "Response was " + str(type(e)) + " " + str(e)) finally: # Give up if this is the last time round if i == 5: errorTrace( "rules.py", "Can't get rules from Github, using existing set") return # Otherwise wait 30 seconds before trying to get the rules again xbmc.sleep(30000) try: # Overwrite RULES.txt output = open(RULES_PATH, 'w') for r in download_rules: output.write(r) output.close() infoTrace("rules.py", "Updated the rules file from GitHub") except Exception as e: errorTrace( "rules.py", "Couldn't write the rules files downloaded from Github") errorTrace("rules.py", str(e))
def checkKillallCommand(addon): # Only necessary with Linux, sees if killall is installed/working p = getPlatform() if p == platforms.RPI or p == platforms.LINUX: # Issue Linux command command = getKillallPath() + " vpnmanagertest > " + getTestFilePath( ) + " 2>&1 &" if useSudo(): command = "sudo " + command infoTrace("vpnplatform.py", "Testing killall with : " + command) os.system(command) else: return True # Waiting for the log file to appear xbmc.sleep(1000) i = 0 while not xbmcvfs.exists(getTestFilePath()) and i < 10: xbmc.sleep(1000) i = i + 1 # If the log file appears, check it's what we expect if xbmcvfs.exists(getTestFilePath()): log_file = open(getTestFilePath(), 'r') log_file_lines = log_file.readlines() log_file.close() # Look for a phrase we'd expect to see if the call # worked and a killall error message was displayed for line in log_file_lines: if "vpnmanagertest" in line: deleteTestFile() return True # Write the log file in case there's something in it errorTrace("vpnplatform.py", "Ran killall command and it failed") writeTestFile() dialog_msg = "The command 'killall' is required to run this add-on. Please install it and ensure it's available on the command path." else: errorTrace("vpnplatform.py", "Ran killall command and the log didn't appear") dialog_msg = "The 'killall' command isn't writing out a response. Try changing the Kodi log directory setting in Settings-Debug menu and retry." # Display an error message xbmcgui.Dialog().ok(addon.getAddonInfo("name"), dialog_msg) return False
def renewNordVPN(renew): # Renew a user with the API and store the tokens returned response = "" try: download_url = "https://api.nordvpn.com/v1/users/tokens/renew" download_data = "renewToken=" + renew if ifHTTPTrace(): infoTrace("alternativeNord.py", "Renewing authentication using " + download_url + ", " + download_data) else: debugTrace("Renewing authentication") req = Request(download_url, download_data) t_before = now() response = urlopen(req, timeout=10) user_data = json.load(response) t_after = now() response.close() if ifJSONTrace(): infoTrace("alternativeNord.py", "JSON received is \n" + json.dumps(user_data, indent=4)) if t_after - t_before > TIME_WARN: infoTrace("alternativeNord.py", "Renewing authentication took " + str(t_after - t_before) + " seconds") setTokens(user_data["token"], user_data["renew_token"], None) return True except HTTPError as e: errorTrace("alternativeNord.py", "Couldn't renew user token") errorTrace("alternativeNord.py", "API call was " + download_url + ", " + download_data[:download_data.index("renewToken")+11] + "********") errorTrace("alternativeNord.py", "Response was " + str(e.code) + " " + e.reason) errorTrace("alternativeNord.py", e.read()) except Exception as e: errorTrace("alternativeNord.py", "Couldn't renew user token") errorTrace("alternativeNord.py", "API call was " + download_url + ", " + download_data[:download_data.index("renewToken")+11] + "********") errorTrace("alternativeNord.py", "Response was " + str(type(e)) + " " + str(e)) resetTokens() return False
def getNordVPNUserPass(vpn_provider): # Download the opvn file try: download_url = "https://api.nordvpn.com/v1/users/services/credentials" if ifHTTPTrace(): infoTrace("alternativeNord.py", "Getting user credentials " + download_url) else: debugTrace("Getting user credentials") token = getTokenNordVPN() req = Request(download_url) req.add_header("Authorization", "token:" + token) t_before = now() response = urlopen(req, timeout=10) user_data = json.load(response) t_after = now() response.close() if ifJSONTrace(): infoTrace("alternativeNord.py", "JSON received is \n" + json.dumps(user_data, indent=4)) if t_after - t_before > TIME_WARN: infoTrace("alternativeNord.py", "Getting user credentials took " + str(t_after - t_before) + " seconds") return user_data["username"], user_data["password"] except HTTPError as e: errorTrace("alternativeNord.py", "Couldn't get user credentials") errorTrace("alternativeNord.py", "API call was " + download_url) errorTrace("alternativeNord.py", "Response was " + str(e.code) + " " + e.reason) errorTrace("alternativeNord.py", e.read()) return "", "" except Exception as e: errorTrace("alternativeNord.py", "Couldn't get user credentials") errorTrace("alternativeNord.py", "API call was " + download_url) errorTrace("alternativeNord.py", "Response was " + str(type(e)) + " " + str(e)) return "", ""
def checkVPNCommand(addon): # Issue the openvpn command and see if the output is a bunch of commands if not fakeConnection(): p = getPlatform() if p == platforms.RPI or p == platforms.LINUX: # Issue the openvpn command, expecting to get the options screen back command = getOpenVPNPath() + " > " + getVPNLogFilePath() + " &" infoTrace("platform.py", "Testing openvpn with : " + command) os.system(command) xbmc.sleep(1000) i = 0 # Waiting for the log file to appear while not xbmcvfs.exists(getVPNLogFilePath()) and i < 10: xbmc.sleep(1000) i = i + 1 # If the log file appears, check it's what we expect if xbmcvfs.exists(getVPNLogFilePath()): log_file = open(getVPNLogFilePath(), 'r') log_file_lines = log_file.readlines() log_file.close() i = 0 # Look for a phrase we'd expect to see if the call # worked and the list of options was displayed for line in log_file_lines: if "General Options" in line: return True i = i + 1 # Write the log file in case there's something in it errorTrace("platform.py", "Ran openvpn command and it failed") writeVPNLog() # **** ADD MORE PLATFORMS HERE **** # Display an error message dialog_msg = "The OpenVPN executable isn't working. Check the log, then from a command line prompt type 'openvpn' and fix any problems reported\n" xbmcgui.Dialog().ok(addon.getAddonInfo("name"), dialog_msg) return False else: return True
def generateAll(): infoTrace("generation.py", "Generating Location files") generateBTGuard() return generateVPNUnlim() generateHideMe() generatePIA() generateLimeVPN() generateHideIPVPN() generateVyprVPN() generateIvacy() generateCyberGhost() generateTorGuard() generateibVPN() generatePP() generateAirVPN() generatePureVPN() generateLiquidVPN() generatetigerVPN() generateHMA() generateIPVanish() generateNordVPN()
def authenticateNordVPN(vpn_provider, userid, password): # Authenticate with the API and store the tokens returned # If the same credentials have been used before, don't bother authenticating _, _, _, creds = getTokens() if creds == vpn_provider + userid + password: debugTrace("Previous authentication was good") return True response = "" try: download_url = "https://api.nordvpn.com/v1/users/tokens" download_data = urllib.urlencode({ 'username': userid, 'password': password }) if ifHTTPTrace(): infoTrace( "alternativeNord.py", "Authenticating with VPN using " + download_url + ", " + download_data) else: debugTrace("Authenticating with VPN for user " + userid) req = urllib2.Request(download_url, download_data) t_before = now() response = urllib2.urlopen(req, timeout=10) user_data = json.load(response) t_after = now() response.close() if ifJSONTrace(): infoTrace("alternativeNord.py", "JSON received is \n" + json.dumps(user_data, indent=4)) if t_after - t_before > TIME_WARN: infoTrace( "alternativeNord.py", "Authenticating with VPN for " + userid + " took " + str(t_after - t_before) + " seconds") setTokens(user_data["token"], user_data["renew_token"], None) setTokens(user_data["token"], user_data["renew_token"], vpn_provider + userid + password) return True except urllib2.HTTPError as e: errorTrace("alternativeNord.py", "Couldn't authenticate with " + vpn_provider) errorTrace( "alternativeNord.py", "API call was " + download_url + ", " + download_data[:download_data.index("&password") + 10] + "********") errorTrace("alternativeNord.py", "Response was " + str(e.code) + " " + e.reason) errorTrace("alternativeNord.py", e.read()) except Exception as e: errorTrace("alternativeNord.py", "Couldn't authenticate with " + vpn_provider) errorTrace( "alternativeNord.py", "API call was " + download_url + ", " + download_data[:download_data.index("&password") + 10] + "********") errorTrace("alternativeNord.py", "Response was " + str(type(e)) + " " + str(e)) resetTokens() return False
def copyLog(): addon = xbmcaddon.Addon("service.zomboided.tools") addon_name = addon.getAddonInfo("name") # Copy the log file log_path = "" dest_path = "" try: log_path = xbmc.translatePath("special://logpath/kodi.log") start_dir = "" dest_folder = xbmcgui.Dialog().browse( 0, "Select folder to copy log file into", "files", "", False, False, start_dir, False) dest_path = "kodi " + datetime.datetime.now().strftime( "%y-%m-%d %H-%M-%S") + ".log" dest_path = dest_folder + dest_path.replace(" ", "_") debugTrace("Copying " + log_path + " to " + dest_path) addon = xbmcaddon.Addon("service.zomboided.tools") infoTrace( "managefiles.py", "Copying log file to " + dest_path + ". Using version " + addon.getSetting("version_number")) xbmcvfs.copy(log_path, dest_path) if not xbmcvfs.exists(dest_path): raise IOError('Failed to copy log ' + log_path + " to " + dest_path) dialog_message = "Copied log file to:\n" + dest_path except: errorTrace("managefiles.py", "Failed to copy log from " + log_path + " to " + dest_path) if xbmcvfs.exists(log_path): dialog_message = "Error copying log, try copying it to a different location." else: dialog_messsage = "Could not find the kodi.log file." errorTrace("managefiles.py", dialog_message + " " + log_path + ", " + dest_path) xbmcgui.Dialog().ok("Log Copy", dialog_message)
def fixKeymaps(): # Fix the keymap file name if it's been changed or the old name was being used name = getKeyMapsFileName() dir = getKeyMapsPath("*") full_name = getKeyMapsPath(name) try: debugTrace("Getting contents of keymaps directory " + dir) files = (glob(dir)) if not full_name in files and len(files) > 0: for file in files: if (name in file): infoTrace("common.py", "Renaming " + file + " to " + full_name) xbmcvfs.rename(file, full_name) xbmc.sleep(100) # Wait 10 seconds for rename to happen otherwise quit and let it fail in the future for i in range(0, 9): if xbmcvfs.exists(full_name): break xbmc.sleep(1000) return True except Exception as e: errorTrace("common.py", "Problem fixing the keymap filename") errorTrace("common.py", str(e)) return False
def generateAll(): infoTrace("generation.py", "Generating Location files") generateRA4W() generateVPNSecure() generateIPVanish() generateHideIPVPN() generateExpressVPN() generateSecureVPN() generateLimeVPN() generateSecureVPN() generateNordVPN() generateIVPN() generateproXPN() generatePureVPN() generateWiTopia() generateVPNht() generateTotalVPN() generateCelo() generateSaferVPN() generateVyprVPN() generateBTGuard() generateVPNUnlim() generateHideMe() generateHideIPVPN() generateVyprVPN() generateCyberGhost() generateTorGuard() generateibVPN() generatePP() generateAirVPN() generatePIA() generateLiquidVPN() generatetigerVPN() generateHMA() generateIPVanish() return
def resetVPNConnections(addon): # Reset all connection information so the user is forced to revalidate everything infoTrace("resetVPN.py", "Resetting all validated VPN settings and disconnected existing VPN connections") forceCycleLock() resetVPNConfig(addon, 1) # Remove any last connect settings setVPNLastConnectedProfile("") setVPNLastConnectedProfileFriendly("") # Removal any password files that were created (they'll get recreated if needed) debugTrace("Deleting all pass.txt files") cleanPassFiles() # No need to stop/start monitor, just need to let it know that things have changed. # Because this is a reset of the VPN, the monitor should just work out it has no good connections updateService() debugTrace("Stopping any active VPN connections") stopVPNConnection() freeCycleLock() xbmcgui.Dialog().notification(addon.getAddonInfo("name"), "Disconnected", getIconPath()+"disconnected.png", 5000, False)
def sendAPI(command, command_text, api_data, check_response): # Common routine to send an API command try: response = "" rc = True rest_url = REQUEST_URL + command auth_token,_,_,_ = getTokens() # Login again if the token is blank and the command is not login anyway if auth_token == "" and not "=login" in command: debugTrace("Logging in again because auth token not valid") addon = xbmcaddon.Addon(getID()) rc = authenticateShellfire(addon.getSetting("vpn_provider"), addon.getSetting("vpn_username"), addon.getSetting("vpn_password")) auth_token,_,_,_ = getTokens() if auth_token == "" or not rc: raise Exception(command_text + " was not authorized") if ifHTTPTrace(): infoTrace("alternativeShellfire.py", command_text + " " + rest_url) else: debugTrace(command_text) req = urllib2.Request(rest_url, api_data, REQUEST_HEADERS) if not auth_token == "": req.add_header("x-authorization-token", auth_token) t_before = now() response = urllib2.urlopen(req) api_data = json.load(response) t_after = now() response.close() # Trace if the command took a long time if ifJSONTrace(): infoTrace("alternativeShellfire.py", "JSON received is \n" + json.dumps(api_data, indent=4)) if t_after - t_before > TIME_WARN: infoTrace("alternativeShellfire.py", command_text + " took " + str(t_after - t_before) + " seconds") # Check the response and fail if it's bad if check_response: if not api_data["status"] == "success": raise Exception(command_text + " returned bad response, " + api_data["status"]) except urllib2.HTTPError as e: errorTrace("alternativeShellfire.py", command_text + " failed") errorTrace("alternativeShellfire.py", "API call was " + rest_url) if not api_data == "": errorTrace("alternativeShellfire.py", "Data returned was \n" + json.dumps(api_data, indent=4)) errorTrace("alternativeShellfire.py", "Response was " + str(e.code) + " " + e.reason) errorTrace("alternativeShellfire.py", e.read()) rc = False except Exception as e: errorTrace("alternativeShellfire.py", command_text + " failed") errorTrace("alternativeShellfire.py", "API call was " + rest_url) if not api_data == "": errorTrace("alternativeShellfire.py", "Data returned was \n" + json.dumps(api_data, indent=4)) errorTrace("alternativeShellfire.py", "Response was " + str(type(e)) + " " + str(e)) rc = False return rc, api_data
def writeVPNConfiguration(ovpn): # Write the openvpn configuration to the error file try: if xbmcvfs.exists(ovpn): ovpn_file = open(ovpn, 'r') ovpn_output = ovpn_file.readlines() ovpn_file.close() infoTrace("vpnplatform.py", "VPN configuration " + ovpn + " start >>>") for line in ovpn_output: line = line.strip("\n") infoPrint(line) infoTrace("vpnplatform.py", "<<< VPN configuration file end") else: infoTrace("vpnplatform.py", "No VPN configuration " + ovpn + " exists to write") except Exception as e: errorTrace("vpnplatform.py", "Couldn't write VPN error log") errorTrace("vpnplatform.py", str(e))
def writeVPNLog(): # Write the openvpn output log to the error file try: if xbmcvfs.exists(getVPNLogFilePath()): log_file = open(getVPNLogFilePath(), 'r') log_output = log_file.readlines() log_file.close() infoTrace("vpnplatform.py", "VPN log file start >>>") for line in log_output: line = line.strip("\n") infoPrint(line) infoTrace("vpnplatform.py", "<<< VPN log file end") else: infoTrace("vpnplatform.py", "No VPN log file exists to write") except Exception as e: errorTrace("vpnplatform.py", "Couldn't write VPN error log") errorTrace("vpnplatform.py", str(e))
if __name__ == '__main__': # Initialise some variables we'll be using repeatedly monitor = xbmc.Monitor() player = xbmc.Player() addon = xbmcaddon.Addon() # See if this is a new install...we might want to do things here if xbmcvfs.exists(getAddonPath(True, "INSTALL.txt")): xbmcvfs.delete(getAddonPath(True, "INSTALL.txt")) # This is just wiping out the old way of using pre-generated ovpn files before # moving to the brave new world of generating them when they're needed if addon.getSetting("version_number") == "": infoTrace("service.py", "Resetting the world for 0.1.0, found " + addon.getSetting("version_number")) cleanPassFiles() removeGeneratedFiles() resetVPNConfig(addon, 1) xbmcgui.Dialog().ok(addon_name, "This particular update to VPN Manager for OpenVPN requires that all VPN connections are re-validated before use. Sorry about that, won't happen again...") xbmc.executebuiltin("Addon.OpenSettings(service.vpn.manager)") # PIA changed in 1.5.0 to offer different options. If PIA is using the old connections, force a reconnection if addon.getSetting("vpn_provider_validated") == "Private Internet Access" and addon.getSetting("vpn_locations_list") == "": addon.setSetting("1_vpn_validated", "reset") addon.setSetting("version_number", addon.getAddonInfo("version")) # If the addon was running happily previously (like before an uninstall/reinstall or update) # then regenerate the OVPNs for the validated provider. primary_path = addon.getSetting("1_vpn_validated") if not primary_path == "" and not xbmcvfs.exists(primary_path):
if __name__ == '__main__': # Initialise some variables we'll be using repeatedly monitor = xbmc.Monitor() player = xbmc.Player() #command = 'chmod +x ' + str(getAddonPath(True, vpn_provider + "/dnsLeak.py")) # See if this is a new install...we might want to do things here if xbmcvfs.exists(getAddonPath(True, "INSTALL.txt")): xbmcvfs.delete(getAddonPath(True, "INSTALL.txt")) # This is just wiping out the old way of using pre-generated ovpn files before # moving to the brave new world of generating them when they're needed if addon.getSetting("version_number") == "": infoTrace( "service.py", "Resetting the world for 0.1.0, found " + addon.getSetting("version_number")) cleanPassFiles() removeGeneratedFiles() resetVPNConfig(addon, 1) xbmcgui.Dialog().ok( addon_name, "This particular update to PureVPN for Kodi requires that all VPN connections are re-validated before use. Sorry about that, won't happen again..." ) defCred() xbmc.executebuiltin("Addon.OpenSettings(service.purevpn.monitor)") addon.setSetting("version_number", addon.getAddonInfo("version")) # If the addon was running happily previously (like before an uninstall/reinstall or update) # then regenerate the OVPNs for the validated provider.
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # # This module kicks the VPN Manager for OpenVPN background monitor # service to get it to re-read the configuration details. import xbmcgui import xbmcaddon from libs.common import updateService from libs.utility import debugTrace, errorTrace, infoTrace debugTrace("-- Entered recycle.py --") # Get info about the addon that this script is pretending to be attached to addon = xbmcaddon.Addon("service.vpn.manager") addon_name = addon.getAddonInfo("name") # Reset the VPN connection values stored in the settings.xml xbmcgui.Dialog().notification(addon_name, "VPN monitor using updated settings.", xbmcgui.NOTIFICATION_INFO, 3000) # No need to stop/start monitor, just need to let the monitor know things have changed infoTrace("recycle.py", "Requested update to service process") updateService() xbmc.executebuiltin("Addon.OpenSettings(service.vpn.manager)") debugTrace("-- Exit recycle.py --")
def updateVPNFiles(vpn_provider): # If the OVPN files aren't generated then they need to be updated with location info infoTrace("vpnproviders.py", "Updating VPN profiles for " + vpn_provider) # Get the list of VPN profile files ovpn_connections = getAddonList(vpn_provider, "*.ovpn") # 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) for connection in ovpn_connections: try: f = open(connection, 'r+') debugTrace("Processing file " + connection) lines = f.readlines() f.seek(0) f.truncate() # Get the profile friendly name in case we need to generate key/cert names name = connection[connection.rfind(getSeparator())+1:] # Update the necessary values in the ovpn file for line in lines: # Update path to pass.txt if not isUserDefined(vpn_provider) or addon.getSetting("user_def_credentials") == "true": if line.startswith("auth-user-pass"): line = "auth-user-pass " + getAddonPathWrapper(vpn_provider + "/" + "pass.txt\n") # Update port numbers if line.startswith("remote "): port = "" for newline in lines: if "proto " in newline: if "tcp" in newline and not portTCP == "": port = portTCP if "udp" in newline and not portUDP == "": port = portUDP if not port == "": tokens = line.split() line = "remote " + tokens[1] + " " + port + "\n" # Update user cert and key if usesUserKeys(vpn_provider): if line.startswith("cert "): line = "cert " + getUserDataPathWrapper(vpn_provider + "/" + getCertName(vpn_provider, name) + "\n") if line.startswith("key "): line = "key " + getUserDataPathWrapper(vpn_provider + "/" + getKeyName(vpn_provider, name) + "\n") # For user defined profile we need to replace any path tags with the addon dir path if isUserDefined(vpn_provider): line = line.replace("#PATH", getAddonPathWrapper(vpn_provider)) # Set the logging level if line.startswith("verb "): line = "verb " + verb_value + "\n" f.write(line) f.close() except: errorTrace("vpnproviders.py", "Failed to update ovpn file") return False # Flag that the files have been generated writeGeneratedFile(vpn_provider) return True
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 getShellfirePreFetch(vpn_provider): # Fetch and store location info filename = getAddonPath(True, vpn_provider + "/" + SHELLFIRE_LOCATIONS) if xbmcvfs.exists(filename): try: st = xbmcvfs.Stat(filename) create_time = int(st.st_ctime()) t = now() # Fetch again if this is more than a day old otherwise use what there is if create_time + 86400 < t: debugTrace("Create time of " + filename + " is " + str(create_time) + " time now is " + str(t) + ", fetching location data again") else: debugTrace("Create time of " + filename + " is " + str(create_time) + " time now is " + str(t) + ", using existing data") # Less than a day old, so using the existing file return True except Exception as e: errorTrace("alternativeShellfire.py", "List of countries exist but couldn't get the time stamp for " + filename) errorTrace("alternativeShellfire.py", str(e)) return False # Download the list of locations error = True try: response = "" api_data = "" rest_url = "https://www.shellfire.de/webservice/serverlist.php" if ifHTTPTrace(): infoTrace("alternativeShellfire.py", "Downloading list of locations using " + rest_url) else: debugTrace("Downloading list of locations") # This is not a JSON call, a header and servers are returned in a ; separated list req = urllib2.Request(rest_url, "", REQUEST_HEADERS) t_before = now() response = urllib2.urlopen(req) api_data = response.read() t_after = now() response.close() if ifJSONTrace(): infoTrace("alternativeShellfire.py", "Text received is \n" + api_data) if t_after - t_before > TIME_WARN: infoTrace("alternativeShellfire.py", "Retrieving list of locations took " + str(t_after - t_before) + " seconds") except urllib2.HTTPError as e: errorTrace("alternativeShellfire.py", "Couldn't retrieve the list of locations") errorTrace("alternativeShellfire.py", "API call was " + rest_url) if not api_data == "": errorTrace("alternativeShellfire.py", "Data returned was \n" + api_data) errorTrace("alternativeShellfire.py", "Response was " + str(e.code) + " " + e.reason) errorTrace("alternativeShellfire.py", e.read()) return False except Exception as e: errorTrace("alternativeShellfire.py", "Couldn't retrieve the list of locations") errorTrace("alternativeShellfire.py", "API call was " + rest_url) if not api_data == "": errorTrace("alternativeShellfire.py", "Data returned was \n" + api_data) errorTrace("alternativeShellfire.py", "Response was " + str(type(e)) + " " + str(e)) return False # The first line has the headers, so find the position of the information that's interesting api_table = api_data.split("\n") headers = api_table[0].split(";") id_pos = headers.index("iVpnServerId") country_pos = headers.index("Country") city_pos = headers.index("sCity") host_pos = headers.index("sHost") type_pos = headers.index("eServerType") debugTrace("Header decoded. ID is " + str(id_pos) + ", Country is " + str(country_pos) + ", City is " + str(city_pos) + ", Host is " + str(host_pos) + ", Type is " + str(type_pos)) api_table[0] = "" try: line = "" cleaned_data = [] debugTrace("Parsing the text and extracting the country, server and type") for line in api_table: server_data = line.split(";") # Avoid parsing empty lines, or lines where there's not enough data if len(server_data) > 5: cleaned_data.append(server_data[country_pos] + " - " + server_data[city_pos] + " (S" + server_data[id_pos] + ")," + server_data[host_pos] + "," + server_data[type_pos] + "," + server_data[id_pos] + "\n") except Exception as e: errorTrace("alternativeShellfire`.py", "Couldn't parse the list of locations for " + vpn_provider) if not server_data == "": errorTrace("alternativeShellfire.py", "Processing line " + line) errorTrace("alternativeShellfire.py", str(e)) return False # Sort the locations alphabetically cleaned_data.sort() try: line = "" debugTrace("Parsing the text and writing the list of locations") output = open(filename, 'w') # Parse the data and create list containing the stuff we care about for line in cleaned_data: output.write(line) output.close() return True except Exception as e: errorTrace("alternativeShellfire`.py", "Couldn't write the list of locations for " + vpn_provider + " to " + filename) if not server_data == "": errorTrace("alternativeShellfire.py", "Processing server " + line) errorTrace("alternativeShellfire.py", str(e)) # Delete the location file if the was a problem creating it. This will force a download next time through try: if xbmcvfs.exists(filename): errorTrace("alternativeShellfire.py", "Deleting location file " + filename + " to clean up after previous error") xbmcvfs.delete(filename) except Exception as e: errorTrace("alternativeShellfire.py", "Couldn't delete the location file " + filename) errorTrace("alternativeShellfire.py", str(e)) return False
xbmcgui.Dialog().ok(addon_name, "Source file does not exist\nFile : " + source) else: # Open the file and get the size of it try: debugTrace("Opening file " + source) file = xbmcvfs.File(source, "r") total_size = file.size() except: errorTrace("speedtest.py", "Error opening file " + source) total_size = -1 # Only run the test if the file is bigger than 50MB if total_size > (one_mb * 50): infoTrace("speedtest.py", "Running speed test with " + source) progress = xbmcgui.DialogProgress() progress_title = "Running speed test" progress.create(addon_name,progress_title) total_read = 0 total_to_mb = 0 percent = 0 time_start = time.clock() last_time = time_start transfer_speed = 0 bytes_read = file.read(chunk_size) while bytes_read: bytes_read = file.read(chunk_size) total_read = total_read + chunk_size
# Copy the log file elif action == "log": log_path = "" dest_path = "" try: log_path = getLogPath() start_dir = "" dest_folder = xbmcgui.Dialog().browse(0, "Select folder to copy log file into", "files", "", False, False, start_dir, False) dest_path = "kodi " + datetime.datetime.now().strftime("%y-%m-%d %H-%M-%S") + ".log" dest_path = dest_folder + dest_path.replace(" ", "_") # Write VPN log to log before copying writeVPNLog() debugTrace("Copying " + log_path + " to " + dest_path) addon = xbmcaddon.Addon("service.vpn.manager") infoTrace("managefiles.py", "Copying log file to " + dest_path + ". Using version " + addon.getSetting("version_number")) xbmcvfs.copy(log_path, dest_path) dialog_message = "Copied log file to:\n" + dest_path except: errorTrace("Failed to copy log from " + log_path + " to " + dest_path) if xbmcvfs.exists(log_path): dialog_message = "Error copying log, try copying it to a different location." else: dialog_messsage = "Could not find the kodi.log file." errorTrace("managefiles.py", dialog_message + " " + log_path + ", " + dest_path) xbmcgui.Dialog().ok("Log Copy", dialog_message) # Delete the user key and cert files elif action == "user": if addon.getSetting("1_vpn_validated") == "" or xbmcgui.Dialog().yesno(addon_name, "Deleting key and certificate files will reset all VPN connections. Connections must be re-validated before use.\nContinue?"):
def importWizard(): addon = xbmcaddon.Addon(getID()) addon_name = getName() errorMessage = "" success = False cancel = False xbmcgui.Dialog().ok(addon_name, "The User Defined import wizard helps you set up an unsupported VPN provider. It may not work without additional user intervention. You should review the import log and subsequent VPN logs to debug any problems.") # Warn the user that files will be deleted and kittens will be harmed if xbmcgui.Dialog().yesno(addon_name, "Any existing User Defined settings and files will be deleted. Do you want to continue?"): removeGeneratedFiles() success = clearUserData() addon.setSetting("vpn_provider", "User Defined") if not success: errorMessage = "Could not clear the UserDefined directory. Check the log." else: success = False errorMessage = "Import wizard has not been run, no settings or files have been changed." # Get the list of files to be used if success: if xbmcgui.Dialog().yesno(addon_name, "Select ALL files needed to connect to the VPN provider, including .ovpn, .key and .crt files. Select a directory (sub directories are ignored) or select multiple files within a directory?.", nolabel="Directory", yeslabel="Files"): directory_input = False files = xbmcgui.Dialog().browse(1, "Select all VPN provider files", "files", "", False, False, "", True) else: directory_input = True dname = xbmcgui.Dialog().browse(0, "Select a directory containing VPN provider files", "files", "", False, False, "", False) debugTrace("Import from directory " + dname) dirs, files = xbmcvfs.listdir(dname) # Separate the selected files into ovpn files and other files ovpn_files = [] other_files = [] for name in files: if directory_input: name = dname + name debugTrace("Found file " + name) if name.endswith(".ovpn"): ovpn_files.append(name) else: other_files.append(name) if len(ovpn_files) == 0: success = False errorMessage = "No .ovpn files found. You must provide at least one .ovpn file." # Copy and modify the ovpn files if success: # Create some logs to write out later summary = [] detail = [] summary.append("Importing selected files to User Defined directory, " + getUserDataPath("UserDefined/") + "\n") summary.append("at " + time.strftime('%Y-%m-%d %H:%M:%S') + "\n") detail.append("\n=== Import details ===\n\n") update = False rename = False if not xbmcgui.Dialog().yesno(addon_name, "Update the .ovpn files to best guess values and determine the best User Defined provider settings [I](recommended)[/I]?", nolabel="Yes", yeslabel="No"): update = True detail.append("Updating the .ovpn files to best guess settings\n") if not xbmcgui.Dialog().yesno(addon_name, "Rename the .ovpn files to indicate either a UDP or TCP connection type to allow filtering of connections [I](recommended)[/I]?", nolabel="Yes", yeslabel="No"): rename = True detail.append("Files will be renamed to indicate UDP or TCP\n") # Display dialog to show progress of copying files dialog_step = 100/(len(ovpn_files) + len(other_files)) progress = xbmcgui.DialogProgress() progress_title = "Copying User Defined files." progress.create(addon_name,progress_title) prog_step = 0 xbmc.sleep(500) try: dest_path = getUserDataPath("UserDefined/") debugTrace("Checking directory path exists before copying " + dest_path) if not os.path.exists(dest_path): infoTrace("userdefined.py", "Creating " + dest_path) os.makedirs(os.path.dirname(dest_path)) xbmc.sleep(500) # Loop around waiting for the directory to be created. After 10 seconds we'll carry # on and let he open file calls fail and throw an exception t = 0 while not os.path.exists(os.path.dirname(dest_path)): if t == 9: errorTrace("userdefined.py", "Waited 10 seconds to create directory but it never appeared") break xbmc.sleep(1000) t += 1 other_files_count = [] for fname in other_files: path, dest_name = os.path.split(fname) dest_name = getUserDataPath("UserDefined/" + dest_name) # Report file being copied, then do it progress_message = "Copying " + fname progress.update(prog_step, progress_title, progress_message) xbmc.sleep(100) prog_step += dialog_step infoTrace("userdefined.py", "Copying " + fname + " to " + dest_name) detail.append("Copying " + fname + " to " + dest_name + "\n") xbmcvfs.copy(fname, dest_name) if not xbmcvfs.exists(dest_name): raise IOError('Failed to copy user def file ' + fname + " to " + dest_name) other_files_count.append(0) if progress.iscanceled(): cancel = True break auth_count = 0 auth_found = 0 cert_count = 0 cert_found = 0 multiple_certs = False last_cert_found = "" ecert_count = 0 key_count = 0 key_found = 0 key_pass_found = 0 key_pass_count = 0 multiple_keys = False last_key_found = "" ekey_count = 0 if not cancel: metadata = getGitMetaData("UserDefined") mods = [] if not metadata == None: for line in metadata: line = line.strip(' \t\n\r') mods.append(line) for oname in ovpn_files: path, dest_name = os.path.split(oname) dest_name = getUserDataPath("UserDefined/" + dest_name) # Update dialog to saywhat's happening if update: progress_message = "Copying and updating " + oname else: progress_message = "Copying " + oname progress.update(prog_step, progress_title, progress_message) xbmc.sleep(100) prog_step += dialog_step # Copy the ovpn file infoTrace("userdefined.py", "Copying " + oname + " to " + dest_name) detail.append("Copying " + oname + " to " + dest_name + "\n") xbmcvfs.copy(oname, dest_name) if not xbmcvfs.exists(dest_name): raise IOError('Failed to copy user def ovpn ' + oname + " to " + dest_name) if update: # Read the copied file in and then overwrite it with any updates needed # Was doing a read from source and write here but this failed on Linux over an smb mount (file not found) auth = False keypass = False infoTrace("userdefined.py", "Updating " + dest_name) detail.append("Updating " + dest_name + "\n") source_file = open(dest_name, 'r') source = source_file.readlines() source_file.close() dest_file = open(dest_name, 'w') proto = "UDP" flags = [False, False, False, False, False] for line in source: line = line.strip(' \t\n\r') old_line = line i = 0 # Look for each non ovpn file uploaded and update it to make sure the path is good for fname in other_files: path, name = os.path.split(fname) if not line.startswith("#"): params = line.split() if len(params) > 2: # Remove the separator in order to get any fully qualified filename as space delimited params[1].replace(getSeparator(), " ") # Add in a leading space for unqualified filenames params[1] = " " + params[1] if params[1].endswith(" " + name): old_line = line line = params[0] + " " + "#PATH" + getSeparatorOutput() + name # Add any trailing parameters back in if len(params) > 2: for i in range(2, len(params)): line = line + " " + params[i] detail.append(" Found " + name + ", old line was : " + old_line + "\n") detail.append(" New line is " + line + "\n") other_files_count[i] += 1 if line.startswith("auth-user-pass"): auth_found += 1 auth = True if line.startswith("cert "): cert_found += 1 if line.startswith("key "): key_found += 1 if line.startswith("askpass "): key_pass_found += 1 keypass = True i += 1 # Do some tag counting to determine authentication methods to use if not line.startswith("#"): for mod in mods: flag, verb, parms = mod.split(",") if flag == "1" and line.startswith(verb) and parms in line: flags[0] = True if flag == "3" and line.startswith(verb): flags[2] = True if flag == "4" and line.startswith(verb): line = verb + " " + parms if flag == "5" and not flags[4] and verb in line: detail.append(" WARNING, " + parms + "\n") flags[4] = True if line.startswith("auth-user-pass"): auth_count += 1 if not auth: line = "auth-user-pass #PATH" + getSeparatorOutput() + "pass.txt" if line.startswith("cert "): cert_count += 1 if not last_cert_found == old_line: if not last_cert_found == "": multiple_certs = True last_cert_found = old_line if line.startswith("key "): key_count += 1 if not last_key_found == old_line: if not last_key_found == "": multiple_keys = True last_key_found = old_line if line.startswith("askpass"): key_pass_count += 1 if not keypass: line = "askpass #PATH" + getSeparatorOutput() + "key.txt" if line.startswith("proto "): if "tcp" in (line.lower()): proto = "TCP" if line.startswith("<cert>"): ecert_count += 1 if line.startswith("<key>"): ekey_count += 1 if not flags[2]: dest_file.write(line+"\n") flags[2] = False for mod in mods: flag, verb, parms = mod.split(",") if flag == "2": dest_file.write(verb+"\n") dest_file.close() flags[4] = False if flags[0]: if xbmcvfs.exists(dest_name): xbmcvfs.delete(dest_name) detail.append(" wARNING, couldn't import file as it contains errors or is unsupported\n") elif rename: proto = " (" + proto + ").ovpn" new_name = dest_name.replace(".ovpn", proto) if not xbmcvfs.exists(new_name): xbmcvfs.rename(dest_name, new_name) detail.append(" Renamed to " + new_name + "\n") else: detail.append(" WARNING, couldn't rename file to " + new_name + " as a file with that name already exists\n") if progress.iscanceled(): cancel = True break except Exception as e: errorTrace("userdefined.py", "Failed to copy (or update) file") errorTrace("userdefined.py", str(e)) success = False errorMessage = "Failed to copy (or update) selected files. Check the log." progress_message = "Outputting results of import wizard" progress.update(100, progress_title, progress_message) xbmc.sleep(500) # General import results summary.append("\n=== Summary of import ===\n\n") if cancel: summary.append("Import was cancelled\n") else: summary.append("Imported " + str(len(ovpn_files)) + " .ovpn files and " + str(len(other_files)) + " other files.\n") summary.append("\nYou should understand any WARNINGs below, and validate that the .ovpn files imported have been updated correctly.\n\n") summary.append("If the VPN connection fails view the VPN log to determine why, using Google to understand the errors if necessary.\n") summary.append("You can fix problems either by editing your local files and re-importing, or by editing the contents of the User Defined directory.\n\n") if update: # Report on how user names and passwords will be handled if auth_count > 0: if auth_found > 0: # Not using a password as resolved by file addon.setSetting("user_def_credentials", "false") summary.append("The auth-user-pass tag was found " + str(auth_count) + " times, but was resolved using a supplied file so user name and password don't need to be entered.\n") if not auth_found == auth_count: summary.append(" WARNING : The auth-user-pass tag was found " + str(auth_count) + " times, but only resolved using a supplied file " + str(auth_found) + " times. Some connections may not work.\n") else: # Using a password as auth-user-pass tag was found addon.setSetting("user_def_credentials", "true") summary.append("The auth-user-pass tag was found " + str(auth_count) + " times so assuming user name and password authentication is used.\n") if auth_count < len(ovpn_files): summary.append(" WARNING : The auth-user-pass tag was only found in " + str(auth_count) + " .ovpn files, out of " + str(len(ovpn_files)) + ". Some connections may not work.\n") else: # Not using a password as no auth-user-pass tag was found addon.setSetting("user_def_credentials", "false") summary.append("No auth-user-pass tag was found, so assuming user name and password is not needed.\n") # Report on how keys and certs will be handled if (cert_count > 0 or key_count > 0): summary.append("The key tag was found " + str(key_count) + " times, and the cert tag was found " + str(cert_count) + " times.\n") if cert_found > 0 or key_found > 0: # Key and cert resolved by file so not asking user for them addon.setSetting("user_def_keys", "None") summary.append("The key and certificate don't need to be requested as the key tags were resolved using a supplied file " + str(key_found) + " times, and the cert tags were resolved using a supplied file " + str(cert_found) + " times.\n") if (not cert_found == cert_count) or (not key_found == key_count): summary.append(" WARNING : The key or cert tags were not resolved by a supplied file for all occurrences. Some connections may not work.\n") else: if multiple_certs or multiple_keys: # Key and cert tags found with different file names, but no files supplied. Assume multiple files, user supplied addon.setSetting("user_def_keys", "Multiple") summary.append("Found key and cert tags with multiple filenames, but no key or certificate files were supplied. These will be requested during connection.\n") else: # Key and cert tags found with same file names, but no files supplied. Assume single file, user supplied addon.setSetting("user_def_keys", "Single") summary.append("Found key and cert tags all with the same filename, but no key or certificate files were supplied. These will be requested during connection.\n") if cert_count < len(ovpn_files) or key_count < len(ovpn_files): summary.append(" WARNING : The key tag was found " + str(key_count) + " times, and the cert tag was found " + str(cert_count) + " times. Expected to find one of each in all " + str(len(ovpn_files)) + " .ovpn files. Some connections may not work.\n") else: # Embedded key and certs found, so not asking user for them addon.setSetting("user_def_keys", "None") if (ekey_count > 0 or ecert_count > 0): if ekey_count == ecert_count and key_count == len(ovpn_files): summary.append("Using embedded user keys and certificates so keys and certs don't need to be entered.\n") else: summary.append(" WARNING : Using embedded user keys and certificates, but found " + str(ekey_count) + " keys and " + str(ecert_count) + " certificates in " + str(len(ovpn_files)) + " .ovpn files. There should be one of each in all .ovpn files otherwise some connections may not work.\n") else: summary.append("No user key or cert tags were found so assuming this type of authentication is not used.\n") # Report on how key passwords will be handled if key_pass_count > 0: if key_pass_found > 0: # Not using a password as resolved by file addon.setSetting("user_def_key_password", "false") summary.append("The askpass tag was found " + str(auth_count) + " times, but was resolved using a supplied file so the key password doesn't need to be entered.\n") if not key_pass_found == key_pass_count: summary.append(" WARNING : The askpass tag was found " + str(key_pass_count) + " times, but only resolved using a supplied file " + str(key_pass_found) + " times. Some connections may not work.\n") else: # Using a password as auth-user-pass tag was found addon.setSetting("user_def_key_password", "true") summary.append("The askpass tag was found " + str(key_pass_count) + " times so assuming key password authentication is used.\n") if key_pass_count < len(ovpn_files): summary.append(" WARNING : The askpass tag was only found in " + str(key_pass_count) + " .ovpn files, out of " + str(len(ovpn_files)) + ". Some connections may not work, or you may be asked to enter a password when it's not necessary.\n") else: # Not using a password as no askpass tag was found addon.setSetting("user_def_key_password", "false") summary.append("No askpass tag was found, so assuming key password is not needed.\n") # Report how many times each of the non .ovpn files were used i = 0 for oname in other_files: summary.append("File " + oname + " was found and used in .ovpn files " + str(other_files_count[i]) + " times.\n") if not other_files_count[i] == len(ovpn_files): if other_files_count[i] == 0: summary.append(" WARNING : " + oname + " was not used to update any .ovpn files and could be unused.\n") else: summary.append(" WARNING : The number of updates for " + oname + " was different to the number of .ovpn files, " + str(len(ovpn_files)) + ", which could be a problem.\n") i += 1 else: summary.append("None of the files were updated during import.\n") # Open a log file so all changes can be recorded without fouling up the kodi log log_name = getImportLogPath() if xbmcvfs.exists(log_name): xbmcvfs.delete(log_name) log_file = open(log_name, 'w') for line in summary: log_file.write(line) for line in detail: log_file.write(line) log_file.close() progress.close() xbmc.sleep(100) if success: if xbmcgui.Dialog().yesno(addon_name, "Import wizard finished. You should view the import log to review any issues, enter your user ID and password (if necessary) and then try and validate a VPN connection.", nolabel="OK", yeslabel="Import Log"): popupImportLog() else: xbmcgui.Dialog().ok(addon_name, errorMessage) return success
def 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')
xbmcgui.Dialog().ok(addon_name, "Source file does not exist\nFile : " + source) else: # Open the file and get the size of it try: debugTrace("Opening file " + source) file = xbmcvfs.File(source, "r") total_size = file.size() except: errorTrace("speedtest.py", "Error opening file " + source) total_size = -1 # Only run the test if the file is bigger than 50MB if total_size > (one_mb * 50): infoTrace("speedtest.py", "Running speed test with " + source) progress = xbmcgui.DialogProgress() progress_title = "Running speed test" progress.create(addon_name, progress_title) total_read = 0 total_to_mb = 0 percent = 0 time_start = time.clock() last_time = time_start transfer_speed = 0 bytes_read = file.read(chunk_size) while bytes_read: bytes_read = file.read(chunk_size) total_read = total_read + chunk_size
def disconnectVPN(): # 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") debugTrace("Disconnecting the VPN") forceCycleLock() # Show a progress box before executing stop progress = xbmcgui.DialogProgress() progress_title = "Disconnecting from VPN." progress.create(addon_name,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 in an ok dialog, user will need to do something... errorTrace("common.py", "VPN monitor service is not running, can't stop VPN") xbmcgui.Dialog().ok(progress_title, "Error, Service not running.\nCheck log and reboot.") freeCycleLock() return xbmc.sleep(500) progress_message = "Stopping any active VPN connection." progress.update(1, progress_title, progress_message) # Kill the VPN connection if the user hasn't gotten bored waiting if not progress.iscanceled(): stopVPNConnection() xbmc.sleep(500) progress_message = "Disconnected from VPN, restarting VPN monitor" setVPNLastConnectedProfile("") setVPNLastConnectedProfileFriendly("") setVPNState("off") else: progress_message = "Disconnect cancelled, restarting VPN monitor" # Restart service if not startService(): progress.close() errorTrace("common.py", "VPN monitor service is not running, VPN has stopped") 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() # Update screen and display result in an ok dialog xbmc.executebuiltin('Container.Refresh') _, ip, country, isp = getIPInfo(addon) dialog_message = "Disconnected from VPN.\nNetwork location is " + country + ".\nExternal IP address is " + ip + ".\nService Provider is " + isp infoTrace("common.py", "Disconnected from the VPN") freeCycleLock() xbmcgui.Dialog().ok(addon_name, dialog_message)
dest_path = "" try: log_path = getLogPath() start_dir = "" dest_folder = xbmcgui.Dialog().browse( 0, "Select folder to copy log file into", "files", "", False, False, start_dir, False) dest_path = "kodi " + datetime.datetime.now().strftime( "%y-%m-%d %H-%M-%S") + ".log" dest_path = dest_folder + dest_path.replace(" ", "_") # Write VPN log to log before copying writeVPNLog() debugTrace("Copying " + log_path + " to " + dest_path) addon = xbmcaddon.Addon(getID()) infoTrace( "managefiles.py", "Copying log file to " + dest_path + ". Using version " + addon.getSetting("version_number")) xbmcvfs.copy(log_path, dest_path) if not xbmcvfs.exists(dest_path): raise IOError('Failed to copy log ' + log_path + " to " + dest_path) dialog_message = "Copied log file to:\n" + dest_path except: errorTrace( "managefiles.py", "Failed to copy log from " + log_path + " to " + dest_path) if xbmcvfs.exists(log_path): dialog_message = "Error copying log, try copying it to a different location." else: dialog_messsage = "Could not find the kodi.log file." errorTrace("managefiles.py",
out = xml_key.replace("#KEY", info_key) out = out.replace("#PATH", getAddonPath(True, "")) out = out.replace("#COMMAND", info_command) map_file.write(out) map_file.write(xml_end) map_file.close() xbmcgui.Dialog().ok(addon_name, "Keymap has been updated. You must restart for these changes to take effect.") except Exception as e: errorTrace("mapkey.py", "Couldn't write keymap file " + path) errorTrace("mapkey.py", str(e)) xbmcgui.Dialog().ok(addon_name, "Couldn't update VPN Manager.xml keymap file, check error log.") # Warn the user if maps could clash path = getKeyMapsPath("*.xml") try: debugTrace("Getting contents of keymaps directory " + path) files = (glob.glob(path)) if len(files) > 1: xbmcgui.Dialog().ok(addon_name, "Other keymaps exist and are applied in alphabetical order. If your mappings don't work then it could be that they're being over written by another map.") infoTrace("mapkey.py", "Multiple (" + str(len(files)) + ") keymaps, including " + map_name + " detected in " + getKeyMapsPath("")) except Exception as e: errorTrace("import.py", "Couldn't check to see if other keymaps were clashing") errorTrace("import.py", str(e)) xbmc.executebuiltin("Addon.OpenSettings(service.vpn.manager)") debugTrace("-- Exit mapkey.py --")