IP : 3.137.41.133Hostname : host45.registrar-servers.comKernel : Linux host45.registrar-servers.com 4.18.0-513.18.1.lve.2.el8.x86_64 #1 SMP Sat Mar 30 15:36:11 UTC 2024 x86_64Disable Function : None :) OS : Linux
PATH:
/
home/
../
./
./
home1/
../
../
../
lib64/
security/
../
./
python3.8/
plistlib.py/
/
r"""plistlib.py -- a tool to generate and parse MacOSX .plist files.
The property list (.plist) file format is a simple XML pickle supporting basic object types, like dictionaries, lists, numbers and strings. Usually the top level object is a dictionary.
To write out a plist file, use the dump(value, file) function. 'value' is the top level object, 'file' is a (writable) file object.
To parse a plist from a file, use the load(file) function, with a (readable) file object as the only argument. It returns the top level object (again, usually a dictionary).
To work with plist data in bytes objects, you can use loads() and dumps().
Values can be strings, integers, floats, booleans, tuples, lists, dictionaries (but only with string keys), Data, bytes, bytearray, or datetime.datetime objects.
@contextlib.contextmanager def _maybe_open(pathOrFile, mode): if isinstance(pathOrFile, str): with open(pathOrFile, mode) as fp: yield fp
else: yield pathOrFile
def readPlist(pathOrFile): """ Read a .plist from a path or file. pathOrFile should either be a file name, or a readable binary file object.
This function is deprecated, use load instead. """ warn("The readPlist function is deprecated, use load() instead", DeprecationWarning, 2)
with _maybe_open(pathOrFile, 'rb') as fp: return load(fp, fmt=None, use_builtin_types=False)
def writePlist(value, pathOrFile): """ Write 'value' to a .plist file. 'pathOrFile' may either be a file name or a (writable) file object.
This function is deprecated, use dump instead. """ warn("The writePlist function is deprecated, use dump() instead", DeprecationWarning, 2) with _maybe_open(pathOrFile, 'wb') as fp: dump(value, fp, fmt=FMT_XML, sort_keys=True, skipkeys=False)
def readPlistFromBytes(data): """ Read a plist data from a bytes object. Return the root object.
This function is deprecated, use loads instead. """ warn("The readPlistFromBytes function is deprecated, use loads() instead", DeprecationWarning, 2) return load(BytesIO(data), fmt=None, use_builtin_types=False)
def writePlistToBytes(value): """ Return 'value' as a plist-formatted bytes object.
This function is deprecated, use dumps instead. """ warn("The writePlistToBytes function is deprecated, use dumps() instead", DeprecationWarning, 2) f = BytesIO() dump(value, f, fmt=FMT_XML, sort_keys=True, skipkeys=False) return f.getvalue()
class Data: """ Wrapper for binary data.
This class is deprecated, use a bytes object instead. """
def __init__(self, data): if not isinstance(data, bytes): raise TypeError("data must be as bytes") self.data = data
@classmethod def fromBase64(cls, data): # base64.decodebytes just calls binascii.a2b_base64; # it seems overkill to use both base64 and binascii. return cls(_decode_base64(data))
class UID: def __init__(self, data): if not isinstance(data, int): raise TypeError("data must be an int") if data >= 1 << 64: raise ValueError("UIDs cannot be >= 2**64") if data < 0: raise ValueError("UIDs must be positive") self.data = data
def __eq__(self, other): if not isinstance(other, UID): return NotImplemented return self.data == other.data
def __hash__(self): return hash(self.data)
# # XML support #
# XML 'header' PLISTHEADER = b"""\ <?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd"> """
# Regex to find any control chars, except for \t \n and \r _controlCharPat = re.compile( r"[\x00\x01\x02\x03\x04\x05\x06\x07\x08\x0b\x0c\x0e\x0f" r"\x10\x11\x12\x13\x14\x15\x16\x17\x18\x19\x1a\x1b\x1c\x1d\x1e\x1f]")
def _encode_base64(s, maxlinelength=76): # copied from base64.encodebytes(), with added maxlinelength argument maxbinsize = (maxlinelength//4)*3 pieces = [] for i in range(0, len(s), maxbinsize): chunk = s[i : i + maxbinsize] pieces.append(binascii.b2a_base64(chunk)) return b''.join(pieces)
def _decode_base64(s): if isinstance(s, str): return binascii.a2b_base64(s.encode("utf-8"))
else: return binascii.a2b_base64(s)
# Contents should conform to a subset of ISO 8601 # (in particular, YYYY '-' MM '-' DD 'T' HH ':' MM ':' SS 'Z'. Smaller units # may be omitted with # a loss of precision) _dateParser = re.compile(r"(?P<year>\d\d\d\d)(?:-(?P<month>\d\d)(?:-(?P<day>\d\d)(?:T(?P<hour>\d\d)(?::(?P<minute>\d\d)(?::(?P<second>\d\d))?)?)?)?)?Z", re.ASCII)
def _date_from_string(s): order = ('year', 'month', 'day', 'hour', 'minute', 'second') gd = _dateParser.match(s).groupdict() lst = [] for key in order: val = gd[key] if val is None: break lst.append(int(val)) return datetime.datetime(*lst)
def _escape(text): m = _controlCharPat.search(text) if m is not None: raise ValueError("strings can't contains control characters; " "use bytes instead") text = text.replace("\r\n", "\n") # convert DOS line endings text = text.replace("\r", "\n") # convert Mac line endings text = text.replace("&", "&") # escape '&' text = text.replace("<", "<") # escape '<' text = text.replace(">", ">") # escape '>' return text
def handle_entity_decl(self, entity_name, is_parameter_entity, value, base, system_id, public_id, notation_name): # Reject plist files with entity declarations to avoid XML vulnerabilies in expat. # Regular plist files don't contain those declerations, and Apple's plutil tool does not # accept them either. raise InvalidFileException("XML entity declarations are not supported in plist files")
def handle_begin_element(self, element, attrs): self.data = [] handler = getattr(self, "begin_" + element, None) if handler is not None: handler(attrs)
def handle_end_element(self, element): handler = getattr(self, "end_" + element, None) if handler is not None: handler()
def add_object(self, value): if self.current_key is not None: if not isinstance(self.stack[-1], type({})): raise ValueError("unexpected element at line %d" % self.parser.CurrentLineNumber) self.stack[-1][self.current_key] = value self.current_key = None elif not self.stack: # this is the root object self.root = value else: if not isinstance(self.stack[-1], type([])): raise ValueError("unexpected element at line %d" % self.parser.CurrentLineNumber) self.stack[-1].append(value)
def get_data(self): data = ''.join(self.data) self.data = [] return data
# element handlers
def begin_dict(self, attrs): d = self._dict_type() self.add_object(d) self.stack.append(d)
def end_dict(self): if self.current_key: raise ValueError("missing value for key '%s' at line %d" % (self.current_key,self.parser.CurrentLineNumber)) self.stack.pop()
def end_key(self): if self.current_key or not isinstance(self.stack[-1], type({})): raise ValueError("unexpected key at line %d" % self.parser.CurrentLineNumber) self.current_key = self.get_data()
def begin_array(self, attrs): a = [] self.add_object(a) self.stack.append(a)
def end_array(self): self.stack.pop()
def end_true(self): self.add_object(True)
def end_false(self): self.add_object(False)
def end_integer(self): raw = self.get_data() if raw.startswith('0x') or raw.startswith('0X'): self.add_object(int(raw, 16)) else: self.add_object(int(raw))
def simple_element(self, element, value=None): if value is not None: value = _escape(value) self.writeln("<%s>%s</%s>" % (element, value, element))
else: self.writeln("<%s/>" % element)
def writeln(self, line): if line: # plist has fixed encoding of utf-8
# XXX: is this test needed? if isinstance(line, str): line = line.encode('utf-8') self.file.write(self._indent_level * self.indent) self.file.write(line) self.file.write(b'\n')
for line in _encode_base64(data, maxlinelength).split(b"\n"): if line: self.writeln(line) self._indent_level += 1 self.end_element("data")
def write_dict(self, d): if d: self.begin_element("dict") if self._sort_keys: items = sorted(d.items()) else: items = d.items()
for key, value in items: if not isinstance(key, str): if self._skipkeys: continue raise TypeError("keys must be strings") self.simple_element("key", key) self.write_value(value) self.end_element("dict")
else: self.simple_element("dict")
def write_array(self, array): if array: self.begin_element("array") for value in array: self.write_value(value) self.end_element("array")
for pfx in prefixes: if header.startswith(pfx): return True
# Also check for alternative XML encodings, this is slightly # overkill because the Apple tools (and plistlib) will not # generate files with these encodings. for bom, encoding in ( (codecs.BOM_UTF8, "utf-8"), (codecs.BOM_UTF16_BE, "utf-16-be"), (codecs.BOM_UTF16_LE, "utf-16-le"), # expat does not support utf-32 #(codecs.BOM_UTF32_BE, "utf-32-be"), #(codecs.BOM_UTF32_LE, "utf-32-le"), ): if not header.startswith(bom): continue
for start in prefixes: prefix = bom + start.decode('ascii').encode(encoding) if header[:len(prefix)] == prefix: return True
return False
# # Binary Plist #
class InvalidFileException (ValueError): def __init__(self, message="Invalid file"): ValueError.__init__(self, message)
_BINARY_FORMAT = {1: 'B', 2: 'H', 4: 'L', 8: 'Q'}
_undefined = object()
class _BinaryPlistParser: """ Read or write a binary plist file, following the description of the binary format. Raise InvalidFileException in case of error, otherwise return the root object.
def _get_size(self, tokenL): """ return the size of the next object.""" if tokenL == 0xF: m = self._fp.read(1)[0] & 0x3 s = 1 << m f = '>' + _BINARY_FORMAT[s] return struct.unpack(f, self._fp.read(s))[0]
return tokenL
def _read_ints(self, n, size): data = self._fp.read(size * n) if size in _BINARY_FORMAT: return struct.unpack(f'>{n}{_BINARY_FORMAT[size]}', data) else: if not size or len(data) != size * n: raise InvalidFileException() return tuple(int.from_bytes(data[i: i + size], 'big') for i in range(0, size * n, size))
# The referenced source code also mentions URL (0x0c, 0x0d) and # UUID (0x0e), but neither can be generated using the Cocoa libraries.
elif token == 0x0f: result = b''
elif tokenH == 0x10: # int result = int.from_bytes(self._fp.read(1 << tokenL), 'big', signed=tokenL >= 3)
elif token == 0x22: # real result = struct.unpack('>f', self._fp.read(4))[0]
elif token == 0x23: # real result = struct.unpack('>d', self._fp.read(8))[0]
elif token == 0x33: # date f = struct.unpack('>d', self._fp.read(8))[0] # timestamp 0 of binary plists corresponds to 1/1/2001 # (year of Mac OS X 10.0), instead of 1/1/1970. result = (datetime.datetime(2001, 1, 1) + datetime.timedelta(seconds=f))
elif tokenH == 0x40: # data s = self._get_size(tokenL) result = self._fp.read(s) if len(result) != s: raise InvalidFileException() if not self._use_builtin_types: result = Data(result)
elif tokenH == 0x50: # ascii string s = self._get_size(tokenL) data = self._fp.read(s) if len(data) != s: raise InvalidFileException() result = data.decode('ascii')
elif tokenH == 0x60: # unicode string s = self._get_size(tokenL) * 2 data = self._fp.read(s) if len(data) != s: raise InvalidFileException() result = data.decode('utf-16be')
elif tokenH == 0x80: # UID # used by Key-Archiver plist files result = UID(int.from_bytes(self._fp.read(1 + tokenL), 'big'))
elif tokenH == 0xA0: # array s = self._get_size(tokenL) obj_refs = self._read_refs(s) result = [] self._objects[ref] = result result.extend(self._read_object(x) for x in obj_refs)
# tokenH == 0xB0 is documented as 'ordset', but is not actually # implemented in the Apple reference code.
# tokenH == 0xC0 is documented as 'set', but sets cannot be used in # plists.
elif tokenH == 0xD0: # dict s = self._get_size(tokenL) key_refs = self._read_refs(s) obj_refs = self._read_refs(s) result = self._dict_type() self._objects[ref] = result try: for k, o in zip(key_refs, obj_refs): result[self._read_object(k)] = self._read_object(o) except TypeError: raise InvalidFileException() else: raise InvalidFileException()
self._objects[ref] = result return result
def _count_to_size(count): if count < 1 << 8: return 1
# Mappings from object->objectid # First dict has (type(object), object) as the key, # second dict is used when object is not hashable and # has id(object) as the key. self._objtable = {} self._objidtable = {}
# Create list of all objects in the plist self._flatten(value)
# Size of object references in serialized containers # depends on the number of objects in the plist. num_objects = len(self._objlist) self._object_offsets = [0]*num_objects self._ref_size = _count_to_size(num_objects)
self._ref_format = _BINARY_FORMAT[self._ref_size]
# Write file header self._fp.write(b'bplist00')
# Write object list for obj in self._objlist: self._write_object(obj)
def _flatten(self, value): # First check if the object is in the object table, not used for # containers to ensure that two subcontainers with the same contents # will be serialized as distinct values. if isinstance(value, _scalars): if (type(value), value) in self._objtable: return
elif isinstance(value, Data): if (type(value.data), value.data) in self._objtable: return
if self._sort_keys: rootItems = sorted(value.items()) else: rootItems = value.items()
for k, v in rootItems: if not isinstance(k, str): if self._skipkeys: continue raise TypeError("keys must be strings") keyRefs.append(self._getrefnum(k)) valRefs.append(self._getrefnum(v))
def load(fp, *, fmt=None, use_builtin_types=True, dict_type=dict): """Read a .plist file. 'fp' should be a readable and binary file object. Return the unpacked root object (which usually is a dictionary). """ if fmt is None: header = fp.read(32) fp.seek(0) for info in _FORMATS.values(): if info['detect'](header): P = info['parser'] break
else: raise InvalidFileException()
else: P = _FORMATS[fmt]['parser']
p = P(use_builtin_types=use_builtin_types, dict_type=dict_type) return p.parse(fp)
def loads(value, *, fmt=None, use_builtin_types=True, dict_type=dict): """Read a .plist file from a bytes object. Return the unpacked root object (which usually is a dictionary). """ fp = BytesIO(value) return load( fp, fmt=fmt, use_builtin_types=use_builtin_types, dict_type=dict_type)
def dump(value, fp, *, fmt=FMT_XML, sort_keys=True, skipkeys=False): """Write 'value' to a .plist file. 'fp' should be a writable, binary file object. """ if fmt not in _FORMATS: raise ValueError("Unsupported format: %r"%(fmt,))