home *** CD-ROM | disk | FTP | other *** search
/ OS/2 Shareware BBS: 10 Tools / 10-Tools.zip / pyos2bin.zip / Lib / binhex.py < prev    next >
Text File  |  1997-12-24  |  13KB  |  530 lines

  1. """binhex - Macintosh binhex compression/decompression
  2. easy interface:
  3. binhex(inputfilename, outputfilename)
  4. hexbin(inputfilename, outputfilename)
  5. """
  6.  
  7. #
  8. # Jack Jansen, CWI, August 1995.
  9. #
  10. # The module is supposed to be as compatible as possible. Especially the
  11. # easy interface should work "as expected" on any platform.
  12. # XXXX Note: currently, textfiles appear in mac-form on all platforms.
  13. # We seem to lack a simple character-translate in python.
  14. # (we should probably use ISO-Latin-1 on all but the mac platform).
  15. # XXXX The simeple routines are too simple: they expect to hold the complete
  16. # files in-core. Should be fixed.
  17. # XXXX It would be nice to handle AppleDouble format on unix
  18. # (for servers serving macs).
  19. # XXXX I don't understand what happens when you get 0x90 times the same byte on
  20. # input. The resulting code (xx 90 90) would appear to be interpreted as an
  21. # escaped *value* of 0x90. All coders I've seen appear to ignore this nicety...
  22. #
  23. import sys
  24. import os
  25. import struct
  26. import string
  27. import binascii
  28.     
  29. Error = 'binhex.Error'
  30.  
  31. # States (what have we written)
  32. [_DID_HEADER, _DID_DATA, _DID_RSRC] = range(3)
  33.  
  34. # Various constants
  35. REASONABLY_LARGE=32768    # Minimal amount we pass the rle-coder
  36. LINELEN=64
  37. RUNCHAR=chr(0x90)    # run-length introducer
  38.  
  39. #
  40. # This code is no longer byte-order dependent
  41.  
  42. #
  43. # Workarounds for non-mac machines.
  44. if os.name == 'mac':
  45.     import macfs
  46.     import MacOS
  47.     try:
  48.         openrf = MacOS.openrf
  49.     except AttributeError:
  50.         # Backward compatability
  51.         openrf = open
  52.     
  53.     def FInfo():
  54.         return macfs.FInfo()
  55.     
  56.     def getfileinfo(name):
  57.         finfo = macfs.FSSpec(name).GetFInfo()
  58.         dir, file = os.path.split(name)
  59.         # XXXX Get resource/data sizes
  60.         fp = open(name, 'rb')
  61.         fp.seek(0, 2)
  62.         dlen = fp.tell()
  63.         fp = openrf(name, '*rb')
  64.         fp.seek(0, 2)
  65.         rlen = fp.tell()
  66.         return file, finfo, dlen, rlen
  67.     
  68.     def openrsrc(name, *mode):
  69.         if not mode:
  70.             mode = '*rb'
  71.         else:
  72.             mode = '*' + mode[0]
  73.         return openrf(name, mode)
  74.  
  75. else:
  76.     #
  77.     # Glue code for non-macintosh useage
  78.     #
  79.     
  80.     class FInfo:
  81.         def __init__(self):
  82.             self.Type = '????'
  83.             self.Creator = '????'
  84.             self.Flags = 0
  85.  
  86.     def getfileinfo(name):
  87.         finfo = FInfo()
  88.         # Quick check for textfile
  89.         fp = open(name)
  90.         data = open(name).read(256)
  91.         for c in data:
  92.             if not c in string.whitespace \
  93.             and (c<' ' or ord(c) > 0177):
  94.             break
  95.         else:
  96.             finfo.Type = 'TEXT'
  97.         fp.seek(0, 2)
  98.         dsize = fp.tell()
  99.         fp.close()
  100.         dir, file = os.path.split(name)
  101.         file = string.replace(file, ':', '-', 1)
  102.         return file, finfo, dsize, 0
  103.  
  104.     class openrsrc:
  105.         def __init__(self, *args):
  106.             pass
  107.     
  108.         def read(self, *args):
  109.             return ''
  110.     
  111.         def write(self, *args):
  112.             pass
  113.             
  114.         def close(self):
  115.             pass
  116.     
  117. class _Hqxcoderengine:
  118.     """Write data to the coder in 3-byte chunks"""
  119.     
  120.     def __init__(self, ofp):
  121.         self.ofp = ofp
  122.         self.data = ''
  123.         self.hqxdata = ''
  124.         self.linelen = LINELEN-1
  125.  
  126.     def write(self, data):
  127.         self.data = self.data + data
  128.         datalen = len(self.data)
  129.         todo = (datalen/3)*3
  130.         data = self.data[:todo]
  131.         self.data = self.data[todo:]
  132.         if not data:
  133.             return
  134.         self.hqxdata = self.hqxdata + binascii.b2a_hqx(data)
  135.         self._flush(0)
  136.  
  137.     def _flush(self, force):
  138.         first = 0
  139.         while first <= len(self.hqxdata)-self.linelen:
  140.             last = first + self.linelen
  141.             self.ofp.write(self.hqxdata[first:last]+'\n')
  142.             self.linelen = LINELEN
  143.             first = last
  144.         self.hqxdata = self.hqxdata[first:]
  145.         if force:
  146.             self.ofp.write(self.hqxdata + ':\n')
  147.  
  148.     def close(self):
  149.         if self.data:
  150.             self.hqxdata = \
  151.                  self.hqxdata + binascii.b2a_hqx(self.data)
  152.         self._flush(1)
  153.         self.ofp.close()
  154.         del self.ofp
  155.  
  156. class _Rlecoderengine:
  157.     """Write data to the RLE-coder in suitably large chunks"""
  158.  
  159.     def __init__(self, ofp):
  160.         self.ofp = ofp
  161.         self.data = ''
  162.  
  163.     def write(self, data):
  164.         self.data = self.data + data
  165.         if len(self.data) < REASONABLY_LARGE:
  166.             return
  167.         rledata = binascii.rlecode_hqx(self.data)
  168.         self.ofp.write(rledata)
  169.         self.data = ''
  170.  
  171.     def close(self):
  172.         if self.data:
  173.             rledata = binascii.rlecode_hqx(self.data)
  174.             self.ofp.write(rledata)
  175.         self.ofp.close()
  176.         del self.ofp
  177.  
  178. class BinHex:
  179.     def __init__(self, (name, finfo, dlen, rlen), ofp):
  180.         if type(ofp) == type(''):
  181.             ofname = ofp
  182.             ofp = open(ofname, 'w')
  183.             if os.name == 'mac':
  184.                 fss = macfs.FSSpec(ofname)
  185.                 fss.SetCreatorType('BnHq', 'TEXT')
  186.         ofp.write('(This file must be converted with BinHex 4.0)\n\n:')
  187.         hqxer = _Hqxcoderengine(ofp)
  188.         self.ofp = _Rlecoderengine(hqxer)
  189.         self.crc = 0
  190.         if finfo == None:
  191.             finfo = FInfo()
  192.         self.dlen = dlen
  193.         self.rlen = rlen
  194.         self._writeinfo(name, finfo)
  195.         self.state = _DID_HEADER
  196.  
  197.     def _writeinfo(self, name, finfo):
  198.         name = name
  199.         nl = len(name)
  200.         if nl > 63:
  201.             raise Error, 'Filename too long'
  202.         d = chr(nl) + name + '\0'
  203.         d2 = finfo.Type + finfo.Creator
  204.  
  205.         # Force all structs to be packed with big-endian
  206.         d3 = struct.pack('>h', finfo.Flags)
  207.         d4 = struct.pack('>ii', self.dlen, self.rlen)
  208.         info = d + d2 + d3 + d4
  209.         self._write(info)
  210.         self._writecrc()
  211.  
  212.     def _write(self, data):
  213.         self.crc = binascii.crc_hqx(data, self.crc)
  214.         self.ofp.write(data)
  215.  
  216.     def _writecrc(self):
  217.         # XXXX Should this be here??
  218.         # self.crc = binascii.crc_hqx('\0\0', self.crc)
  219.         self.ofp.write(struct.pack('>h', self.crc))
  220.         self.crc = 0
  221.  
  222.     def write(self, data):
  223.         if self.state != _DID_HEADER:
  224.             raise Error, 'Writing data at the wrong time'
  225.         self.dlen = self.dlen - len(data)
  226.         self._write(data)
  227.  
  228.     def close_data(self):
  229.         if self.dlen <> 0:
  230.             raise Error, 'Incorrect data size, diff='+`self.rlen`
  231.         self._writecrc()
  232.         self.state = _DID_DATA
  233.  
  234.     def write_rsrc(self, data):
  235.         if self.state < _DID_DATA:
  236.             self.close_data()
  237.         if self.state != _DID_DATA:
  238.             raise Error, 'Writing resource data at the wrong time'
  239.         self.rlen = self.rlen - len(data)
  240.         self._write(data)
  241.  
  242.     def close(self):
  243.         if self.state < _DID_DATA:
  244.             self.close_data()
  245.         if self.state != _DID_DATA:
  246.             raise Error, 'Close at the wrong time'
  247.         if self.rlen <> 0:
  248.             raise Error, \
  249.                   "Incorrect resource-datasize, diff="+`self.rlen`
  250.         self._writecrc()
  251.         self.ofp.close()
  252.         self.state = None
  253.         del self.ofp
  254.     
  255. def binhex(inp, out):
  256.     """(infilename, outfilename) - Create binhex-encoded copy of a file"""
  257.     finfo = getfileinfo(inp)
  258.     ofp = BinHex(finfo, out)
  259.     
  260.     ifp = open(inp, 'rb')
  261.     # XXXX Do textfile translation on non-mac systems
  262.     while 1:
  263.         d = ifp.read(128000)
  264.         if not d: break
  265.         ofp.write(d)
  266.     ofp.close_data()
  267.     ifp.close()
  268.  
  269.     ifp = openrsrc(inp, 'rb')
  270.     while 1:
  271.         d = ifp.read(128000)
  272.         if not d: break
  273.         ofp.write_rsrc(d)
  274.     ofp.close()
  275.     ifp.close() 
  276.  
  277. class _Hqxdecoderengine:
  278.     """Read data via the decoder in 4-byte chunks"""
  279.     
  280.     def __init__(self, ifp):
  281.         self.ifp = ifp
  282.         self.eof = 0
  283.  
  284.     def read(self, totalwtd):
  285.         """Read at least wtd bytes (or until EOF)"""
  286.         decdata = ''
  287.         wtd = totalwtd
  288.         #
  289.         # The loop here is convoluted, since we don't really now how 
  290.         # much to decode: there may be newlines in the incoming data.
  291.         while wtd > 0:
  292.             if self.eof: return decdata
  293.             wtd = ((wtd+2)/3)*4
  294.             data = self.ifp.read(wtd)
  295.             #
  296.             # Next problem: there may not be a complete number of
  297.             # bytes in what we pass to a2b. Solve by yet another
  298.             # loop.
  299.             #
  300.             while 1:
  301.                 try:
  302.                     decdatacur, self.eof = \
  303.                             binascii.a2b_hqx(data)
  304.                     break
  305.                 except binascii.Incomplete:
  306.                     pass
  307.                 newdata = self.ifp.read(1)
  308.                 if not newdata:
  309.                     raise Error, \
  310.                           'Premature EOF on binhex file'
  311.                 data = data + newdata
  312.             decdata = decdata + decdatacur
  313.             wtd = totalwtd - len(decdata)
  314.             if not decdata and not self.eof:
  315.                 raise Error, 'Premature EOF on binhex file'
  316.         return decdata
  317.  
  318.     def close(self):
  319.         self.ifp.close()
  320.  
  321. class _Rledecoderengine:
  322.     """Read data via the RLE-coder"""
  323.  
  324.     def __init__(self, ifp):
  325.         self.ifp = ifp
  326.         self.pre_buffer = ''
  327.         self.post_buffer = ''
  328.         self.eof = 0
  329.  
  330.     def read(self, wtd):
  331.         if wtd > len(self.post_buffer):
  332.             self._fill(wtd-len(self.post_buffer))
  333.         rv = self.post_buffer[:wtd]
  334.         self.post_buffer = self.post_buffer[wtd:]
  335.         return rv
  336.  
  337.     def _fill(self, wtd):
  338.         self.pre_buffer = self.pre_buffer + self.ifp.read(wtd+4)
  339.         if self.ifp.eof:
  340.             self.post_buffer = self.post_buffer + \
  341.                 binascii.rledecode_hqx(self.pre_buffer)
  342.             self.pre_buffer = ''
  343.             return
  344.             
  345.         #
  346.         # Obfuscated code ahead. We have to take care that we don't
  347.         # end up with an orphaned RUNCHAR later on. So, we keep a couple
  348.         # of bytes in the buffer, depending on what the end of
  349.         # the buffer looks like:
  350.         # '\220\0\220' - Keep 3 bytes: repeated \220 (escaped as \220\0)
  351.         # '?\220' - Keep 2 bytes: repeated something-else
  352.         # '\220\0' - Escaped \220: Keep 2 bytes.
  353.         # '?\220?' - Complete repeat sequence: decode all
  354.         # otherwise: keep 1 byte.
  355.         #
  356.         mark = len(self.pre_buffer)
  357.         if self.pre_buffer[-3:] == RUNCHAR + '\0' + RUNCHAR:
  358.             mark = mark - 3
  359.         elif self.pre_buffer[-1] == RUNCHAR:
  360.             mark = mark - 2
  361.         elif self.pre_buffer[-2:] == RUNCHAR + '\0':
  362.             mark = mark - 2
  363.         elif self.pre_buffer[-2] == RUNCHAR:
  364.             pass # Decode all
  365.         else:
  366.             mark = mark - 1
  367.  
  368.         self.post_buffer = self.post_buffer + \
  369.             binascii.rledecode_hqx(self.pre_buffer[:mark])
  370.         self.pre_buffer = self.pre_buffer[mark:]
  371.  
  372.     def close(self):
  373.         self.ifp.close()
  374.  
  375. class HexBin:
  376.     def __init__(self, ifp):
  377.         if type(ifp) == type(''):
  378.             ifp = open(ifp)
  379.         #
  380.         # Find initial colon.
  381.         #
  382.         while 1:
  383.             ch = ifp.read(1)
  384.             if not ch:
  385.                 raise Error, "No binhex data found"
  386.             # Cater for \r\n terminated lines (which show up as \n\r, hence
  387.             # all lines start with \r)
  388.             if ch == '\r':
  389.                 continue
  390.             if ch == ':':
  391.                 break
  392.             if ch != '\n':
  393.                 dummy = ifp.readline()
  394.             
  395.         hqxifp = _Hqxdecoderengine(ifp)
  396.         self.ifp = _Rledecoderengine(hqxifp)
  397.         self.crc = 0
  398.         self._readheader()
  399.         
  400.     def _read(self, len):
  401.         data = self.ifp.read(len)
  402.         self.crc = binascii.crc_hqx(data, self.crc)
  403.         return data
  404.         
  405.     def _checkcrc(self):
  406.         filecrc = struct.unpack('>h', self.ifp.read(2))[0] & 0xffff
  407.         #self.crc = binascii.crc_hqx('\0\0', self.crc)
  408.         # XXXX Is this needed??
  409.         self.crc = self.crc & 0xffff
  410.         if filecrc != self.crc:
  411.             raise Error, 'CRC error, computed %x, read %x' \
  412.                   %(self.crc, filecrc)
  413.         self.crc = 0
  414.  
  415.     def _readheader(self):
  416.         len = self._read(1)
  417.         fname = self._read(ord(len))
  418.         rest = self._read(1+4+4+2+4+4)
  419.         self._checkcrc()
  420.         
  421.         type = rest[1:5]
  422.         creator = rest[5:9]
  423.         flags = struct.unpack('>h', rest[9:11])[0]
  424.         self.dlen = struct.unpack('>l', rest[11:15])[0]
  425.         self.rlen = struct.unpack('>l', rest[15:19])[0]
  426.         
  427.         self.FName = fname
  428.         self.FInfo = FInfo()
  429.         self.FInfo.Creator = creator
  430.         self.FInfo.Type = type
  431.         self.FInfo.Flags = flags
  432.         
  433.         self.state = _DID_HEADER
  434.         
  435.     def read(self, *n):
  436.         if self.state != _DID_HEADER:
  437.             raise Error, 'Read data at wrong time'
  438.         if n:
  439.             n = n[0]
  440.             n = min(n, self.dlen)
  441.         else:
  442.             n = self.dlen
  443.         rv = ''
  444.         while len(rv) < n:
  445.             rv = rv + self._read(n-len(rv))
  446.         self.dlen = self.dlen - n
  447.         return rv
  448.         
  449.     def close_data(self):
  450.         if self.state != _DID_HEADER:
  451.             raise Error, 'close_data at wrong time'
  452.         if self.dlen:
  453.             dummy = self._read(self.dlen)
  454.         self._checkcrc()
  455.         self.state = _DID_DATA
  456.         
  457.     def read_rsrc(self, *n):
  458.         if self.state == _DID_HEADER:
  459.             self.close_data()
  460.         if self.state != _DID_DATA:
  461.             raise Error, 'Read resource data at wrong time'
  462.         if n:
  463.             n = n[0]
  464.             n = min(n, self.rlen)
  465.         else:
  466.             n = self.rlen
  467.         self.rlen = self.rlen - n
  468.         return self._read(n)
  469.         
  470.     def close(self):
  471.         if self.rlen:
  472.             dummy = self.read_rsrc(self.rlen)
  473.         self._checkcrc()
  474.         self.state = _DID_RSRC
  475.         self.ifp.close()
  476.         
  477. def hexbin(inp, out):
  478.     """(infilename, outfilename) - Decode binhexed file"""
  479.     ifp = HexBin(inp)
  480.     finfo = ifp.FInfo
  481.     if not out:
  482.         out = ifp.FName
  483.     if os.name == 'mac':
  484.         ofss = macfs.FSSpec(out)
  485.         out = ofss.as_pathname()
  486.  
  487.     ofp = open(out, 'wb')
  488.     # XXXX Do translation on non-mac systems
  489.     while 1:
  490.         d = ifp.read(128000)
  491.         if not d: break
  492.         ofp.write(d)
  493.     ofp.close()
  494.     ifp.close_data()
  495.     
  496.     d = ifp.read_rsrc(128000)
  497.     if d:
  498.         ofp = openrsrc(out, 'wb')
  499.         ofp.write(d)
  500.         while 1:
  501.             d = ifp.read_rsrc(128000)
  502.             if not d: break
  503.             ofp.write(d)
  504.         ofp.close()
  505.  
  506.     if os.name == 'mac':
  507.         nfinfo = ofss.GetFInfo()
  508.         nfinfo.Creator = finfo.Creator
  509.         nfinfo.Type = finfo.Type
  510.         nfinfo.Flags = finfo.Flags
  511.         ofss.SetFInfo(nfinfo)
  512.     
  513.     ifp.close()
  514.  
  515. def _test():
  516.     if os.name == 'mac':
  517.         fss, ok = macfs.PromptGetFile('File to convert:')
  518.         if not ok:
  519.             sys.exit(0)
  520.         fname = fss.as_pathname()
  521.     else:
  522.         fname = sys.argv[1]
  523.     binhex(fname, fname+'.hqx')
  524.     hexbin(fname+'.hqx', fname+'.viahqx')
  525.     #hexbin(fname, fname+'.unpacked')
  526.     sys.exit(1)
  527.     
  528. if __name__ == '__main__':
  529.     _test()
  530.