def do_SETUP(self): dacp_id = self.headers.get("DACP-ID") active_remote = self.headers.get("Active-Remote") ua = self.headers.get("User-Agent") print("SETUP %s" % self.path) print(self.headers) if self.headers["Content-Type"] == HTTP_CT_BPLIST: content_len = int(self.headers["Content-Length"]) if content_len > 0: body = self.rfile.read(content_len) plist = readPlistFromString(body) self.pp.pprint(plist) if "streams" not in plist: print("Sending EVENT:") event_port, self.event_proc = Event.spawn() sonos_one_setup["eventPort"] = event_port print("[+] eventPort=%d" % event_port) self.pp.pprint(sonos_one_setup) res = writePlistToString(sonos_one_setup) self.send_response(200) self.send_header("Content-Length", len(res)) self.send_header("Content-Type", HTTP_CT_BPLIST) self.send_header("Server", self.version_string()) self.send_header("CSeq", self.headers["CSeq"]) self.end_headers() self.wfile.write(res) else: print("Sending CONTROL/DATA:") stream = Stream(plist["streams"][0], AUDIO_DEVICE, USE_PORTAUDIO) self.server.streams.append(stream) sonos_one_setup_data["streams"][0][ "controlPort"] = stream.control_port sonos_one_setup_data["streams"][0][ "dataPort"] = stream.data_port print("[+] controlPort=%d dataPort=%d" % (stream.control_port, stream.data_port)) if stream.type == Stream.BUFFERED: sonos_one_setup_data["streams"][0][ "type"] = stream.type sonos_one_setup_data["streams"][0][ "audioBufferSize"] = 8388608 self.pp.pprint(sonos_one_setup_data) res = writePlistToString(sonos_one_setup_data) self.send_response(200) self.send_header("Content-Length", len(res)) self.send_header("Content-Type", HTTP_CT_BPLIST) self.send_header("Server", self.version_string()) self.send_header("CSeq", self.headers["CSeq"]) self.end_headers() self.wfile.write(res) return self.send_error(404)
def do_SETUP(self): dacp_id = self.headers.get("DACP-ID") active_remote = self.headers.get("Active-Remote") ua = self.headers.get("User-Agent") print("SETUP %s" % self.path) print(self.headers) if self.headers["Content-Type"] == HTTP_CT_BPLIST: content_len = int(self.headers["Content-Length"]) if content_len > 0: body = self.rfile.read(content_len) plist = readPlistFromString(body) self.pp.pprint(plist) if "streams" not in plist: print("Sending EVENT:") event_port, self.event_proc = Event.spawn( self.server.server_address) device_setup["eventPort"] = event_port print("[+] eventPort=%d" % event_port) self.pp.pprint(device_setup) res = writePlistToString(device_setup) self.send_response(200) self.send_header("Content-Length", len(res)) self.send_header("Content-Type", HTTP_CT_BPLIST) self.send_header("Server", self.version_string()) self.send_header("CSeq", self.headers["CSeq"]) self.end_headers() self.wfile.write(res) else: print("Sending CONTROL/DATA:") buff = 8388608 # determines how many CODEC frame size 1024 we can hold stream = Stream(plist["streams"][0], buff) set_volume_pid(stream.data_proc.pid) self.server.streams.append(stream) device_setup_data["streams"][0][ "controlPort"] = stream.control_port device_setup_data["streams"][0][ "dataPort"] = stream.data_port print("[+] controlPort=%d dataPort=%d" % (stream.control_port, stream.data_port)) if stream.type == Stream.BUFFERED: device_setup_data["streams"][0]["type"] = stream.type device_setup_data["streams"][0][ "audioBufferSize"] = buff self.pp.pprint(device_setup_data) res = writePlistToString(device_setup_data) self.send_response(200) self.send_header("Content-Length", len(res)) self.send_header("Content-Type", HTTP_CT_BPLIST) self.send_header("Server", self.version_string()) self.send_header("CSeq", self.headers["CSeq"]) self.end_headers() self.wfile.write(res) return self.send_error(404)
def export(self): """ Export `self` as a binary bplist. 将自己导出成二进制的bplist """ result = deepcopy(self._data) self._update_exportable(result) if self.src_type == "bp": return biplist.writePlistToString(result) elif self.src_type == "xml": return biplist.writePlistToString(result, False)
def handle_configure(self): print("configure %s" % self.path) print(self.headers) content_len = int(self.headers["Content-Length"]) if content_len > 0: body = self.rfile.read(content_len) plist = readPlistFromString(body) self.pp.pprint(plist) accessory_id, accessory_ltpk = self.server.hap.configure() configure_info = { 'Identifier': accessory_id.decode('utf-8'), 'Enable_HK_Access_Control': True, 'PublicKey': accessory_ltpk, 'Device_Name': 'NEWBORNE', 'Access_Control_Level': 0 } res = writePlistToString(configure_info) self.pp.pprint(configure_info) file = open("./plist.bin", "wb") file.write(res) file.close() self.send_response(200) self.send_header("Content-Length", len(res)) self.send_header("Content-Type", HTTP_CT_BPLIST) self.send_header("Server", self.version_string()) self.send_header("CSeq", self.headers["CSeq"]) self.end_headers() self.wfile.write(res) if self.server.hap.encrypted: hexdump(self.server.hap.accessory_shared_key) self.upgrade_to_encrypted(self.server.hap.accessory_shared_key)
def parse_provisioning_profiles(cls, provisioning_profiles): """ Parse provisioning profiles into two maps of application id -> provisioning profile path application id -> dict of entitlements as string, provisioning profile path """ app_id_to_pprof = {} app_id_to_entitlements_info = {} for provisioning_profile in provisioning_profiles: entitlements = cls.extract_entitlements(provisioning_profile) if 'application-identifier' not in entitlements: raise Exception( "Could not find application-identifier in entitlements from provisioning profile {}" .format(provisioning_profile)) app_id = entitlements['application-identifier'] if app_id in app_id_to_pprof: raise Exception( "At least 2 provisioning profiles target the same application identifier: " "{}, {}".format(provisioning_profile, app_id_to_pprof[app_id])) app_id_to_pprof[app_id] = provisioning_profile app_id_to_entitlements_info[app_id] = { "path": provisioning_profile, "entitlements": biplist.writePlistToString(entitlements) } return app_id_to_pprof, app_id_to_entitlements_info
def serialize(datastructure, format_hint): """Serialize the datastructure to either YAML, TOML, JSON or PLIST string (or bytes). Args: datastructure (any): The datastructure to serialize into a string using 'format_hint' format. format_hint (str): see 'unserialize'. """ if format_hint == 'toml': return TOML.dumps(datastructure) elif format_hint == 'yaml': return yaml_serialize(datastructure)[:-1] elif format_hint == 'json': output = JSON.dumps(datastructure, indent=2) # Remove whitespace before line breaks (needed for Python2.7) return output.replace(' \n', '\n') elif format_hint == 'plist' or format_hint == 'plist_binary': write_as_binary = format_hint == 'plist_binary' output = PLIST.writePlistToString(datastructure, write_as_binary) # Remove whitespace before line breaks (needed for Python2.7) return output.rstrip()
def serialize_bundle(bundle_path): if have_biplist: data = biplist.writePlistToString(encode_directory(bundle_path), binary=True) else: data = plistlib.writePlistToString(encode_directory(bundle_path)) return data
def inject_plist(self, plist): """ Inject a plist into the session. This is essentially a reverse of `rawDataReceived`: * the plist dictionary is converted into to a binary plist * the size is measured and the appropriate 02... header generated * header and body are concatenated, compressed, and injected. """ if hasattr(plist, 'to_dict'): plist = plist.to_dict() if not isinstance(plist, dict): self.logger.warning('Rejecting inject invalid plist data %s' % plist) return self.logger.info("* %s %s" % (plist['class'], plist.get('refId', ''))) ref_id = plist.get('refId', None) if ref_id: self.ref_id = ref_id data = writePlistToString(plist) data_len = len(data) if data_len > 0: ## Add data_len to 0x200000000 and convert to hex, zero-padded to 10 digits #header = '{:x}'.format(0x0200000000 + data_len).rjust(10, '0') header = '%x' % (0x0200000000 + data_len) data = self.zlib_c.compress(unhexlify(header.rjust(10,'0')) + data) self.peer.transport.write(data) self.peer.transport.write(self.zlib_c.flush(zlib.Z_FULL_FLUSH))
def init_extra(self, dict_): self._zip = GzipWrapper("") self._zip._data[0] = BPList( biplist.readPlistFromString(biplist.writePlistToString(dict_)), "xml") self._zip._data[0] = self._parse(self._zip._data[0]) self.has_extra = True
def write_xattr_tags(file_path, tags): """THE MODULE HAS BEEN BUILD FOR writePlistToString.""" bpl_tags = biplist.writePlistToString(tags) optional_tag = "com.apple.metadata:" map(lambda a: xattr.setxattr(file_path, optional_tag + a, bpl_tags), ["kMDItemFinderComment", "_kMDItemUserTags", "kMDItemOMUserTags"]) return 'Updated xattr'
def send_plist(self, plist): self.sendLock.acquire() print "Sending: ", plist bplist = biplist.writePlistToString(plist); # self.unzipped_output_buffer = struct.pack('>BI', 2,len(bplist)) + bplist self.flush_unzipped_output() self.sendLock.release()
def convert(data, args): class holder(): pass placeholder = holder() placeholder.pretty = True if len(args) == 1: if (args[0] == "json" or args[0] == "JSON"): # xml2json() converts newlines and tabs in strings to "\n" & "\t". # Stripping them out of XML before conversion to JSON. rawxml = writePlistToString(readPlistFromString(data),binary=False) rawxml = rawxml.replace("\t","") rawxml = rawxml.replace("\n","") return [xml2json(rawxml,placeholder)] else: return [writePlistToString(readPlistFromString(data),binary=False)]
def write_xattr_metadata(file_list, meta_data): if meta_data.has_key('caption'): #Simple, just replace all the captions bipl = biplist.writePlistToString(meta_data['caption']) for file in file_list: xattr.setxattr(file, 'com.apple.metadata:kMDItemDescription', bipl) if meta_data.has_key('keywords'): #A little more involved. For each file, load original keywords, #then remove or add the relevant keywords for file in file_list: if 'com.apple.metadata:kMDItemKeywords' in xattr.listxattr(file): orig_keywd_list = set(biplist.readPlistFromString(xattr.getxattr(file, 'com.apple.metadata:kMDItemKeywords'))) else: orig_keywd_list = set([]) for keyword in meta_data['keywords']: if keyword[0] == '+': orig_keywd_list.add(keyword[1]) if keyword[0] == '-': orig_keywd_list.remove(keyword[1]) xattr.setxattr(file, 'com.apple.metadata:kMDItemKeywords', biplist.writePlistToString(list(orig_keywd_list)))
def send_plist(self, plist): self.sendLock.acquire() self.logger.debug("Sending:\n{0}".format(pprint.pformat(plist, width=40))) bplist = biplist.writePlistToString(plist); # self.unzipped_output_buffer = struct.pack('>BI', 2,len(bplist)) + bplist self.flush_unzipped_output() self.sendLock.release()
def _get_bplisthtml(self, buf): parsed = biplist.readPlistFromString(buf) html = """<button class="btn btn-primary btn-sm" onclick="hideshow(this);"> Show XML <span class="glyphicon glyphicon-chevron-down"></span> </button>""" content = biplist.writePlistToString(parsed,False) html += self._get_xmlhtml(content, hidden=True) return html
def _get_bplisthtml(self, buf): parsed = biplist.readPlistFromString(buf) html = """<button class="btn btn-primary btn-sm" onclick="hideshow(this);"> Show XML <span class="glyphicon glyphicon-chevron-down"></span> </button>""" content = biplist.writePlistToString(parsed, False) html += self._get_xmlhtml(content, hidden=True) return html
def send_plist(self, plist): self.sendLock.acquire() self.logger.debug("Sending packet with class: {0}".format(plist["class"])) self.logger.debug("packet with content:\n{0}".format(pprint.pformat(plist, width=40))) bplist = biplist.writePlistToString(plist) self.unzipped_output_buffer = struct.pack(">BI", 2, len(bplist)) + bplist self.flush_unzipped_output() self.sendLock.release()
def convert_bin_xml(bin_xml_file): """Convert Binary XML to Readable XML.""" try: plist_obj = readPlist(bin_xml_file) data = writePlistToString(plist_obj) return data except InvalidPlistException: logger.warning('Failed to convert plist')
def convert_bin_xml(bin_xml_file): """Convert Binary XML to Readable XML""" try: plist_obj = readPlist(bin_xml_file) data = writePlistToString(plist_obj) return data except biplist.InvalidPlistException: logger.warning("Failed to convert plist")
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)) BinaryProtocol.sendpacket(self, self.TYPE_PLIST, tag, biplist.writePlistToString(payload))
def write(self, *tags): """ Overwrites the existing tags with the iterable of tags provided. """ if not all(isinstance(tag, str) for tag in tags): raise TypeError("Tags must be strings") tag_plist = writePlistToString(list(map(tag_normalize, tags))) for key in self.TAG_XATTRS: self.xa.set(key, tag_plist)
def writePlist(obj, path, binary=False): if not os.path.isabs(path): path = storage(path) if binary: biplist.writePlist(obj, path, binary) s = biplist.writePlistToString(obj) with codecs.open(path, "w", "utf-8") as f: f.write(s)
def to_plist(self, data, options=None): """ Given some Python data, produces binary plist output. """ options = options or {} if biplist is None: raise UnsupportedSerializationFormat("Usage of the plist aspects requires biplist.") return biplist.writePlistToString(self.to_simple(data, options))
def send_plist(self, plist): self.sendLock.acquire() self.logger.debug("Sending:\n{0}".format( pprint.pformat(plist, width=40))) bplist = biplist.writePlistToString(plist) # self.unzipped_output_buffer = struct.pack('>BI', 2, len(bplist)) + bplist self.flush_unzipped_output() self.sendLock.release()
def save_comic(self, number): raw_comic = self.fetch_comic(number) if not raw_comic: return False cleaned = self.process(raw_comic) encoded = biplist.writePlistToString(cleaned) basename = "{number:09d}{suffix}".format(number=number, suffix=FILE_SUFFIX) with open(os.path.join(self.directory, basename), "wb") as outfile: outfile.write(encoded) return True
def handle_info(self): if "Content-Type" in self.headers: if self.headers["Content-Type"] == HTTP_CT_BPLIST: content_len = int(self.headers["Content-Length"]) if content_len > 0: body = self.rfile.read(content_len) plist = readPlistFromString(body) self.pp.pprint(plist) if "qualifier" in plist and "txtAirPlay" in plist[ "qualifier"]: print("Sending:") self.pp.pprint(sonos_one_info) res = writePlistToString(sonos_one_info) self.send_response(200) self.send_header("Content-Length", len(res)) self.send_header("Content-Type", HTTP_CT_BPLIST) self.send_header("Server", self.version_string()) self.send_header("CSeq", self.headers["CSeq"]) self.end_headers() self.wfile.write(res) else: print("No txtAirPlay") self.send_error(404) return else: print("No content") self.send_error(404) return else: print("Content-Type: %s | Not implemented" % self.headers["Content-Type"]) self.send_error(404) else: res = writePlistToString(sonos_one_info) self.send_response(200) self.send_header("Content-Length", len(res)) self.send_header("Content-Type", HTTP_CT_BPLIST) self.send_header("Server", self.version_string()) self.send_header("CSeq", self.headers["CSeq"]) self.end_headers() self.wfile.write(res)
def to_plist(self, data, options=None): """ Given some Python data, produces binary plist output. """ options = options or {} if biplist is None: raise ImproperlyConfigured("Usage of the plist aspects requires biplist.") return biplist.writePlistToString(self.to_simple(data, options))
def get_prep_value(self, value): if value: try: biplist.readPlistFromString(value) except biplist.InvalidPlistException: return biplist.writePlistToString( value, binary=True) else: return value return value
def test_parse_binary_plist(self): obj = { 'date': datetime.datetime.now().replace(microsecond=0), 'int': 1, 'real': 2.0, 'none': None, 'string': 'abc', } binary = writePlistToString(obj) data = self.parser.parse(binary) self.assertEqual(data, obj)
def handle_configure(self): acl_s = 'Access_Control_Level' acl = 0 cd_s = 'ConfigurationDictionary' dn = 'NEWBORNE' dn_s = 'Device_Name' hkac = False hkac_s = 'Enable_HK_Access_Control' pw = '' pw_s = 'Password' print("configure %s" % self.path) print(self.headers) content_len = int(self.headers["Content-Length"]) if content_len > 0: body = self.rfile.read(content_len) plist = readPlistFromString(body) self.pp.pprint(plist) if acl_s in plist[cd_s]: # 0 == Everyone on the LAN # 1 == Home members # 2 == Admin members acl = int(plist[cd_s][acl_s]) if dn_s in plist[cd_s]: dn = plist[cd_s][dn_s] if hkac_s in plist[cd_s]: hkac = bool(plist[cd_s][hkac_s]) if pw_s in plist[cd_s]: pw = plist[cd_s][pw_s] accessory_id, accessory_ltpk = self.server.hap.configure() configure_info = { 'Identifier': accessory_id.decode('utf-8'), 'Enable_HK_Access_Control': hkac, 'PublicKey': accessory_ltpk, 'Device_Name': dn, 'Access_Control_Level': acl } if pw != '': configure_info['Password'] = pw res = writePlistToString(configure_info) self.pp.pprint(configure_info) self.send_response(200) self.send_header("Content-Length", len(res)) self.send_header("Content-Type", HTTP_CT_BPLIST) self.send_header("Server", self.version_string()) self.send_header("CSeq", self.headers["CSeq"]) self.end_headers() self.wfile.write(res)
def handler_bplist(filename, filepath, info, out=None, settings=None ): if out != None: out.put("\t[PLIST] Extractiong: " + filepath) else: print "\t[PLIST] Extractiong: " + filepath try: plist = biplist.readPlist(filepath) content = biplist.writePlistToString(plist,False) fobj = ExtractStore.ApplicationFile(filename,ExtractStore.TYPE_XML) fobj.add_content(content) return fobj except: return handle_data(filename,filepath,info,out)
def test_notification_with_biplist_payload(self): imessage_hash = 'e4e6d952954168d0a5db02dbaf27cc35fc18d159' self.dict['topic'] = imessage_hash.decode('hex') self.dict['payload'] = biplist.writePlistToString({'int': 160}) notification = messages.APSNotification(**self.dict) notification.parsingFinished() formatted = str(notification) self.assertEquals(formatted, '''APSNotification com.apple.madrid timestamp: 2011-10-29 15:52:20.335509 expiry: 2011-10-30 15:52:20 messageId: deadbeef storageFlags: 00 unknown9: None payload decoded (biplist) {'int': 160}''')
def createPlist(self, data): import biplist plist_data = biplist.writePlistToString(data, binary=False) try: with open('tmp.plist', 'w') as f: f.write(plist_data) os.system('plutil -convert binary1 tmp.plist') with open('tmp.plist', 'rb') as f: plist_data = f.read() finally: os.unlink('tmp.plist') header = hex(0x0200000000 + eval(hex(len(plist_data))))[2:].zfill(10).decode('hex') data = self.compressor.compress(header) + self.compressor.compress(plist_data) return data + self.compressor.flush(zlib.Z_SYNC_FLUSH)
def test_notification_with_biplist_payload(self): imessage_hash = 'e4e6d952954168d0a5db02dbaf27cc35fc18d159' self.dict['topic'] = imessage_hash.decode('hex') self.dict['payload'] = biplist.writePlistToString({'int': 160}) notification = messages.APSNotification(**self.dict) notification.parsingFinished() formatted = str(notification) self.assertEquals( formatted, '''APSNotification com.apple.madrid timestamp: 2011-10-29 15:52:20.335509 expiry: 2011-10-30 15:52:20 messageId: deadbeef storageFlags: 00 unknown9: None payload decoded (biplist) {'int': 160}''')
def hash_to_dep_biplist(cls, secret, config=None, **kwds): validate_secret(secret) self = cls(use_defaults=True, **kwds) self.checksum = self._calc_checksum(secret) plist_dict = { 'SALTED-SHA512-PBKDF2': { 'entropy': biplist.Data(self.checksum), 'salt': biplist.Data(self.salt), 'iterations': int(self.rounds), } } return biplist.writePlistToString(plist_dict)
def set_rating(path, rating): """Set star rating of `path` to `rating`. Args: path (unicode): File whose rating to set. rating (float): Star rating between 0.0 and 5.0. Raises: IOError: Raised if `setxattr` call fails. """ p = c_path(path) bplist = writePlistToString(rating) size = c_uint64(len(bplist)) success = xattr.setxattr(p, RATING_KEY_C, bplist, size, 0, 0) if success == -1: raise IOError('setxattr failed for path `{}`'.format(path))
def to_binary(self): import biplist return biplist.writePlistToString(self) self.obj_index = 0 self.obj_offsets = {} self._values = {} self.obj_count = self._get_obj_count() self.ref_size = self._pack_int(self.obj_count)[2] _, buf, offset = self._write_object(self, 0, 8) if (len(buf) + 8) != offset: raise RuntimeError("(buf length[%s] + 8) != offset[%s]" % (len(buf), offset)) for obj_offset in self.obj_offsets.values(): buf += struct.pack(">H", obj_offset) buf += struct.pack(">6xBBQQQ", 2, self.ref_size, self.obj_count, 0, offset) return b"bplist00" + buf
def send_rloevent_response(rloconf, environ, start_response): evqueue = rloevents.get(rloconf) if evqueue: del rloevents[rloconf] q = qenv(environ['QUERY_STRING']) use_xml = q('xml') data = '' params = {'events': tuple(evqueue)} if not use_xml and have_biplist: data = biplist.writePlistToString(params, binary=True) else: data = plistlib.writePlistToString(params) response_headers = [('RLOResponseType', 'RLOEvent'), ('Content-type', 'text/html'), ('Content-Length', str(len(data)))] start_response("200 OK", response_headers) return [data]
def send_rloevent_response(rloconf, environ, start_response): evqueue = rloevents.get(rloconf) if evqueue: del rloevents[rloconf] q = qenv(environ['QUERY_STRING']) use_xml = q('xml') data = '' params = { 'events': tuple(evqueue) } if not use_xml and have_biplist: data = biplist.writePlistToString(params, binary=True) else: data = plistlib.writePlistToString(params) response_headers = [('RLOResponseType', 'RLOEvent'), ('Content-type', 'text/html'), ('Content-Length', str(len(data))) ] start_response("200 OK", response_headers) return [data]
def post(self, request, token): instance = Instance.objects.select_related( 'project__bundle_identifier', 'project__name').get(token=token) zipped_file = ZipFile(instance.ipa_path.path, 'a') path = request.POST['path'] option = request.POST.get('option') options = [] if option: options = option.split(',') contents = request.POST.get('contents') print path if not contents: uploaded_file = request.FILES['file'] zipped_file.writestr('Payload/' + instance.name + '.app' + path, uploaded_file.read()) else: if "convert_to_binary_plist" in options: contents = biplist.writePlistToString(contents) zipped_file.writestr('Payload/' + instance.name + '.app' + path, contents) return HttpResponse('success')
def _create_ipa(self, create_info_plist=True, universal=False, iphone=False, ipad=False, app_name=None, bundle_display_name=None): h, zippath = mkstemp(prefix='libipa-', suffix='.ipa') self._temp_files.append(zippath) if not app_name: app_name = self._random_string() if six.PY2: app_dir = b'%s.app' % (app_name,) else: app_dir = '{0}.app'.format(app_name).encode('utf-8') with ZipFile(zippath, 'w', ZIP_DEFLATED) as h: if create_info_plist: info = dict( CFBundleIdentifier='com.{0}.{1}'.format( self._random_string(), self._random_string(), ), CFBundleDisplayName=app_name, LSRequiresIPhoneOS=True, MinimumOSVersion='6.0', UIStatusBarStyle='UIStatusBarStyleDefault', ) if six.PY3 and type(app_dir) is str: app_dir = app_dir.encode('utf-8') if six.PY3 and type(app_name) is str: app_name = app_name.encode('utf-8') app_dir = b'Payload/' + app_dir + b'/' app_path = app_dir + app_name if six.PY3: app_path = app_path.decode('utf-8') h.writestr(app_path, b'FACE') if bundle_display_name is False: del info['CFBundleDisplayName'] if universal: info['UIDeviceFamily'] = [1, 2] elif iphone: info['UIDeviceFamily'] = [1] elif ipad: info['UIDeviceFamily'] = [2] else: # Default to one. info['UIDeviceFamily'] = [1] info_plist_name = app_dir + b'Info.plist' if six.PY3: info_plist_name = info_plist_name.decode('utf-8') h.writestr(info_plist_name, writePlistToString(info)) h.writestr('iTunesMetadata.plist', writePlistToString({'Test': 'Data'})) return zippath
def encode(self, data): return biplist.writePlistToString(data)
def convert_bin_xml(bin_xml_file): """Convert Binary XML to Readable XML""" plist_obj = readPlist(bin_xml_file) data = writePlistToString(plist_obj) return data
def convert_data_to_binary_plist(self, context): # TODO: handle datetime classes import biplist return biplist.writePlistToString(context)
def set_tags(path, tags): data = biplist.writePlistToString(tags) xattr.setxattr(path, 'com.apple.metadata:_kMDItemUserTags', data)
def dumps(data): return biplist.writePlistToString(data)
def sendPList(self, content, binary=False): mime = "application/x-plist" if binary else "text/x-apple-plist+xml" self.sendContent(biplist.writePlistToString(content, binary), mime)
def encode(plist): return biplist.writePlistToString(plist)
def send_plist(self, plist): print "Sending: ", plist bplist = biplist.writePlistToString(plist); self.unzipped_output_buffer = struct.pack('>BI', 2,len(bplist)) + bplist self.flush_unzipped_output()
def send_file(environ, start_response, filename): global last_rloconf q = qenv(environ['QUERY_STRING']) rloconf = q('rloconf') if not rloconf_valid(rloconf): start_response("404 NOT FOUND", [('Content-type', 'text/plain')]) return ['Invalid rloconf parameter'] last_rloconf = rloconf if not is_cache_operation(filename) and find_file(rloconf, filename) is None and filename != TESTCONF_NAME: start_response("404 NOT FOUND", [('Content-type', 'text/plain')]) return ['What are you looking for?'] clear_rlodict(rloconf) recent_configurations.add(rloconf) extra_headers = [] if filename == TESTCONF_NAME: use_xml = q('xml') data, mimetype, changed_file, extra_headers, changetype = wait_for_change(rloconf, filename, q) if changetype == "rloevent": return send_rloevent_response(rloconf, environ, start_response) if changed_file is not None: if data is not None: # A new bundle is ready filename = changed_file else: if changed_file == TESTCONF_NAME: # rloconfig has changed, clear updated variables if not persistent_updates: try: del updated_variables[rloconf] except KeyError: pass try: del updated_variables_changed[rloconf] except KeyError: pass else: filename = changed_file data, mimetype, encoding = data_from_file(rloconf, filename) if data is None: root = rloconfigAsDict(rloconf) if not use_xml and have_biplist: data = biplist.writePlistToString(root, binary=True) else: data = plistlib.writePlistToString(root) else: data, mimetype, encoding = data_from_file(rloconf, filename) response_headers = [ ('Filename', urllib.quote(filename.encode('utf-8'))), ('Content-type', mimetype or 'text/plain') ] response_headers.extend(extra_headers) # Compress data as gzip if this is requested and it reduces the amount of traffic if data and 'gzip' in environ.get('HTTP_ACCEPT_ENCODING', ''): zbuf = cStringIO.StringIO() zfile = gzip.GzipFile(mode='wb', compresslevel=6, fileobj=zbuf) zfile.write(data) zfile.close() cdata = zbuf.getvalue() gzip_header = ('Content-Encoding', 'gzip') gzip_header_length = len(': '.join(gzip_header)) if len(cdata) + gzip_header_length < len(data): data = cdata response_headers.append(gzip_header) if data is None: start_response("404 NOT FOUND", [('Content-type', 'text/plain')]) return ['What are you looking for?'] response_headers.append(('Content-Length', str(len(data)))) start_response("200 OK", response_headers) return [data]
def write(self, *tags): tag_plist = writePlistToString(list(map(tag_normalize, tags))) for key in self.TAG_XATTRS: self.xa.set(key, tag_plist)