plistlib.py 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902
  1. r"""plistlib.py -- a tool to generate and parse MacOSX .plist files.
  2. The property list (.plist) file format is a simple XML pickle supporting
  3. basic object types, like dictionaries, lists, numbers and strings.
  4. Usually the top level object is a dictionary.
  5. To write out a plist file, use the dump(value, file)
  6. function. 'value' is the top level object, 'file' is
  7. a (writable) file object.
  8. To parse a plist from a file, use the load(file) function,
  9. with a (readable) file object as the only argument. It
  10. returns the top level object (again, usually a dictionary).
  11. To work with plist data in bytes objects, you can use loads()
  12. and dumps().
  13. Values can be strings, integers, floats, booleans, tuples, lists,
  14. dictionaries (but only with string keys), Data, bytes, bytearray, or
  15. datetime.datetime objects.
  16. Generate Plist example:
  17. pl = dict(
  18. aString = "Doodah",
  19. aList = ["A", "B", 12, 32.1, [1, 2, 3]],
  20. aFloat = 0.1,
  21. anInt = 728,
  22. aDict = dict(
  23. anotherString = "<hello & hi there!>",
  24. aUnicodeValue = "M\xe4ssig, Ma\xdf",
  25. aTrueValue = True,
  26. aFalseValue = False,
  27. ),
  28. someData = b"<binary gunk>",
  29. someMoreData = b"<lots of binary gunk>" * 10,
  30. aDate = datetime.datetime.fromtimestamp(time.mktime(time.gmtime())),
  31. )
  32. with open(fileName, 'wb') as fp:
  33. dump(pl, fp)
  34. Parse Plist example:
  35. with open(fileName, 'rb') as fp:
  36. pl = load(fp)
  37. print(pl["aKey"])
  38. """
  39. __all__ = [
  40. "InvalidFileException", "FMT_XML", "FMT_BINARY", "load", "dump", "loads", "dumps", "UID"
  41. ]
  42. import binascii
  43. import codecs
  44. import datetime
  45. import enum
  46. from io import BytesIO
  47. import itertools
  48. import os
  49. import re
  50. import struct
  51. from xml.parsers.expat import ParserCreate
  52. PlistFormat = enum.Enum('PlistFormat', 'FMT_XML FMT_BINARY', module=__name__)
  53. globals().update(PlistFormat.__members__)
  54. class UID:
  55. def __init__(self, data):
  56. if not isinstance(data, int):
  57. raise TypeError("data must be an int")
  58. if data >= 1 << 64:
  59. raise ValueError("UIDs cannot be >= 2**64")
  60. if data < 0:
  61. raise ValueError("UIDs must be positive")
  62. self.data = data
  63. def __index__(self):
  64. return self.data
  65. def __repr__(self):
  66. return "%s(%s)" % (self.__class__.__name__, repr(self.data))
  67. def __reduce__(self):
  68. return self.__class__, (self.data,)
  69. def __eq__(self, other):
  70. if not isinstance(other, UID):
  71. return NotImplemented
  72. return self.data == other.data
  73. def __hash__(self):
  74. return hash(self.data)
  75. #
  76. # XML support
  77. #
  78. # XML 'header'
  79. PLISTHEADER = b"""\
  80. <?xml version="1.0" encoding="UTF-8"?>
  81. <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
  82. """
  83. # Regex to find any control chars, except for \t \n and \r
  84. _controlCharPat = re.compile(
  85. r"[\x00\x01\x02\x03\x04\x05\x06\x07\x08\x0b\x0c\x0e\x0f"
  86. r"\x10\x11\x12\x13\x14\x15\x16\x17\x18\x19\x1a\x1b\x1c\x1d\x1e\x1f]")
  87. def _encode_base64(s, maxlinelength=76):
  88. # copied from base64.encodebytes(), with added maxlinelength argument
  89. maxbinsize = (maxlinelength//4)*3
  90. pieces = []
  91. for i in range(0, len(s), maxbinsize):
  92. chunk = s[i : i + maxbinsize]
  93. pieces.append(binascii.b2a_base64(chunk))
  94. return b''.join(pieces)
  95. def _decode_base64(s):
  96. if isinstance(s, str):
  97. return binascii.a2b_base64(s.encode("utf-8"))
  98. else:
  99. return binascii.a2b_base64(s)
  100. # Contents should conform to a subset of ISO 8601
  101. # (in particular, YYYY '-' MM '-' DD 'T' HH ':' MM ':' SS 'Z'. Smaller units
  102. # may be omitted with # a loss of precision)
  103. _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)
  104. def _date_from_string(s):
  105. order = ('year', 'month', 'day', 'hour', 'minute', 'second')
  106. gd = _dateParser.match(s).groupdict()
  107. lst = []
  108. for key in order:
  109. val = gd[key]
  110. if val is None:
  111. break
  112. lst.append(int(val))
  113. return datetime.datetime(*lst)
  114. def _date_to_string(d):
  115. return '%04d-%02d-%02dT%02d:%02d:%02dZ' % (
  116. d.year, d.month, d.day,
  117. d.hour, d.minute, d.second
  118. )
  119. def _escape(text):
  120. m = _controlCharPat.search(text)
  121. if m is not None:
  122. raise ValueError("strings can't contains control characters; "
  123. "use bytes instead")
  124. text = text.replace("\r\n", "\n") # convert DOS line endings
  125. text = text.replace("\r", "\n") # convert Mac line endings
  126. text = text.replace("&", "&amp;") # escape '&'
  127. text = text.replace("<", "&lt;") # escape '<'
  128. text = text.replace(">", "&gt;") # escape '>'
  129. return text
  130. class _PlistParser:
  131. def __init__(self, dict_type):
  132. self.stack = []
  133. self.current_key = None
  134. self.root = None
  135. self._dict_type = dict_type
  136. def parse(self, fileobj):
  137. self.parser = ParserCreate()
  138. self.parser.StartElementHandler = self.handle_begin_element
  139. self.parser.EndElementHandler = self.handle_end_element
  140. self.parser.CharacterDataHandler = self.handle_data
  141. self.parser.EntityDeclHandler = self.handle_entity_decl
  142. self.parser.ParseFile(fileobj)
  143. return self.root
  144. def handle_entity_decl(self, entity_name, is_parameter_entity, value, base, system_id, public_id, notation_name):
  145. # Reject plist files with entity declarations to avoid XML vulnerabilies in expat.
  146. # Regular plist files don't contain those declerations, and Apple's plutil tool does not
  147. # accept them either.
  148. raise InvalidFileException("XML entity declarations are not supported in plist files")
  149. def handle_begin_element(self, element, attrs):
  150. self.data = []
  151. handler = getattr(self, "begin_" + element, None)
  152. if handler is not None:
  153. handler(attrs)
  154. def handle_end_element(self, element):
  155. handler = getattr(self, "end_" + element, None)
  156. if handler is not None:
  157. handler()
  158. def handle_data(self, data):
  159. self.data.append(data)
  160. def add_object(self, value):
  161. if self.current_key is not None:
  162. if not isinstance(self.stack[-1], type({})):
  163. raise ValueError("unexpected element at line %d" %
  164. self.parser.CurrentLineNumber)
  165. self.stack[-1][self.current_key] = value
  166. self.current_key = None
  167. elif not self.stack:
  168. # this is the root object
  169. self.root = value
  170. else:
  171. if not isinstance(self.stack[-1], type([])):
  172. raise ValueError("unexpected element at line %d" %
  173. self.parser.CurrentLineNumber)
  174. self.stack[-1].append(value)
  175. def get_data(self):
  176. data = ''.join(self.data)
  177. self.data = []
  178. return data
  179. # element handlers
  180. def begin_dict(self, attrs):
  181. d = self._dict_type()
  182. self.add_object(d)
  183. self.stack.append(d)
  184. def end_dict(self):
  185. if self.current_key:
  186. raise ValueError("missing value for key '%s' at line %d" %
  187. (self.current_key,self.parser.CurrentLineNumber))
  188. self.stack.pop()
  189. def end_key(self):
  190. if self.current_key or not isinstance(self.stack[-1], type({})):
  191. raise ValueError("unexpected key at line %d" %
  192. self.parser.CurrentLineNumber)
  193. self.current_key = self.get_data()
  194. def begin_array(self, attrs):
  195. a = []
  196. self.add_object(a)
  197. self.stack.append(a)
  198. def end_array(self):
  199. self.stack.pop()
  200. def end_true(self):
  201. self.add_object(True)
  202. def end_false(self):
  203. self.add_object(False)
  204. def end_integer(self):
  205. raw = self.get_data()
  206. if raw.startswith('0x') or raw.startswith('0X'):
  207. self.add_object(int(raw, 16))
  208. else:
  209. self.add_object(int(raw))
  210. def end_real(self):
  211. self.add_object(float(self.get_data()))
  212. def end_string(self):
  213. self.add_object(self.get_data())
  214. def end_data(self):
  215. self.add_object(_decode_base64(self.get_data()))
  216. def end_date(self):
  217. self.add_object(_date_from_string(self.get_data()))
  218. class _DumbXMLWriter:
  219. def __init__(self, file, indent_level=0, indent="\t"):
  220. self.file = file
  221. self.stack = []
  222. self._indent_level = indent_level
  223. self.indent = indent
  224. def begin_element(self, element):
  225. self.stack.append(element)
  226. self.writeln("<%s>" % element)
  227. self._indent_level += 1
  228. def end_element(self, element):
  229. assert self._indent_level > 0
  230. assert self.stack.pop() == element
  231. self._indent_level -= 1
  232. self.writeln("</%s>" % element)
  233. def simple_element(self, element, value=None):
  234. if value is not None:
  235. value = _escape(value)
  236. self.writeln("<%s>%s</%s>" % (element, value, element))
  237. else:
  238. self.writeln("<%s/>" % element)
  239. def writeln(self, line):
  240. if line:
  241. # plist has fixed encoding of utf-8
  242. # XXX: is this test needed?
  243. if isinstance(line, str):
  244. line = line.encode('utf-8')
  245. self.file.write(self._indent_level * self.indent)
  246. self.file.write(line)
  247. self.file.write(b'\n')
  248. class _PlistWriter(_DumbXMLWriter):
  249. def __init__(
  250. self, file, indent_level=0, indent=b"\t", writeHeader=1,
  251. sort_keys=True, skipkeys=False):
  252. if writeHeader:
  253. file.write(PLISTHEADER)
  254. _DumbXMLWriter.__init__(self, file, indent_level, indent)
  255. self._sort_keys = sort_keys
  256. self._skipkeys = skipkeys
  257. def write(self, value):
  258. self.writeln("<plist version=\"1.0\">")
  259. self.write_value(value)
  260. self.writeln("</plist>")
  261. def write_value(self, value):
  262. if isinstance(value, str):
  263. self.simple_element("string", value)
  264. elif value is True:
  265. self.simple_element("true")
  266. elif value is False:
  267. self.simple_element("false")
  268. elif isinstance(value, int):
  269. if -1 << 63 <= value < 1 << 64:
  270. self.simple_element("integer", "%d" % value)
  271. else:
  272. raise OverflowError(value)
  273. elif isinstance(value, float):
  274. self.simple_element("real", repr(value))
  275. elif isinstance(value, dict):
  276. self.write_dict(value)
  277. elif isinstance(value, (bytes, bytearray)):
  278. self.write_bytes(value)
  279. elif isinstance(value, datetime.datetime):
  280. self.simple_element("date", _date_to_string(value))
  281. elif isinstance(value, (tuple, list)):
  282. self.write_array(value)
  283. else:
  284. raise TypeError("unsupported type: %s" % type(value))
  285. def write_bytes(self, data):
  286. self.begin_element("data")
  287. self._indent_level -= 1
  288. maxlinelength = max(
  289. 16,
  290. 76 - len(self.indent.replace(b"\t", b" " * 8) * self._indent_level))
  291. for line in _encode_base64(data, maxlinelength).split(b"\n"):
  292. if line:
  293. self.writeln(line)
  294. self._indent_level += 1
  295. self.end_element("data")
  296. def write_dict(self, d):
  297. if d:
  298. self.begin_element("dict")
  299. if self._sort_keys:
  300. items = sorted(d.items())
  301. else:
  302. items = d.items()
  303. for key, value in items:
  304. if not isinstance(key, str):
  305. if self._skipkeys:
  306. continue
  307. raise TypeError("keys must be strings")
  308. self.simple_element("key", key)
  309. self.write_value(value)
  310. self.end_element("dict")
  311. else:
  312. self.simple_element("dict")
  313. def write_array(self, array):
  314. if array:
  315. self.begin_element("array")
  316. for value in array:
  317. self.write_value(value)
  318. self.end_element("array")
  319. else:
  320. self.simple_element("array")
  321. def _is_fmt_xml(header):
  322. prefixes = (b'<?xml', b'<plist')
  323. for pfx in prefixes:
  324. if header.startswith(pfx):
  325. return True
  326. # Also check for alternative XML encodings, this is slightly
  327. # overkill because the Apple tools (and plistlib) will not
  328. # generate files with these encodings.
  329. for bom, encoding in (
  330. (codecs.BOM_UTF8, "utf-8"),
  331. (codecs.BOM_UTF16_BE, "utf-16-be"),
  332. (codecs.BOM_UTF16_LE, "utf-16-le"),
  333. # expat does not support utf-32
  334. #(codecs.BOM_UTF32_BE, "utf-32-be"),
  335. #(codecs.BOM_UTF32_LE, "utf-32-le"),
  336. ):
  337. if not header.startswith(bom):
  338. continue
  339. for start in prefixes:
  340. prefix = bom + start.decode('ascii').encode(encoding)
  341. if header[:len(prefix)] == prefix:
  342. return True
  343. return False
  344. #
  345. # Binary Plist
  346. #
  347. class InvalidFileException (ValueError):
  348. def __init__(self, message="Invalid file"):
  349. ValueError.__init__(self, message)
  350. _BINARY_FORMAT = {1: 'B', 2: 'H', 4: 'L', 8: 'Q'}
  351. _undefined = object()
  352. class _BinaryPlistParser:
  353. """
  354. Read or write a binary plist file, following the description of the binary
  355. format. Raise InvalidFileException in case of error, otherwise return the
  356. root object.
  357. see also: http://opensource.apple.com/source/CF/CF-744.18/CFBinaryPList.c
  358. """
  359. def __init__(self, dict_type):
  360. self._dict_type = dict_type
  361. def parse(self, fp):
  362. try:
  363. # The basic file format:
  364. # HEADER
  365. # object...
  366. # refid->offset...
  367. # TRAILER
  368. self._fp = fp
  369. self._fp.seek(-32, os.SEEK_END)
  370. trailer = self._fp.read(32)
  371. if len(trailer) != 32:
  372. raise InvalidFileException()
  373. (
  374. offset_size, self._ref_size, num_objects, top_object,
  375. offset_table_offset
  376. ) = struct.unpack('>6xBBQQQ', trailer)
  377. self._fp.seek(offset_table_offset)
  378. self._object_offsets = self._read_ints(num_objects, offset_size)
  379. self._objects = [_undefined] * num_objects
  380. return self._read_object(top_object)
  381. except (OSError, IndexError, struct.error, OverflowError,
  382. ValueError):
  383. raise InvalidFileException()
  384. def _get_size(self, tokenL):
  385. """ return the size of the next object."""
  386. if tokenL == 0xF:
  387. m = self._fp.read(1)[0] & 0x3
  388. s = 1 << m
  389. f = '>' + _BINARY_FORMAT[s]
  390. return struct.unpack(f, self._fp.read(s))[0]
  391. return tokenL
  392. def _read_ints(self, n, size):
  393. data = self._fp.read(size * n)
  394. if size in _BINARY_FORMAT:
  395. return struct.unpack(f'>{n}{_BINARY_FORMAT[size]}', data)
  396. else:
  397. if not size or len(data) != size * n:
  398. raise InvalidFileException()
  399. return tuple(int.from_bytes(data[i: i + size], 'big')
  400. for i in range(0, size * n, size))
  401. def _read_refs(self, n):
  402. return self._read_ints(n, self._ref_size)
  403. def _read_object(self, ref):
  404. """
  405. read the object by reference.
  406. May recursively read sub-objects (content of an array/dict/set)
  407. """
  408. result = self._objects[ref]
  409. if result is not _undefined:
  410. return result
  411. offset = self._object_offsets[ref]
  412. self._fp.seek(offset)
  413. token = self._fp.read(1)[0]
  414. tokenH, tokenL = token & 0xF0, token & 0x0F
  415. if token == 0x00:
  416. result = None
  417. elif token == 0x08:
  418. result = False
  419. elif token == 0x09:
  420. result = True
  421. # The referenced source code also mentions URL (0x0c, 0x0d) and
  422. # UUID (0x0e), but neither can be generated using the Cocoa libraries.
  423. elif token == 0x0f:
  424. result = b''
  425. elif tokenH == 0x10: # int
  426. result = int.from_bytes(self._fp.read(1 << tokenL),
  427. 'big', signed=tokenL >= 3)
  428. elif token == 0x22: # real
  429. result = struct.unpack('>f', self._fp.read(4))[0]
  430. elif token == 0x23: # real
  431. result = struct.unpack('>d', self._fp.read(8))[0]
  432. elif token == 0x33: # date
  433. f = struct.unpack('>d', self._fp.read(8))[0]
  434. # timestamp 0 of binary plists corresponds to 1/1/2001
  435. # (year of Mac OS X 10.0), instead of 1/1/1970.
  436. result = (datetime.datetime(2001, 1, 1) +
  437. datetime.timedelta(seconds=f))
  438. elif tokenH == 0x40: # data
  439. s = self._get_size(tokenL)
  440. result = self._fp.read(s)
  441. if len(result) != s:
  442. raise InvalidFileException()
  443. elif tokenH == 0x50: # ascii string
  444. s = self._get_size(tokenL)
  445. data = self._fp.read(s)
  446. if len(data) != s:
  447. raise InvalidFileException()
  448. result = data.decode('ascii')
  449. elif tokenH == 0x60: # unicode string
  450. s = self._get_size(tokenL) * 2
  451. data = self._fp.read(s)
  452. if len(data) != s:
  453. raise InvalidFileException()
  454. result = data.decode('utf-16be')
  455. elif tokenH == 0x80: # UID
  456. # used by Key-Archiver plist files
  457. result = UID(int.from_bytes(self._fp.read(1 + tokenL), 'big'))
  458. elif tokenH == 0xA0: # array
  459. s = self._get_size(tokenL)
  460. obj_refs = self._read_refs(s)
  461. result = []
  462. self._objects[ref] = result
  463. result.extend(self._read_object(x) for x in obj_refs)
  464. # tokenH == 0xB0 is documented as 'ordset', but is not actually
  465. # implemented in the Apple reference code.
  466. # tokenH == 0xC0 is documented as 'set', but sets cannot be used in
  467. # plists.
  468. elif tokenH == 0xD0: # dict
  469. s = self._get_size(tokenL)
  470. key_refs = self._read_refs(s)
  471. obj_refs = self._read_refs(s)
  472. result = self._dict_type()
  473. self._objects[ref] = result
  474. try:
  475. for k, o in zip(key_refs, obj_refs):
  476. result[self._read_object(k)] = self._read_object(o)
  477. except TypeError:
  478. raise InvalidFileException()
  479. else:
  480. raise InvalidFileException()
  481. self._objects[ref] = result
  482. return result
  483. def _count_to_size(count):
  484. if count < 1 << 8:
  485. return 1
  486. elif count < 1 << 16:
  487. return 2
  488. elif count < 1 << 32:
  489. return 4
  490. else:
  491. return 8
  492. _scalars = (str, int, float, datetime.datetime, bytes)
  493. class _BinaryPlistWriter (object):
  494. def __init__(self, fp, sort_keys, skipkeys):
  495. self._fp = fp
  496. self._sort_keys = sort_keys
  497. self._skipkeys = skipkeys
  498. def write(self, value):
  499. # Flattened object list:
  500. self._objlist = []
  501. # Mappings from object->objectid
  502. # First dict has (type(object), object) as the key,
  503. # second dict is used when object is not hashable and
  504. # has id(object) as the key.
  505. self._objtable = {}
  506. self._objidtable = {}
  507. # Create list of all objects in the plist
  508. self._flatten(value)
  509. # Size of object references in serialized containers
  510. # depends on the number of objects in the plist.
  511. num_objects = len(self._objlist)
  512. self._object_offsets = [0]*num_objects
  513. self._ref_size = _count_to_size(num_objects)
  514. self._ref_format = _BINARY_FORMAT[self._ref_size]
  515. # Write file header
  516. self._fp.write(b'bplist00')
  517. # Write object list
  518. for obj in self._objlist:
  519. self._write_object(obj)
  520. # Write refnum->object offset table
  521. top_object = self._getrefnum(value)
  522. offset_table_offset = self._fp.tell()
  523. offset_size = _count_to_size(offset_table_offset)
  524. offset_format = '>' + _BINARY_FORMAT[offset_size] * num_objects
  525. self._fp.write(struct.pack(offset_format, *self._object_offsets))
  526. # Write trailer
  527. sort_version = 0
  528. trailer = (
  529. sort_version, offset_size, self._ref_size, num_objects,
  530. top_object, offset_table_offset
  531. )
  532. self._fp.write(struct.pack('>5xBBBQQQ', *trailer))
  533. def _flatten(self, value):
  534. # First check if the object is in the object table, not used for
  535. # containers to ensure that two subcontainers with the same contents
  536. # will be serialized as distinct values.
  537. if isinstance(value, _scalars):
  538. if (type(value), value) in self._objtable:
  539. return
  540. elif id(value) in self._objidtable:
  541. return
  542. # Add to objectreference map
  543. refnum = len(self._objlist)
  544. self._objlist.append(value)
  545. if isinstance(value, _scalars):
  546. self._objtable[(type(value), value)] = refnum
  547. else:
  548. self._objidtable[id(value)] = refnum
  549. # And finally recurse into containers
  550. if isinstance(value, dict):
  551. keys = []
  552. values = []
  553. items = value.items()
  554. if self._sort_keys:
  555. items = sorted(items)
  556. for k, v in items:
  557. if not isinstance(k, str):
  558. if self._skipkeys:
  559. continue
  560. raise TypeError("keys must be strings")
  561. keys.append(k)
  562. values.append(v)
  563. for o in itertools.chain(keys, values):
  564. self._flatten(o)
  565. elif isinstance(value, (list, tuple)):
  566. for o in value:
  567. self._flatten(o)
  568. def _getrefnum(self, value):
  569. if isinstance(value, _scalars):
  570. return self._objtable[(type(value), value)]
  571. else:
  572. return self._objidtable[id(value)]
  573. def _write_size(self, token, size):
  574. if size < 15:
  575. self._fp.write(struct.pack('>B', token | size))
  576. elif size < 1 << 8:
  577. self._fp.write(struct.pack('>BBB', token | 0xF, 0x10, size))
  578. elif size < 1 << 16:
  579. self._fp.write(struct.pack('>BBH', token | 0xF, 0x11, size))
  580. elif size < 1 << 32:
  581. self._fp.write(struct.pack('>BBL', token | 0xF, 0x12, size))
  582. else:
  583. self._fp.write(struct.pack('>BBQ', token | 0xF, 0x13, size))
  584. def _write_object(self, value):
  585. ref = self._getrefnum(value)
  586. self._object_offsets[ref] = self._fp.tell()
  587. if value is None:
  588. self._fp.write(b'\x00')
  589. elif value is False:
  590. self._fp.write(b'\x08')
  591. elif value is True:
  592. self._fp.write(b'\x09')
  593. elif isinstance(value, int):
  594. if value < 0:
  595. try:
  596. self._fp.write(struct.pack('>Bq', 0x13, value))
  597. except struct.error:
  598. raise OverflowError(value) from None
  599. elif value < 1 << 8:
  600. self._fp.write(struct.pack('>BB', 0x10, value))
  601. elif value < 1 << 16:
  602. self._fp.write(struct.pack('>BH', 0x11, value))
  603. elif value < 1 << 32:
  604. self._fp.write(struct.pack('>BL', 0x12, value))
  605. elif value < 1 << 63:
  606. self._fp.write(struct.pack('>BQ', 0x13, value))
  607. elif value < 1 << 64:
  608. self._fp.write(b'\x14' + value.to_bytes(16, 'big', signed=True))
  609. else:
  610. raise OverflowError(value)
  611. elif isinstance(value, float):
  612. self._fp.write(struct.pack('>Bd', 0x23, value))
  613. elif isinstance(value, datetime.datetime):
  614. f = (value - datetime.datetime(2001, 1, 1)).total_seconds()
  615. self._fp.write(struct.pack('>Bd', 0x33, f))
  616. elif isinstance(value, (bytes, bytearray)):
  617. self._write_size(0x40, len(value))
  618. self._fp.write(value)
  619. elif isinstance(value, str):
  620. try:
  621. t = value.encode('ascii')
  622. self._write_size(0x50, len(value))
  623. except UnicodeEncodeError:
  624. t = value.encode('utf-16be')
  625. self._write_size(0x60, len(t) // 2)
  626. self._fp.write(t)
  627. elif isinstance(value, UID):
  628. if value.data < 0:
  629. raise ValueError("UIDs must be positive")
  630. elif value.data < 1 << 8:
  631. self._fp.write(struct.pack('>BB', 0x80, value))
  632. elif value.data < 1 << 16:
  633. self._fp.write(struct.pack('>BH', 0x81, value))
  634. elif value.data < 1 << 32:
  635. self._fp.write(struct.pack('>BL', 0x83, value))
  636. elif value.data < 1 << 64:
  637. self._fp.write(struct.pack('>BQ', 0x87, value))
  638. else:
  639. raise OverflowError(value)
  640. elif isinstance(value, (list, tuple)):
  641. refs = [self._getrefnum(o) for o in value]
  642. s = len(refs)
  643. self._write_size(0xA0, s)
  644. self._fp.write(struct.pack('>' + self._ref_format * s, *refs))
  645. elif isinstance(value, dict):
  646. keyRefs, valRefs = [], []
  647. if self._sort_keys:
  648. rootItems = sorted(value.items())
  649. else:
  650. rootItems = value.items()
  651. for k, v in rootItems:
  652. if not isinstance(k, str):
  653. if self._skipkeys:
  654. continue
  655. raise TypeError("keys must be strings")
  656. keyRefs.append(self._getrefnum(k))
  657. valRefs.append(self._getrefnum(v))
  658. s = len(keyRefs)
  659. self._write_size(0xD0, s)
  660. self._fp.write(struct.pack('>' + self._ref_format * s, *keyRefs))
  661. self._fp.write(struct.pack('>' + self._ref_format * s, *valRefs))
  662. else:
  663. raise TypeError(value)
  664. def _is_fmt_binary(header):
  665. return header[:8] == b'bplist00'
  666. #
  667. # Generic bits
  668. #
  669. _FORMATS={
  670. FMT_XML: dict(
  671. detect=_is_fmt_xml,
  672. parser=_PlistParser,
  673. writer=_PlistWriter,
  674. ),
  675. FMT_BINARY: dict(
  676. detect=_is_fmt_binary,
  677. parser=_BinaryPlistParser,
  678. writer=_BinaryPlistWriter,
  679. )
  680. }
  681. def load(fp, *, fmt=None, dict_type=dict):
  682. """Read a .plist file. 'fp' should be a readable and binary file object.
  683. Return the unpacked root object (which usually is a dictionary).
  684. """
  685. if fmt is None:
  686. header = fp.read(32)
  687. fp.seek(0)
  688. for info in _FORMATS.values():
  689. if info['detect'](header):
  690. P = info['parser']
  691. break
  692. else:
  693. raise InvalidFileException()
  694. else:
  695. P = _FORMATS[fmt]['parser']
  696. p = P(dict_type=dict_type)
  697. return p.parse(fp)
  698. def loads(value, *, fmt=None, dict_type=dict):
  699. """Read a .plist file from a bytes object.
  700. Return the unpacked root object (which usually is a dictionary).
  701. """
  702. fp = BytesIO(value)
  703. return load(fp, fmt=fmt, dict_type=dict_type)
  704. def dump(value, fp, *, fmt=FMT_XML, sort_keys=True, skipkeys=False):
  705. """Write 'value' to a .plist file. 'fp' should be a writable,
  706. binary file object.
  707. """
  708. if fmt not in _FORMATS:
  709. raise ValueError("Unsupported format: %r"%(fmt,))
  710. writer = _FORMATS[fmt]["writer"](fp, sort_keys=sort_keys, skipkeys=skipkeys)
  711. writer.write(value)
  712. def dumps(value, *, fmt=FMT_XML, skipkeys=False, sort_keys=True):
  713. """Return a bytes object with the contents for a .plist file.
  714. """
  715. fp = BytesIO()
  716. dump(value, fp, fmt=fmt, skipkeys=skipkeys, sort_keys=sort_keys)
  717. return fp.getvalue()