| 1 |
"""biplist -- a library for reading and writing binary property list files. |
| 2 |
|
| 3 |
Binary Property List (plist) files provide a faster and smaller serialization |
| 4 |
format for property lists on OS X. This is a library for generating binary |
| 5 |
plists which can be read by OS X, iOS, or other clients. |
| 6 |
|
| 7 |
The API models the plistlib API, and will call through to plistlib when |
| 8 |
XML serialization or deserialization is required. |
| 9 |
|
| 10 |
To generate plists with UID values, wrap the values with the Uid object. The |
| 11 |
value must be an int. |
| 12 |
|
| 13 |
To generate plists with NSData/CFData values, wrap the values with the |
| 14 |
Data object. The value must be a string. |
| 15 |
|
| 16 |
Date values can only be datetime.datetime objects. |
| 17 |
|
| 18 |
The exceptions InvalidPlistException and NotBinaryPlistException may be |
| 19 |
thrown to indicate that the data cannot be serialized or deserialized as |
| 20 |
a binary plist. |
| 21 |
|
| 22 |
Plist generation example: |
| 23 |
|
| 24 |
from biplist import * |
| 25 |
from datetime import datetime |
| 26 |
plist = {'aKey':'aValue', |
| 27 |
'0':1.322, |
| 28 |
'now':datetime.now(), |
| 29 |
'list':[1,2,3], |
| 30 |
'tuple':('a','b','c') |
| 31 |
} |
| 32 |
try: |
| 33 |
writePlist(plist, "example.plist") |
| 34 |
except (InvalidPlistException, NotBinaryPlistException), e: |
| 35 |
print "Something bad happened:", e |
| 36 |
|
| 37 |
Plist parsing example: |
| 38 |
|
| 39 |
from biplist import * |
| 40 |
try: |
| 41 |
plist = readPlist("example.plist") |
| 42 |
print plist |
| 43 |
except (InvalidPlistException, NotBinaryPlistException), e: |
| 44 |
print "Not a plist:", e |
| 45 |
""" |
| 46 |
|
| 47 |
from collections import namedtuple |
| 48 |
import datetime |
| 49 |
import io |
| 50 |
import math |
| 51 |
import plistlib |
| 52 |
from struct import pack, unpack, unpack_from |
| 53 |
from struct import error as struct_error |
| 54 |
import sys |
| 55 |
import time |
| 56 |
|
| 57 |
try: |
| 58 |
unicode |
| 59 |
unicodeEmpty = r'' |
| 60 |
except NameError: |
| 61 |
unicode = str |
| 62 |
unicodeEmpty = '' |
| 63 |
try: |
| 64 |
long |
| 65 |
except NameError: |
| 66 |
long = int |
| 67 |
try: |
| 68 |
{}.iteritems |
| 69 |
iteritems = lambda x: x.iteritems() |
| 70 |
except AttributeError: |
| 71 |
iteritems = lambda x: x.items() |
| 72 |
|
| 73 |
__all__ = [ |
| 74 |
'Uid', 'Data', 'readPlist', 'writePlist', 'readPlistFromString', |
| 75 |
'writePlistToString', 'InvalidPlistException', 'NotBinaryPlistException' |
| 76 |
] |
| 77 |
|
| 78 |
|
| 79 |
apple_reference_date = datetime.datetime.utcfromtimestamp(978307200) |
| 80 |
|
| 81 |
class Uid(object): |
| 82 |
"""Wrapper around integers for representing UID values. This |
| 83 |
is used in keyed archiving.""" |
| 84 |
integer = 0 |
| 85 |
def __init__(self, integer): |
| 86 |
self.integer = integer |
| 87 |
|
| 88 |
def __repr__(self): |
| 89 |
return "Uid(%d)" % self.integer |
| 90 |
|
| 91 |
def __eq__(self, other): |
| 92 |
if isinstance(self, Uid) and isinstance(other, Uid): |
| 93 |
return self.integer == other.integer |
| 94 |
return False |
| 95 |
|
| 96 |
def __cmp__(self, other): |
| 97 |
return self.integer - other.integer |
| 98 |
|
| 99 |
def __lt__(self, other): |
| 100 |
return self.integer < other.integer |
| 101 |
|
| 102 |
def __hash__(self): |
| 103 |
return self.integer |
| 104 |
|
| 105 |
def __int__(self): |
| 106 |
return int(self.integer) |
| 107 |
|
| 108 |
class Data(bytes): |
| 109 |
"""Wrapper around bytes to distinguish Data values.""" |
| 110 |
|
| 111 |
class InvalidPlistException(Exception): |
| 112 |
"""Raised when the plist is incorrectly formatted.""" |
| 113 |
|
| 114 |
class NotBinaryPlistException(Exception): |
| 115 |
"""Raised when a binary plist was expected but not encountered.""" |
| 116 |
|
| 117 |
def readPlist(pathOrFile): |
| 118 |
"""Raises NotBinaryPlistException, InvalidPlistException""" |
| 119 |
didOpen = False |
| 120 |
result = None |
| 121 |
if isinstance(pathOrFile, (bytes, unicode)): |
| 122 |
pathOrFile = open(pathOrFile, 'rb') |
| 123 |
didOpen = True |
| 124 |
try: |
| 125 |
reader = PlistReader(pathOrFile) |
| 126 |
result = reader.parse() |
| 127 |
except NotBinaryPlistException as e: |
| 128 |
try: |
| 129 |
pathOrFile.seek(0) |
| 130 |
result = None |
| 131 |
if hasattr(plistlib, 'loads'): |
| 132 |
contents = None |
| 133 |
if isinstance(pathOrFile, (bytes, unicode)): |
| 134 |
with open(pathOrFile, 'rb') as f: |
| 135 |
contents = f.read() |
| 136 |
else: |
| 137 |
contents = pathOrFile.read() |
| 138 |
result = plistlib.loads(contents) |
| 139 |
else: |
| 140 |
result = plistlib.readPlist(pathOrFile) |
| 141 |
result = wrapDataObject(result, for_binary=True) |
| 142 |
except Exception as e: |
| 143 |
raise InvalidPlistException(e) |
| 144 |
finally: |
| 145 |
if didOpen: |
| 146 |
pathOrFile.close() |
| 147 |
return result |
| 148 |
|
| 149 |
def wrapDataObject(o, for_binary=False): |
| •150 |
if isinstance(o, tuple): |
| 151 |
o = wrapDataObject(list(o), for_binary) |
| 152 |
o = tuple(o) |
| 153 |
elif isinstance(o, list): |
| 154 |
for i in range(len(o)): |
| 155 |
o[i] = wrapDataObject(o[i], for_binary) |
| 156 |
elif isinstance(o, dict): |
| 157 |
for k in o: |
| 158 |
o[k] = wrapDataObject(o[k], for_binary) |
| 159 |
return o |
| 160 |
|
| 161 |
def writePlist(rootObject, pathOrFile, binary=True): |
| 162 |
if not binary: |
| 163 |
rootObject = wrapDataObject(rootObject, binary) |
| 164 |
if hasattr(plistlib, "dump"): |
| 165 |
if isinstance(pathOrFile, (bytes, unicode)): |
| 166 |
with open(pathOrFile, 'wb') as f: |
| 167 |
return plistlib.dump(rootObject, f) |
| 168 |
else: |
| 169 |
return plistlib.dump(rootObject, pathOrFile) |
| 170 |
else: |
| 171 |
return plistlib.writePlist(rootObject, pathOrFile) |
| 172 |
else: |
| 173 |
didOpen = False |
| 174 |
if isinstance(pathOrFile, (bytes, unicode)): |
| 175 |
pathOrFile = open(pathOrFile, 'wb') |
| 176 |
didOpen = True |
| 177 |
writer = PlistWriter(pathOrFile) |
| 178 |
result = writer.writeRoot(rootObject) |
| 179 |
if didOpen: |
| 180 |
pathOrFile.close() |
| 181 |
return result |
| 182 |
|
| 183 |
def readPlistFromString(data): |
| 184 |
return readPlist(io.BytesIO(data)) |
| 185 |
|
| 186 |
def writePlistToString(rootObject, binary=True): |
| 187 |
if not binary: |
| 188 |
rootObject = wrapDataObject(rootObject, binary) |
| 189 |
if hasattr(plistlib, "dumps"): |
| 190 |
return plistlib.dumps(rootObject) |
| 191 |
elif hasattr(plistlib, "writePlistToBytes"): |
| 192 |
return plistlib.writePlistToBytes(rootObject) |
| 193 |
else: |
| 194 |
return plistlib.writePlistToString(rootObject) |
| 195 |
else: |
| 196 |
ioObject = io.BytesIO() |
| 197 |
writer = PlistWriter(ioObject) |
| 198 |
writer.writeRoot(rootObject) |
| 199 |
return ioObject.getvalue() |
| 200 |
|
| 201 |
def is_stream_binary_plist(stream): |
| 202 |
stream.seek(0) |
| 203 |
header = stream.read(7) |
| 204 |
if header == b'bplist0': |
| 205 |
return True |
| 206 |
else: |
| 207 |
return False |
| 208 |
|
| 209 |
PlistTrailer = namedtuple('PlistTrailer', 'offsetSize, objectRefSize, offsetCount, topLevelObjectNumber, offsetTableOffset') |
| 210 |
PlistByteCounts = namedtuple('PlistByteCounts', 'nullBytes, boolBytes, intBytes, realBytes, dateBytes, dataBytes, stringBytes, uidBytes, arrayBytes, setBytes, dictBytes') |
| 211 |
|
| 212 |
class PlistReader(object): |
| 213 |
file = None |
| 214 |
contents = '' |
| 215 |
offsets = None |
| 216 |
trailer = None |
| 217 |
currentOffset = 0 |
| 218 |
|
| 219 |
offsetsStack = [] |
| 220 |
|
| 221 |
def __init__(self, fileOrStream): |
| 222 |
"""Raises NotBinaryPlistException.""" |
| 223 |
self.reset() |
| 224 |
self.file = fileOrStream |
| 225 |
|
| 226 |
def parse(self): |
| 227 |
return self.readRoot() |
| 228 |
|
| 229 |
def reset(self): |
| 230 |
self.trailer = None |
| 231 |
self.contents = '' |
| 232 |
self.offsets = [] |
| 233 |
self.currentOffset = 0 |
| 234 |
self.offsetsStack = [] |
| 235 |
|
| 236 |
def readRoot(self): |
| 237 |
result = None |
| 238 |
self.reset() |
| 239 |
|
| 240 |
if not is_stream_binary_plist(self.file): |
| 241 |
raise NotBinaryPlistException() |
| 242 |
self.file.seek(0) |
| 243 |
self.contents = self.file.read() |
| 244 |
if len(self.contents) < 32: |
| 245 |
raise InvalidPlistException("File is too short.") |
| 246 |
trailerContents = self.contents[-32:] |
| 247 |
try: |
| 248 |
self.trailer = PlistTrailer._make(unpack("!xxxxxxBBQQQ", trailerContents)) |
| 249 |
|
| 250 |
if pow(2, self.trailer.offsetSize*8) < self.trailer.offsetTableOffset: |
| 251 |
raise InvalidPlistException("Offset size insufficient to reference all objects.") |
| 252 |
|
| 253 |
if pow(2, self.trailer.objectRefSize*8) < self.trailer.offsetCount: |
| 254 |
raise InvalidPlistException("Too many offsets to represent in size of object reference representation.") |
| 255 |
|
| 256 |
offset_size = self.trailer.offsetSize * self.trailer.offsetCount |
| 257 |
offset = self.trailer.offsetTableOffset |
| 258 |
|
| 259 |
if offset + offset_size > pow(2, 64): |
| 260 |
raise InvalidPlistException("Offset table is excessively long.") |
| 261 |
|
| 262 |
if self.trailer.offsetSize > 16: |
| 263 |
raise InvalidPlistException("Offset size is greater than maximum integer size.") |
| 264 |
|
| 265 |
if self.trailer.objectRefSize == 0: |
| 266 |
raise InvalidPlistException("Object reference size is zero.") |
| 267 |
|
| 268 |
if offset >= len(self.contents) - 32: |
| 269 |
raise InvalidPlistException("Offset table offset is too large.") |
| 270 |
|
| 271 |
if offset < len("bplist00x"): |
| 272 |
raise InvalidPlistException("Offset table offset is too small.") |
| 273 |
|
| 274 |
if self.trailer.topLevelObjectNumber >= self.trailer.offsetCount: |
| 275 |
raise InvalidPlistException("Top level object number is larger than the number of objects.") |
| 276 |
|
| 277 |
offset_contents = self.contents[offset:offset+offset_size] |
| 278 |
offset_i = 0 |
| 279 |
offset_table_length = len(offset_contents) |
| 280 |
|
| 281 |
while offset_i < self.trailer.offsetCount: |
| 282 |
begin = self.trailer.offsetSize*offset_i |
| 283 |
end = begin+self.trailer.offsetSize |
| 284 |
if end > offset_table_length: |
| 285 |
raise InvalidPlistException("End of object is at invalid offset %d in offset table of length %d" % (end, offset_table_length)) |
| 286 |
tmp_contents = offset_contents[begin:end] |
| 287 |
tmp_sized = self.getSizedInteger(tmp_contents, self.trailer.offsetSize) |
| 288 |
self.offsets.append(tmp_sized) |
| 289 |
offset_i += 1 |
| 290 |
self.setCurrentOffsetToObjectNumber(self.trailer.topLevelObjectNumber) |
| 291 |
result = self.readObject() |
| 292 |
except TypeError as e: |
| 293 |
raise InvalidPlistException(e) |
| 294 |
return result |
| 295 |
|
| 296 |
def setCurrentOffsetToObjectNumber(self, objectNumber): |
| 297 |
if objectNumber > len(self.offsets) - 1: |
| 298 |
raise InvalidPlistException("Invalid offset number: %d" % objectNumber) |
| 299 |
self.currentOffset = self.offsets[objectNumber] |
| 300 |
if self.currentOffset in self.offsetsStack: |
| 301 |
raise InvalidPlistException("Recursive data structure detected in object: %d" % objectNumber) |
| 302 |
|
| 303 |
def beginOffsetProtection(self): |
| 304 |
self.offsetsStack.append(self.currentOffset) |
| 305 |
return self.currentOffset |
| 306 |
|
| 307 |
def endOffsetProtection(self, offset): |
| 308 |
try: |
| 309 |
index = self.offsetsStack.index(offset) |
| 310 |
self.offsetsStack = self.offsetsStack[:index] |
| 311 |
except ValueError as e: |
| 312 |
pass |
| 313 |
|
| 314 |
def readObject(self): |
| 315 |
protection = self.beginOffsetProtection() |
| 316 |
result = None |
| 317 |
tmp_byte = self.contents[self.currentOffset:self.currentOffset+1] |
| 318 |
if len(tmp_byte) != 1: |
| 319 |
raise InvalidPlistException("No object found at offset: %d" % self.currentOffset) |
| 320 |
marker_byte = unpack("!B", tmp_byte)[0] |
| 321 |
format = (marker_byte >> 4) & 0x0f |
| 322 |
extra = marker_byte & 0x0f |
| 323 |
self.currentOffset += 1 |
| 324 |
|
| 325 |
def proc_extra(extra): |
| 326 |
if extra == 0b1111: |
| 327 |
extra = self.readObject() |
| 328 |
return extra |
| 329 |
|
| 330 |
|
| 331 |
if format == 0b0000: |
| 332 |
if extra == 0b0000: |
| 333 |
result = None |
| 334 |
elif extra == 0b1000: |
| 335 |
result = False |
| 336 |
elif extra == 0b1001: |
| 337 |
result = True |
| 338 |
elif extra == 0b1111: |
| 339 |
pass |
| 340 |
else: |
| 341 |
raise InvalidPlistException("Invalid object found at offset: %d" % (self.currentOffset - 1)) |
| 342 |
|
| 343 |
elif format == 0b0001: |
| 344 |
result = self.readInteger(pow(2, extra)) |
| 345 |
|
| 346 |
elif format == 0b0010: |
| 347 |
result = self.readReal(extra) |
| 348 |
|
| 349 |
elif format == 0b0011 and extra == 0b0011: |
| 350 |
result = self.readDate() |
| 351 |
|
| 352 |
elif format == 0b0100: |
| 353 |
extra = proc_extra(extra) |
| 354 |
result = self.readData(extra) |
| 355 |
|
| 356 |
elif format == 0b0101: |
| 357 |
extra = proc_extra(extra) |
| 358 |
result = self.readAsciiString(extra) |
| 359 |
|
| 360 |
elif format == 0b0110: |
| 361 |
extra = proc_extra(extra) |
| 362 |
result = self.readUnicode(extra) |
| 363 |
|
| 364 |
elif format == 0b1000: |
| 365 |
result = self.readUid(extra) |
| 366 |
|
| 367 |
elif format == 0b1010: |
| 368 |
extra = proc_extra(extra) |
| 369 |
result = self.readArray(extra) |
| 370 |
|
| 371 |
elif format == 0b1100: |
| 372 |
extra = proc_extra(extra) |
| 373 |
result = set(self.readArray(extra)) |
| 374 |
|
| 375 |
elif format == 0b1101: |
| 376 |
extra = proc_extra(extra) |
| 377 |
result = self.readDict(extra) |
| 378 |
else: |
| 379 |
raise InvalidPlistException("Invalid object found: {format: %s, extra: %s}" % (bin(format), bin(extra))) |
| 380 |
self.endOffsetProtection(protection) |
| 381 |
return result |
| 382 |
|
| 383 |
def readContents(self, length, description="Object contents"): |
| 384 |
end = self.currentOffset + length |
| 385 |
if end >= len(self.contents) - 32: |
| 386 |
raise InvalidPlistException("%s extends into trailer" % description) |
| 387 |
elif length < 0: |
| 388 |
raise InvalidPlistException("%s length is less than zero" % length) |
| 389 |
data = self.contents[self.currentOffset:end] |
| 390 |
return data |
| 391 |
|
| 392 |
def readInteger(self, byteSize): |
| 393 |
data = self.readContents(byteSize, "Integer") |
| 394 |
self.currentOffset = self.currentOffset + byteSize |
| 395 |
return self.getSizedInteger(data, byteSize, as_number=True) |
| 396 |
|
| 397 |
def readReal(self, length): |
| 398 |
to_read = pow(2, length) |
| 399 |
data = self.readContents(to_read, "Real") |
| 400 |
if length == 2: |
| 401 |
result = unpack('>f', data)[0] |
| 402 |
elif length == 3: |
| 403 |
result = unpack('>d', data)[0] |
| 404 |
else: |
| 405 |
raise InvalidPlistException("Unknown Real of length %d bytes" % to_read) |
| 406 |
return result |
| 407 |
|
| 408 |
def readRefs(self, count): |
| 409 |
refs = [] |
| 410 |
i = 0 |
| 411 |
while i < count: |
| 412 |
fragment = self.readContents(self.trailer.objectRefSize, "Object reference") |
| 413 |
ref = self.getSizedInteger(fragment, len(fragment)) |
| 414 |
refs.append(ref) |
| 415 |
self.currentOffset += self.trailer.objectRefSize |
| 416 |
i += 1 |
| 417 |
return refs |
| 418 |
|
| 419 |
def readArray(self, count): |
| 420 |
if not isinstance(count, (int, long)): |
| 421 |
raise InvalidPlistException("Count of entries in dict isn't of integer type.") |
| 422 |
result = [] |
| 423 |
values = self.readRefs(count) |
| 424 |
i = 0 |
| 425 |
while i < len(values): |
| 426 |
self.setCurrentOffsetToObjectNumber(values[i]) |
| 427 |
value = self.readObject() |
| 428 |
result.append(value) |
| 429 |
i += 1 |
| 430 |
return result |
| 431 |
|
| 432 |
def readDict(self, count): |
| 433 |
if not isinstance(count, (int, long)): |
| 434 |
raise InvalidPlistException("Count of keys/values in dict isn't of integer type.") |
| 435 |
result = {} |
| 436 |
keys = self.readRefs(count) |
| 437 |
values = self.readRefs(count) |
| 438 |
i = 0 |
| 439 |
while i < len(keys): |
| 440 |
self.setCurrentOffsetToObjectNumber(keys[i]) |
| 441 |
key = self.readObject() |
| 442 |
self.setCurrentOffsetToObjectNumber(values[i]) |
| 443 |
value = self.readObject() |
| 444 |
result[key] = value |
| 445 |
i += 1 |
| 446 |
return result |
| 447 |
|
| 448 |
def readAsciiString(self, length): |
| 449 |
if not isinstance(length, (int, long)): |
| 450 |
raise InvalidPlistException("Length of ASCII string isn't of integer type.") |
| 451 |
data = self.readContents(length, "ASCII string") |
| 452 |
result = unpack("!%ds" % length, data)[0] |
| 453 |
self.currentOffset += length |
| 454 |
return str(result.decode('ascii')) |
| 455 |
|
| 456 |
def readUnicode(self, length): |
| 457 |
if not isinstance(length, (int, long)): |
| 458 |
raise InvalidPlistException("Length of Unicode string isn't of integer type.") |
| 459 |
actual_length = length*2 |
| 460 |
data = self.readContents(actual_length, "Unicode string") |
| 461 |
self.currentOffset += actual_length |
| 462 |
return data.decode('utf_16_be') |
| 463 |
|
| 464 |
def readDate(self): |
| 465 |
data = self.readContents(8, "Date") |
| 466 |
x = unpack(">d", data)[0] |
| 467 |
if math.isnan(x): |
| 468 |
raise InvalidPlistException("Date is NaN") |
| 469 |
|
| 470 |
try: |
| 471 |
result = datetime.timedelta(seconds=x) + apple_reference_date |
| 472 |
except OverflowError: |
| 473 |
if x > 0: |
| 474 |
result = datetime.datetime.max |
| 475 |
else: |
| 476 |
result = datetime.datetime.min |
| 477 |
self.currentOffset += 8 |
| 478 |
return result |
| 479 |
|
| 480 |
def readData(self, length): |
| 481 |
if not isinstance(length, (int, long)): |
| 482 |
raise InvalidPlistException("Length of data isn't of integer type.") |
| 483 |
result = self.readContents(length, "Data") |
| 484 |
self.currentOffset += length |
| 485 |
return Data(result) |
| 486 |
|
| 487 |
def readUid(self, length): |
| 488 |
if not isinstance(length, (int, long)): |
| 489 |
raise InvalidPlistException("Uid length isn't of integer type.") |
| 490 |
return Uid(self.readInteger(length+1)) |
| 491 |
|
| 492 |
def getSizedInteger(self, data, byteSize, as_number=False): |
| 493 |
"""Numbers of 8 bytes are signed integers when they refer to numbers, but unsigned otherwise.""" |
| 494 |
result = 0 |
| 495 |
if byteSize == 0: |
| 496 |
raise InvalidPlistException("Encountered integer with byte size of 0.") |
| 497 |
|
| 498 |
elif byteSize == 1: |
| 499 |
result = unpack('>B', data)[0] |
| 500 |
elif byteSize == 2: |
| 501 |
result = unpack('>H', data)[0] |
| 502 |
elif byteSize == 4: |
| 503 |
result = unpack('>L', data)[0] |
| 504 |
elif byteSize == 8: |
| 505 |
if as_number: |
| 506 |
result = unpack('>q', data)[0] |
| 507 |
else: |
| 508 |
result = unpack('>Q', data)[0] |
| 509 |
elif byteSize <= 16: |
| 510 |
|
| 511 |
|
| 512 |
result = 0 |
| 513 |
if hasattr(int, 'from_bytes'): |
| 514 |
result = int.from_bytes(data, 'big') |
| 515 |
else: |
| 516 |
for byte in data: |
| 517 |
if not isinstance(byte, int): |
| 518 |
byte = unpack_from('>B', byte)[0] |
| 519 |
result = (result << 8) | byte |
| 520 |
else: |
| 521 |
raise InvalidPlistException("Encountered integer longer than 16 bytes.") |
| 522 |
return result |
| 523 |
|
| 524 |
class HashableWrapper(object): |
| 525 |
def __init__(self, value): |
| 526 |
self.value = value |
| 527 |
def __repr__(self): |
| 528 |
return "<HashableWrapper: %s>" % [self.value] |
| 529 |
|
| 530 |
class BoolWrapper(object): |
| 531 |
def __init__(self, value): |
| 532 |
self.value = value |
| 533 |
def __repr__(self): |
| 534 |
return "<BoolWrapper: %s>" % self.value |
| 535 |
|
| 536 |
class FloatWrapper(object): |
| 537 |
_instances = {} |
| 538 |
def __new__(klass, value): |
| 539 |
|
| 540 |
wrapper = klass._instances.get(value) |
| 541 |
if wrapper is None: |
| 542 |
wrapper = object.__new__(klass) |
| 543 |
wrapper.value = value |
| 544 |
klass._instances[value] = wrapper |
| 545 |
return wrapper |
| 546 |
def __repr__(self): |
| 547 |
return "<FloatWrapper: %s>" % self.value |
| 548 |
|
| 549 |
class StringWrapper(object): |
| 550 |
__instances = {} |
| 551 |
|
| 552 |
encodedValue = None |
| 553 |
encoding = None |
| 554 |
|
| 555 |
def __new__(cls, value): |
| 556 |
'''Ensure we only have a only one instance for any string, |
| 557 |
and that we encode ascii as 1-byte-per character when possible''' |
| 558 |
|
| 559 |
encodedValue = None |
| 560 |
|
| 561 |
for encoding in ('ascii', 'utf_16_be'): |
| 562 |
try: |
| 563 |
encodedValue = value.encode(encoding) |
| 564 |
except: pass |
| 565 |
if encodedValue is not None: |
| 566 |
if encodedValue not in cls.__instances: |
| 567 |
cls.__instances[encodedValue] = super(StringWrapper, cls).__new__(cls) |
| 568 |
cls.__instances[encodedValue].encodedValue = encodedValue |
| 569 |
cls.__instances[encodedValue].encoding = encoding |
| 570 |
return cls.__instances[encodedValue] |
| 571 |
|
| 572 |
raise ValueError('Unable to get ascii or utf_16_be encoding for %s' % repr(value)) |
| 573 |
|
| 574 |
def __len__(self): |
| 575 |
'''Return roughly the number of characters in this string (half the byte length)''' |
| 576 |
if self.encoding == 'ascii': |
| 577 |
return len(self.encodedValue) |
| 578 |
else: |
| 579 |
return len(self.encodedValue)//2 |
| 580 |
|
| 581 |
def __lt__(self, other): |
| 582 |
return self.encodedValue < other.encodedValue |
| 583 |
|
| 584 |
@property |
| 585 |
def encodingMarker(self): |
| 586 |
if self.encoding == 'ascii': |
| 587 |
return 0b0101 |
| 588 |
else: |
| 589 |
return 0b0110 |
| 590 |
|
| 591 |
def __repr__(self): |
| 592 |
return '<StringWrapper (%s): %s>' % (self.encoding, self.encodedValue) |
| 593 |
|
| 594 |
class PlistWriter(object): |
| 595 |
header = b'bplist00bybiplist1.0' |
| 596 |
file = None |
| 597 |
byteCounts = None |
| 598 |
trailer = None |
| 599 |
computedUniques = None |
| 600 |
writtenReferences = None |
| 601 |
referencePositions = None |
| 602 |
wrappedTrue = None |
| 603 |
wrappedFalse = None |
| 604 |
|
| 605 |
objectsStack = [] |
| 606 |
|
| 607 |
def __init__(self, file): |
| 608 |
self.reset() |
| 609 |
self.file = file |
| 610 |
self.wrappedTrue = BoolWrapper(True) |
| 611 |
self.wrappedFalse = BoolWrapper(False) |
| 612 |
|
| 613 |
def reset(self): |
| 614 |
self.byteCounts = PlistByteCounts(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0) |
| 615 |
self.trailer = PlistTrailer(0, 0, 0, 0, 0) |
| 616 |
|
| 617 |
|
| 618 |
self.computedUniques = set() |
| 619 |
|
| 620 |
self.writtenReferences = {} |
| 621 |
|
| 622 |
self.referencePositions = {} |
| 623 |
|
| 624 |
self.objectsStack = [] |
| 625 |
|
| 626 |
def positionOfObjectReference(self, obj): |
| 627 |
"""If the given object has been written already, return its |
| 628 |
position in the offset table. Otherwise, return None.""" |
| 629 |
return self.writtenReferences.get(obj) |
| 630 |
|
| 631 |
def writeRoot(self, root): |
| 632 |
""" |
| 633 |
Strategy is: |
| 634 |
- write header |
| 635 |
- wrap root object so everything is hashable |
| 636 |
- compute size of objects which will be written |
| 637 |
- need to do this in order to know how large the object refs |
| 638 |
will be in the list/dict/set reference lists |
| 639 |
- write objects |
| 640 |
- keep objects in writtenReferences |
| 641 |
- keep positions of object references in referencePositions |
| 642 |
- write object references with the length computed previously |
| 643 |
- computer object reference length |
| 644 |
- write object reference positions |
| 645 |
- write trailer |
| 646 |
""" |
| 647 |
output = self.header |
| 648 |
wrapped_root = self.wrapRoot(root) |
| 649 |
self.computeOffsets(wrapped_root, asReference=True, isRoot=True) |
| 650 |
self.trailer = self.trailer._replace(**{'objectRefSize':self.intSize(len(self.computedUniques))}) |
| 651 |
self.writeObjectReference(wrapped_root, output) |
| 652 |
output = self.writeObject(wrapped_root, output, setReferencePosition=True) |
| 653 |
|
| 654 |
|
| 655 |
|
| 656 |
self.trailer = self.trailer._replace(**{ |
| 657 |
'offsetSize':self.intSize(len(output)), |
| 658 |
'offsetCount':len(self.computedUniques), |
| 659 |
'offsetTableOffset':len(output), |
| 660 |
'topLevelObjectNumber':0 |
| 661 |
}) |
| 662 |
|
| 663 |
output = self.writeOffsetTable(output) |
| 664 |
output += pack('!xxxxxxBBQQQ', *self.trailer) |
| 665 |
self.file.write(output) |
| 666 |
|
| 667 |
def beginRecursionProtection(self, obj): |
| 668 |
if not isinstance(obj, (set, dict, list, tuple)): |
| 669 |
return |
| 670 |
if id(obj) in self.objectsStack: |
| 671 |
raise InvalidPlistException("Recursive containers are not allowed in plists.") |
| 672 |
self.objectsStack.append(id(obj)) |
| 673 |
|
| 674 |
def endRecursionProtection(self, obj): |
| 675 |
if not isinstance(obj, (set, dict, list, tuple)): |
| 676 |
return |
| 677 |
try: |
| 678 |
index = self.objectsStack.index(id(obj)) |
| 679 |
self.objectsStack = self.objectsStack[:index] |
| 680 |
except ValueError as e: |
| 681 |
pass |
| 682 |
|
| 683 |
def wrapRoot(self, root): |
| 684 |
result = None |
| 685 |
self.beginRecursionProtection(root) |
| 686 |
|
| 687 |
if isinstance(root, bool): |
| 688 |
if root is True: |
| 689 |
result = self.wrappedTrue |
| 690 |
else: |
| 691 |
result = self.wrappedFalse |
| 692 |
elif isinstance(root, float): |
| 693 |
result = FloatWrapper(root) |
| 694 |
elif isinstance(root, set): |
| 695 |
n = set() |
| 696 |
for value in root: |
| 697 |
n.add(self.wrapRoot(value)) |
| 698 |
result = HashableWrapper(n) |
| 699 |
elif isinstance(root, dict): |
| 700 |
n = {} |
| 701 |
for key, value in iteritems(root): |
| 702 |
n[self.wrapRoot(key)] = self.wrapRoot(value) |
| 703 |
result = HashableWrapper(n) |
| 704 |
elif isinstance(root, list): |
| 705 |
n = [] |
| 706 |
for value in root: |
| 707 |
n.append(self.wrapRoot(value)) |
| 708 |
result = HashableWrapper(n) |
| 709 |
elif isinstance(root, tuple): |
| 710 |
n = tuple([self.wrapRoot(value) for value in root]) |
| 711 |
result = HashableWrapper(n) |
| 712 |
elif isinstance(root, (str, unicode)) and not isinstance(root, Data): |
| 713 |
result = StringWrapper(root) |
| 714 |
elif isinstance(root, bytes): |
| 715 |
result = Data(root) |
| 716 |
else: |
| 717 |
result = root |
| 718 |
|
| 719 |
self.endRecursionProtection(root) |
| 720 |
return result |
| 721 |
|
| 722 |
def incrementByteCount(self, field, incr=1): |
| 723 |
self.byteCounts = self.byteCounts._replace(**{field:self.byteCounts.__getattribute__(field) + incr}) |
| 724 |
|
| 725 |
def computeOffsets(self, obj, asReference=False, isRoot=False): |
| 726 |
def check_key(key): |
| 727 |
if key is None: |
| 728 |
raise InvalidPlistException('Dictionary keys cannot be null in plists.') |
| 729 |
elif isinstance(key, Data): |
| 730 |
raise InvalidPlistException('Data cannot be dictionary keys in plists.') |
| 731 |
elif not isinstance(key, StringWrapper): |
| 732 |
raise InvalidPlistException('Keys must be strings.') |
| 733 |
|
| 734 |
def proc_size(size): |
| 735 |
if size > 0b1110: |
| 736 |
size += self.intSize(size) |
| 737 |
return size |
| 738 |
|
| 739 |
|
| 740 |
if asReference: |
| 741 |
if obj in self.computedUniques: |
| 742 |
return |
| 743 |
else: |
| 744 |
self.computedUniques.add(obj) |
| 745 |
|
| 746 |
if obj is None: |
| 747 |
self.incrementByteCount('nullBytes') |
| 748 |
elif isinstance(obj, BoolWrapper): |
| 749 |
self.incrementByteCount('boolBytes') |
| 750 |
elif isinstance(obj, Uid): |
| 751 |
size = self.intSize(obj.integer) |
| 752 |
self.incrementByteCount('uidBytes', incr=1+size) |
| 753 |
elif isinstance(obj, (int, long)): |
| 754 |
size = self.intSize(obj) |
| 755 |
self.incrementByteCount('intBytes', incr=1+size) |
| 756 |
elif isinstance(obj, FloatWrapper): |
| 757 |
size = self.realSize(obj) |
| 758 |
self.incrementByteCount('realBytes', incr=1+size) |
| 759 |
elif isinstance(obj, datetime.datetime): |
| 760 |
self.incrementByteCount('dateBytes', incr=2) |
| 761 |
elif isinstance(obj, Data): |
| 762 |
size = proc_size(len(obj)) |
| 763 |
self.incrementByteCount('dataBytes', incr=1+size) |
| 764 |
elif isinstance(obj, StringWrapper): |
| 765 |
size = proc_size(len(obj)) |
| 766 |
self.incrementByteCount('stringBytes', incr=1+size) |
| 767 |
elif isinstance(obj, HashableWrapper): |
| 768 |
obj = obj.value |
| 769 |
if isinstance(obj, set): |
| 770 |
size = proc_size(len(obj)) |
| 771 |
self.incrementByteCount('setBytes', incr=1+size) |
| 772 |
for value in obj: |
| 773 |
self.computeOffsets(value, asReference=True) |
| 774 |
elif isinstance(obj, (list, tuple)): |
| 775 |
size = proc_size(len(obj)) |
| 776 |
self.incrementByteCount('arrayBytes', incr=1+size) |
| 777 |
for value in obj: |
| 778 |
asRef = True |
| 779 |
self.computeOffsets(value, asReference=True) |
| 780 |
elif isinstance(obj, dict): |
| 781 |
size = proc_size(len(obj)) |
| 782 |
self.incrementByteCount('dictBytes', incr=1+size) |
| 783 |
for key, value in iteritems(obj): |
| 784 |
check_key(key) |
| 785 |
self.computeOffsets(key, asReference=True) |
| 786 |
self.computeOffsets(value, asReference=True) |
| 787 |
else: |
| 788 |
raise InvalidPlistException("Unknown object type: %s (%s)" % (type(obj).__name__, repr(obj))) |
| 789 |
|
| 790 |
def writeObjectReference(self, obj, output): |
| 791 |
"""Tries to write an object reference, adding it to the references |
| 792 |
table. Does not write the actual object bytes or set the reference |
| 793 |
position. Returns a tuple of whether the object was a new reference |
| 794 |
(True if it was, False if it already was in the reference table) |
| 795 |
and the new output. |
| 796 |
""" |
| 797 |
position = self.positionOfObjectReference(obj) |
| 798 |
if position is None: |
| 799 |
self.writtenReferences[obj] = len(self.writtenReferences) |
| 800 |
output += self.binaryInt(len(self.writtenReferences) - 1, byteSize=self.trailer.objectRefSize) |
| 801 |
return (True, output) |
| 802 |
else: |
| 803 |
output += self.binaryInt(position, byteSize=self.trailer.objectRefSize) |
| 804 |
return (False, output) |
| 805 |
|
| 806 |
def writeObject(self, obj, output, setReferencePosition=False): |
| 807 |
"""Serializes the given object to the output. Returns output. |
| 808 |
If setReferencePosition is True, will set the position the |
| 809 |
object was written. |
| 810 |
""" |
| 811 |
def proc_variable_length(format, length): |
| 812 |
result = b'' |
| 813 |
if length > 0b1110: |
| 814 |
result += pack('!B', (format << 4) | 0b1111) |
| 815 |
result = self.writeObject(length, result) |
| 816 |
else: |
| 817 |
result += pack('!B', (format << 4) | length) |
| 818 |
return result |
| 819 |
|
| 820 |
def timedelta_total_seconds(td): |
| 821 |
|
| 822 |
|
| 823 |
return (td.microseconds + (td.seconds + td.days * 24 * 3600) * 10.0**6) / 10.0**6 |
| 824 |
|
| 825 |
if setReferencePosition: |
| 826 |
self.referencePositions[obj] = len(output) |
| 827 |
|
| 828 |
if obj is None: |
| 829 |
output += pack('!B', 0b00000000) |
| 830 |
elif isinstance(obj, BoolWrapper): |
| 831 |
if obj.value is False: |
| 832 |
output += pack('!B', 0b00001000) |
| 833 |
else: |
| 834 |
output += pack('!B', 0b00001001) |
| 835 |
elif isinstance(obj, Uid): |
| 836 |
size = self.intSize(obj.integer) |
| 837 |
output += pack('!B', (0b1000 << 4) | size - 1) |
| 838 |
output += self.binaryInt(obj.integer) |
| 839 |
elif isinstance(obj, (int, long)): |
| 840 |
byteSize = self.intSize(obj) |
| 841 |
root = math.log(byteSize, 2) |
| 842 |
output += pack('!B', (0b0001 << 4) | int(root)) |
| 843 |
output += self.binaryInt(obj, as_number=True) |
| 844 |
elif isinstance(obj, FloatWrapper): |
| 845 |
|
| 846 |
output += pack('!B', (0b0010 << 4) | 3) |
| 847 |
output += self.binaryReal(obj) |
| 848 |
elif isinstance(obj, datetime.datetime): |
| 849 |
try: |
| 850 |
timestamp = (obj - apple_reference_date).total_seconds() |
| 851 |
except AttributeError: |
| 852 |
timestamp = timedelta_total_seconds(obj - apple_reference_date) |
| 853 |
output += pack('!B', 0b00110011) |
| 854 |
output += pack('!d', float(timestamp)) |
| 855 |
elif isinstance(obj, Data): |
| 856 |
output += proc_variable_length(0b0100, len(obj)) |
| 857 |
output += obj |
| 858 |
elif isinstance(obj, StringWrapper): |
| 859 |
output += proc_variable_length(obj.encodingMarker, len(obj)) |
| 860 |
output += obj.encodedValue |
| 861 |
elif isinstance(obj, bytes): |
| 862 |
output += proc_variable_length(0b0101, len(obj)) |
| 863 |
output += obj |
| 864 |
elif isinstance(obj, HashableWrapper): |
| 865 |
obj = obj.value |
| 866 |
if isinstance(obj, (set, list, tuple)): |
| 867 |
if isinstance(obj, set): |
| 868 |
output += proc_variable_length(0b1100, len(obj)) |
| 869 |
else: |
| 870 |
output += proc_variable_length(0b1010, len(obj)) |
| 871 |
|
| 872 |
objectsToWrite = [] |
| 873 |
for objRef in sorted(obj) if isinstance(obj, set) else obj: |
| 874 |
(isNew, output) = self.writeObjectReference(objRef, output) |
| 875 |
if isNew: |
| 876 |
objectsToWrite.append(objRef) |
| 877 |
for objRef in objectsToWrite: |
| 878 |
output = self.writeObject(objRef, output, setReferencePosition=True) |
| 879 |
elif isinstance(obj, dict): |
| 880 |
output += proc_variable_length(0b1101, len(obj)) |
| 881 |
keys = [] |
| 882 |
values = [] |
| 883 |
objectsToWrite = [] |
| 884 |
for key, value in sorted(iteritems(obj)): |
| 885 |
keys.append(key) |
| 886 |
values.append(value) |
| 887 |
for key in keys: |
| 888 |
(isNew, output) = self.writeObjectReference(key, output) |
| 889 |
if isNew: |
| 890 |
objectsToWrite.append(key) |
| 891 |
for value in values: |
| 892 |
(isNew, output) = self.writeObjectReference(value, output) |
| 893 |
if isNew: |
| 894 |
objectsToWrite.append(value) |
| 895 |
for objRef in objectsToWrite: |
| 896 |
output = self.writeObject(objRef, output, setReferencePosition=True) |
| 897 |
return output |
| 898 |
|
| 899 |
def writeOffsetTable(self, output): |
| 900 |
"""Writes all of the object reference offsets.""" |
| 901 |
all_positions = [] |
| 902 |
writtenReferences = list(self.writtenReferences.items()) |
| 903 |
writtenReferences.sort(key=lambda x: x[1]) |
| 904 |
for obj,order in writtenReferences: |
| 905 |
|
| 906 |
|
| 907 |
|
| 908 |
|
| 909 |
|
| 910 |
if bytes != str and obj == unicodeEmpty: |
| 911 |
obj = b'' |
| 912 |
position = self.referencePositions.get(obj) |
| 913 |
if position is None: |
| 914 |
raise InvalidPlistException("Error while writing offsets table. Object not found. %s" % obj) |
| 915 |
output += self.binaryInt(position, self.trailer.offsetSize) |
| 916 |
all_positions.append(position) |
| 917 |
return output |
| 918 |
|
| 919 |
def binaryReal(self, obj): |
| 920 |
|
| 921 |
result = pack('>d', obj.value) |
| 922 |
return result |
| 923 |
|
| 924 |
def binaryInt(self, obj, byteSize=None, as_number=False): |
| 925 |
result = b'' |
| 926 |
if byteSize is None: |
| 927 |
byteSize = self.intSize(obj) |
| 928 |
if byteSize == 1: |
| 929 |
result += pack('>B', obj) |
| 930 |
elif byteSize == 2: |
| 931 |
result += pack('>H', obj) |
| 932 |
elif byteSize == 4: |
| 933 |
result += pack('>L', obj) |
| 934 |
elif byteSize == 8: |
| 935 |
if as_number: |
| 936 |
result += pack('>q', obj) |
| 937 |
else: |
| 938 |
result += pack('>Q', obj) |
| 939 |
elif byteSize <= 16: |
| 940 |
try: |
| 941 |
result = pack('>Q', 0) + pack('>Q', obj) |
| 942 |
except struct_error as e: |
| 943 |
raise InvalidPlistException("Unable to pack integer %d: %s" % (obj, e)) |
| 944 |
else: |
| 945 |
raise InvalidPlistException("Core Foundation can't handle integers with size greater than 16 bytes.") |
| 946 |
return result |
| 947 |
|
| 948 |
def intSize(self, obj): |
| 949 |
"""Returns the number of bytes necessary to store the given integer.""" |
| 950 |
|
| 951 |
if obj < 0: |
| 952 |
return 8 |
| 953 |
|
| 954 |
elif obj <= 0xFF: |
| 955 |
return 1 |
| 956 |
elif obj <= 0xFFFF: |
| 957 |
return 2 |
| 958 |
elif obj <= 0xFFFFFFFF: |
| 959 |
return 4 |
| 960 |
|
| 961 |
|
| 962 |
elif obj <= 0x7FFFFFFFFFFFFFFF: |
| 963 |
return 8 |
| 964 |
elif obj <= 0xffffffffffffffff: |
| 965 |
return 16 |
| 966 |
else: |
| 967 |
raise InvalidPlistException("Core Foundation can't handle integers with size greater than 8 bytes.") |
| 968 |
|
| 969 |
def realSize(self, obj): |
| 970 |
return 8 |