yenc-0.4.0/0000775000076400007640000000000011754145301011760 5ustar nicolanicolayenc-0.4.0/debian/0000775000076400007640000000000011754144775013220 5ustar nicolanicolayenc-0.4.0/debian/DEBIAN/0000775000076400007640000000000011754144775014142 5ustar nicolanicolayenc-0.4.0/debian/DEBIAN/control0000644000076400007640000000117011631343001015513 0ustar nicolanicolaPackage: python-yenc Architecture: i386 Version: 0.4 Depends: python2.6 Maintainer: Alessandro Duca (DuAL) Section: news Priority: optional Standards-Version: 3.5.6.1 Description: yEnc encoding/decoding extension for Python The yEnc module provide a simple API for doing raw encoding/decoding of yencoded binaries, mainly for retrieving or posting to the usenet. This implementation is really simple and intended mainly as an exercise to the author but is also significatively faster than any possible pure Python implementation and it's being actually used by some Python nntp clients out there. yenc-0.4.0/debian/rules0000755000076400007640000000057011631343001014251 0ustar nicolanicola#!/usr/bin/make -f PYTHON='python2.6' build: clean /usr/bin/env $PYTHON setup.py build /usr/bin/env $PYTHON setup.py install --root=debian/tmp cp -av debian/DEBIAN debian/tmp/DEBIAN binary: binary-arch binary-indep binary-indep: dpkg-gencontrol dpkg --build debian/tmp ../python-yenc_0.4.deb binary-arch: clean: rm -rf debian/tmp/* rm -rf dist/* rm -rf build/* yenc-0.4.0/debian/control0000644000076400007640000000123511631343001014573 0ustar nicolanicolaSource: python-yenc Maintainer: Alessandro Duca (DuAL) Section: news Priority: optional Build-Depends: python2.6-dev Standards-Version: 3.5.6.1 Package: python-yenc Architecture: i386 Depends: python2.6 Description: yEnc encoding/decoding extension for Python The yEnc module provide a simple API for doing raw encoding/decoding of yencoded binaries, mainly for retrieving or posting to the usenet. This implementation is really simple and intended mainly as an exercise to the author but is also significatively faster than any possible pure Python implementation and it's being actually used by some Python nntp clients out there. yenc-0.4.0/debian/changelog0000644000076400007640000000022511631343001015040 0ustar nicolanicolapython-yenc (0.3) experimental; urgency=LOW * Initial version -- Alessandro Duca Tue, 17 Feb 2004 11:16:54 +0100 yenc-0.4.0/MANIFEST.in0000644000076400007640000000030711631343001013503 0ustar nicolanicolainclude *.py MANIFEST* README TODO COPYING CHANGES recursive-include src *.h *.c recursive-include test *.py recursive-include examples * recursive-include doc *txt *html recursive-include debian * yenc-0.4.0/test/0000775000076400007640000000000011754144775012755 5ustar nicolanicolayenc-0.4.0/test/test.py0000755000076400007640000001574011631343001014267 0ustar nicolanicola#!/usr/bin/env python # -*- coding: utf-8 -*- ##============================================================================= # # Copyright (C) 2003, 2011 Alessandro Duca # # This library is free software; you can redistribute it and/or # modify it under the terms of the GNU Lesser General Public # License as published by the Free Software Foundation; either # version 2.1 of the License, or (at your option) any later version. # # This library is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU # Lesser General Public License for more details. # # You should have received a copy of the GNU Lesser General Public # License along with this library; if not, write to the Free Software # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA #============================================================================= # ##============================================================================= import os import sys import time import logging import unittest from binascii import crc32 from stat import * import yenc import _yenc BLOCK_SIZE = 4096 class BaseTest(object): CMD_DATA = "dd if=/dev/urandom of=%s bs=1b count=%d" FILE_E = 'sampledata_e' FILE_O = 'sampledata_o' def setUp(self): os.system(BaseTest.CMD_DATA % (BaseTest.FILE_E, 128)) os.system(BaseTest.CMD_DATA % (BaseTest.FILE_O, 129)) def tearDown(self): os.unlink(BaseTest.FILE_E) os.unlink(BaseTest.FILE_O) for x in os.listdir('.'): if x.endswith('.out') or x.endswith('.dec'): os.unlink(x) def _readFile(self, filename): file_in = open(filename, 'rb') data = file_in.read() file_in.close() return data, "%08x" % (crc32(data) & 0xffffffffL) class TestLowLevel(unittest.TestCase): def testEncode(self): e, c, z = _yenc.encode_string('Hello world!') self.assertEquals(e, 'r\x8f\x96\x96\x99J\xa1\x99\x9c\x96\x8eK') self.assertEquals(c, 3833259626L) def testDecode(self): d, c, x = _yenc.decode_string('r\x8f\x96\x96\x99J\xa1\x99\x9c\x96\x8eK') self.assertEquals(d, 'Hello world!') self.assertEquals(c, 3833259626L) class TestFileFunctions(BaseTest, unittest.TestCase): def _testEncodeFile(self, filename): data, crc = self._readFile(filename) file_in = open(filename, 'rb') file_out = open(filename + ".out", 'wb') bytes_out, crc_out = yenc.encode(file_in, file_out, len(data)) self.assertEquals(crc, crc_out) def testEncodeE(self): self._testEncodeFile(BaseTest.FILE_E) def testEncodeO(self): self._testEncodeFile(BaseTest.FILE_O) def _testDecodeFile(self, filename): data, crc = self._readFile(filename) file_in = open(filename, 'rb') file_out = open(filename + ".out", 'wb') bytes_out, crc_out = yenc.encode(file_in, file_out, len(data)) file_in = open(filename + ".out", 'rb') file_out = open(filename + ".dec", 'wb') bytes_dec, crc_dec = yenc.decode(file_in, file_out) self.assertEquals(crc, crc_dec) def testDecodeE(self): self._testDecodeFile(BaseTest.FILE_E) def testDecodeO(self): self._testDecodeFile(BaseTest.FILE_O) class TestEncoderDecoderOnFile(BaseTest, unittest.TestCase): def _testEncoderDecoder(self, filename): file_data, crc = self._readFile(filename) file_out = open(filename + '.out', 'wb') file_in = open(filename, 'rb') encoder = yenc.Encoder(file_out) data = file_in.read(BLOCK_SIZE) while(len(data)): encoder.feed(data) data = file_in.read(BLOCK_SIZE) file_in.close() encoder.terminate() logging.info("orig: %s enc: %s" %(crc, encoder.getCrc32())) self.assertEquals(crc, encoder.getCrc32()) # deleting forces files to be flushed del encoder file_in = open(filename + '.out', 'rb') file_out = open(filename + '.dec', 'wb') decoder = yenc.Decoder(file_out) data = file_in.read(BLOCK_SIZE) while(len(data) > 0): decoder.feed(data) data = file_in.read(BLOCK_SIZE) file_in.close() decoder.flush() logging.info("orig: %s dec: %s" %(crc, decoder.getCrc32())) self.assertEquals(crc, decoder.getCrc32()) # deleting forces files to be flushed # if __del__ is not called further tests are going to fail del decoder data_dec, crc_dec = self._readFile(filename + '.dec') self.assertEquals(file_data, data_dec) self.assertEquals(crc, crc_dec) def testEncoderDecoderE(self): self._testEncoderDecoder(BaseTest.FILE_E) def testEncoderDecoderO(self): self._testEncoderDecoder(BaseTest.FILE_O) def testEncoderClosed(self): encoder = yenc.Encoder(open('afile.out', 'wb')) encoder.feed('some data') encoder.close() self.assertFalse(encoder._output_file) self.assertRaises(IOError, encoder.feed, ('some data')) def testEncoderTerminated(self): encoder = yenc.Encoder(open('afile.out', 'wb')) encoder.terminate() self.assertRaises(IOError, encoder.feed, ('some data')) def testDecoderClose(self): decoder = yenc.Decoder(open('afile.out', 'wb')) decoder.feed('some data') decoder.close() self.assertFalse(decoder._output_file) class TestEncoderDecoderInMemory(BaseTest, unittest.TestCase): def testEncodeInMemory(self): """ Checks simple encoding in memory """ encoder = yenc.Encoder() encoder.feed('Hello world!') self.assertEquals('r\x8f\x96\x96\x99J\xa1\x99\x9c\x96\x8eK', encoder.getEncoded()) self.assertEquals(encoder.getCrc32(), "%08x" % (crc32("Hello world!") & 0xffffffff)) def testEncodeAndWriteInMemory(self): pass def testDecodeInMemory(self): decoder = yenc.Decoder() decoder.feed('r\x8f\x96\x96\x99J\xa1\x99\x9c\x96\x8eK') self.assertEquals("Hello world!", decoder.getDecoded()) self.assertEquals(decoder.getCrc32(), "%08x" % (crc32("Hello world!") & 0xffffffff)) def testDecodeAndWriteInMemory(self): pass def testEncoderCloseInMemory(self): encoder = yenc.Encoder() self.assertRaises(ValueError, encoder.close) def testDecoderCloseInMemory(self): decoder = yenc.Decoder() self.assertRaises(ValueError, decoder.close) def testEncoderFlushInMemory(self): encoder = yenc.Encoder() self.assertRaises(ValueError, encoder.flush) def testDecodeFlushInMemory(self): decoder = yenc.Decoder() self.assertRaises(ValueError, decoder.flush) if __name__ == "__main__": logging.basicConfig(level=logging.INFO) unittest.main() yenc-0.4.0/examples/0000775000076400007640000000000011754144775013614 5ustar nicolanicolayenc-0.4.0/examples/yencode.py0000755000076400007640000000410011631343001015561 0ustar nicolanicola#!/usr/bin/env python # -*- coding: utf-8 -*- ##============================================================================= # # Copyright (C) 2003, 2011 Alessandro Duca # # This library is free software; you can redistribute it and/or # modify it under the terms of the GNU Lesser General Public # License as published by the Free Software Foundation; either # version 2.1 of the License, or (at your option) any later version. # # This library is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU # Lesser General Public License for more details. # # You should have received a copy of the GNU Lesser General Public # License along with this library; if not, write to the Free Software # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA #============================================================================= # ##============================================================================= import sys import os import os.path import yenc import getopt from stat import * from binascii import crc32 def main(): try: opts, args = getopt.getopt(sys.argv[1:], "o:") except getopt.GetoptError: usage() file_out = sys.stdout for o,a in opts: if o == '-o': file_out = open(a,"wb") if args: filename = args[0] if os.access( filename, os.F_OK | os.R_OK ): file_in = open(filename,"rb") else: print "couldn't access %s" % filename sys.exit(2) else: usage() crc = "%08x"%(0xFFFFFFFF & crc32(open(filename,"rb").read())) name = os.path.split(filename)[1] size = os.stat(filename)[ST_SIZE] file_out.write("=ybegin line=128 size=%d crc32=%s name=%s\r\n" % (size, crc, name) ) try: encoded, crc_out = yenc.encode(file_in, file_out, size) except Exception, e: print e sys.exit(3) file_out.write("=yend size=%d crc32=%s\r\n" % (encoded, crc_out)) def usage(): print "Usage: yencode.py <-o outfile> filename" sys.exit(1) if __name__ == "__main__": main() yenc-0.4.0/examples/ydecode.py0000755000076400007640000000550411631343001015560 0ustar nicolanicola#!/usr/bin/env python # -*- coding: utf-8 -*- ##============================================================================= # # Copyright (C) 2003, 2011 Alessandro Duca # # This library is free software; you can redistribute it and/or # modify it under the terms of the GNU Lesser General Public # License as published by the Free Software Foundation; either # version 2.1 of the License, or (at your option) any later version. # # This library is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU # Lesser General Public License for more details. # # You should have received a copy of the GNU Lesser General Public # License along with this library; if not, write to the Free Software # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA #============================================================================= # ##============================================================================= import yenc import os import sys import re NAME_RE = re.compile(r"^.*? name=(.+?)\r\n$") LINE_RE = re.compile(r"^.*? line=(\d{3}) .*$") SIZE_RE = re.compile(r"^.*? size=(\d+) .*$") CRC32_RE = re.compile(r"^.*? crc32=(\w+)") def main(): if len(sys.argv) > 1: file_in = open(sys.argv[1],"rb") else: file_in = sys.stdin while 1: line = file_in.readline() if line.startswith("=ybegin "): try: name, size = NAME_RE.match(line).group(1), int(SIZE_RE.match(line).group(1)) m_obj = CRC32_RE.match(line) if m_obj: head_crc = m_obj.group(1) except re.error, e: sys.stderr.write("err-critical: malformed =ybegin header\n") sys.exit(1) break elif not line: sys.stderr.write("err-critical: no valid =ybegin header found\n") sys.exit(1) file_out = open(name,"wb") try: dec, dec_crc = yenc.decode(file_in, file_out, size) except yenc.Error, e: sys.stderr.write(str(e) + '\n') sys.exit(1) head_crc = trail_crc = tmp_crc = "" garbage = 0 for line in file_in.read().split("\r\n"): if line.startswith("=yend "): try: size = int( SIZE_RE.match(line).group(1) ) m_obj = CRC32_RE.match(line) if m_obj: trail_crc = m_obj.group(1) except re.error, e: sys.stderr.write("err: malformed =yend trailer\n") break elif not line: continue else: garbage = 1 else: sys.stderr.write("warning: couldn't find =yend trailer\n") if garbage: sys.stderr.write("warning: garbage before =yend trailer\n") if head_crc: tmp_crc = head_crc.lower() elif trail_crc: tmp_crc = trail_crc.lower() else: sys.exit(0) if cmp(tmp_crc,dec_crc): sys.stderr.write("err: header: %s dec: %s CRC32 mismatch\n" % (tmp_crc,dec_crc) ) sys.exit(1) else: sys.exit(0) if __name__ == "__main__": main() yenc-0.4.0/examples/yencode_Encoder.py0000755000076400007640000000427711631343001017237 0ustar nicolanicola#!/usr/bin/env python # -*- coding: utf-8 -*- ##============================================================================= # # Copyright (C) 2003, 2011 Alessandro Duca # # This library is free software; you can redistribute it and/or # modify it under the terms of the GNU Lesser General Public # License as published by the Free Software Foundation; either # version 2.1 of the License, or (at your option) any later version. # # This library is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU # Lesser General Public License for more details. # # You should have received a copy of the GNU Lesser General Public # License along with this library; if not, write to the Free Software # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA #============================================================================= # ##============================================================================= import sys import os import os.path import yenc import getopt from stat import * from binascii import crc32 def main(): try: opts, args = getopt.getopt(sys.argv[1:], "o:") except getopt.GetoptError: usage() file_out = sys.stdout for o,a in opts: if o == '-o': file_out = open(a,"wb") if args: filename = args[0] if os.access( filename, os.F_OK | os.R_OK ): file_in = open(filename,"rb") else: print "couldn't access %s" % filename sys.exit(2) else: usage() crc = "%x"%(0xFFFFFFFF & crc32( open(filename,"rb").read())) name = os.path.split(filename)[1] size = os.stat(filename)[ST_SIZE] file_out.write("=ybegin line=128 size=%d crc32=%s name=%s\r\n" % (size, crc, name) ) file_in = open(filename, "rb") encoder = yenc.Encoder(file_out) while True: data_in = file_in.read(1024) encoder.feed(data_in) encoder.flush() if len(data_in) < 1024: break encoder.terminate() encoder.flush() file_out.write("=yend size=%d crc32=%s\r\n" % (size, encoder.getCrc32()) ) def usage(): print "Usage: yencode_Encoder.py <-o outfile> filename" sys.exit(1) if __name__ == "__main__": main() yenc-0.4.0/examples/logo.gif0000644000076400007640000003771711631343001015231 0ustar nicolanicolaGIF89a/pP88hH (P0xhHАP0X08д(ؤ بhhh|tXH0 rv#HߑM۰'>8( Ϳ+ >ц8I,_{1pQZ.YrxrNJ.xyw9erzZ!?IƴQ!)f[2إ 9NLI^bԹי kT{TfFb}}؞YvF'0`*^uəDQZz^:ӁJj䗡xjpyklv+lkc{l>l`2=ka6{hw&d #Iiq#rKWLv{n+mLR)W^|d䬓ٿ%:o) pm]DƆ]׬Q 0ᄶ1Q\1Ic >ѱ$v8aң j\֪Yّ:ibh!u`: gX Mdw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,\qn8v@jo?kHj?2B)+ =nRwԪxP򫄅FovBZKfPr?J\,7~!LouoB+B6m#lS܆MBP^Pe2>8ZfE8=}IJjCP߅AZWBkJJ +]`Sx*BZS-:-$XyQ}`-+.JfV9M8R3.,\> `$]T]$<2:m32aJ.la5!`]V} !a1.*e =yend size=16335 crc32=547266c7 yenc-0.4.0/examples/ydecode_Decoder.py0000755000076400007640000000550411631343001017205 0ustar nicolanicola#!/usr/bin/env python ## -*- coding: utf-8 -*- ##============================================================================= # # Copyright (C) 2003, 2011 Alessandro Duca # # This library is free software; you can redistribute it and/or # modify it under the terms of the GNU Lesser General Public # License as published by the Free Software Foundation; either # version 2.1 of the License, or (at your option) any later version. # # This library is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU # Lesser General Public License for more details. # # You should have received a copy of the GNU Lesser General Public # License along with this library; if not, write to the Free Software # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA #============================================================================= # ##============================================================================= import os import sys import re import yenc NAME_RE = re.compile(r"^.*? name=(.+?)\r\n$") LINE_RE = re.compile(r"^.*? line=(\d{3}) .*$") SIZE_RE = re.compile(r"^.*? size=(\d+) .*$") CRC32_RE = re.compile(r"^.*? crc32=(\w+)") def main(): head_crc = trail_crc = "" if len(sys.argv) > 1: file_in = open(sys.argv[1],"rb") else: file_in = sys.stdin while 1: line = file_in.readline() if line.startswith("=ybegin "): try: name, size = NAME_RE.match(line).group(1), int(SIZE_RE.match(line).group(1)) m_obj = CRC32_RE.match(line) if m_obj: head_crc = m_obj.group(1) except re.error, e: sys.stderr.write("err-critical: malformed =ybegin header\n") sys.exit(1) break elif not line: sys.stderr.write("err-critical: no valid =ybegin header found\n") sys.exit(1) file_out = open(name,"wb") dec = yenc.Decoder(file_out) trailer = "" garbage = 0 while True: data = file_in.readline() if data.startswith("=yend"): trailer = data break elif dec.getSize() >= size: garbage = 1 else: dec.feed(data) dec.flush() if trailer: try: size = int(SIZE_RE.match(trailer).group(1)) m_obj = CRC32_RE.search(trailer) if m_obj: trail_crc = m_obj.group(1) except re.error, e: sys.stderr.write("err: malformed =yend trailer\n") else: sys.stderr.write("warning: couldn't find =yend trailer\n") if garbage: sys.stderr.write("warning: garbage before =yend trailer\n") if head_crc: tmp_crc = head_crc.lower() elif trail_crc: tmp_crc = trail_crc.lower() else: sys.exit(0) # print "comparing" if cmp(tmp_crc, dec.getCrc32()): sys.stderr.write("err: header: %s dec: %s CRC32 mismatch\n" % (tmp_crc,dec.getCrc32()) ) sys.exit(1) else: sys.exit(0) if __name__ == "__main__": main() yenc-0.4.0/CHANGES0000644000076400007640000000316111631343001012741 0ustar nicolanicolaversion: 0.1 - Initial release. version: 0.2 - Included patch from Michael Muller that fixes some possible buffer overflows, and some yEnc incompatibilities. - A few enanchments in C code, mainly cosmetic (it should be a little faster in encoding). - Files opened in O_RDWR mode are now handled properly. - yenc.i interface adapted to latest SWIG releases. - Passing a file opened in a wrong mode now raises a ValueError (rather than an AssertionError). - encode()/decode() now accepts filenames and stdin/stdout as arguments. - Reaching EOF while encoding/decoding no more raises an exception (it was redundant since the number of encoded/decoded bytes were already returned), this could break some implementations. - Passing 0 to the encode o decode functions causes file to be encoded/decoded up to EOF (this is made possible by the previous change). version: 0.3 - Encoded lines now are correctly terminated with CRLF. - Encoded lines size now is 128 chars. - using fread() instead of fgets in decode() function (much faster). - SWIG isn't used anymore for wrapper generation. version: 0.4 - change license to LGPL - crc32 codes are now Python longs (returned from _yenc calls) in the range [2**0, 2**32 -1] - crc32 formatting is fixed - 'bytes' arguments named 'bytez' to avoid collision with 'bytes' type - basic unit testing - unescaped dots at the beginning of line caused ydecode to fail under some circumstances dots at the beginning of line are now always escaped - Encoder's and Decoder's output files (if any) are automatically flushed and closed upon deletion - new method close() on Encoder and Decoder yenc-0.4.0/README0000644000076400007640000001240111631343001012623 0ustar nicolanicola##============================================================================= # # Copyright (C) 2003, 2011 Alessandro Duca # # This library is free software; you can redistribute it and/or # modify it under the terms of the GNU Lesser General Public # License as published by the Free Software Foundation; either # version 2.1 of the License, or (at your option) any later version. # # This library is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU # Lesser General Public License for more details. # # You should have received a copy of the GNU Lesser General Public # License along with this library; if not, write to the Free Software # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA #============================================================================= # ##============================================================================= Description: ----------- This a fairly simple module, it provide only raw yEnc encoding/decoding with builitin crc32 calculation. Header parsing, checkings and yenc formatting are left to you (see examples directory for possible implementations). The interface was originally intended to be similar to the uu module from Python standard library. Version 0.2 changed a bit the previous (0.1) behaviour, but it should be more usable and flexible (now you can encode/decode from and to standard input and output and use filenames instead of file objects as arguments for encode() and decode() ). See CHANGES file for details. Version 0.3 doesn't introduce anything new, just a bugfix a some internals changes. Version 0.4 introduces the close() method on Encoder and Decoder, fixes crc32 formatting and adds escaping of '.' for compatibility with some ydecode tools, strictly speaking this wasn't a bug and yenc specs reccomend this behaviour only for clients that write directly on the tcp steam. Version 0.4 is meant to be backward compatible with both 0.3 and 0.2. Requirements: ------------ A C developement environment, Python>=2.6 and python developement libs (look for python-dev or something like that if you're using .rpm or .deb packages, if you installed from sources you already have everything you need). The module is known to work with Python2.6, testing with other version is needed. Installation: ------------ To install: tar xzfv yenc-0.4.tar.gz cd yenc-0.4 python setup.py build su python setup.py install To uninstall: Simply remove _yenc.so, yenc.py and yenc.pyc from your PYTHONPATH. On my Ubuntu: /usr/local/lib/python2.6/site-packages/{_yenc.so,yenc.py,yenc.pyc} Usage: ----- As usual: import yenc in your modules. The 'yenc' module defines 2 functions (encode() and decode()) and an error class, yenc.Error(Exception). encode(in_file, out_file, bytes=0): Accepts both filenames or file objects as arguments, if "in_file" is a file type object it must be opened for reading ("r","rw"...), if "out_file" is a file type object it must be opened for writing ("w","rw"..), when files are specified as filenames the files are (if possible) automatically opened in the correct mode. The "bytes" argument is an optional numeric value, if set to 0 or omitted it causes the input file to be read and encoded until EOF, otherwise it specifies the maximum number of bytes to read and encode. When reading from stdin "bytes" argument can't be 0 (or omitted). If arguments don't match such criteria an exception is raised. encode() reads data from "in_file" and writes the encoded data on "out_file", it returns a tuple containing the number of encoded bytes and a crc32 sum of the original data. Specifing "-" as "in_file" or "out_file" arguments causes the input/output to be read/written on standard input/output. decode(in_file, out_file, size=0, crc_in=""): Same as encode (of course it does the inverse job). Exceptions are raised when output can't be written or calculated crc doesn't match the optional crc_in argument (useful for writing decoding tools). CRC32 sums are always represented as lowercase strings, whithout any preceeding simbol (like '0x'). Decoder and Encoder: ------------------- Encoder and Decoder are facility classes meant for encoding data one chunk at time, optionally writing the encoded/decoded data to an output file. import yenc.Encoder encoder = Encoder() encoder.feed('some data') encoder.feed('some other data') encoder.terminate() # writes the \r\n terminator on file, further feed(..) will fail encoded_data = encoder.getEncoded() # returns encoded data as string crc32 = encoder.getCrc32() # returns crc32 of clear data optionally you can write onto an output file: encoder = Encoder(file('outputfile.ync', 'wb')) encoder.feed('some data') encoder.feed('some other data') encoder.terminate() encoder.flush() # writes the local buffer to the output file encoder.close() # flushes and closes output_file, called automatically upon deletion crc32 = encoder.getCrc32() Decoder works basically the same way. Performances: ------------ Fast enough. Author: ------: Alessandro Duca Thanks: ------ Michael Muller for code reviewing and fixing. Greets, Sandro. yenc-0.4.0/setup.cfg0000644000076400007640000000000011631343001013554 0ustar nicolanicolayenc-0.4.0/lib/0000775000076400007640000000000011754144775012544 5ustar nicolanicolayenc-0.4.0/lib/yenc.py0000644000076400007640000001712211631343001014026 0ustar nicolanicola##============================================================================= # # Copyright (C) 2003, 2011 Alessandro Duca # # This library is free software; you can redistribute it and/or # modify it under the terms of the GNU Lesser General Public # License as published by the Free Software Foundation; either # version 2.1 of the License, or (at your option) any later version. # # This library is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU # Lesser General Public License for more details. # # You should have received a copy of the GNU Lesser General Public # License along with this library; if not, write to the Free Software # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA #============================================================================= # ##============================================================================= import sys from cStringIO import StringIO import _yenc E_ERROR = 64 E_CRC32 = 65 E_PARMS = 66 BIN_MASK = 0xffffffffL class Error(Exception): """ Class for specific yenc errors """ def __init__(self, value="", code=E_ERROR): self.value = value def __str__(self): return "yenc.Error: %s\n" % self.value, self.value def _checkArgsType(file_in, file_out, bytez): """ Internal checkings, not to be used from outside this module. """ if bytez < 0: raise Error("No. of bytes can't be negative", E_PARMS) if type(file_in) == str: if file_in == "-": if bytez == 0: raise Error("No. of bytes is 0 or not \ specified while reading from stdin", E_PARMS) file_in = sys.stdin else: file_in = open(file_in,"rb") if type(file_out) == str: if file_out == "-": file_out = sys.stdout else: file_out = open(file_out,"wb") return file_in, file_out, bytez def encode(file_in, file_out, bytez=0): """ encode(file_in, file_out, bytez=0): write "bytez" encoded bytes from file_in to file_out, if "bytez" is 0 encodes bytez until EOF. """ file_in, file_out, bytez = _checkArgsType(file_in, file_out, bytez) encoded, crc32 = _yenc.encode(file_in, file_out, bytez) return encoded, "%08x" % (crc32 ^ BIN_MASK) def decode(file_in, file_out, bytez=0, crc_in=""): """ decode(file_in, file_out, bytez=0): write "bytez" decoded bytes from file_in to file_out, if "bytez" is 0 decodes bytes until EOF. """ file_in, file_out, bytez = _checkArgsType(file_in, file_out, bytez) decoded, crc32 = _yenc.decode(file_in, file_out, bytez) crc_hex = "%08x" % (crc32 ^ BIN_MASK) if crc_in and not cmp(crc_hex, crc_in.lower()): raise Error("crc32 error", E_CRC32) else: return decoded, crc_hex class Encoder: """ class Encoder: facility class for encoding one string at time Constructor accepts an optional "output_file" argument, file must be opened in write mode. When output_file is specified flush() will write the buffer content onto the and close() will flush and close the file. After close() further calls to feed() will fail. """ def __init__(self, output_file = None): self._buffer = StringIO() self._column = 0 self._output_file = output_file self._crc = BIN_MASK self._encoded = 0 self._feedable = True def __del__(self): if self._output_file is not None: self.flush() self.close() def feed(self, data): """ Encode some data and write the encoded data into the internal buffer. """ if not self._feedable: raise IOError("Encoding already terminated") encoded, self._crc, self._column = _yenc.encode_string(data, self._crc, self._column) self._encoded = self._encoded + len(encoded) self._buffer.write(encoded) return len(encoded) def terminate(self): """ Appends the terminal CRLF sequence to the encoded data. Further calls to feed() will fail. """ self._buffer.write("\r\n") self._feedable = False def flush(self): """ Writes the content of the internal buffer on output_file. """ if self._output_file is None: raise ValueError("Output file is 'None'") self._output_file.write(self._buffer.getvalue()) self._buffer = StringIO() def close(self): """ Flushes and closes output_file. The output buffer IS NOT automatically written to the file. """ if self._output_file is None: raise ValueError("Output file is 'None'") self._output_file.flush() self._output_file.close() self._output_file = None self._feedable = False def getEncoded(self): """ Returns the data in the internal buffer. """ if self._output_file is not None: raise ValueError("Output file is not 'None'") return self._buffer.getvalue() def getSize(self): """ Returns the total number of encoded bytes (not the size of the buffer). """ return self._encoded def getCrc32(self): """ Returns the calculated crc32 string for the clear data. """ return "%08x" % (self._crc ^ BIN_MASK) class Decoder: """ class Decoder: facility class for decoding one string at time Constructor accepts an optional "output_file" argument, file must be opened in write mode. When output_file is specified flush() will write the buffer content onto the and close() will flush and close the file. After close() further calls to feed() will fail. """ def __init__(self, output_file = None): self._buffer = StringIO() self._escape = 0 self._output_file = output_file self._crc = BIN_MASK self._decoded = 0 self._feedable = True def __del__(self): if self._output_file is not None: self.flush() self.close() def feed(self, data): """ Decode some data and write the decoded data into the internal buffer. """ if not self._feedable: raise IOError("Decoding already terminated") decoded, self._crc, self._escape = _yenc.decode_string(data, self._crc, self._escape) self._decoded = self._decoded + len(decoded) self._buffer.write(decoded) return len(decoded) def flush(self): """ Writes the content of the internal buffer on the file passed as argument to the constructor. """ if self._output_file is None: raise ValueError("Output file is 'None'") self._output_file.write(self._buffer.getvalue()) self._buffer = StringIO() def close(self): """ Flushes and closes output_file. The output file is flushed before closing, further calls to feed() will fail. """ if self._output_file is None: raise ValueError("Output file is 'None'") self._output_file.flush() self._output_file.close() self._output_file = None self._feedable = False def getDecoded(self): """ Returns the decoded data from the internal buffer. If output_file is not None this is going to raise a ValueError. """ if self._output_file is not None: raise ValueError("Output file is not 'None'") return self._buffer.getvalue() def getSize(self): """ Returns the total number of decoded bytes (not the size of the buffer). """ return self._decoded def getCrc32(self): """ Returns the calculated crc32 string for the decoded data. """ return "%08x" % (self._crc ^ BIN_MASK) yenc-0.4.0/doc/0000775000076400007640000000000011754144775012543 5ustar nicolanicolayenc-0.4.0/doc/yenc-draft.1.3.txt0000644000076400007640000004123111631343001015610 0ustar nicolanicolayEncode - A quick and dirty encoding for binaries --------------------------------------------------------------------------- Version 1.2 - 28-Feb-2002 - by Juergen Helbing Revisions: v1.0, 31-Jul-2001 - Juergen Helbing (juergen@helbing.de) v1.1, 17-Feb-2002 - Steve Blinch (yenc32@esitemedia.com) v1.2, 28-Feb-2002 - Juergen Helbing (juergen@helbing.de) v1.3, 05-Mar-2002 - Juergen Helbing (juergen@helbing.de) Introduction --------------------------------------------------------------------------- This document describes a mechanism for encoding arbitrary binary information for transmission by electronic mail and newsgroups. Unlike similar encoding schemes, yEncode takes advantage of the entire 8-bit character set, rendering output only 1-2% larger than the original binary source. Motivation --------------------------------------------------------------------------- Existing mechanisms for transmission of binary information by electronic mail and newsgroups make use of only 7-bit ASCII text. The resulting encoded data are up to 40% larger than the original binary information. yEncode intends to reduce the additional overhead of existing encoding schemes by taking advantage of the full 8-bit character set, which has become widely used and acceptable in Internet newsgroups. Special consideration is provided for specific reserved ASCII control characters to avoid interference with existing message transfer protocols. The overhead of yEncoded binary data can be as little as 1-2%. Encoding Principle --------------------------------------------------------------------------- The encoding process represents each octet of input data with a single corresponding encoded output character. The ASCII value of each output character is derived by the following simple formula: O = (I+42) % 256 That is, the output value is equal to the ASCII value of each input character plus 42, all modulo 256. This reduces overhead by reducing the number of NULL characters (ASCII 00) that would otherwise have had needed to be escaped, since many binaries contain a disproportionately large number of NULLs). Under special circumstances, a single escape character (ASCII 3Dh, "=") is used to indicate that the following output character is "critical", and requires special handling. Critical characters include the following: ASCII 00h (NULL) ASCII 0Ah (LF) ASCII 0Dh (CR) ASCII 3Dh (=) > ASCII 09h (TAB) -- removed in version (1.2) These characters should always be escaped. Additionally, technique used to encode critical characters (described in the next section) provides for any character to be escaped; yDecoder implementations should be capable of decoding any character following an escape sequence. The probability of occurance of these 4 characters in binary input data is approximately 0.4%. On average, escape sequences cause approximately 1.6% overhead when only these 4 characters are escaped. The carriage return/linefeed overhead for every line depends on the developer-defined line length. Header and trailer lines are relatively small, and cause negligible impact on output size. >(1.2) Careful writers of encoders will encode TAB (09h) SPACES (20h) >if they would appear in the first or last column of a line. >Implementors who write directly to a TCP stream will care about the doubling of dots in the first column - or also encode a DOT in the first column. Encoding Technique --------------------------------------------------------------------------- A typical encoding process might look something like this: 1. Fetch a character from the input stream. 2. Increment the character's ASCII value by 42, modulo 256 3. If the result is a critical character (as defined in the previous section), write the escape character to the output stream and increment character's ASCII value by 64, modulo 256. 4. Output the character to the output stream. 5. Repeat from start. To facilitate transmission via existing standard protocols (most notably NNTP), carriage return/linefeed pairs should be written to the output stream after every n characters, where n is the desired line length. Typical values for n are 128 and 256. >(1.2) See additional experience information If a critical character appears in the nth position of a line, both the escape character and the encoded critical character must be written to the same line, before the carriage return/linefeed. In this event, the actual number of characters in the line is equal to n+1. Effectively, this means that a line cannot end with an escape character, and that a line with n+1 characters must end with an encoded critical character. Headers and Trailers --------------------------------------------------------------------------- Similar to other binary encoding mechanisms, yEncode makes use of special keyword lines to mark the beginning and end of encoded data blocks. These blocks may be embedded in any standard 8-bit ASCII text file. yDecoder implementations must ignore any text outside the header/trailer blocks. All keyword lines must begin with an escape character ('='), followed by an ASCII 79h ('y'). This '=y' combination uniquely identifies a line as a keyword line, since 'y' is not a valid encoded critical character. Header and trailer keyword lines always begin with an escape character, followed by a keyword indicating the line type, followed by any keywords appropriate for that particular line type. A typical header line should look similar to this: =ybegin line=128 size=123456 name=mybinary.dat >(1.2) Future versions of yEnc (if any) might use a different keyword > than =ybegin. Perhaps "=ybegin2". Decoders should scan for "=ybegin " > - with a SPACE behind =ybegin. >(1.2) If the parameters "line=" "size=" "name=" are not present then >the =ybegin might be part of a text-message with a discussion about >yEnc. In such cases the decoder should assume that there is no binary. Header lines must always begin with the "ybegin" keyword, and contain the typical line length, the size of the original unencoded binary (in bytes), and the name of the original binary file. The filename must always be the last item on the header line. This ensures that all characters and character sequences may be included in the filename without interfering with other keywords. Although quotes (ASCII 22h, '"') are technically permitted, they are not recommended for use in filenames. > (1.2): Leading and trailing spaces will be cut by decoders! > (1.2): See additional experience information > Implementors of decoders should be careful about the filename. > It can contain non-US-ASCII-characters (80h-FFh), control-characters > (01h..1Fh), and characters which conflict with the current platform: > / \ < | > : ? * @ > It can be a very long parameter (up to 256 characters). A typical trailer line should look similar to this: =yend size=123456 Trailer lines must always begin with the "yend" keyword, and must contain the size of the original unencoded binary (in bytes). The size of the original binary must be repeated in the trailer for redundancy checking. yDecoder implementations should compare the header size value with both the trailer size value and the actual size of the resulting decoded binary. If any of these three values differ then the attachment is corrupt, and a warning must be issued; the resulting decoded binary must be discarded. (1.2) See additional experience information Verifying Integrity --------------------------------------------------------------------------- yEncoded documents may also include a 32-bit Cyclic Redundancy Check (CRC) value, to assist in verifying the integrity of the encoded binary data. A CRC32 value, if present, should be included as a "crc32" keyword in the trailer line. Such a trailer line might look similar to this: =yend size=123456 crc32=abcdef12 It should be noted that CRC32 values are not mandatory, but should, if possible, be processed if present. >(1.2) See additional experience information Sample yEncoded File Part --------------------------------------------------------------------------- The following is an excerpt from an actual yEncoded file block: =ybegin line=128 size=111401 name=al_larsonbw030_ball.jpg )_)=J*:tpsp*++++V+V**)_*m*0./0/.00/011024:44334>896:A>.... .... .... ....R̴R̴R̴R̴R̴R̴R̴R̴R̴R̴R̴R̴R̴R̴R̴R̴R̴R̴R̴R̴R̴R̴R̴R̴R̴R̴R̴ ´R̴R̴R̴R̴R̴R̴R̴R̴R̴R̴R̴R̴Rͩ)_ =yend size=111401 Complete yEncoded file samples are also available at www.yenc.org. Multi-part Encoded Binaries --------------------------------------------------------------------------- It is frequently desirable to split large binary files into multiple parts for transmissio n over the Internet. Such binaries are often rendered unusable by missing parts and/or data corruption. To address these problems, yEncode defines an additional keyword line, "ypart", and several additional keywords to handle multipart binaries. Each individual file part begins with a standard "ybegin" header line, but an additional keyword, "part", is added to specify the part number and identify the file as a multipart binary. When the "part" keyword is included in a header line, the following line must be a "ypart" keyword line which specifies information about the part. The "ypart" keyword line requires a "begin" and "end" keyword; these specify the starting and ending points, in bytes, of the block in the original file. The file part must end with a slightly modified "ypart" trailer line. An additional keyword, "part", is added to specify the part number. This part number must match the part number found in the header line. > (1.2) An additional keyword "total" should be also added. > This total number must match the total number of parts found in the header > line. First implementation of yEnc do NOT include this parameter. The trailer line must also contain a "pcrc32" keyword representing the CRC32 of the preceeding encoded part. As always, it is also desirable (but not required) to include a "crc32" keyword representing the CRC32 of the entire encoded binary. Unlike single-part yEncoded documents, the "size" keyword in the trailer lines of multipart encoded binaries must represent the size of the file part, not the size of the entire file. To verify integrity, a decoder implementation must recompute the expected part size from the "begin" and "end" keyword values in the "ypart" line. If the expected part size differs from the part size specified in the "yend" line, the file is corrupt. A sample multipart encoded binary might look similar to this: > (1.1) =ybegin part=1 line=128 size=500000 name=mybinary.dat > (1.2) =ybegin part=1 total=10 line=128 size=500000 name=mybinary.dat =ypart begin=1 end=100000 .... data =yend size=100000 part=1 pcrc32=abcdef12 =ybegin part=5 line=128 size=500000 name=mybinary.dat =ypart begin=400001 end=500000 .... data =yend size=100000 part=10 pcrc32=12a45c78 crc32=abcdef12 It should be noted that if a decoder does not implement multipart support, or fails to detect a multipart encoded binary, then it will not successfully decode the individual file parts because the "size" keyword in the "ybegin" line will differ from the "size" keyword in the "yend" line. Multipart binaries are usually quite sensitive to corruption. Transferring hundreds of megabytes in vain, simply because a corrupt part cannot be identified is a significant waste of bandwidth. Using the "begin" and "end" keywords, yEncode allows decoders to identify the position of an individual part in a larger file, which allows parts to be combined from several different sources regardless of the part size. This feature is unique to yEncode, and is very easy to include in an encoder implementation. Subject Line Conventions --------------------------------------------------------------------------- Standard single-part yEncoded binaries require no special conventions for the subject line. It is recommended, however, that yEncoded binaries be specifically identified as such, until the yEncode encoding format becomes more widely implemented. The suggested format for subject lines for single-part binaries is: [Comment1] "filename" 12345 yEnc bytes [Comment2] [Comment1] and [Comment2] are optional. The filename should always be enclosed in quotes; this allows for easy detection, even when the filename includes spaces or other special characters. The word "yEnc" should be placed in between the file size and the word "bytes". > (1.2) see additional experience information > Placing the word "yEnc" between filename+bytes or bytes+comment2 > is acceptable. Multi-part archives should always be identified as such. As with single-part binaries, they should also be identified as yEncoded until yEncoding becomes more mainstream. The (strongly) recommended format for subject lines for multi-part binaries is: [Comment1] "filename" yEnc (partnum/numparts) [size] [Comment2] Again, [Comment1] and [Comment2] are optional. The [size] value is also optional here. The filename must be included, in quotes. The keyword "yEnc" is mandatory, and must appear between the filename and the size (or Comment2, if size is omitted). Future revisions of the draft may specify additional information may be inserted between the "yEnc" keyword and the opening parenthesis of the part number. > (1.2) see additional experience information > Placing the word "yEnc" between (#/#)+size or size+comment2 > is acceptable. >(1.2) Handling of corrupt messages >(1.2) ------------------------------------------------------------------- Decoders should use error-detection whenever possible. The user should be notified about corrupt messages. If warnings are disabled then it is strongly recommended to store binaries with an error-text in the filename. Examples: picture(size-error).jpg homemovie(crc32-error).avi document(line-error).rtf longmusic(missing-parts).mp3 It is acceptable to store also corrupt binaries (some might be even partially usable). But it is _not_ acceptable to hide detected errors from the user entirely. yEnc has the design target to _detect_ corruption. Advanced newsreaders might fetch corrupt messages even from other sources. Protection and Copyright --------------------------------------------------------------------------- The yEncode encoding method is released into the public domain. Everyone is permitted to copy it, to use it, and to implement it. Neither this document nor the yEncode encoding method may be patented, protected, or restricted in any way. Everyone should benefit from it, and its predecessors. This document may be freely distributed, as long as credit remains with the original author(s). Do not claim that it's your own work! Public domain example software is also available at www.yenc.org. Credits --------------------------------------------------------------------------- This document has been created based on my [Juergen Helbing] own personal experience, and help and input from a few Usenet activists. Thanks to: Jeremy Nixon Curt Welch Ed Andrew Stuart JBerg Marco d'Itri The Meowbot Jan Ingvoldstat The UseFor taskforce (others - please remind me!) .... Draft revised (02/17/02) by Steve Blinch Draft extended (02/28/02) by Juergen Helbing Conclusion --------------------------------------------------------------------------- This is an informal proposal, not an RFC. Your input is greatly appreciated. The author is just a poor programmer - with a few years of binary experience. Thanks for reading. Juergen Helbing (yenc@infostar.de) ----------------------- Changes from 1.1 -> 1.2 ----------------------- The "total=" parameter has been added to =ybegin TAB is no longer a critical character No. of critical characters is now 4 (old: 5) Leading TABs & SPACEs, Trailing TABs and SPACEs and leading DOTs may be encoded as critical characters. Additional hints for filenames Additional hints for corrupted by size-value Additional hints for position of "yEnc" keyword Additional hints for line sizes Scanning for the keword =ybegin should scan for "=ybegin " with a SPACE at the end - for avoiding conflicts with successor versions of yEnc "=ybegin2 ". Missing parameters behind =ybegin Handling of corrupt messages. Mailbox changed Changes from 1.2 -> 1.3 ----------------------- "the proceeding character" --> "the following character" (N.R.) "modulo 255" -> "modulo 256" (J.H.) "should be encoded" -> "may be encoded" (J.B.) yenc-0.4.0/TODO0000644000076400007640000000017411631343001012437 0ustar nicolanicolaversion 0.4: - Provide *real* documentation. - More examples (especially: multipart encoding/decoding). - More testing. yenc-0.4.0/COPYING0000644000076400007640000005764711631343001013023 0ustar nicolanicola GNU LESSER GENERAL PUBLIC LICENSE Version 2.1, February 1999 Copyright (C) 1991, 1999 Free Software Foundation, Inc. 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. [This is the first released version of the Lesser GPL. It also counts as the successor of the GNU Library Public License, version 2, hence the version number 2.1.] Preamble The licenses for most software are designed to take away your freedom to share and change it. By contrast, the GNU General Public Licenses are intended to guarantee your freedom to share and change free software--to make sure the software is free for all its users. This license, the Lesser General Public License, applies to some specially designated software packages--typically libraries--of the Free Software Foundation and other authors who decide to use it. You can use it too, but we suggest you first think carefully about whether this license or the ordinary General Public License is the better strategy to use in any particular case, based on the explanations below. When we speak of free software, we are referring to freedom of use, not price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for this service if you wish); that you receive source code or can get it if you want it; that you can change the software and use pieces of it in new free programs; and that you are informed that you can do these things. To protect your rights, we need to make restrictions that forbid distributors to deny you these rights or to ask you to surrender these rights. These restrictions translate to certain responsibilities for you if you distribute copies of the library or if you modify it. For example, if you distribute copies of the library, whether gratis or for a fee, you must give the recipients all the rights that we gave you. You must make sure that they, too, receive or can get the source code. If you link other code with the library, you must provide complete object files to the recipients, so that they can relink them with the library after making changes to the library and recompiling it. And you must show them these terms so they know their rights. We protect your rights with a two-step method: (1) we copyright the library, and (2) we offer you this license, which gives you legal permission to copy, distribute and/or modify the library. To protect each distributor, we want to make it very clear that there is no warranty for the free library. Also, if the library is modified by someone else and passed on, the recipients should know that what they have is not the original version, so that the original author's reputation will not be affected by problems that might be introduced by others. Finally, software patents pose a constant threat to the existence of any free program. We wish to make sure that a company cannot effectively restrict the users of a free program by obtaining a restrictive license from a patent holder. Therefore, we insist that any patent license obtained for a version of the library must be consistent with the full freedom of use specified in this license. Most GNU software, including some libraries, is covered by the ordinary GNU General Public License. This license, the GNU Lesser General Public License, applies to certain designated libraries, and is quite different from the ordinary General Public License. We use this license for certain libraries in order to permit linking those libraries into non-free programs. When a program is linked with a library, whether statically or using a shared library, the combination of the two is legally speaking a combined work, a derivative of the original library. The ordinary General Public License therefore permits such linking only if the entire combination fits its criteria of freedom. The Lesser General Public License permits more lax criteria for linking other code with the library. We call this license the "Lesser" General Public License because it does Less to protect the user's freedom than the ordinary General Public License. It also provides other free software developers Less of an advantage over competing non-free programs. These disadvantages are the reason we use the ordinary General Public License for many libraries. However, the Lesser license provides advantages in certain special circumstances. For example, on rare occasions, there may be a special need to encourage the widest possible use of a certain library, so that it becomes a de-facto standard. To achieve this, non-free programs must be allowed to use the library. A more frequent case is that a free library does the same job as widely used non-free libraries. In this case, there is little to gain by limiting the free library to free software only, so we use the Lesser General Public License. In other cases, permission to use a particular library in non-free programs enables a greater number of people to use a large body of free software. For example, permission to use the GNU C Library in non-free programs enables many more people to use the whole GNU operating system, as well as its variant, the GNU/Linux operating system. Although the Lesser General Public License is Less protective of the users' freedom, it does ensure that the user of a program that is linked with the Library has the freedom and the wherewithal to run that program using a modified version of the Library. The precise terms and conditions for copying, distribution and modification follow. Pay close attention to the difference between a "work based on the library" and a "work that uses the library". The former contains code derived from the library, whereas the latter must be combined with the library in order to run. GNU LESSER GENERAL PUBLIC LICENSE TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION 0. This License Agreement applies to any software library or other program which contains a notice placed by the copyright holder or other authorized party saying it may be distributed under the terms of this Lesser General Public License (also called "this License"). Each licensee is addressed as "you". A "library" means a collection of software functions and/or data prepared so as to be conveniently linked with application programs (which use some of those functions and data) to form executables. The "Library", below, refers to any such software library or work which has been distributed under these terms. A "work based on the Library" means either the Library or any derivative work under copyright law: that is to say, a work containing the Library or a portion of it, either verbatim or with modifications and/or translated straightforwardly into another language. (Hereinafter, translation is included without limitation in the term "modification".) "Source code" for a work means the preferred form of the work for making modifications to it. For a library, complete source code means all the source code for all modules it contains, plus any associated interface definition files, plus the scripts used to control compilation and installation of the library. Activities other than copying, distribution and modification are not covered by this License; they are outside its scope. The act of running a program using the Library is not restricted, and output from such a program is covered only if its contents constitute a work based on the Library (independent of the use of the Library in a tool for writing it). Whether that is true depends on what the Library does and what the program that uses the Library does. 1. You may copy and distribute verbatim copies of the Library's complete source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice and disclaimer of warranty; keep intact all the notices that refer to this License and to the absence of any warranty; and distribute a copy of this License along with the Library. You may charge a fee for the physical act of transferring a copy, and you may at your option offer warranty protection in exchange for a fee. 2. You may modify your copy or copies of the Library or any portion of it, thus forming a work based on the Library, and copy and distribute such modifications or work under the terms of Section 1 above, provided that you also meet all of these conditions: a) The modified work must itself be a software library. b) You must cause the files modified to carry prominent notices stating that you changed the files and the date of any change. c) You must cause the whole of the work to be licensed at no charge to all third parties under the terms of this License. d) If a facility in the modified Library refers to a function or a table of data to be supplied by an application program that uses the facility, other than as an argument passed when the facility is invoked, then you must make a good faith effort to ensure that, in the event an application does not supply such function or table, the facility still operates, and performs whatever part of its purpose remains meaningful. (For example, a function in a library to compute square roots has a purpose that is entirely well-defined independent of the application. Therefore, Subsection 2d requires that any application-supplied function or table used by this function must be optional: if the application does not supply it, the square root function must still compute square roots.) These requirements apply to the modified work as a whole. If identifiable sections of that work are not derived from the Library, and can be reasonably considered independent and separate works in themselves, then this License, and its terms, do not apply to those sections when you distribute them as separate works. But when you distribute the same sections as part of a whole which is a work based on the Library, the distribution of the whole must be on the terms of this License, whose permissions for other licensees extend to the entire whole, and thus to each and every part regardless of who wrote it. Thus, it is not the intent of this section to claim rights or contest your rights to work written entirely by you; rather, the intent is to exercise the right to control the distribution of derivative or collective works based on the Library. In addition, mere aggregation of another work not based on the Library with the Library (or with a work based on the Library) on a volume of a storage or distribution medium does not bring the other work under the scope of this License. 3. You may opt to apply the terms of the ordinary GNU General Public License instead of this License to a given copy of the Library. To do this, you must alter all the notices that refer to this License, so that they refer to the ordinary GNU General Public License, version 2, instead of to this License. (If a newer version than version 2 of the ordinary GNU General Public License has appeared, then you can specify that version instead if you wish.) Do not make any other change in these notices. Once this change is made in a given copy, it is irreversible for that copy, so the ordinary GNU General Public License applies to all subsequent copies and derivative works made from that copy. This option is useful when you wish to copy part of the code of the Library into a program that is not a library. 4. You may copy and distribute the Library (or a portion or derivative of it, under Section 2) in object code or executable form under the terms of Sections 1 and 2 above provided that you accompany it with the complete corresponding machine-readable source code, which must be distributed under the terms of Sections 1 and 2 above on a medium customarily used for software interchange. If distribution of object code is made by offering access to copy from a designated place, then offering equivalent access to copy the source code from the same place satisfies the requirement to distribute the source code, even though third parties are not compelled to copy the source along with the object code. 5. A program that contains no derivative of any portion of the Library, but is designed to work with the Library by being compiled or linked with it, is called a "work that uses the Library". Such a work, in isolation, is not a derivative work of the Library, and therefore falls outside the scope of this License. However, linking a "work that uses the Library" with the Library creates an executable that is a derivative of the Library (because it contains portions of the Library), rather than a "work that uses the library". The executable is therefore covered by this License. Section 6 states terms for distribution of such executables. When a "work that uses the Library" uses material from a header file that is part of the Library, the object code for the work may be a derivative work of the Library even though the source code is not. Whether this is true is especially significant if the work can be linked without the Library, or if the work is itself a library. The threshold for this to be true is not precisely defined by law. If such an object file uses only numerical parameters, data structure layouts and accessors, and small macros and small inline functions (ten lines or less in length), then the use of the object file is unrestricted, regardless of whether it is legally a derivative work. (Executables containing this object code plus portions of the Library will still fall under Section 6.) Otherwise, if the work is a derivative of the Library, you may distribute the object code for the work under the terms of Section 6. Any executables containing that work also fall under Section 6, whether or not they are linked directly with the Library itself. 6. As an exception to the Sections above, you may also combine or link a "work that uses the Library" with the Library to produce a work containing portions of the Library, and distribute that work under terms of your choice, provided that the terms permit modification of the work for the customer's own use and reverse engineering for debugging such modifications. You must give prominent notice with each copy of the work that the Library is used in it and that the Library and its use are covered by this License. You must supply a copy of this License. If the work during execution displays copyright notices, you must include the copyright notice for the Library among them, as well as a reference directing the user to the copy of this License. Also, you must do one of these things: a) Accompany the work with the complete corresponding machine-readable source code for the Library including whatever changes were used in the work (which must be distributed under Sections 1 and 2 above); and, if the work is an executable linked with the Library, with the complete machine-readable "work that uses the Library", as object code and/or source code, so that the user can modify the Library and then relink to produce a modified executable containing the modified Library. (It is understood that the user who changes the contents of definitions files in the Library will not necessarily be able to recompile the application to use the modified definitions.) b) Use a suitable shared library mechanism for linking with the Library. A suitable mechanism is one that (1) uses at run time a copy of the library already present on the user's computer system, rather than copying library functions into the executable, and (2) will operate properly with a modified version of the library, if the user installs one, as long as the modified version is interface-compatible with the version that the work was made with. c) Accompany the work with a written offer, valid for at least three years, to give the same user the materials specified in Subsection 6a, above, for a charge no more than the cost of performing this distribution. d) If distribution of the work is made by offering access to copy from a designated place, offer equivalent access to copy the above specified materials from the same place. e) Verify that the user has already received a copy of these materials or that you have already sent this user a copy. For an executable, the required form of the "work that uses the Library" must include any data and utility programs needed for reproducing the executable from it. However, as a special exception, the materials to be distributed need not include anything that is normally distributed (in either source or binary form) with the major components (compiler, kernel, and so on) of the operating system on which the executable runs, unless that component itself accompanies the executable. It may happen that this requirement contradicts the license restrictions of other proprietary libraries that do not normally accompany the operating system. Such a contradiction means you cannot use both them and the Library together in an executable that you distribute. 7. You may place library facilities that are a work based on the Library side-by-side in a single library together with other library facilities not covered by this License, and distribute such a combined library, provided that the separate distribution of the work based on the Library and of the other library facilities is otherwise permitted, and provided that you do these two things: a) Accompany the combined library with a copy of the same work based on the Library, uncombined with any other library facilities. This must be distributed under the terms of the Sections above. b) Give prominent notice with the combined library of the fact that part of it is a work based on the Library, and explaining where to find the accompanying uncombined form of the same work. 8. You may not copy, modify, sublicense, link with, or distribute the Library except as expressly provided under this License. Any attempt otherwise to copy, modify, sublicense, link with, or distribute the Library is void, and will automatically terminate your rights under this License. However, parties who have received copies, or rights, from you under this License will not have their licenses terminated so long as such parties remain in full compliance. 9. You are not required to accept this License, since you have not signed it. However, nothing else grants you permission to modify or distribute the Library or its derivative works. These actions are prohibited by law if you do not accept this License. Therefore, by modifying or distributing the Library (or any work based on the Library), you indicate your acceptance of this License to do so, and all its terms and conditions for copying, distributing or modifying the Library or works based on it. 10. Each time you redistribute the Library (or any work based on the Library), the recipient automatically receives a license from the original licensor to copy, distribute, link with or modify the Library subject to these terms and conditions. You may not impose any further restrictions on the recipients' exercise of the rights granted herein. You are not responsible for enforcing compliance by third parties with this License. 11. If, as a consequence of a court judgment or allegation of patent infringement or for any other reason (not limited to patent issues), conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not excuse you from the conditions of this License. If you cannot distribute so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not distribute the Library at all. For example, if a patent license would not permit royalty-free redistribution of the Library by all those who receive copies directly or indirectly through you, then the only way you could satisfy both it and this License would be to refrain entirely from distribution of the Library. If any portion of this section is held invalid or unenforceable under any particular circumstance, the balance of the section is intended to apply, and the section as a whole is intended to apply in other circumstances. It is not the purpose of this section to induce you to infringe any patents or other property right claims or to contest validity of any such claims; this section has the sole purpose of protecting the integrity of the free software distribution system which is implemented by public license practices. Many people have made generous contributions to the wide range of software distributed through that system in reliance on consistent application of that system; it is up to the author/donor to decide if he or she is willing to distribute software through any other system and a licensee cannot impose that choice. This section is intended to make thoroughly clear what is believed to be a consequence of the rest of this License. 12. If the distribution and/or use of the Library is restricted in certain countries either by patents or by copyrighted interfaces, the original copyright holder who places the Library under this License may add an explicit geographical distribution limitation excluding those countries, so that distribution is permitted only in or among countries not thus excluded. In such case, this License incorporates the limitation as if written in the body of this License. 13. The Free Software Foundation may publish revised and/or new versions of the Lesser General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns. Each version is given a distinguishing version number. If the Library specifies a version number of this License which applies to it and "any later version", you have the option of following the terms and conditions either of that version or of any later version published by the Free Software Foundation. If the Library does not specify a license version number, you may choose any version ever published by the Free Software Foundation. 14. If you wish to incorporate parts of the Library into other free programs whose distribution conditions are incompatible with these, write to the author to ask for permission. For software which is copyrighted by the Free Software Foundation, write to the Free Software Foundation; we sometimes make exceptions for this. Our decision will be guided by the two goals of preserving the free status of all derivatives of our free software and of promoting the sharing and reuse of software generally. NO WARRANTY 15. BECAUSE THE LIBRARY IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY FOR THE LIBRARY, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE LIBRARY "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE LIBRARY IS WITH YOU. SHOULD THE LIBRARY PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 16. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR REDISTRIBUTE THE LIBRARY AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE LIBRARY (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE LIBRARY TO OPERATE WITH ANY OTHER SOFTWARE), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. END OF TERMS AND CONDITIONS yenc-0.4.0/setup.py0000644000076400007640000000523111631343001013460 0ustar nicolanicola#!/usr/bin/env python # -*- coding: utf-8 -*- ##============================================================================= # # Copyright (C) 2003, 2011 Alessandro Duca # # This library is free software; you can redistribute it and/or #modify it under the terms of the GNU Lesser General Public # License as published by the Free Software Foundation; either # version 2.1 of the License, or (at your option) any later version. # # This library is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU # Lesser General Public License for more details. # # You should have received a copy of the GNU Lesser General Public # License along with this library; if not, write to the Free Software # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA #============================================================================= # ##============================================================================= from distutils.core import setup, Extension setup( name = "yenc", version = "0.4.0", author = "Alessandro Duca", author_email = "alessandro.duca@gmail.com", url = "https://bitbucket.org/dual75/yenc", license = "LGPL", platforms = ["Unix"], package_dir = { '': 'lib' }, py_modules = ["yenc"], ext_modules = [Extension("_yenc",["src/_yenc.c"],extra_compile_args=["-O2","-g"])], classifiers = [ "Programming Language :: Python", "Programming Language :: Python :: 2.5", "Programming Language :: Python :: 2.6", "Programming Language :: Python :: 2.7", "Programming Language :: C", "License :: OSI Approved :: GNU Library or Lesser General Public License (LGPL)", "Operating System :: Unix", "Development Status :: 4 - Beta", "Environment :: Other Environment", "Intended Audience :: Developers", "Topic :: Software Development :: Libraries :: Python Modules", "Topic :: Communications :: Usenet News" ], description = "yEnc Module for Python", long_description = """ yEnc Encoding/Decoding for Python --------------------------------- This a fairly simple module, it provide only raw yEnc encoding/decoding with builitin crc32 calculation. Header parsing, checkings and yenc formatting are left to you (see examples directory for possible implementations). Supports encoding and decoding directly to files or to memory buffers with helper classes Encoder and Decoder. """ ) yenc-0.4.0/PKG-INFO0000644000076400007640000000035611631343001013046 0ustar nicolanicolaMetadata-Version: 1.0 Name: yenc Version: 0.3.1 Summary: yEnc Module for Python Home-page: http://www.golug.it/yenc.html Author: Alessandro Duca Author-email: alessandro.duca@gmail.com License: LGPL Description: UNKNOWN Platform: UNKNOWN yenc-0.4.0/src/0000775000076400007640000000000011754144775012565 5ustar nicolanicolayenc-0.4.0/src/_yenc.h0000644000076400007640000000435711631343001014013 0ustar nicolanicola /*============================================================================= * * Copyright (C) 2003, 2011 Alessandro Duca * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA *============================================================================= */ #include #include #include #include /* Constants */ #define LINESIZE 128 /* BLOCK defines the size of the input buffer used while encoding data. */ #define BLOCK 65536 /* LONGBUFF: ((2 * BLOCK) / 128 + 2 ) * 128 * In the worst case we will escape every byte thus doubling output's size, * since we write out lines of LINESIZE characters, we must add 2 more bytes for * CRLF sequence at the end of each line. * This is the maximum encoded size of BLOCK bytes. */ #define LONGBUFF ( 2 * BLOCK / LINESIZE + 1) * ( LINESIZE + 2 ) #define SMALLBUFF 512 #define ZERO 0x00 #define CR 0x0d #define LF 0x0a #define ESC 0x3d #define TAB 0x09 #define SPACE 0x20 #define DOT 0x2e #define E_MODE 1 #define E_EOF 2 #define E_IO 3 #define E_MODE_MSG "Invalide mode for '*file' arguments" #define E_IO_MSG "I/O Error" #define _DDEBUG_ /* Customized types */ typedef unsigned long uLong; typedef unsigned int uInt; typedef unsigned char Byte; typedef int Bool; /* Functions */ PyObject* encode_file(PyObject*, PyObject*, PyObject*); PyObject* decode_file(PyObject*, PyObject*, PyObject*); PyObject* encode_string(PyObject* ,PyObject* ,PyObject*); PyObject* decode_string(PyObject* ,PyObject* , PyObject*); void init_yenc(void); yenc-0.4.0/src/_yenc.c0000644000076400007640000003125711631343001014005 0ustar nicolanicola /*============================================================================= * * Copyright (C) 2003, 2011 Alessandro Duca * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA *============================================================================= */ #include "_yenc.h" /* Typedefs */ typedef struct { uInt crc; uLong bytes; } Crc32; /* Declarations */ static uInt crc_tab[256] = { 0x00000000, 0x77073096, 0xee0e612c, 0x990951ba, 0x076dc419, 0x706af48f, 0xe963a535, 0x9e6495a3, 0x0edb8832, 0x79dcb8a4, 0xe0d5e91e, 0x97d2d988, 0x09b64c2b, 0x7eb17cbd, 0xe7b82d07, 0x90bf1d91, 0x1db71064, 0x6ab020f2, 0xf3b97148, 0x84be41de, 0x1adad47d, 0x6ddde4eb, 0xf4d4b551, 0x83d385c7, 0x136c9856, 0x646ba8c0, 0xfd62f97a, 0x8a65c9ec, 0x14015c4f, 0x63066cd9, 0xfa0f3d63, 0x8d080df5, 0x3b6e20c8, 0x4c69105e, 0xd56041e4, 0xa2677172, 0x3c03e4d1, 0x4b04d447, 0xd20d85fd, 0xa50ab56b, 0x35b5a8fa, 0x42b2986c, 0xdbbbc9d6, 0xacbcf940, 0x32d86ce3, 0x45df5c75, 0xdcd60dcf, 0xabd13d59, 0x26d930ac, 0x51de003a, 0xc8d75180, 0xbfd06116, 0x21b4f4b5, 0x56b3c423, 0xcfba9599, 0xb8bda50f, 0x2802b89e, 0x5f058808, 0xc60cd9b2, 0xb10be924, 0x2f6f7c87, 0x58684c11, 0xc1611dab, 0xb6662d3d, 0x76dc4190, 0x01db7106, 0x98d220bc, 0xefd5102a, 0x71b18589, 0x06b6b51f, 0x9fbfe4a5, 0xe8b8d433, 0x7807c9a2, 0x0f00f934, 0x9609a88e, 0xe10e9818, 0x7f6a0dbb, 0x086d3d2d, 0x91646c97, 0xe6635c01, 0x6b6b51f4, 0x1c6c6162, 0x856530d8, 0xf262004e, 0x6c0695ed, 0x1b01a57b, 0x8208f4c1, 0xf50fc457, 0x65b0d9c6, 0x12b7e950, 0x8bbeb8ea, 0xfcb9887c, 0x62dd1ddf, 0x15da2d49, 0x8cd37cf3, 0xfbd44c65, 0x4db26158, 0x3ab551ce, 0xa3bc0074, 0xd4bb30e2, 0x4adfa541, 0x3dd895d7, 0xa4d1c46d, 0xd3d6f4fb, 0x4369e96a, 0x346ed9fc, 0xad678846, 0xda60b8d0, 0x44042d73, 0x33031de5, 0xaa0a4c5f, 0xdd0d7cc9, 0x5005713c, 0x270241aa, 0xbe0b1010, 0xc90c2086, 0x5768b525, 0x206f85b3, 0xb966d409, 0xce61e49f, 0x5edef90e, 0x29d9c998, 0xb0d09822, 0xc7d7a8b4, 0x59b33d17, 0x2eb40d81, 0xb7bd5c3b, 0xc0ba6cad, 0xedb88320, 0x9abfb3b6, 0x03b6e20c, 0x74b1d29a, 0xead54739, 0x9dd277af, 0x04db2615, 0x73dc1683, 0xe3630b12, 0x94643b84, 0x0d6d6a3e, 0x7a6a5aa8, 0xe40ecf0b, 0x9309ff9d, 0x0a00ae27, 0x7d079eb1, 0xf00f9344, 0x8708a3d2, 0x1e01f268, 0x6906c2fe, 0xf762575d, 0x806567cb, 0x196c3671, 0x6e6b06e7, 0xfed41b76, 0x89d32be0, 0x10da7a5a, 0x67dd4acc, 0xf9b9df6f, 0x8ebeeff9, 0x17b7be43, 0x60b08ed5, 0xd6d6a3e8, 0xa1d1937e, 0x38d8c2c4, 0x4fdff252, 0xd1bb67f1, 0xa6bc5767, 0x3fb506dd, 0x48b2364b, 0xd80d2bda, 0xaf0a1b4c, 0x36034af6, 0x41047a60, 0xdf60efc3, 0xa867df55, 0x316e8eef, 0x4669be79, 0xcb61b38c, 0xbc66831a, 0x256fd2a0, 0x5268e236, 0xcc0c7795, 0xbb0b4703, 0x220216b9, 0x5505262f, 0xc5ba3bbe, 0xb2bd0b28, 0x2bb45a92, 0x5cb36a04, 0xc2d7ffa7, 0xb5d0cf31, 0x2cd99e8b, 0x5bdeae1d, 0x9b64c2b0, 0xec63f226, 0x756aa39c, 0x026d930a, 0x9c0906a9, 0xeb0e363f, 0x72076785, 0x05005713, 0x95bf4a82, 0xe2b87a14, 0x7bb12bae, 0x0cb61b38, 0x92d28e9b, 0xe5d5be0d, 0x7cdcefb7, 0x0bdbdf21, 0x86d3d2d4, 0xf1d4e242, 0x68ddb3f8, 0x1fda836e, 0x81be16cd, 0xf6b9265b, 0x6fb077e1, 0x18b74777, 0x88085ae6, 0xff0f6a70, 0x66063bca, 0x11010b5c, 0x8f659eff, 0xf862ae69, 0x616bffd3, 0x166ccf45, 0xa00ae278, 0xd70dd2ee, 0x4e048354, 0x3903b3c2, 0xa7672661, 0xd06016f7, 0x4969474d, 0x3e6e77db, 0xaed16a4a, 0xd9d65adc, 0x40df0b66, 0x37d83bf0, 0xa9bcae53, 0xdebb9ec5, 0x47b2cf7f, 0x30b5ffe9, 0xbdbdf21c, 0xcabac28a, 0x53b39330, 0x24b4a3a6, 0xbad03605, 0xcdd70693, 0x54de5729, 0x23d967bf, 0xb3667a2e, 0xc4614ab8, 0x5d681b02, 0x2a6f2b94, 0xb40bbe37, 0xc30c8ea1, 0x5a05df1b, 0x2d02ef8d }; static char* argnames[] = {"infile", "outfile", "bytez", NULL}; /* Function declarations */ static void crc_init(Crc32 *, uInt); static void crc_update(Crc32 *, uInt); static Bool readable(FILE *); static Bool writable(FILE *); void init_yenc(void); static int encode_buffer(Byte *, Byte *, uInt, Crc32 *, uInt *); static int decode_buffer(Byte *, Byte *, uInt, Crc32 *, Bool *); PyObject* decode_string(PyObject* ,PyObject* ,PyObject* ); /* Python API requirements */ static char encode_doc[] = "encode(input_file, output_file, )"; static char decode_doc[] = "decode(input_file, output_file, )"; static char encode_string_doc[] = "encode_string(string, crc32, column)"; static char decode_string_doc[] = "decode_string(string, crc32, escape)"; static PyMethodDef funcs[] = { {"encode", (PyCFunction) encode_file, METH_KEYWORDS | METH_VARARGS, encode_doc}, {"decode", (PyCFunction) decode_file, METH_KEYWORDS | METH_VARARGS, decode_doc}, {"encode_string", (PyCFunction) encode_string, METH_KEYWORDS | METH_VARARGS, encode_string_doc}, {"decode_string", (PyCFunction) decode_string, METH_KEYWORDS | METH_VARARGS, decode_string_doc}, {NULL, NULL, 0, NULL} }; /* Function definitions */ static void crc_init(Crc32 *crc, uInt value) { crc->crc = value; crc->bytes = 0UL; } static void crc_update(Crc32 *crc, uInt c) { crc->crc=crc_tab[(crc->crc^c)&0xff]^((crc->crc>>8)&0xffffff); crc->bytes++; } /* * Todo: provide alternatives for this to work on win32 */ static Bool writable(FILE *file) { int mode = fcntl(fileno(file),F_GETFL) & O_ACCMODE; return (mode == O_WRONLY) || (mode == O_RDWR); } static Bool readable(FILE *file) { int mode = fcntl(fileno(file),F_GETFL) & O_ACCMODE; return (mode == O_RDONLY) || (mode == O_RDWR); } /* * */ static int encode_buffer( Byte *input_buffer, Byte *output_buffer, uInt bytes, Crc32 *crc, uInt *col ) { uInt encoded; uInt in_ind; uInt out_ind; Byte byte; out_ind = 0; for(in_ind=0; in_ind < bytes; in_ind++) { byte = (Byte)(input_buffer[in_ind] + 42); crc_update(crc, input_buffer[in_ind]); switch(byte){ case ZERO: case LF: case CR: case ESC: goto escape_string; case TAB: case SPACE: if(*col == 0 || *col == LINESIZE-1) { goto escape_string; } case DOT: if(*col == 0) { goto escape_string; } default: goto plain_string; } escape_string: byte = (Byte)(byte + 64); output_buffer[out_ind++] = ESC; (*col)++; plain_string: output_buffer[out_ind++] = byte; (*col)++; encoded++; if(*col >= LINESIZE) { output_buffer[out_ind++] = CR; output_buffer[out_ind++] = LF; *col = 0; } } return out_ind; } PyObject* encode_file( PyObject* self, PyObject* args, PyObject* kwds ) { Byte read_buffer[BLOCK]; Byte write_buffer[LONGBUFF]; uLong encoded = 0; uInt col = 0; uInt read_bytes; uInt in_ind; uInt encoded_bytes; uLong bytes = 0; Crc32 crc; FILE *infile = NULL, *outfile = NULL; PyObject *Py_infile = NULL, *Py_outfile = NULL; if(!PyArg_ParseTupleAndKeywords(args, kwds, "O!O!|l", argnames, \ &PyFile_Type, &Py_infile, \ &PyFile_Type, &Py_outfile, \ &bytes)) return NULL; infile = PyFile_AsFile(Py_infile); outfile = PyFile_AsFile(Py_outfile); if(!readable(infile) || !writable(outfile) ) { return PyErr_Format(PyExc_ValueError, "file objects not writeable/readable"); } crc_init(&crc, 0xffffffffl); while(encoded < bytes || bytes == 0){ if( bytes && (bytes - encoded) < BLOCK) { in_ind = bytes - encoded; } else { in_ind = BLOCK; } read_bytes = fread(&read_buffer, 1, in_ind, infile); if(read_bytes < 1) { break; } encoded_bytes = encode_buffer(&read_buffer[0], &write_buffer[0], read_bytes, &crc, &col); if(fwrite(&write_buffer, 1, encoded_bytes, outfile) != encoded_bytes) { break; } encoded += read_bytes; } if(ferror(infile) || ferror(outfile)) { return PyErr_Format(PyExc_IOError, "I/O Error while encoding"); } if(col > 0) { fputc(CR, outfile); fputc(LF, outfile); } fflush(outfile); return Py_BuildValue("(l,L)", encoded, (long long)crc.crc); } static int decode_buffer( Byte *input_buffer, Byte *output_buffer, uInt bytes, Crc32 *crc, Bool *escape ) { uInt read_ind; uInt decoded_bytes; Byte byte; decoded_bytes = 0; for(read_ind = 0; read_ind < bytes; read_ind++) { byte = input_buffer[read_ind]; if(*escape) { byte = (Byte)(byte - 106); *escape = 0; } else if(byte == ESC) { *escape = 1; continue; } else if(byte == LF || byte == CR) { continue; } else { byte = (Byte)(byte - 42); } output_buffer[decoded_bytes] = byte; decoded_bytes++; crc_update(crc, byte); } return decoded_bytes; } PyObject* encode_string( PyObject* self, PyObject* args, PyObject* kwds ) { PyObject *Py_input_string; PyObject *Py_output_string; PyObject *retval; Byte *input_buffer = NULL; Byte *output_buffer = NULL; long long crc_value = 0xffffffffll; uInt input_len = 0; uInt output_len = 0; uInt col = 0; Crc32 crc; static char *kwlist[] = { "string", "crc32", "column", NULL }; if(!PyArg_ParseTupleAndKeywords(args, kwds, "O!|Li", kwlist, &PyString_Type, &Py_input_string, &crc_value, &col )) return NULL; crc_init(&crc, (uInt)crc_value); input_len = PyString_Size(Py_input_string); input_buffer = (Byte *) PyString_AsString(Py_input_string); output_buffer = (Byte *) malloc((2 * input_len / LINESIZE + 1) * (LINESIZE + 2)); output_len = encode_buffer(input_buffer, output_buffer, input_len, &crc, &col); Py_output_string = PyString_FromStringAndSize((char *)output_buffer, output_len); retval = Py_BuildValue("(S,L,i)", Py_output_string, (long long)crc.crc, col); free(output_buffer); Py_DECREF(Py_output_string); return retval; } PyObject* decode_file( PyObject* self, PyObject* args, PyObject* kwds ) { Byte read_buffer[BLOCK]; Byte write_buffer[LONGBUFF]; uLong decoded = 0; uInt decoded_bytes; uInt read_bytes; uLong read_max; Bool escape = 0; uLong bytes = 0; Crc32 crc; FILE *infile = NULL, *outfile = NULL; PyObject *Py_infile = NULL, *Py_outfile = NULL; if(!PyArg_ParseTupleAndKeywords(args, kwds, "O!O!|l", argnames, \ &PyFile_Type, &Py_infile, \ &PyFile_Type, &Py_outfile, \ &bytes)) return NULL; infile = PyFile_AsFile(Py_infile); outfile = PyFile_AsFile(Py_outfile); if(!readable(infile) || !writable(outfile)) { return PyErr_Format(PyExc_ValueError, "file objects not writeable/readable"); } crc_init(&crc, 0xffffffffl); while(decoded < bytes || bytes == 0){ if(bytes){ read_max=(bytes-decoded)