"""Macintosh binhex compression/decompression.
binhex(inputfilename, outputfilename)
hexbin(inputfilename, outputfilename)
# Jack Jansen, CWI, August 1995.
# The module is supposed to be as compatible as possible. Especially the
# easy interface should work "as expected" on any platform.
# XXXX Note: currently, textfiles appear in mac-form on all platforms.
# We seem to lack a simple character-translate in python.
# (we should probably use ISO-Latin-1 on all but the mac platform).
# XXXX The simple routines are too simple: they expect to hold the complete
# files in-core. Should be fixed.
# XXXX It would be nice to handle AppleDouble format on unix
# (for servers serving macs).
# XXXX I don't understand what happens when you get 0x90 times the same byte on
# input. The resulting code (xx 90 90) would appear to be interpreted as an
# escaped *value* of 0x90. All coders I've seen appear to ignore this nicety...
__all__ = ["binhex","hexbin","Error"]
# States (what have we written)
REASONABLY_LARGE = 32768 # Minimal amount we pass the rle-coder
# This code is no longer byte-order dependent
with io.open(name, 'rb') as fp:
# Quick check for textfile
dir, file = os.path.split(name)
file = file.replace(':', '-', 1)
return file, finfo, dsize, 0
def __init__(self, *args):
"""Write data to the coder in 3-byte chunks"""
self.linelen = LINELEN - 1
self.data = self.data + data
todo = (datalen // 3) * 3
self.data = self.data[todo:]
self.hqxdata = self.hqxdata + binascii.b2a_hqx(data)
while first <= len(self.hqxdata) - self.linelen:
last = first + self.linelen
self.ofp.write(self.hqxdata[first:last] + b'\r')
self.hqxdata = self.hqxdata[first:]
self.ofp.write(self.hqxdata + b':\r')
self.hqxdata = self.hqxdata + binascii.b2a_hqx(self.data)
"""Write data to the RLE-coder in suitably large chunks"""
self.data = self.data + data
if len(self.data) < REASONABLY_LARGE:
rledata = binascii.rlecode_hqx(self.data)
rledata = binascii.rlecode_hqx(self.data)
def __init__(self, name_finfo_dlen_rlen, ofp):
name, finfo, dlen, rlen = name_finfo_dlen_rlen
ofp = io.open(ofname, 'wb')
ofp.write(b'(This file must be converted with BinHex 4.0)\r\r:')
hqxer = _Hqxcoderengine(ofp)
self.ofp = _Rlecoderengine(hqxer)
self._writeinfo(name, finfo)
def _writeinfo(self, name, finfo):
raise Error('Filename too long')
d = bytes([nl]) + name.encode("latin-1") + b'\0'
tp, cr = finfo.Type, finfo.Creator
tp = tp.encode("latin-1")
cr = cr.encode("latin-1")
# Force all structs to be packed with big-endian
d3 = struct.pack('>h', finfo.Flags)
d4 = struct.pack('>ii', self.dlen, self.rlen)
self.crc = binascii.crc_hqx(data, self.crc)
# XXXX Should this be here??
# self.crc = binascii.crc_hqx('\0\0', self.crc)
self.ofp.write(struct.pack(fmt, self.crc))
if self.state != _DID_HEADER:
raise Error('Writing data at the wrong time')
self.dlen = self.dlen - len(data)
raise Error('Incorrect data size, diff=%r' % (self.rlen,))
def write_rsrc(self, data):
if self.state < _DID_DATA:
if self.state != _DID_DATA:
raise Error('Writing resource data at the wrong time')
self.rlen = self.rlen - len(data)
if self.state < _DID_DATA:
if self.state != _DID_DATA:
raise Error('Close at the wrong time')
raise Error("Incorrect resource-datasize, diff=%r" % (self.rlen,))
"""binhex(infilename, outfilename): create binhex-encoded copy of a file"""
with io.open(inp, 'rb') as ifp:
# XXXX Do textfile translation on non-mac systems
ifp = openrsrc(inp, 'rb')
"""Read data via the decoder in 4-byte chunks"""
def read(self, totalwtd):
"""Read at least wtd bytes (or until EOF)"""
# The loop here is convoluted, since we don't really now how
# much to decode: there may be newlines in the incoming data.
if self.eof: return decdata
wtd = ((wtd + 2) // 3) * 4
data = self.ifp.read(wtd)
# Next problem: there may not be a complete number of
# bytes in what we pass to a2b. Solve by yet another
decdatacur, self.eof = binascii.a2b_hqx(data)
except binascii.Incomplete:
newdata = self.ifp.read(1)
raise Error('Premature EOF on binhex file')
decdata = decdata + decdatacur
wtd = totalwtd - len(decdata)
if not decdata and not self.eof:
raise Error('Premature EOF on binhex file')
"""Read data via the RLE-coder"""
if wtd > len(self.post_buffer):
self._fill(wtd - len(self.post_buffer))
rv = self.post_buffer[:wtd]
self.post_buffer = self.post_buffer[wtd:]
self.pre_buffer = self.pre_buffer + self.ifp.read(wtd + 4)
self.post_buffer = self.post_buffer + \
binascii.rledecode_hqx(self.pre_buffer)
# Obfuscated code ahead. We have to take care that we don't
# end up with an orphaned RUNCHAR later on. So, we keep a couple
# of bytes in the buffer, depending on what the end of
# '\220\0\220' - Keep 3 bytes: repeated \220 (escaped as \220\0)
# '?\220' - Keep 2 bytes: repeated something-else
# '\220\0' - Escaped \220: Keep 2 bytes.
# '?\220?' - Complete repeat sequence: decode all
# otherwise: keep 1 byte.
mark = len(self.pre_buffer)
if self.pre_buffer[-3:] == RUNCHAR + b'\0' + RUNCHAR:
elif self.pre_buffer[-1:] == RUNCHAR:
elif self.pre_buffer[-2:] == RUNCHAR + b'\0':
elif self.pre_buffer[-2:-1] == RUNCHAR:
self.post_buffer = self.post_buffer + \
binascii.rledecode_hqx(self.pre_buffer[:mark])
self.pre_buffer = self.pre_buffer[mark:]
raise Error("No binhex data found")
# Cater for \r\n terminated lines (which show up as \n\r, hence
# all lines start with \r)
hqxifp = _Hqxdecoderengine(ifp)
self.ifp = _Rledecoderengine(hqxifp)
data = self.ifp.read(len)
self.crc = binascii.crc_hqx(data, self.crc)
filecrc = struct.unpack('>h', self.ifp.read(2))[0] & 0xffff
#self.crc = binascii.crc_hqx('\0\0', self.crc)
self.crc = self.crc & 0xffff
raise Error('CRC error, computed %x, read %x'
fname = self._read(ord(len))
rest = self._read(1 + 4 + 4 + 2 + 4 + 4)
flags = struct.unpack('>h', rest[9:11])[0]
self.dlen = struct.unpack('>l', rest[11:15])[0]
self.rlen = struct.unpack('>l', rest[15:19])[0]
self.FInfo.Creator = creator
if self.state != _DID_HEADER:
raise Error('Read data at wrong time')
rv = rv + self._read(n-len(rv))
self.dlen = self.dlen - n
if self.state != _DID_HEADER:
raise Error('close_data at wrong time')
dummy = self._read(self.dlen)
if self.state == _DID_HEADER:
if self.state != _DID_DATA:
raise Error('Read resource data at wrong time')
self.rlen = self.rlen - n
dummy = self.read_rsrc(self.rlen)
"""hexbin(infilename, outfilename) - Decode binhexed file"""
with io.open(out, 'wb') as ofp:
# XXXX Do translation on non-mac systems
d = ifp.read_rsrc(128000)
ofp = openrsrc(out, 'wb')
d = ifp.read_rsrc(128000)