Class: CFPropertyList::Binary

Inherits:
Object
  • Object
show all
Defined in:
lib/cfpropertylist/rbBinaryCFPropertyList.rb

Overview

Binary PList parser class

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.ascii_string?(str) ⇒ Boolean

Returns:

  • (Boolean)


446
447
448
449
450
451
452
# File 'lib/cfpropertylist/rbBinaryCFPropertyList.rb', line 446

def Binary.ascii_string?(str)
  if str.respond_to?(:ascii_only?)
    str.ascii_only?
  else
    str !~ /[\x80-\xFF]/mn
  end
end

.bytes_needed(count) ⇒ Object

calculate how many bytes are needed to save count



392
393
394
395
396
397
398
399
400
401
# File 'lib/cfpropertylist/rbBinaryCFPropertyList.rb', line 392

def Binary.bytes_needed(count)
  case
  when count < 2**8  then 1
  when count < 2**16 then 2
  when count < 2**32 then 4
  when count < 2**64 then 8
  else
    raise CFFormatError.new("Data size too large: #{count}")
  end
end

.charset_convert(str, from, to = "UTF-8") ⇒ Object

Convert the given string from one charset to another



221
222
223
224
# File 'lib/cfpropertylist/rbBinaryCFPropertyList.rb', line 221

def Binary.charset_convert(str,from,to="UTF-8")
  return str.dup.force_encoding(from).encode(to) if str.respond_to?("encode")
  Iconv.conv(to,from,str)
end

.charset_strlen(str, charset = "UTF-8") ⇒ Object

Count characters considering character set



227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
# File 'lib/cfpropertylist/rbBinaryCFPropertyList.rb', line 227

def Binary.charset_strlen(str,charset="UTF-8")
  if str.respond_to?(:encode)
    size = str.length
  else
    utf8_str = Iconv.conv("UTF-8",charset,str)
    size = utf8_str.scan(/./mu).size
  end

  # UTF-16 code units in the range D800-DBFF are the beginning of
  # a surrogate pair, and count as one additional character for
  # length calculation.
  if charset =~ /^UTF-16/
    if str.respond_to?(:encode)
      str.bytes.to_a.each_slice(2) { |pair| size += 1 if (0xd8..0xdb).include?(pair[0]) }
    else
      str.split('').each_slice(2) { |pair| size += 1 if ("\xd8".."\xdb").include?(pair[0]) }
    end
  end

  size
end

.pack_int_array_with_size(nbytes, array) ⇒ Object



379
380
381
382
383
384
385
386
387
388
389
# File 'lib/cfpropertylist/rbBinaryCFPropertyList.rb', line 379

def Binary.pack_int_array_with_size(nbytes, array)
  case nbytes
  when 1 then array.pack('C*')
  when 2 then array.pack('n*')
  when 4 then array.pack('N*')
  when 8
    array.map { |int| [int >> 32, int & 0xFFFFFFFF].pack('NN') }.join
  else
    raise CFFormatError.new("Don't know how to pack #{nbytes} byte integer")
  end
end

.pack_it_with_size(nbytes, int) ⇒ Object

pack an int of nbytes with size



367
368
369
370
371
372
373
374
375
376
377
# File 'lib/cfpropertylist/rbBinaryCFPropertyList.rb', line 367

def Binary.pack_it_with_size(nbytes,int)
  case nbytes
  when 1 then [int].pack('c')
  when 2 then [int].pack('n')
  when 4 then [int].pack('N')
  when 8
    [int >> 32, int & 0xFFFFFFFF].pack('NN')
  else
    raise CFFormatError.new("Don't know how to pack #{nbytes} byte integer")
  end
end

.type_bytes(type, length) ⇒ Object

Create a type byte for binary format as defined by apple



404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
# File 'lib/cfpropertylist/rbBinaryCFPropertyList.rb', line 404

def Binary.type_bytes(type, length)
  if length < 15
    [(type << 4) | length].pack('C')
  else
    bytes = [(type << 4) | 0xF]
    if length <= 0xFF
      bytes.push(0x10, length).pack('CCC')                              # 1 byte length
    elsif length <= 0xFFFF
      bytes.push(0x11, length).pack('CCn')                              # 2 byte length
    elsif length <= 0xFFFFFFFF
      bytes.push(0x12, length).pack('CCN')                              # 4 byte length
    elsif length <= 0x7FFFFFFFFFFFFFFF
      bytes.push(0x13, length >> 32, length & 0xFFFFFFFF).pack('CCNN')  # 8 byte length
    else
      raise CFFormatError.new("Integer too large: #{int}")
    end
  end
end

Instance Method Details

#array_to_binary(val) ⇒ Object

Convert array to binary format and add it to the object table



572
573
574
575
576
577
578
579
580
581
582
583
584
# File 'lib/cfpropertylist/rbBinaryCFPropertyList.rb', line 572

def array_to_binary(val)
  saved_object_count = @written_object_count
  @written_object_count += 1
  #@object_refs += val.value.size

  values = val.value.map { |v| v.to_binary(self) }
  bdata = Binary.type_bytes(0b1010, val.value.size) <<
    Binary.pack_int_array_with_size(object_ref_size(@object_refs),
                                    values)

  @object_table[saved_object_count] = bdata
  saved_object_count
end

#bool_to_binary(val) ⇒ Object

Convert a bool value to binary and add it to the object table



555
556
557
558
559
560
# File 'lib/cfpropertylist/rbBinaryCFPropertyList.rb', line 555

def bool_to_binary(val)

  @object_table[@written_object_count] = val ? "\x9" : "\x8" # 0x9 is 1001, type indicator for true; 0x8 is 1000, type indicator for false
  @written_object_count += 1
  @written_object_count - 1
end

#count_object_refs(object) ⇒ Object



423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
# File 'lib/cfpropertylist/rbBinaryCFPropertyList.rb', line 423

def count_object_refs(object)
  case object
  when CFArray
    contained_refs = 0
    object.value.each do |element|
      if CFArray === element || CFDictionary === element
        contained_refs += count_object_refs(element)
      end
    end
    return object.value.size + contained_refs
  when CFDictionary
    contained_refs = 0
    object.value.each_value do |value|
      if CFArray === value || CFDictionary === value
        contained_refs += count_object_refs(value)
      end
    end
    return object.value.keys.size * 2 + contained_refs
  else
    return 0
  end
end

#data_to_binary(val) ⇒ Object

Convert data value to binary format and add it to the object table



563
564
565
566
567
568
569
# File 'lib/cfpropertylist/rbBinaryCFPropertyList.rb', line 563

def data_to_binary(val)
  @object_table[@written_object_count] =
    (Binary.type_bytes(0b0100, val.bytesize) << val)

  @written_object_count += 1
  @written_object_count - 1
end

#date_to_binary(val) ⇒ Object

Convert date value (apple format) to binary and adds it to the object table



544
545
546
547
548
549
550
551
552
# File 'lib/cfpropertylist/rbBinaryCFPropertyList.rb', line 544

def date_to_binary(val)
  val = val.getutc.to_f - CFDate::DATE_DIFF_APPLE_UNIX # CFDate is a real, number of seconds since 01/01/2001 00:00:00 GMT

  @object_table[@written_object_count] =
    (Binary.type_bytes(0b0011, 3) << [val].pack("d").reverse)

  @written_object_count += 1
  @written_object_count - 1
end

#dict_to_binary(val) ⇒ Object

Convert dictionary to binary format and add it to the object table



587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
# File 'lib/cfpropertylist/rbBinaryCFPropertyList.rb', line 587

def dict_to_binary(val)
  saved_object_count = @written_object_count
  @written_object_count += 1

  #@object_refs += val.value.keys.size * 2

  keys_and_values = val.value.keys.map { |k| CFString.new(k).to_binary(self) }
  keys_and_values.concat(val.value.values.map { |v| v.to_binary(self) })

  bdata = Binary.type_bytes(0b1101,val.value.size) <<
    Binary.pack_int_array_with_size(object_ref_size(@object_refs), keys_and_values)

  @object_table[saved_object_count] = bdata
  return saved_object_count
end

#int_to_binary(value) ⇒ Object

Codes an integer to binary format



476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
# File 'lib/cfpropertylist/rbBinaryCFPropertyList.rb', line 476

def int_to_binary(value)
  nbytes = 0
  nbytes = 1  if value > 0xFF # 1 byte integer
  nbytes += 1 if value > 0xFFFF # 4 byte integer
  nbytes += 1 if value > 0xFFFFFFFF # 8 byte integer
  nbytes = 3  if value < 0 # 8 byte integer, since signed

  Binary.type_bytes(0b0001, nbytes) <<
    if nbytes < 3
      [value].pack(
        if nbytes == 0    then "C"
        elsif nbytes == 1 then "n"
        else "N"
        end
      )
    else
      # 64 bit signed integer; we need the higher and the lower 32 bit of the value
      high_word = value >> 32
      low_word = value & 0xFFFFFFFF
      [high_word,low_word].pack("NN")
    end
end

#load(opts) ⇒ Object

Read a binary plist file

Raises:



9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
# File 'lib/cfpropertylist/rbBinaryCFPropertyList.rb', line 9

def load(opts)
  @unique_table = {}
  @count_objects = 0
  @object_refs = 0

  @written_object_count = 0
  @object_table = []
  @object_ref_size = 0

  @offsets = []

  fd = nil
  if(opts.has_key?(:file))
    fd = File.open(opts[:file],"rb")
    file = opts[:file]
  else
    fd = StringIO.new(opts[:data],"rb")
    file = "<string>"
  end

  # first, we read the trailer: 32 byte from the end
  fd.seek(-32,IO::SEEK_END)
  buff = fd.read(32)

  offset_size, object_ref_size, number_of_objects, top_object, table_offset = buff.unpack "x6CCx4Nx4Nx4N"

  # after that, get the offset table
  fd.seek(table_offset, IO::SEEK_SET)
  coded_offset_table = fd.read(number_of_objects * offset_size)
  raise CFFormatError.new("#{file}: Format error!") unless coded_offset_table.bytesize == number_of_objects * offset_size

  @count_objects = number_of_objects

  # decode offset table
  if(offset_size != 3)
    formats = ["","C*","n*","","N*"]
    @offsets = coded_offset_table.unpack(formats[offset_size])
  else
    @offsets = coded_offset_table.unpack("C*").each_slice(3).map {
      |x,y,z| (x << 16) | (y << 8) | z
    }
  end

  @object_ref_size = object_ref_size
  val = read_binary_object_at(file,fd,top_object)

  fd.close
  val
end

#num_to_binary(value) ⇒ Object

Converts a numeric value to binary and adds it to the object table



505
506
507
508
509
510
511
512
513
514
515
# File 'lib/cfpropertylist/rbBinaryCFPropertyList.rb', line 505

def num_to_binary(value)
  @object_table[@written_object_count] =
    if value.is_a?(CFInteger)
      int_to_binary(value.value)
    else
      real_to_binary(value.value)
    end

  @written_object_count += 1
  @written_object_count - 1
end

#object_ref_size(object_refs) ⇒ Object



107
108
109
# File 'lib/cfpropertylist/rbBinaryCFPropertyList.rb', line 107

def object_ref_size object_refs
  Binary.bytes_needed(object_refs)
end

#read_fd(fd, length) ⇒ Object



208
209
210
# File 'lib/cfpropertylist/rbBinaryCFPropertyList.rb', line 208

def read_fd fd, length
  length > 0 ? fd.read(length) : ""
end

#real_to_binary(val) ⇒ Object

Codes a real value to binary format



500
501
502
# File 'lib/cfpropertylist/rbBinaryCFPropertyList.rb', line 500

def real_to_binary(val)
  Binary.type_bytes(0b0010,3) << [val].pack("d").reverse
end

#string_to_binary(val) ⇒ Object

Uniques and transforms a string value to binary format and adds it to the object table



455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
# File 'lib/cfpropertylist/rbBinaryCFPropertyList.rb', line 455

def string_to_binary(val)
  val = val.to_s

  @unique_table[val] ||= begin
    if !Binary.ascii_string?(val)
      val = Binary.charset_convert(val,"UTF-8","UTF-16BE")
      bdata = Binary.type_bytes(0b0110, Binary.charset_strlen(val,"UTF-16BE"))

      val.force_encoding("ASCII-8BIT") if val.respond_to?("encode")
      @object_table[@written_object_count] = bdata << val
    else
      bdata = Binary.type_bytes(0b0101,val.bytesize)
      @object_table[@written_object_count] = bdata << val
    end

    @written_object_count += 1
    @written_object_count - 1
  end
end

#to_str(opts = {}) ⇒ Object

Convert CFPropertyList to binary format; since we have to count our objects we simply unique CFDictionary and CFArray



61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
# File 'lib/cfpropertylist/rbBinaryCFPropertyList.rb', line 61

def to_str(opts={})
  @unique_table = {}
  @count_objects = 0
  @object_refs = 0

  @written_object_count = 0
  @object_table = []

  @offsets = []

  binary_str = "bplist00"

  @object_refs = count_object_refs(opts[:root])

  opts[:root].to_binary(self)

  next_offset = 8
  offsets = @object_table.map do |object|
    offset = next_offset
    next_offset += object.bytesize
    offset
  end
  binary_str << @object_table.join

  table_offset = next_offset
  offset_size = Binary.bytes_needed(table_offset)

  if offset_size < 8
    # Fast path: encode the entire offset array at once.
    binary_str << offsets.pack((%w(C n N N)[offset_size - 1]) + '*')
  else
    # Slow path: host may be little or big endian, must pack each offset
    # separately.
    offsets.each do |offset|
      binary_str << "#{Binary.pack_it_with_size(offset_size,offset)}"
    end
  end

  binary_str << [offset_size, object_ref_size(@object_refs)].pack("x6CC")
  binary_str << [@object_table.size].pack("x4N")
  binary_str << [0].pack("x4N")
  binary_str << [table_offset].pack("x4N")

  binary_str
end

#uid_to_binary(value) ⇒ Object



517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
# File 'lib/cfpropertylist/rbBinaryCFPropertyList.rb', line 517

def uid_to_binary(value)
  nbytes = 0
  nbytes = 1  if value > 0xFF # 1 byte integer
  nbytes += 1 if value > 0xFFFF # 4 byte integer
  nbytes += 1 if value > 0xFFFFFFFF # 8 byte integer
  nbytes = 3  if value < 0 # 8 byte integer, since signed

  @object_table[@written_object_count] = Binary.type_bytes(0b1000, nbytes) <<
    if nbytes < 3
      [value].pack(
        if nbytes == 0    then "C"
        elsif nbytes == 1 then "n"
        else "N"
        end
      )
    else
      # 64 bit signed integer; we need the higher and the lower 32 bit of the value
      high_word = value >> 32
      low_word = value & 0xFFFFFFFF
      [high_word,low_word].pack("NN")
    end

  @written_object_count += 1
  @written_object_count - 1
end

#unpack_with_size(nbytes, buff) ⇒ Object



261
262
263
264
265
266
267
268
269
# File 'lib/cfpropertylist/rbBinaryCFPropertyList.rb', line 261

def unpack_with_size(nbytes, buff)
  format = ["C*", "n*", "N*", "N*"][nbytes - 1];

  if nbytes == 3
    buff = "\0" + buff.scan(/.{1,3}/).join("\0")
  end

  return buff.unpack(format)
end