| 1 |
# This Source Code Form is subject to the terms of the Mozilla Public |
| 2 |
# License, v. 2.0. If a copy of the MPL was not distributed with this |
| 3 |
# file, You can obtain one at http://mozilla.org/MPL/2.0/. |
| 4 |
|
| 5 |
import functools |
| 6 |
import os |
| 7 |
import struct |
| 8 |
import zlib |
| 9 |
from collections import OrderedDict |
| 10 |
from io import BytesIO, UnsupportedOperation |
| 11 |
from zipfile import ZIP_DEFLATED, ZIP_STORED |
| 12 |
|
| 13 |
import mozpack.path as mozpath |
| 14 |
from mozbuild.util import ensure_bytes |
| 15 |
|
| 16 |
JAR_STORED = ZIP_STORED |
| 17 |
JAR_DEFLATED = ZIP_DEFLATED |
| 18 |
MAX_WBITS = 15 |
| 19 |
|
| 20 |
|
| 21 |
class JarReaderError(Exception): |
| 22 |
"""Error type for Jar reader errors.""" |
| 23 |
|
| 24 |
|
| 25 |
class JarWriterError(Exception): |
| 26 |
"""Error type for Jar writer errors.""" |
| 27 |
|
| 28 |
|
| 29 |
class JarStruct: |
| 30 |
""" |
| 31 |
Helper used to define ZIP archive raw data structures. Data structures |
| 32 |
handled by this helper all start with a magic number, defined in |
| 33 |
subclasses MAGIC field as a 32-bits unsigned integer, followed by data |
| 34 |
structured as described in subclasses STRUCT field. |
| 35 |
|
| 36 |
The STRUCT field contains a list of (name, type) pairs where name is a |
| 37 |
field name, and the type can be one of 'uint32', 'uint16' or one of the |
| 38 |
field names. In the latter case, the field is considered to be a string |
| 39 |
buffer with a length given in that field. |
| 40 |
For example, |
| 41 |
|
| 42 |
.. code-block:: python |
| 43 |
|
| 44 |
STRUCT = [ |
| 45 |
('version', 'uint32'), |
| 46 |
('filename_size', 'uint16'), |
| 47 |
('filename', 'filename_size') |
| 48 |
] |
| 49 |
|
| 50 |
describes a structure with a 'version' 32-bits unsigned integer field, |
| 51 |
followed by a 'filename_size' 16-bits unsigned integer field, followed by a |
| 52 |
filename_size-long string buffer 'filename'. |
| 53 |
|
| 54 |
Fields that are used as other fields size are not stored in objects. In the |
| 55 |
above example, an instance of such subclass would only have two attributes: |
| 56 |
- obj['version'] |
| 57 |
- obj['filename'] |
| 58 |
|
| 59 |
filename_size would be obtained with len(obj['filename']). |
| 60 |
|
| 61 |
JarStruct subclasses instances can be either initialized from existing data |
| 62 |
(deserialized), or with empty fields. |
| 63 |
""" |
| 64 |
|
| 65 |
TYPE_MAPPING = {"uint32": (b"I", 4), "uint16": (b"H", 2)} |
| 66 |
|
| 67 |
def __init__(self, data=None): |
| 68 |
""" |
| 69 |
Create an instance from the given data. Data may be omitted to create |
| 70 |
an instance with empty fields. |
| 71 |
""" |
| 72 |
assert self.MAGIC and isinstance(self.STRUCT, OrderedDict) |
| 73 |
self.size_fields = set( |
| 74 |
t for t in self.STRUCT.values() if t not in JarStruct.TYPE_MAPPING |
| 75 |
) |
| 76 |
self._values = {} |
| 77 |
if data: |
| 78 |
self._init_data(data) |
| 79 |
else: |
| 80 |
self._init_empty() |
| 81 |
|
| 82 |
def _init_data(self, data): |
| 83 |
""" |
| 84 |
Initialize an instance from data, following the data structure |
| 85 |
described in self.STRUCT. The self.MAGIC signature is expected at |
| 86 |
data[:4]. |
| 87 |
""" |
| 88 |
assert data is not None |
| 89 |
self.signature, size = JarStruct.get_data("uint32", data) |
| 90 |
if self.signature != self.MAGIC: |
| 91 |
raise JarReaderError("Bad magic") |
| 92 |
offset = size |
| 93 |
# For all fields used as other fields sizes, keep track of their value |
| 94 |
# separately. |
| 95 |
sizes = dict((t, 0) for t in self.size_fields) |
| 96 |
for name, t in self.STRUCT.items(): |
| 97 |
if t in JarStruct.TYPE_MAPPING: |
| 98 |
value, size = JarStruct.get_data(t, data[offset:]) |
| 99 |
else: |
| 100 |
size = sizes[t] |
| 101 |
value = data[offset : offset + size] |
| 102 |
if isinstance(value, memoryview): |
| 103 |
value = value.tobytes() |
| 104 |
if name not in sizes: |
| 105 |
self._values[name] = value |
| 106 |
else: |
| 107 |
sizes[name] = value |
| 108 |
offset += size |
| 109 |
|
| 110 |
def _init_empty(self): |
| 111 |
""" |
| 112 |
Initialize an instance with empty fields. |
| 113 |
""" |
| 114 |
self.signature = self.MAGIC |
| 115 |
for name, t in self.STRUCT.items(): |
| 116 |
if name in self.size_fields: |
| 117 |
continue |
| 118 |
self._values[name] = 0 if t in JarStruct.TYPE_MAPPING else "" |
| 119 |
|
| 120 |
@staticmethod |
| 121 |
def get_data(type, data): |
| 122 |
""" |
| 123 |
Deserialize a single field of given type (must be one of |
| 124 |
JarStruct.TYPE_MAPPING) at the given offset in the given data. |
| 125 |
""" |
| 126 |
assert type in JarStruct.TYPE_MAPPING |
| 127 |
assert data is not None |
| 128 |
format, size = JarStruct.TYPE_MAPPING[type] |
| 129 |
data = data[:size] |
| 130 |
if isinstance(data, memoryview): |
| 131 |
data = data.tobytes() |
| 132 |
return struct.unpack(b"<" + format, data)[0], size |
| 133 |
|
| 134 |
def serialize(self): |
| 135 |
""" |
| 136 |
Serialize the data structure according to the data structure definition |
| 137 |
from self.STRUCT. |
| 138 |
""" |
| 139 |
serialized = struct.pack(b"<I", self.signature) |
| 140 |
sizes = dict( |
| 141 |
(t, name) |
| 142 |
for name, t in self.STRUCT.items() |
| 143 |
if t not in JarStruct.TYPE_MAPPING |
| 144 |
) |
| 145 |
for name, t in self.STRUCT.items(): |
| 146 |
if t in JarStruct.TYPE_MAPPING: |
| 147 |
format, size = JarStruct.TYPE_MAPPING[t] |
| 148 |
if name in sizes: |
| 149 |
value = len(self[sizes[name]]) |
| 150 |
else: |
| 151 |
value = self[name] |
| 152 |
serialized += struct.pack(b"<" + format, value) |
| 153 |
else: |
| 154 |
serialized += ensure_bytes(self[name]) |
| 155 |
return serialized |
| 156 |
|
| 157 |
@property |
| 158 |
def size(self): |
| 159 |
""" |
| 160 |
Return the size of the data structure, given the current values of all |
| 161 |
variable length fields. |
| 162 |
""" |
| 163 |
size = JarStruct.TYPE_MAPPING["uint32"][1] |
| 164 |
for name, type in self.STRUCT.items(): |
| 165 |
if type in JarStruct.TYPE_MAPPING: |
| 166 |
size += JarStruct.TYPE_MAPPING[type][1] |
| 167 |
else: |
| 168 |
size += len(self[name]) |
| 169 |
return size |
| 170 |
|
| 171 |
def __getitem__(self, key): |
| 172 |
return self._values[key] |
| 173 |
|
| 174 |
def __setitem__(self, key, value): |
| 175 |
if key not in self.STRUCT: |
| 176 |
raise KeyError(key) |
| 177 |
if key in self.size_fields: |
| 178 |
raise AttributeError("can't set attribute") |
| 179 |
self._values[key] = value |
| 180 |
|
| 181 |
def __contains__(self, key): |
| 182 |
return key in self._values |
| 183 |
|
| 184 |
def __iter__(self): |
| 185 |
return iter(self._values.items()) |
| 186 |
|
| 187 |
def __repr__(self): |
| 188 |
return "<%s %s>" % ( |
| 189 |
self.__class__.__name__, |
| 190 |
" ".join("%s=%s" % (n, v) for n, v in self), |
| 191 |
) |
| 192 |
|
| 193 |
|
| 194 |
class JarCdirEnd(JarStruct): |
| 195 |
""" |
| 196 |
End of central directory record. |
| 197 |
""" |
| 198 |
|
| 199 |
MAGIC = 0x06054B50 |
| 200 |
STRUCT = OrderedDict( |
| 201 |
[ |
| 202 |
("disk_num", "uint16"), |
| 203 |
("cdir_disk", "uint16"), |
| 204 |
("disk_entries", "uint16"), |
| 205 |
("cdir_entries", "uint16"), |
| 206 |
("cdir_size", "uint32"), |
| 207 |
("cdir_offset", "uint32"), |
| 208 |
("comment_size", "uint16"), |
| 209 |
("comment", "comment_size"), |
| 210 |
] |
| 211 |
) |
| 212 |
|
| 213 |
|
| 214 |
CDIR_END_SIZE = JarCdirEnd().size |
| 215 |
|
| 216 |
|
| 217 |
class JarCdirEntry(JarStruct): |
| 218 |
""" |
| 219 |
Central directory file header |
| 220 |
""" |
| 221 |
|
| 222 |
MAGIC = 0x02014B50 |
| 223 |
STRUCT = OrderedDict( |
| 224 |
[ |
| 225 |
("creator_version", "uint16"), |
| 226 |
("min_version", "uint16"), |
| 227 |
("general_flag", "uint16"), |
| 228 |
("compression", "uint16"), |
| 229 |
("lastmod_time", "uint16"), |
| 230 |
("lastmod_date", "uint16"), |
| 231 |
("crc32", "uint32"), |
| 232 |
("compressed_size", "uint32"), |
| 233 |
("uncompressed_size", "uint32"), |
| 234 |
("filename_size", "uint16"), |
| 235 |
("extrafield_size", "uint16"), |
| 236 |
("filecomment_size", "uint16"), |
| 237 |
("disknum", "uint16"), |
| 238 |
("internal_attr", "uint16"), |
| 239 |
("external_attr", "uint32"), |
| 240 |
("offset", "uint32"), |
| 241 |
("filename", "filename_size"), |
| 242 |
("extrafield", "extrafield_size"), |
| 243 |
("filecomment", "filecomment_size"), |
| 244 |
] |
| 245 |
) |
| 246 |
|
| 247 |
|
| 248 |
class JarLocalFileHeader(JarStruct): |
| 249 |
""" |
| 250 |
Local file header |
| 251 |
""" |
| 252 |
|
| 253 |
MAGIC = 0x04034B50 |
| 254 |
STRUCT = OrderedDict( |
| 255 |
[ |
| 256 |
("min_version", "uint16"), |
| 257 |
("general_flag", "uint16"), |
| 258 |
("compression", "uint16"), |
| 259 |
("lastmod_time", "uint16"), |
| 260 |
("lastmod_date", "uint16"), |
| 261 |
("crc32", "uint32"), |
| 262 |
("compressed_size", "uint32"), |
| 263 |
("uncompressed_size", "uint32"), |
| 264 |
("filename_size", "uint16"), |
| 265 |
("extra_field_size", "uint16"), |
| 266 |
("filename", "filename_size"), |
| 267 |
("extra_field", "extra_field_size"), |
| 268 |
] |
| 269 |
) |
| 270 |
|
| 271 |
|
| 272 |
class JarFileReader: |
| 273 |
""" |
| 274 |
File-like class for use by JarReader to give access to individual files |
| 275 |
within a Jar archive. |
| 276 |
""" |
| 277 |
|
| 278 |
def __init__(self, header, data): |
| 279 |
""" |
| 280 |
Initialize a JarFileReader. header is the local file header |
| 281 |
corresponding to the file in the jar archive, data a buffer containing |
| 282 |
the file data. |
| 283 |
""" |
| 284 |
assert header["compression"] in [JAR_DEFLATED, JAR_STORED] |
| 285 |
self._data = data |
| 286 |
# Copy some local file header fields. |
| 287 |
for name in ["compressed_size", "uncompressed_size", "crc32"]: |
| 288 |
setattr(self, name, header[name]) |
| 289 |
self.filename = header["filename"].decode() |
| 290 |
self.compressed = header["compression"] != JAR_STORED |
| 291 |
self.compress = header["compression"] |
| 292 |
|
| 293 |
def readable(self): |
| 294 |
return True |
| 295 |
|
| 296 |
def read(self, length=-1): |
| 297 |
""" |
| 298 |
Read some amount of uncompressed data. |
| 299 |
""" |
| 300 |
return self.uncompressed_data.read(length) |
| 301 |
|
| 302 |
def readinto(self, b): |
| 303 |
""" |
| 304 |
Read bytes into a pre-allocated, writable bytes-like object `b` and return |
| 305 |
the number of bytes read. |
| 306 |
""" |
| 307 |
return self.uncompressed_data.readinto(b) |
| 308 |
|
| 309 |
def readlines(self): |
| 310 |
""" |
| 311 |
Return a list containing all the lines of data in the uncompressed |
| 312 |
data. |
| 313 |
""" |
| 314 |
return self.read().splitlines(True) |
| 315 |
|
| 316 |
def __iter__(self): |
| 317 |
""" |
| 318 |
Iterator, to support the "for line in fileobj" constructs. |
| 319 |
""" |
| 320 |
return iter(self.readlines()) |
| 321 |
|
| 322 |
def seek(self, pos, whence=os.SEEK_SET): |
| 323 |
""" |
| 324 |
Change the current position in the uncompressed data. Subsequent reads |
| 325 |
will start from there. |
| 326 |
""" |
| 327 |
return self.uncompressed_data.seek(pos, whence) |
| 328 |
|
| 329 |
def close(self): |
| 330 |
""" |
| 331 |
Free the uncompressed data buffer. |
| 332 |
""" |
| 333 |
self.uncompressed_data.close() |
| 334 |
|
| 335 |
@property |
| 336 |
def closed(self): |
| 337 |
return self.uncompressed_data.closed |
| 338 |
|
| 339 |
@property |
| 340 |
def compressed_data(self): |
| 341 |
""" |
| 342 |
Return the raw compressed data. |
| 343 |
""" |
| 344 |
return self._data[: self.compressed_size] |
| 345 |
|
| 346 |
@property |
| 347 |
def uncompressed_data(self): |
| 348 |
""" |
| 349 |
Return the uncompressed data. |
| 350 |
""" |
| 351 |
if hasattr(self, "_uncompressed_data"): |
| 352 |
return self._uncompressed_data |
| 353 |
data = self.compressed_data |
| 354 |
if self.compress == JAR_STORED: |
| 355 |
data = data.tobytes() |
| 356 |
elif self.compress == JAR_DEFLATED: |
| 357 |
data = zlib.decompress(data.tobytes(), -MAX_WBITS) |
| 358 |
else: |
| 359 |
assert False # Can't be another value per __init__ |
| 360 |
if len(data) != self.uncompressed_size: |
| 361 |
raise JarReaderError("Corrupted file? %s" % self.filename) |
| 362 |
self._uncompressed_data = BytesIO(data) |
| 363 |
return self._uncompressed_data |
| 364 |
|
| 365 |
|
| 366 |
class JarReader: |
| 367 |
""" |
| 368 |
Class with methods to read Jar files. Can open standard jar files as well |
| 369 |
as Mozilla jar files (see further details in the JarWriter documentation). |
| 370 |
""" |
| 371 |
|
| 372 |
def __init__(self, file=None, fileobj=None, data=None): |
| 373 |
""" |
| 374 |
Opens the given file as a Jar archive. Use the given file-like object |
| 375 |
if one is given instead of opening the given file name. |
| 376 |
""" |
| 377 |
if fileobj: |
| 378 |
data = fileobj.read() |
| 379 |
elif file: |
| 380 |
data = open(file, "rb").read() |
| 381 |
self._data = memoryview(data) |
| 382 |
# The End of Central Directory Record has a variable size because of |
| 383 |
# comments it may contain, so scan for it from the end of the file. |
| 384 |
offset = -CDIR_END_SIZE |
| 385 |
while True: |
| 386 |
signature = JarStruct.get_data("uint32", self._data[offset:])[0] |
| 387 |
if signature == JarCdirEnd.MAGIC: |
| 388 |
break |
| 389 |
if offset == -len(self._data): |
| 390 |
raise JarReaderError("Not a jar?") |
| 391 |
offset -= 1 |
| 392 |
self._cdir_end = JarCdirEnd(self._data[offset:]) |
| 393 |
|
| 394 |
def close(self): |
| 395 |
""" |
| 396 |
Free some resources associated with the Jar. |
| 397 |
""" |
| 398 |
del self._data |
| 399 |
|
| 400 |
@property |
| 401 |
def compression(self): |
| 402 |
entries = self.entries |
| 403 |
if not entries: |
| 404 |
return JAR_STORED |
| 405 |
return max(f["compression"] for f in entries.values()) |
| 406 |
|
| 407 |
@property |
| 408 |
def entries(self): |
| 409 |
""" |
| 410 |
Return an ordered dict of central directory entries, indexed by |
| 411 |
filename, in the order they appear in the Jar archive central |
| 412 |
directory. Directory entries are skipped. |
| 413 |
""" |
| 414 |
if hasattr(self, "_entries"): |
| 415 |
return self._entries |
| 416 |
preload = 0 |
| 417 |
if self.is_optimized: |
| 418 |
preload = JarStruct.get_data("uint32", self._data)[0] |
| 419 |
entries = OrderedDict() |
| 420 |
offset = self._cdir_end["cdir_offset"] |
| 421 |
for e in range(self._cdir_end["cdir_entries"]): |
| 422 |
entry = JarCdirEntry(self._data[offset:]) |
| 423 |
offset += entry.size |
| 424 |
# Creator host system. 0 is MSDOS, 3 is Unix |
| 425 |
host = entry["creator_version"] >> 8 |
| 426 |
# External attributes values depend on host above. On Unix the |
| 427 |
# higher bits are the stat.st_mode value. On MSDOS, the lower bits |
| 428 |
# are the FAT attributes. |
| 429 |
xattr = entry["external_attr"] |
| 430 |
# Skip directories |
| 431 |
if (host == 0 and xattr & 0x10) or (host == 3 and xattr & (0o040000 << 16)): |
| 432 |
continue |
| 433 |
entries[entry["filename"].decode()] = entry |
| 434 |
if entry["offset"] < preload: |
| 435 |
self._last_preloaded = entry["filename"].decode() |
| 436 |
self._entries = entries |
| 437 |
return entries |
| 438 |
|
| 439 |
@property |
| 440 |
def is_optimized(self): |
| 441 |
""" |
| 442 |
Return whether the jar archive is optimized. |
| 443 |
""" |
| 444 |
# In optimized jars, the central directory is at the beginning of the |
| 445 |
# file, after a single 32-bits value, which is the length of data |
| 446 |
# preloaded. |
| 447 |
return self._cdir_end["cdir_offset"] == JarStruct.TYPE_MAPPING["uint32"][1] |
| 448 |
|
| 449 |
@property |
| 450 |
def last_preloaded(self): |
| 451 |
""" |
| 452 |
Return the name of the last file that is set to be preloaded. |
| 453 |
See JarWriter documentation for more details on preloading. |
| 454 |
""" |
| 455 |
if hasattr(self, "_last_preloaded"): |
| 456 |
return self._last_preloaded |
| 457 |
self._last_preloaded = None |
| 458 |
self.entries |
| 459 |
return self._last_preloaded |
| 460 |
|
| 461 |
def _getreader(self, entry): |
| 462 |
""" |
| 463 |
Helper to create a JarFileReader corresponding to the given central |
| 464 |
directory entry. |
| 465 |
""" |
| 466 |
header = JarLocalFileHeader(self._data[entry["offset"] :]) |
| 467 |
for key, value in entry: |
| 468 |
if key in header and header[key] != value: |
| 469 |
raise JarReaderError( |
| 470 |
"Central directory and file header " |
| 471 |
+ "mismatch. Corrupted archive?" |
| 472 |
) |
| 473 |
return JarFileReader(header, self._data[entry["offset"] + header.size :]) |
| 474 |
|
| 475 |
def __iter__(self): |
| 476 |
""" |
| 477 |
Iterate over all files in the Jar archive, in the form of |
| 478 |
JarFileReaders. |
| 479 |
for file in jarReader: |
| 480 |
... |
| 481 |
""" |
| 482 |
for entry in self.entries.values(): |
| 483 |
yield self._getreader(entry) |
| 484 |
|
| 485 |
def __getitem__(self, name): |
| 486 |
""" |
| 487 |
Get a JarFileReader for the given file name. |
| 488 |
""" |
| 489 |
return self._getreader(self.entries[name]) |
| 490 |
|
| 491 |
def __contains__(self, name): |
| 492 |
""" |
| 493 |
Return whether the given file name appears in the Jar archive. |
| 494 |
""" |
| 495 |
return name in self.entries |
| 496 |
|
| 497 |
|
| 498 |
class JarWriter: |
| 499 |
""" |
| 500 |
Class with methods to write Jar files. Can write more-or-less standard jar |
| 501 |
archives as well as jar archives optimized for Gecko. See the documentation |
| 502 |
for the close() member function for a description of both layouts. |
| 503 |
""" |
| 504 |
|
| 505 |
def __init__(self, file=None, fileobj=None, compress=True, compress_level=9): |
| 506 |
""" |
| 507 |
Initialize a Jar archive in the given file. Use the given file-like |
| 508 |
object if one is given instead of opening the given file name. |
| 509 |
The compress option determines the default behavior for storing data |
| 510 |
in the jar archive. The optimize options determines whether the jar |
| 511 |
archive should be optimized for Gecko or not. ``compress_level`` |
| 512 |
defines the zlib compression level. It must be a value between 0 and 9 |
| 513 |
and defaults to 9, the highest and slowest level of compression. |
| 514 |
""" |
| 515 |
if fileobj: |
| 516 |
self._data = fileobj |
| 517 |
else: |
| 518 |
self._data = open(file, "wb") |
| 519 |
if compress is True: |
| 520 |
compress = JAR_DEFLATED |
| 521 |
self._compress = compress |
| 522 |
self._compress_level = compress_level |
| 523 |
self._contents = OrderedDict() |
| 524 |
self._last_preloaded = None |
| 525 |
|
| 526 |
def __enter__(self): |
| 527 |
""" |
| 528 |
Context manager __enter__ method for JarWriter. |
| 529 |
""" |
| 530 |
return self |
| 531 |
|
| 532 |
def __exit__(self, type, value, tb): |
| 533 |
""" |
| 534 |
Context manager __exit__ method for JarWriter. |
| 535 |
""" |
| 536 |
self.finish() |
| 537 |
|
| 538 |
def finish(self): |
| 539 |
""" |
| 540 |
Flush and close the Jar archive. |
| 541 |
|
| 542 |
Standard jar archives are laid out like the following: |
| 543 |
- Local file header 1 |
| 544 |
- File data 1 |
| 545 |
- Local file header 2 |
| 546 |
- File data 2 |
| 547 |
- (...) |
| 548 |
- Central directory entry pointing at Local file header 1 |
| 549 |
- Central directory entry pointing at Local file header 2 |
| 550 |
- (...) |
| 551 |
- End of central directory, pointing at first central directory |
| 552 |
entry. |
| 553 |
|
| 554 |
Jar archives optimized for Gecko are laid out like the following: |
| 555 |
- 32-bits unsigned integer giving the amount of data to preload. |
| 556 |
- Central directory entry pointing at Local file header 1 |
| 557 |
- Central directory entry pointing at Local file header 2 |
| 558 |
- (...) |
| 559 |
- End of central directory, pointing at first central directory |
| 560 |
entry. |
| 561 |
- Local file header 1 |
| 562 |
- File data 1 |
| 563 |
- Local file header 2 |
| 564 |
- File data 2 |
| 565 |
- (...) |
| 566 |
- End of central directory, pointing at first central directory |
| 567 |
entry. |
| 568 |
|
| 569 |
The duplication of the End of central directory is to accomodate some |
| 570 |
Zip reading tools that want an end of central directory structure to |
| 571 |
follow the central directory entries. |
| 572 |
""" |
| 573 |
offset = 0 |
| 574 |
headers = {} |
| 575 |
preload_size = 0 |
| 576 |
# Prepare central directory entries |
| 577 |
for entry, content in self._contents.values(): |
| 578 |
header = JarLocalFileHeader() |
| 579 |
for name in entry.STRUCT: |
| 580 |
if name in header: |
| 581 |
header[name] = entry[name] |
| 582 |
entry["offset"] = offset |
| 583 |
offset += len(content) + header.size |
| 584 |
if entry["filename"].decode() == self._last_preloaded: |
| 585 |
preload_size = offset |
| 586 |
headers[entry] = header |
| 587 |
# Prepare end of central directory |
| 588 |
end = JarCdirEnd() |
| 589 |
end["disk_entries"] = len(self._contents) |
| 590 |
end["cdir_entries"] = end["disk_entries"] |
| 591 |
end["cdir_size"] = functools.reduce( |
| 592 |
lambda x, y: x + y[0].size, self._contents.values(), 0 |
| 593 |
) |
| 594 |
# On optimized archives, store the preloaded size and the central |
| 595 |
# directory entries, followed by the first end of central directory. |
| 596 |
if preload_size: |
| 597 |
end["cdir_offset"] = 4 |
| 598 |
offset = end["cdir_size"] + end["cdir_offset"] + end.size |
| 599 |
preload_size += offset |
| 600 |
self._data.write(struct.pack("<I", preload_size)) |
| 601 |
for entry, _ in self._contents.values(): |
| 602 |
entry["offset"] += offset |
| 603 |
self._data.write(entry.serialize()) |
| 604 |
self._data.write(end.serialize()) |
| 605 |
# Store local file entries followed by compressed data |
| 606 |
for entry, content in self._contents.values(): |
| 607 |
self._data.write(headers[entry].serialize()) |
| 608 |
if isinstance(content, memoryview): |
| 609 |
self._data.write(content.tobytes()) |
| 610 |
else: |
| 611 |
self._data.write(content) |
| 612 |
# On non optimized archives, store the central directory entries. |
| 613 |
if not preload_size: |
| 614 |
end["cdir_offset"] = offset |
| 615 |
for entry, _ in self._contents.values(): |
| 616 |
self._data.write(entry.serialize()) |
| 617 |
# Store the end of central directory. |
| 618 |
self._data.write(end.serialize()) |
| 619 |
self._data.close() |
| 620 |
|
| 621 |
def add(self, name, data, compress=None, mode=None, skip_duplicates=False): |
| 622 |
""" |
| 623 |
Add a new member to the jar archive, with the given name and the given |
| 624 |
data. |
| 625 |
The compress option indicates how the given data should be compressed |
| 626 |
(one of JAR_STORED or JAR_DEFLATE), or compressed according |
| 627 |
to the default defined when creating the JarWriter (None). True and |
| 628 |
False are allowed values for backwards compatibility, mapping, |
| 629 |
respectively, to JAR_DEFLATE and JAR_STORED. |
| 630 |
When the data should be compressed, it is only really compressed if |
| 631 |
the compressed size is smaller than the uncompressed size. |
| 632 |
The mode option gives the unix permissions that should be stored for the |
| 633 |
jar entry, which defaults to 0o100644 (regular file, u+rw, g+r, o+r) if |
| 634 |
not specified. |
| 635 |
If a duplicated member is found skip_duplicates will prevent raising |
| 636 |
an exception if set to True. |
| 637 |
The given data may be a buffer, a file-like instance, a Deflater or a |
| 638 |
JarFileReader instance. The latter two allow to avoid uncompressing |
| 639 |
data to recompress it. |
| 640 |
""" |
| 641 |
if isinstance(name, bytes): |
| 642 |
name = name.decode() |
| 643 |
name = mozpath.normsep(name) |
| 644 |
|
| 645 |
if name in self._contents and not skip_duplicates: |
| 646 |
raise JarWriterError("File %s already in JarWriter" % name) |
| 647 |
if compress is None: |
| 648 |
compress = self._compress |
| 649 |
if compress is True: |
| 650 |
compress = JAR_DEFLATED |
| 651 |
if compress is False: |
| 652 |
compress = JAR_STORED |
| 653 |
if isinstance(data, (JarFileReader, Deflater)) and data.compress == compress: |
| 654 |
deflater = data |
| 655 |
else: |
| 656 |
deflater = Deflater(compress, compress_level=self._compress_level) |
| 657 |
if isinstance(data, (bytes, str)): |
| 658 |
deflater.write(data) |
| 659 |
elif hasattr(data, "read"): |
| 660 |
try: |
| 661 |
data.seek(0) |
| 662 |
except (UnsupportedOperation, AttributeError): |
| 663 |
pass |
| 664 |
deflater.write(data.read()) |
| 665 |
else: |
| 666 |
raise JarWriterError("Don't know how to handle %s" % type(data)) |
| 667 |
# Fill a central directory entry for this new member. |
| 668 |
entry = JarCdirEntry() |
| 669 |
entry["creator_version"] = 20 |
| 670 |
if mode is None: |
| 671 |
# If no mode is given, default to u+rw, g+r, o+r. |
| 672 |
mode = 0o000644 |
| 673 |
if not mode & 0o777000: |
| 674 |
# If no file type is given, default to regular file. |
| 675 |
mode |= 0o100000 |
| 676 |
# Set creator host system (upper byte of creator_version) to 3 (Unix) so |
| 677 |
# mode is honored when there is one. |
| 678 |
entry["creator_version"] |= 3 << 8 |
| 679 |
entry["external_attr"] = (mode & 0xFFFF) << 16 |
| 680 |
if deflater.compressed: |
| 681 |
entry["min_version"] = 20 # Version 2.0 supports deflated streams |
| 682 |
entry["general_flag"] = 2 # Max compression |
| 683 |
entry["compression"] = deflater.compress |
| 684 |
else: |
| 685 |
entry["min_version"] = 10 # Version 1.0 for stored streams |
| 686 |
entry["general_flag"] = 0 |
| 687 |
entry["compression"] = JAR_STORED |
| 688 |
# January 1st, 2010. See bug 592369. |
| 689 |
entry["lastmod_date"] = ((2010 - 1980) << 9) | (1 << 5) | 1 |
| 690 |
entry["lastmod_time"] = 0 |
| 691 |
entry["crc32"] = deflater.crc32 |
| 692 |
entry["compressed_size"] = deflater.compressed_size |
| 693 |
entry["uncompressed_size"] = deflater.uncompressed_size |
| 694 |
entry["filename"] = name.encode() |
| 695 |
self._contents[name] = entry, deflater.compressed_data |
| 696 |
|
| 697 |
def preload(self, files): |
| 698 |
""" |
| 699 |
Set which members of the jar archive should be preloaded when opening |
| 700 |
the archive in Gecko. This reorders the members according to the order |
| 701 |
of given list. |
| 702 |
""" |
| 703 |
new_contents = OrderedDict() |
| 704 |
for f in files: |
| 705 |
if f not in self._contents: |
| 706 |
continue |
| 707 |
new_contents[f] = self._contents[f] |
| 708 |
self._last_preloaded = f |
| 709 |
for f in self._contents: |
| 710 |
if f not in new_contents: |
| 711 |
new_contents[f] = self._contents[f] |
| 712 |
self._contents = new_contents |
| 713 |
|
| 714 |
|
| 715 |
class Deflater: |
| 716 |
""" |
| 717 |
File-like interface to zlib compression. The data is actually not |
| 718 |
compressed unless the compressed form is smaller than the uncompressed |
| 719 |
data. |
| 720 |
""" |
| 721 |
|
| 722 |
def __init__(self, compress=True, compress_level=9): |
| 723 |
""" |
| 724 |
Initialize a Deflater. The compress argument determines how to |
| 725 |
compress. |
| 726 |
""" |
| 727 |
self._data = BytesIO() |
| 728 |
if compress is True: |
| 729 |
compress = JAR_DEFLATED |
| 730 |
elif compress is False: |
| 731 |
compress = JAR_STORED |
| 732 |
self.compress = compress |
| 733 |
if compress == JAR_DEFLATED: |
| 734 |
self._deflater = zlib.compressobj(compress_level, zlib.DEFLATED, -MAX_WBITS) |
| 735 |
self._deflated = BytesIO() |
| 736 |
else: |
| 737 |
assert compress == JAR_STORED |
| 738 |
self._deflater = None |
| 739 |
self.crc32 = 0 |
| 740 |
|
| 741 |
def write(self, data): |
| 742 |
""" |
| 743 |
Append a buffer to the Deflater. |
| 744 |
""" |
| 745 |
if isinstance(data, memoryview): |
| 746 |
data = data.tobytes() |
| 747 |
if isinstance(data, str): |
| 748 |
data = data.encode() |
| 749 |
self._data.write(data) |
| 750 |
|
| 751 |
if self.compress: |
| 752 |
if self._deflater: |
| 753 |
self._deflated.write(self._deflater.compress(data)) |
| 754 |
else: |
| 755 |
raise JarWriterError("Can't write after flush") |
| 756 |
|
| 757 |
self.crc32 = zlib.crc32(data, self.crc32) & 0xFFFFFFFF |
| 758 |
|
| 759 |
def close(self): |
| 760 |
""" |
| 761 |
Close the Deflater. |
| 762 |
""" |
| 763 |
self._data.close() |
| 764 |
if self.compress: |
| 765 |
self._deflated.close() |
| 766 |
|
| 767 |
def _flush(self): |
| 768 |
""" |
| 769 |
Flush the underlying zlib compression object. |
| 770 |
""" |
| 771 |
if self.compress and self._deflater: |
| 772 |
self._deflated.write(self._deflater.flush()) |
| 773 |
self._deflater = None |
| 774 |
|
| 775 |
@property |
| 776 |
def compressed(self): |
| 777 |
""" |
| 778 |
Return whether the data should be compressed. |
| 779 |
""" |
| 780 |
return self._compressed_size < self.uncompressed_size |
| 781 |
|
| 782 |
@property |
| 783 |
def _compressed_size(self): |
| 784 |
""" |
| 785 |
Return the real compressed size of the data written to the Deflater. If |
| 786 |
the Deflater is set not to compress, the uncompressed size is returned. |
| 787 |
Otherwise, the actual compressed size is returned, whether or not it is |
| 788 |
a win over the uncompressed size. |
| 789 |
""" |
| 790 |
if self.compress: |
| 791 |
self._flush() |
| 792 |
return self._deflated.tell() |
| 793 |
return self.uncompressed_size |
| 794 |
|
| 795 |
@property |
| 796 |
def compressed_size(self): |
| 797 |
""" |
| 798 |
Return the compressed size of the data written to the Deflater. If the |
| 799 |
Deflater is set not to compress, the uncompressed size is returned. |
| 800 |
Otherwise, if the data should not be compressed (the real compressed |
| 801 |
size is bigger than the uncompressed size), return the uncompressed |
| 802 |
size. |
| 803 |
""" |
| 804 |
if self.compressed: |
| 805 |
return self._compressed_size |
| 806 |
return self.uncompressed_size |
| 807 |
|
| 808 |
@property |
| 809 |
def uncompressed_size(self): |
| 810 |
""" |
| 811 |
Return the size of the data written to the Deflater. |
| 812 |
""" |
| 813 |
return self._data.tell() |
| 814 |
|
| 815 |
@property |
| 816 |
def compressed_data(self): |
| 817 |
""" |
| 818 |
Return the compressed data, if the data should be compressed (real |
| 819 |
compressed size smaller than the uncompressed size), or the |
| 820 |
uncompressed data otherwise. |
| 821 |
""" |
| 822 |
if self.compressed: |
| 823 |
return self._deflated.getvalue() |
| 824 |
return self._data.getvalue() |
| 825 |
|
| 826 |
|
| 827 |
class JarLog(dict): |
| 828 |
""" |
| 829 |
Helper to read the file Gecko generates when setting MOZ_JAR_LOG_FILE. |
| 830 |
The jar log is then available as a dict with the jar path as key, and |
| 831 |
the corresponding access log as a list value. Only the first access to |
| 832 |
a given member of a jar is stored. |
| 833 |
""" |
| 834 |
|
| 835 |
def __init__(self, file=None, fileobj=None): |
| 836 |
if not fileobj: |
| 837 |
fileobj = open(file) |
| 838 |
for line in fileobj: |
| 839 |
jar, path = line.strip().split(None, 1) |
| 840 |
if not jar or not path: |
| 841 |
continue |
| 842 |
entry = self.setdefault(jar, []) |
| 843 |
if path not in entry: |
| 844 |
entry.append(path) |