def test_bytes(self): pl = self._create() data = plistlib.writePlistToBytes(pl) pl2 = plistlib.readPlistFromBytes(data) self.assertEqual(dict(pl), dict(pl2)) data2 = plistlib.writePlistToBytes(pl2) self.assertEqual(data, data2)
def test_nondictroot(self): test1 = "abc" test2 = [1, 2, 3, "abc"] result1 = plistlib.readPlistFromBytes(plistlib.writePlistToBytes(test1)) result2 = plistlib.readPlistFromBytes(plistlib.writePlistToBytes(test2)) self.assertEqual(test1, result1) self.assertEqual(test2, result2)
def test_bytes_deprecated(self): pl = { 'key': 42, 'sub': { 'key': 9, 'alt': 'value', 'data': b'buffer', } } with self.assertWarns(DeprecationWarning): data = plistlib.writePlistToBytes(pl) with self.assertWarns(DeprecationWarning): pl2 = plistlib.readPlistFromBytes(data) self.assertIsInstance(pl2, dict) self.assertEqual( pl2, dict(key=42, sub=dict( key=9, alt='value', data=plistlib.Data(b'buffer'), ))) with self.assertWarns(DeprecationWarning): data2 = plistlib.writePlistToBytes(pl2) self.assertEqual(data, data2)
def test_bytes_deprecated(self): pl = { 'key': 42, 'sub': { 'key': 9, 'alt': 'value', 'data': b'buffer', } } with self.assertWarns(DeprecationWarning): data = plistlib.writePlistToBytes(pl) with self.assertWarns(DeprecationWarning): pl2 = plistlib.readPlistFromBytes(data) self.assertIsInstance(pl2, plistlib._InternalDict) self.assertEqual(pl2, plistlib._InternalDict( key=42, sub=plistlib._InternalDict( key=9, alt='value', data=plistlib.Data(b'buffer'), ) )) with self.assertWarns(DeprecationWarning): data2 = plistlib.writePlistToBytes(pl2) self.assertEqual(data, data2)
def test_nondictroot(self): test1 = "abc" test2 = [1, 2, 3, "abc"] result1 = plistlib.readPlistFromBytes( plistlib.writePlistToBytes(test1)) result2 = plistlib.readPlistFromBytes( plistlib.writePlistToBytes(test2)) self.assertEqual(test1, result1) self.assertEqual(test2, result2)
def test_controlcharacters(self): for i in range(128): c = chr(i) testString = "string containing %s" % c if i >= 32 or c in "\r\n\t": # \r, \n and \t are the only legal control chars in XML plistlib.writePlistToBytes(testString) else: self.assertRaises(ValueError, plistlib.writePlistToBytes, testString)
def clear(self): """Clear tweaks.""" if not self._lock(): log('Failed to acquire lock!') return self._setup(noedit=True) if self.theme_valid: csm = ColorSchemeMatcher(self.scheme_map["original"]) content = self._get_tmtheme(csm.get_scheme_obj( )) if not NEW_SCHEMES else csm.get_scheme_obj() if NEW_SCHEMES: with codecs.open(self.scheme_clone, "w", encoding='utf-8') as f: f.write(sublime.encode_value(content, pretty=True)) self.scheme_map["redo"] = "" self.scheme_map["undo"] = "" self.p_settings["scheme_map"] = self.scheme_map self._save_tweak_settings() else: with open(self.scheme_clone, "wb") as f: f.write(writePlistToBytes(content)) self.scheme_map["redo"] = "" self.scheme_map["undo"] = "" self.p_settings["scheme_map"] = self.scheme_map self._save_tweak_settings() if self.set_tweaked_scheme: sublime.set_timeout(self._set_tweaked_scheme, 300) else: Lock.release_lock() else: Lock.release_lock() log("Theme has not been tweaked!", status=True)
def do_GET(s): s.send_response(200) s.send_header('Content-Type', 'application/x-apple-aspen-config') s.end_headers() #config_bytes = json.dumps(ConfigProfileHandler.config).encode('utf-8') plist_string = plistlib.writePlistToBytes(ConfigProfileHandler.config) s.wfile.write(plist_string)
def redo(self): """Redo last reverted change.""" self._setup(noedit=True) if self.theme_valid: plist = re.sub( br"^[\r\n\s]*<!--[\s\S]*?-->[\s\r\n]*|<!--[\s\S]*?-->", b'', sublime.load_binary_resource(self.scheme_map["original"])) redo = self.scheme_map["redo"].split(";") if len(redo) == 0 or (len(redo) == 1 and redo[0] == ""): log("Nothing to redo!", status=True) return undo = self.scheme_map["undo"].split(";") undo.append(redo.pop()) self.scheme_map["redo"] = ";".join(redo) self.scheme_map["undo"] = ";".join(undo) self.plist_file = ColorSchemeTweaker().tweak( readPlistFromBytes(plist), self.scheme_map["undo"]) with open(self.scheme_clone, "wb") as f: f.write(writePlistToBytes(self.plist_file)) self.p_settings["scheme_map"] = self.scheme_map self._save_tweak_settings() else: log("Theme has not been tweaked!", status=True)
def _save_as_plist(packages, path_or_file): """Save a list of packages as a Mac OS X property list. Arguments: packages -- a list of TLPackage objects path_or_file -- output file (path or a file-like object) for the database The root object of the output property list is a dictionary. Keys at present are "mirror" (may not exist) and "packages", which is a list of TLPackage dictionary values. """ import plistlib plist = {} # only for remote tlpdb if TLPackage.mirror: plist["mirror"] = TLPackage.mirror plist["packages"] = [] for pkg in all_packages: plist["packages"].append(pkg.dictionary_value()) if python_major_version < 3: plistlib.writePlist(plist, path_or_file) else: bytes_output = plistlib.writePlistToBytes(plist) str_output = bytes_output.decode("UTF-8") if path_or_file == sys.stdout: sys.stdout.write(str_output) else: output_file = open(path_or_file, 'w') output_file.write(str_output)
def check(self,apple_id,passwd,proxy,tor): proxies = {} if tor is True: proxies = {'http':self.tor,'https':self.tor} if proxy != ('' or None): proxies = {'http':proxy,'https':proxy} url = ('https://fmipmobile.icloud.com/fmipservice/device/%s/initClient'%apple_id) headers = { 'User-Agent':'Mozilla/5.0 (iPhone; CPU iPhone OS 7_0_2 like Mac OS X)' } data = {"clientContext": {"appName":"FindMyiPhone","osVersion":"7.0.4","clientTimestamp": 429746389281, "appVersion":"3.0","deviceUDID":"0123456789485ef5b1e6c4f356453be033d15622","inactiveTime":1, "buildVersion":"376","productType":"iPhone6,1"},"serverContext":{}} data = plistlib.writePlistToBytes(data).decode('utf-8') session = Session() req = requests.packages.urllib3.disable_warnings( urllib3.exceptions.InsecureRequestWarning ) req = session.request( method = "POST", url = url, url = https://github.com/nathan4servs/iCloudBrutter-master.git data = data, headers = headers, proxies = proxies, auth = HTTPBasicAuth(apple_id,passwd), verify = False ) if req.status_code == 330: return True elif req.status_code == 401: return False else: return
def clear(self): """Clear tweaks.""" if not self._lock(): log('Failed to acquire lock!') return self._setup(noedit=True) if self.theme_valid: csm = ColorSchemeMatcher(self.scheme_map["original"]) content = self._get_tmtheme(csm.get_scheme_obj()) if not NEW_SCHEMES else csm.get_scheme_obj() if NEW_SCHEMES: with codecs.open(self.scheme_clone, "w", encoding='utf-8') as f: f.write(sublime.encode_value(content, pretty=True)) self.scheme_map["redo"] = "" self.scheme_map["undo"] = "" self.p_settings["scheme_map"] = self.scheme_map self._save_tweak_settings() else: with open(self.scheme_clone, "wb") as f: f.write(writePlistToBytes(content)) self.scheme_map["redo"] = "" self.scheme_map["undo"] = "" self.p_settings["scheme_map"] = self.scheme_map self._save_tweak_settings() if self.set_tweaked_scheme: sublime.set_timeout(self._set_tweaked_scheme, 300) else: Lock.release_lock() else: Lock.release_lock() log("Theme has not been tweaked!", status=True)
def _theme_valid(self, scheme_file, noedit=False): """Check if theme is valid.""" is_working = scheme_file.startswith(TEMP_PATH + '/') if ( is_working and self.scheme_map is not None and self.scheme_map["working"] == scheme_file and self._exists(self.scheme_map["original"]) ): if self._exists(self.scheme_map["working"]): self.scheme_file = packages_path(self.scheme_map["original"]) self.scheme_clone = packages_path(self.scheme_map["working"]) else: # Recover from missing temp log("Revert to original because temp is missing") if self.set_safe: self._set_theme_safely(self.scheme_map["original"]) else: self.settings.set(SCHEME, self.scheme_map["original"]) self.scheme_map["redo"] = "" self.scheme_map["undo"] = "" self.p_settings["scheme_map"] = self.scheme_map self._save_tweak_settings() return True elif not is_working and not noedit: self._ensure_temp() csm = ColorSchemeMatcher(scheme_file) content = get_tmtheme(csm.get_scheme_obj()) if not NEW_SCHEMES else csm.get_scheme_obj() self.scheme_file = packages_path(scheme_file) base, old_ext = splitext(basename(scheme_file)) if NEW_SCHEMES: ext = '.hidden-color-scheme' if old_ext == '.hidden-color-scheme' else '.sublime-color-scheme' else: ext = '.tmTheme' self.scheme_clone = packages_path(join(normpath(TEMP_PATH), 'tweak-' + base + ext)) try: if NEW_SCHEMES: with codecs.open(self.scheme_clone, "w", encoding='utf-8') as f: f.write(sublime.encode_value(content, pretty=True)) else: with open(self.scheme_clone, "wb") as f: f.write(writePlistToBytes(content)) self.scheme_map = { "original": scheme_file, "working": "%s/%s" % (TEMP_PATH, 'tweak-' + base + ext), "undo": "", "redo": "" } self.set_tweaked_scheme = { "set_safe": self.set_safe, "scheme": self.scheme_map["working"], } self.p_settings["scheme_map"] = self.scheme_map self._save_tweak_settings() return True except Exception as e: log(e) sublime.error_message("Cannot clone theme") return False return False
def sendpacket(self, req, tag, payload={}): payload['ClientVersionString'] = 'usbmux.py by marcan' if isinstance(req, int): req = [self.TYPE_CONNECT, self.TYPE_LISTEN][req-2] payload['MessageType'] = req payload['ProgName'] = 'tcprelay' BinaryProtocol.sendpacket(self, self.TYPE_PLIST, tag, plistlib.writePlistToBytes(payload))
def convert_bin_xml(bin_xml_file): """Convert Binary XML to Readable XML""" try: plist_obj = plistlib.readPlist(bin_xml_file) data = plistlib.writePlistToBytes(plist_obj) with open(bin_xml_file, 'wb') as flip: flip.write(data) return data.decode("utf-8", "ignore") except: PrintException("[ERROR] Converting Binary XML to Readable XML")
def test_bytes_deprecated(self): pl = {"key": 42, "sub": {"key": 9, "alt": "value", "data": b"buffer"}} with self.assertWarns(DeprecationWarning): data = plistlib.writePlistToBytes(pl) with self.assertWarns(DeprecationWarning): pl2 = plistlib.readPlistFromBytes(data) self.assertIsInstance(pl2, plistlib._InternalDict) self.assertEqual( pl2, plistlib._InternalDict( key=42, sub=plistlib._InternalDict(key=9, alt="value", data=plistlib.Data(b"buffer")) ), ) with self.assertWarns(DeprecationWarning): data2 = plistlib.writePlistToBytes(pl2) self.assertEqual(data, data2)
def writePlistToBytes(rootObject, binary=True): if not binary: #return plistlib.writePlistToString(rootObject) return plistlib.writePlistToBytes(rootObject) else: #io = StringIO() io = BytesIO() writer = PlistWriter(io) writer.writeRoot(rootObject) return io.getvalue()
def writePlistToString(rootObject, binary=True): if not binary: if six.PY3: return plistlib.writePlistToBytes(rootObject) else: return plistlib.writePlistToString(rootObject) else: io = six.BytesIO() writer = PlistWriter(io) writer.writeRoot(rootObject) return io.getvalue()
def sendpacket(self, req, tag, payload=None): if payload is None: payload = {} payload['ClientVersionString'] = 'usbmux.py by marcan - python2/3 compatibility by phx' if isinstance(req, int): req = [self.TYPE_CONNECT, self.TYPE_LISTEN][req - 2] payload['MessageType'] = req payload['ProgName'] = 'tcprelay' if python3: BinaryProtocol.sendpacket(self, self.TYPE_PLIST, tag, plistlib.writePlistToBytes(payload)) else: BinaryProtocol.sendpacket(self, self.TYPE_PLIST, tag, plistlib.writePlistToString(payload))
def writePlistToString(rootObject, binary=True): if not binary: rootObject = wrapDataObject(rootObject, binary) if six.PY3: return plistlib.writePlistToBytes(rootObject) else: return plistlib.writePlistToString(rootObject) else: io = six.BytesIO() writer = PlistWriter(io) writer.writeRoot(rootObject) return io.getvalue()
def test_indentation_dict_mix(self): data = { '1': { '2': [{ '3': [[[[[{ 'test': plistlib.Data(b'aaaaaa') }]]]]] }] } } self.assertEqual( plistlib.readPlistFromBytes(plistlib.writePlistToBytes(data)), data)
def _dump_plist_value(value): """Create a plist value from a dictionary :param dict value: The value to make the plist from :rtype: dict """ if hasattr(plistlib, 'dumps'): return plistlib.dumps(value) try: return plistlib.writePlistToString(value) except AttributeError: return plistlib.writePlistToBytes(value)
def make_manifest(meta, assets): root = {} items = [] items0 = {} items0['assets'] = assets items0['metadata'] = meta items.append(items0) root['items'] = items if 'writePlistToBytes' in plistlib.__all__: return plistlib.writePlistToBytes(root) else: return plistlib.writePlistToString(root)
def writePlistToString(rootObject, binary=True): if not binary: rootObject = wrapDataObject(rootObject, binary) if hasattr(plistlib, "dumps"): return plistlib.dumps(rootObject) elif hasattr(plistlib, "writePlistToBytes"): return plistlib.writePlistToBytes(rootObject) else: return plistlib.writePlistToString(rootObject) else: ioObject = io.BytesIO() writer = PlistWriter(ioObject) writer.writeRoot(rootObject) return ioObject.getvalue()
def writePlistToBytes(rootObject, binary=True): """ Module function to write a plist bytes object. @param rootObject reference to the object to be written @param binary flag indicating the generation of a binary plist bytes object (boolean) @return bytes object containing the plist data """ if not binary: return plistlib.writePlistToBytes(rootObject) else: io = BytesIO() writer = PlistWriter(io) writer.writeRoot(rootObject) return io.getvalue()
def run(self, filters): self._setup() if self.theme_valid: plist = sublime.load_binary_resource(self.scheme_map["working"]) ct = ColorSchemeTweaker() self.plist_file = ct.tweak( readPlistFromBytes(plist), filters ) with open(self.scheme_clone, "wb") as f: f.write(writePlistToBytes(self.plist_file)) undo = self.scheme_map["undo"].split(";") + ct._get_filters() self.scheme_map["redo"] = "" self.scheme_map["undo"] = ";".join(undo) self.p_settings["scheme_map"] = self.scheme_map self._save_tweak_settings()
def run(self, filters): """Run command.""" self._setup() if self.theme_valid: plist = re.sub( br"^[\r\n\s]*<!--[\s\S]*?-->[\s\r\n]*|<!--[\s\S]*?-->", b'', sublime.load_binary_resource(self.scheme_map["working"])) ct = ColorSchemeTweaker() self.plist_file = ct.tweak(readPlistFromBytes(plist), filters) with open(self.scheme_clone, "wb") as f: f.write(writePlistToBytes(self.plist_file)) undo = self.scheme_map["undo"].split(";") + ct.get_filters() self.scheme_map["redo"] = "" self.scheme_map["undo"] = ";".join(undo) self.p_settings["scheme_map"] = self.scheme_map self._save_tweak_settings()
def redo(self): """Redo last reverted change.""" if not self._lock(): log('Failed to acquire lock!') return self._setup(noedit=True) if self.theme_valid: csm = ColorSchemeMatcher(self.scheme_map["original"]) redo = self.scheme_map["redo"].split(";") if len(redo) == 0 or (len(redo) == 1 and redo[0] == ""): log("Nothing to redo!", status=True) return undo = self.scheme_map["undo"].split(";") undo.append(redo.pop()) self.scheme_map["redo"] = ";".join(redo) self.scheme_map["undo"] = ";".join(undo) self.plist_file = ColorSchemeTweaker().tweak( csm.get_scheme_obj(), self.scheme_map["undo"], not NEW_SCHEMES) if NEW_SCHEMES: with codecs.open(self.scheme_clone, "w", encoding='utf-8') as f: f.write(sublime.encode_value(self.plist_file, pretty=True)) self.p_settings["scheme_map"] = self.scheme_map self._save_tweak_settings() else: with open(self.scheme_clone, "wb") as f: f.write(writePlistToBytes(self.plist_file)) self.p_settings["scheme_map"] = self.scheme_map self._save_tweak_settings() if self.set_tweaked_scheme: sublime.set_timeout(self._set_tweaked_scheme, 300) else: Lock.release_lock() else: Lock.release_lock() log("Theme has not been tweaked!", status=True)
def run(self, filters): """Run command.""" if not self._lock(): log('Failed to acquire lock!') return self._setup() if self.theme_valid: csm = ColorSchemeMatcher(self.scheme_map["working"]) content = csm.get_scheme_obj() ct = ColorSchemeTweaker() self.plist_file = ct.tweak(content, filters, not NEW_SCHEMES) if NEW_SCHEMES: with codecs.open(self.scheme_clone, "w", encoding='utf-8') as f: f.write(sublime.encode_value(self.plist_file, pretty=True)) undo = self.scheme_map["undo"].split( ";") + ct.get_filters() self.scheme_map["redo"] = "" self.scheme_map["undo"] = ";".join(undo) self.p_settings["scheme_map"] = self.scheme_map self._save_tweak_settings() else: with open(self.scheme_clone, "wb") as f: f.write(writePlistToBytes(self.plist_file)) undo = self.scheme_map["undo"].split( ";") + ct.get_filters() self.scheme_map["redo"] = "" self.scheme_map["undo"] = ";".join(undo) self.p_settings["scheme_map"] = self.scheme_map self._save_tweak_settings() if self.set_tweaked_scheme: sublime.set_timeout(self._set_tweaked_scheme, 300) else: Lock.release_lock() else: Lock.release_lock()
def redo(self): """Redo last reverted change.""" if not self._lock(): log('Failed to acquire lock!') return self._setup(noedit=True) if self.theme_valid: csm = ColorSchemeMatcher(self.scheme_map["original"]) redo = self.scheme_map["redo"].split(";") if len(redo) == 0 or (len(redo) == 1 and redo[0] == ""): log("Nothing to redo!", status=True) return undo = self.scheme_map["undo"].split(";") undo.append(redo.pop()) self.scheme_map["redo"] = ";".join(redo) self.scheme_map["undo"] = ";".join(undo) self.plist_file = ColorSchemeTweaker().tweak(csm.get_scheme_obj(), self.scheme_map["undo"], not NEW_SCHEMES) if NEW_SCHEMES: with codecs.open(self.scheme_clone, "w", encoding='utf-8') as f: f.write(sublime.encode_value(self.plist_file, pretty=True)) self.p_settings["scheme_map"] = self.scheme_map self._save_tweak_settings() else: with open(self.scheme_clone, "wb") as f: f.write(writePlistToBytes(self.plist_file)) self.p_settings["scheme_map"] = self.scheme_map self._save_tweak_settings() if self.set_tweaked_scheme: sublime.set_timeout(self._set_tweaked_scheme, 300) else: Lock.release_lock() else: Lock.release_lock() log("Theme has not been tweaked!", status=True)
def _save_as_plist(packages, path_or_file): """Save a list of packages as a Mac OS X property list. Arguments: packages -- a list of TLPackage objects path_or_file -- output file (path or a file-like object) for the database The root object of the output property list is a dictionary. Keys at present are "mirror" (may not exist) and "packages", which is a list of TLPackage dictionary values. """ import plistlib plist = {} # only for remote tlpdb if TLPackage.mirror: plist["mirror"] = TLPackage.mirror plist["packages"] = [] for pkg in all_packages: plist["packages"].append(pkg.dictionary_value()) if python_major_version < 3: plistlib.writePlist(plist, path_or_file) else: # Apparently writePlistToBytes() was removed in Python 3.9, but its # replacement of dumps() is only available in 3.4 and later. This is # some silly bullshit. Try the new method first, and fall back to the # old one, I guess. try: bytes_output = plistlib.dumps(plist) except Exception as exc: bytes_output = plistlib.writePlistToBytes(plist) str_output = bytes_output.decode("UTF-8") if path_or_file == sys.stdout: sys.stdout.write(str_output) else: output_file = open(path_or_file, 'w') output_file.write(str_output)
def redo(self): self._setup(noedit=True) if self.theme_valid: plist = sublime.load_binary_resource(self.scheme_map["original"]) redo = self.scheme_map["redo"].split(";") if len(redo) == 0 or (len(redo) == 1 and redo[0] == ""): log("Nothing to redo!", status=True) return undo = self.scheme_map["undo"].split(";") undo.append(redo.pop()) self.scheme_map["redo"] = ";".join(redo) self.scheme_map["undo"] = ";".join(undo) self.plist_file = ColorSchemeTweaker().tweak( readPlistFromBytes(plist), self.scheme_map["undo"] ) with open(self.scheme_clone, "wb") as f: f.write(writePlistToBytes(self.plist_file)) self.p_settings["scheme_map"] = self.scheme_map self._save_tweak_settings() else: log("Theme has not been tweaked!", status=True)
def test_indentation_dict(self): data = { '1': { '2': { '3': { '4': { '5': { '6': { '7': { '8': { '9': plistlib.Data(b'aaaaaa') } } } } } } } } } self.assertEqual( plistlib.readPlistFromBytes(plistlib.writePlistToBytes(data)), data)
def run(self, filters): """Run command.""" if not self._lock(): log('Failed to acquire lock!') return self._setup() if self.theme_valid: csm = ColorSchemeMatcher(self.scheme_map["working"]) content = csm.get_scheme_obj() ct = ColorSchemeTweaker() self.plist_file = ct.tweak(content, filters, not NEW_SCHEMES) if NEW_SCHEMES: with codecs.open(self.scheme_clone, "w", encoding='utf-8') as f: f.write(sublime.encode_value(self.plist_file, pretty=True)) undo = self.scheme_map["undo"].split(";") + ct.get_filters() self.scheme_map["redo"] = "" self.scheme_map["undo"] = ";".join(undo) self.p_settings["scheme_map"] = self.scheme_map self._save_tweak_settings() else: with open(self.scheme_clone, "wb") as f: f.write(writePlistToBytes(self.plist_file)) undo = self.scheme_map["undo"].split(";") + ct.get_filters() self.scheme_map["redo"] = "" self.scheme_map["undo"] = ";".join(undo) self.p_settings["scheme_map"] = self.scheme_map self._save_tweak_settings() if self.set_tweaked_scheme: sublime.set_timeout(self._set_tweaked_scheme, 300) else: Lock.release_lock() else: Lock.release_lock()
def plist_analysis(src, is_source): """Plist Analysis""" try: logger.info("iOS Info.plist Analysis Started") plist_info = { "bin_name": "", "bin": "", "id": "", "version": "", "build": "", "sdk": "", "pltfm": "", "min": "", "plist_xml": "", "permissions": [], "inseccon": [], "bundle_name": "", "build_version_name": "", "bundle_url_types": [], "bundle_supported_platforms": [], "bundle_localizations": [] } plist_file = None if is_source: logger.info("Finding Info.plist in iOS Source") for ifile in os.listdir(src): if ifile.endswith(".xcodeproj"): app_name = ifile.replace(".xcodeproj", "") break app_plist_file = "Info.plist" for dirpath, dirnames, files in os.walk(src): for name in files: if "__MACOSX" not in dirpath and name == app_plist_file: plist_file = os.path.join(dirpath, name) break else: logger.info("Finding Info.plist in iOS Binary") dirs = os.listdir(src) dot_app_dir = "" for dir_ in dirs: if dir_.endswith(".app"): dot_app_dir = dir_ break bin_dir = os.path.join(src, dot_app_dir) # Full Dir/Payload/x.app plist_file = os.path.join(bin_dir, "Info.plist") if not isFileExists(plist_file): logger.warning("Cannot find Info.plist file. Skipping Plist Analysis.") else: #Generic Plist Analysis plist_obj = plistlib.readPlist(plist_file) plist_info["plist_xml"] = plistlib.writePlistToBytes(plist_obj).decode("utf-8", "ignore") if "CFBundleDisplayName" in plist_obj: plist_info["bin_name"] = plist_obj["CFBundleDisplayName"] else: if not is_source: #For iOS IPA plist_info["bin_name"] = dot_app_dir.replace(".app", "") if "CFBundleExecutable" in plist_obj: plist_info["bin"] = plist_obj["CFBundleExecutable"] if "CFBundleIdentifier" in plist_obj: plist_info["id"] = plist_obj["CFBundleIdentifier"] # build if "CFBundleVersion" in plist_obj: plist_info["build"] = plist_obj["CFBundleVersion"] if "DTSDKName" in plist_obj: plist_info["sdk"] = plist_obj["DTSDKName"] if "DTPlatformVersion" in plist_obj: plist_info["pltfm"] = plist_obj["DTPlatformVersion"] if "MinimumOSVersion" in plist_obj: plist_info["min"] = plist_obj["MinimumOSVersion"] plist_info["bundle_name"] = plist_obj.get("CFBundleName", "") plist_info["bundle_version_name"] = plist_obj.get("CFBundleShortVersionString", "") plist_info["bundle_url_types"] = plist_obj.get("CFBundleURLTypes", []) plist_info["bundle_supported_platforms"] = plist_obj.get("CFBundleSupportedPlatforms", []) plist_info["bundle_localizations"] = plist_obj.get("CFBundleLocalizations", []) # Check possible app-permissions plist_info["permissions"] = __check_permissions(plist_obj) plist_info["inseccon"] = __check_insecure_connections(plist_obj) return plist_info except: PrintException("Reading from Info.plist")
import sublime import plistlib import datetime __all__ = ["readPlistFromView", "plistDumps"] plistDumps = lambda obj, detect_timestamp=False, none_handler="fail": plistlib.writePlistToBytes( plist_convert_to(obj, detect_timestamp, none_handler) ).decode('utf-8') readPlistFromView = lambda view: plist_convert_from( plistlib.readPlistFromBytes( view.substr( sublime.Region(0, view.size()) ).encode('utf8') ) ) def convert_timestamp(obj): time_stamp = None if plistlib._dateParser.match(obj): time_stamp = plistlib._dateFromString(obj) return time_stamp def plist_convert_from(obj): if isinstance(obj, plistlib._InternalDict): for k, v in obj.items():
def plist_analysis(src, is_source): """Plist Analysis""" try: print("[INFO] iOS Info.plist Analysis Started") plist_info = {} plist_info["bin_name"] = "" plist_info["bin"] = "" plist_info["id"] = "" plist_info["ver"] = "" plist_info["sdk"] = "" plist_info["pltfm"] = "" plist_info["min"] = "" plist_info["plist_xml"] = "" plist_info["permissions"] = [] plist_info["inseccon"] = [] if is_source: print("[INFO] Finding Info.plist in iOS Source") for ifile in os.listdir(src): if ifile.endswith(".xcodeproj"): app_name = ifile.replace(".xcodeproj", "") break app_plist_file = "Info.plist" for dirpath, dirnames, files in os.walk(src): for name in files: if "__MACOSX" not in dirpath and name == app_plist_file: plist_file = os.path.join(dirpath, name) break else: print("[INFO] Finding Info.plist in iOS Binary") dirs = os.listdir(src) dot_app_dir = "" for dir_ in dirs: if dir_.endswith(".app"): dot_app_dir = dir_ break bin_dir = os.path.join(src, dot_app_dir) # Full Dir/Payload/x.app plist_file = os.path.join(bin_dir, "Info.plist") if not isFileExists(plist_file): print( "[WARNING] Cannot find Info.plist file. Skipping Plist Analysis." ) else: #Generic Plist Analysis plist_obj = plistlib.readPlist(plist_file) plist_info["plist_xml"] = plistlib.writePlistToBytes( plist_obj).decode("utf-8", "ignore") if "CFBundleDisplayName" in plist_obj: plist_info["bin_name"] = plist_obj["CFBundleDisplayName"] else: if not is_source: #For iOS IPA plist_info["bin_name"] = dot_app_dir.replace(".app", "") if "CFBundleExecutable" in plist_obj: plist_info["bin"] = plist_obj["CFBundleExecutable"] if "CFBundleIdentifier" in plist_obj: plist_info["id"] = plist_obj["CFBundleIdentifier"] if "CFBundleVersion" in plist_obj: plist_info["ver"] = plist_obj["CFBundleVersion"] if "DTSDKName" in plist_obj: plist_info["sdk"] = plist_obj["DTSDKName"] if "DTPlatformVersion" in plist_obj: plist_info["pltfm"] = plist_obj["DTPlatformVersion"] if "MinimumOSVersion" in plist_obj: plist_info["min"] = plist_obj["MinimumOSVersion"] # Check possible app-permissions plist_info["permissions"] = __check_permissions(plist_obj) plist_info["inseccon"] = __check_insecure_connections(plist_obj) return plist_info except: PrintException("[ERROR] - Reading from Info.plist")
def serialize(self, obj, *args, **kwargs): try: return plistlib.writePlistToBytes(obj, *args, **kwargs) # Python 3 except AttributeError: return plistlib.writePlistToString(obj, *args, **kwargs) # Python 2
for arg in args: print(arg, end=" ") print() debug = lambda s, *a: None error = info warn = info # debug = info log = Log() if sys.version_info[0] == 3: if not hasattr(plistlib, 'loads'): plistlib.loads = lambda data: plistlib.readPlistFromBytes(data) plistlib.dumps = lambda value: plistlib.writePlistToBytes(value) else: plistlib.loads = lambda data: plistlib.readPlistFromString(data) plistlib.dumps = lambda value: plistlib.writePlistToString(value) def write_package(path, content): rf = sublime.packages_path() + path try: os.makedirs(os.path.dirname(rf)) except OSError as e: if e.errno != errno.EEXIST: raise with open(rf, 'w') as f: f.write(content)
def test_indentation_dict_mix(self): data = {'1': {'2': [{'3': [[[[[{'test': plistlib.Data(b'aaaaaa')}]]]]]}]}} self.assertEqual(plistlib.readPlistFromBytes(plistlib.writePlistToBytes(data)), data)
def test_appleformatting(self): pl = plistlib.readPlistFromBytes(TESTDATA) data = plistlib.writePlistToBytes(pl) self.assertEqual(data, TESTDATA, "generated data was not identical to Apple's output")
def _theme_valid(self, scheme_file, noedit=False): """Check if theme is valid.""" is_working = scheme_file.startswith(TEMP_PATH + '/') if (is_working and self.scheme_map is not None and self.scheme_map["working"] == scheme_file and self._exists(self.scheme_map["original"])): if self._exists(self.scheme_map["working"]): self.scheme_file = packages_path(self.scheme_map["original"]) self.scheme_clone = packages_path(self.scheme_map["working"]) else: # Recover from missing temp log("Revert to original because temp is missing") if self.set_safe: self._set_theme_safely(self.scheme_map["original"]) else: self.settings.set(SCHEME, self.scheme_map["original"]) self.scheme_map["redo"] = "" self.scheme_map["undo"] = "" self.p_settings["scheme_map"] = self.scheme_map self._save_tweak_settings() return True elif not is_working and not noedit: self._ensure_temp() csm = ColorSchemeMatcher(scheme_file) content = get_tmtheme(csm.get_scheme_obj( )) if not NEW_SCHEMES else csm.get_scheme_obj() self.scheme_file = packages_path(scheme_file) base, old_ext = splitext(basename(scheme_file)) if NEW_SCHEMES: ext = '.hidden-color-scheme' if old_ext == '.hidden-color-scheme' else '.sublime-color-scheme' else: ext = '.tmTheme' self.scheme_clone = packages_path( join(normpath(TEMP_PATH), 'tweak-' + base + ext)) try: if NEW_SCHEMES: with codecs.open(self.scheme_clone, "w", encoding='utf-8') as f: f.write(sublime.encode_value(content, pretty=True)) else: with open(self.scheme_clone, "wb") as f: f.write(writePlistToBytes(content)) self.scheme_map = { "original": scheme_file, "working": "%s/%s" % (TEMP_PATH, 'tweak-' + base + ext), "undo": "", "redo": "" } self.set_tweaked_scheme = { "set_safe": self.set_safe, "scheme": self.scheme_map["working"], } self.p_settings["scheme_map"] = self.scheme_map self._save_tweak_settings() return True except Exception as e: log(e) sublime.error_message("Cannot clone theme") return False return False
"mt2", "mtm", "oga", "ogg", "oggflac", "ogv", "okt", "opus", "s3m", "spc", "spx", "stm", "tta", "ult", "vgm", "wav", "wma", "wmv", "wv", "xm", ], CFBundleTypeRole="Viewer", CFBundleTypeIconFile="quodlibet.icns", ), ], )) else: assert 0 print(writePlistToBytes(plist).decode("utf-8"))
def test_indentation_dict(self): data = {'1': {'2': {'3': {'4': {'5': {'6': {'7': {'8': {'9': plistlib.Data(b'aaaaaa')}}}}}}}}} self.assertEqual(plistlib.readPlistFromBytes(plistlib.writePlistToBytes(data)), data)
return not set(string).issubset(set(printable)) \ or __containsUnicode(string) def __containsUnicode(string): try: string.encode('ascii') return False except: return True if six.PY3: # Monkey patch plistlib.readPlistFromString = lambda data: \ plistlib.readPlistFromBytes(data.encode("utf-8")) plistlib.writePlistToString = lambda data: \ plistlib.writePlistToBytes(data).decode("utf-8") def readPlist(filePath): try: data = plistlib.readPlist(filePath) except Exception as e: # Solo si tiene error data = plistlib.readPlistFromString(__fixString(encoding.read(filePath)[0])) return __fixItems(data, __fixReadItem) def writePlist(dictionary, filePath): plistlib.writePlist(__fixItems(dictionary, __fixWriteItem), filePath) def readPlistFromString(string): try: data = plistlib.readPlistFromString(string)
def test_indentation_array(self): data = [[[[[[[[{'test': plistlib.Data(b'aaaaaa')}]]]]]]]] self.assertEqual(plistlib.readPlistFromBytes(plistlib.writePlistToBytes(data)), data)
def render(self, *args, **kwargs): context = self.get_context(*args, **kwargs) if sys.version < '3': return plistlib.writePlistToString(context) return plistlib.writePlistToBytes(context).decode('unicode_escape')
def plist_analysis(src, is_source): """Plist Analysis.""" try: logger.info('iOS Info.plist Analysis Started') plist_info = { 'bin_name': '', 'bin': '', 'id': '', 'version': '', 'build': '', 'sdk': '', 'pltfm': '', 'min': '', 'plist_xml': '', 'permissions': [], 'inseccon': [], 'bundle_name': '', 'build_version_name': '', 'bundle_url_types': [], 'bundle_supported_platforms': [], 'bundle_localizations': [], } plist_file = None if is_source: logger.info('Finding Info.plist in iOS Source') app_plist_file = 'Info.plist' for dirpath, _dirnames, files in os.walk(src): for name in files: if '__MACOSX' not in dirpath and name == app_plist_file: plist_file = os.path.join(dirpath, name) break else: logger.info('Finding Info.plist in iOS Binary') dirs = os.listdir(src) dot_app_dir = '' for dir_ in dirs: if dir_.endswith('.app'): dot_app_dir = dir_ break bin_dir = os.path.join(src, dot_app_dir) # Full Dir/Payload/x.app plist_file = os.path.join(bin_dir, 'Info.plist') if not is_file_exists(plist_file): logger.warning( 'Cannot find Info.plist file. Skipping Plist Analysis.') else: # Generic Plist Analysis plist_obj = plistlib.readPlist(plist_file) plist_info['plist_xml'] = plistlib.writePlistToBytes( plist_obj).decode('utf-8', 'ignore') if 'CFBundleDisplayName' in plist_obj: plist_info['bin_name'] = plist_obj['CFBundleDisplayName'] else: if not is_source: # For iOS IPA plist_info['bin_name'] = dot_app_dir.replace('.app', '') if 'CFBundleExecutable' in plist_obj: plist_info['bin'] = plist_obj['CFBundleExecutable'] if 'CFBundleIdentifier' in plist_obj: plist_info['id'] = plist_obj['CFBundleIdentifier'] # build if 'CFBundleVersion' in plist_obj: plist_info['build'] = plist_obj['CFBundleVersion'] if 'DTSDKName' in plist_obj: plist_info['sdk'] = plist_obj['DTSDKName'] if 'DTPlatformVersion' in plist_obj: plist_info['pltfm'] = plist_obj['DTPlatformVersion'] if 'MinimumOSVersion' in plist_obj: plist_info['min'] = plist_obj['MinimumOSVersion'] plist_info['bundle_name'] = plist_obj.get('CFBundleName', '') plist_info['bundle_version_name'] = plist_obj.get( 'CFBundleShortVersionString', '') plist_info['bundle_url_types'] = plist_obj.get( 'CFBundleURLTypes', []) plist_info['bundle_supported_platforms'] = plist_obj.get( 'CFBundleSupportedPlatforms', []) plist_info['bundle_localizations'] = plist_obj.get( 'CFBundleLocalizations', []) # Check possible app-permissions plist_info['permissions'] = check_permissions(plist_obj) plist_info['inseccon'] = check_insecure_connections(plist_obj) return plist_info except Exception: logger.exception('Reading from Info.plist')
def dumps(cls, obj, fp, indent = False): try: return plistlib.writePlistToBytes(obj, fp) except Exception, e: raise TranscoderDumpException(e)