ยปCore Development>Code coverage>Lib/binhex.py

Python code coverage for Lib/binhex.py

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