uu.py 6.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199
  1. #! /usr/bin/env python3
  2. # Copyright 1994 by Lance Ellinghouse
  3. # Cathedral City, California Republic, United States of America.
  4. # All Rights Reserved
  5. # Permission to use, copy, modify, and distribute this software and its
  6. # documentation for any purpose and without fee is hereby granted,
  7. # provided that the above copyright notice appear in all copies and that
  8. # both that copyright notice and this permission notice appear in
  9. # supporting documentation, and that the name of Lance Ellinghouse
  10. # not be used in advertising or publicity pertaining to distribution
  11. # of the software without specific, written prior permission.
  12. # LANCE ELLINGHOUSE DISCLAIMS ALL WARRANTIES WITH REGARD TO
  13. # THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND
  14. # FITNESS, IN NO EVENT SHALL LANCE ELLINGHOUSE CENTRUM BE LIABLE
  15. # FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
  16. # WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
  17. # ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT
  18. # OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
  19. #
  20. # Modified by Jack Jansen, CWI, July 1995:
  21. # - Use binascii module to do the actual line-by-line conversion
  22. # between ascii and binary. This results in a 1000-fold speedup. The C
  23. # version is still 5 times faster, though.
  24. # - Arguments more compliant with python standard
  25. """Implementation of the UUencode and UUdecode functions.
  26. encode(in_file, out_file [,name, mode])
  27. decode(in_file [, out_file, mode])
  28. """
  29. import binascii
  30. import os
  31. import sys
  32. __all__ = ["Error", "encode", "decode"]
  33. class Error(Exception):
  34. pass
  35. def encode(in_file, out_file, name=None, mode=None):
  36. """Uuencode file"""
  37. #
  38. # If in_file is a pathname open it and change defaults
  39. #
  40. opened_files = []
  41. try:
  42. if in_file == '-':
  43. in_file = sys.stdin.buffer
  44. elif isinstance(in_file, str):
  45. if name is None:
  46. name = os.path.basename(in_file)
  47. if mode is None:
  48. try:
  49. mode = os.stat(in_file).st_mode
  50. except AttributeError:
  51. pass
  52. in_file = open(in_file, 'rb')
  53. opened_files.append(in_file)
  54. #
  55. # Open out_file if it is a pathname
  56. #
  57. if out_file == '-':
  58. out_file = sys.stdout.buffer
  59. elif isinstance(out_file, str):
  60. out_file = open(out_file, 'wb')
  61. opened_files.append(out_file)
  62. #
  63. # Set defaults for name and mode
  64. #
  65. if name is None:
  66. name = '-'
  67. if mode is None:
  68. mode = 0o666
  69. #
  70. # Write the data
  71. #
  72. out_file.write(('begin %o %s\n' % ((mode & 0o777), name)).encode("ascii"))
  73. data = in_file.read(45)
  74. while len(data) > 0:
  75. out_file.write(binascii.b2a_uu(data))
  76. data = in_file.read(45)
  77. out_file.write(b' \nend\n')
  78. finally:
  79. for f in opened_files:
  80. f.close()
  81. def decode(in_file, out_file=None, mode=None, quiet=False):
  82. """Decode uuencoded file"""
  83. #
  84. # Open the input file, if needed.
  85. #
  86. opened_files = []
  87. if in_file == '-':
  88. in_file = sys.stdin.buffer
  89. elif isinstance(in_file, str):
  90. in_file = open(in_file, 'rb')
  91. opened_files.append(in_file)
  92. try:
  93. #
  94. # Read until a begin is encountered or we've exhausted the file
  95. #
  96. while True:
  97. hdr = in_file.readline()
  98. if not hdr:
  99. raise Error('No valid begin line found in input file')
  100. if not hdr.startswith(b'begin'):
  101. continue
  102. hdrfields = hdr.split(b' ', 2)
  103. if len(hdrfields) == 3 and hdrfields[0] == b'begin':
  104. try:
  105. int(hdrfields[1], 8)
  106. break
  107. except ValueError:
  108. pass
  109. if out_file is None:
  110. # If the filename isn't ASCII, what's up with that?!?
  111. out_file = hdrfields[2].rstrip(b' \t\r\n\f').decode("ascii")
  112. if os.path.exists(out_file):
  113. raise Error('Cannot overwrite existing file: %s' % out_file)
  114. if mode is None:
  115. mode = int(hdrfields[1], 8)
  116. #
  117. # Open the output file
  118. #
  119. if out_file == '-':
  120. out_file = sys.stdout.buffer
  121. elif isinstance(out_file, str):
  122. fp = open(out_file, 'wb')
  123. try:
  124. os.path.chmod(out_file, mode)
  125. except AttributeError:
  126. pass
  127. out_file = fp
  128. opened_files.append(out_file)
  129. #
  130. # Main decoding loop
  131. #
  132. s = in_file.readline()
  133. while s and s.strip(b' \t\r\n\f') != b'end':
  134. try:
  135. data = binascii.a2b_uu(s)
  136. except binascii.Error as v:
  137. # Workaround for broken uuencoders by /Fredrik Lundh
  138. nbytes = (((s[0]-32) & 63) * 4 + 5) // 3
  139. data = binascii.a2b_uu(s[:nbytes])
  140. if not quiet:
  141. sys.stderr.write("Warning: %s\n" % v)
  142. out_file.write(data)
  143. s = in_file.readline()
  144. if not s:
  145. raise Error('Truncated input file')
  146. finally:
  147. for f in opened_files:
  148. f.close()
  149. def test():
  150. """uuencode/uudecode main program"""
  151. import optparse
  152. parser = optparse.OptionParser(usage='usage: %prog [-d] [-t] [input [output]]')
  153. parser.add_option('-d', '--decode', dest='decode', help='Decode (instead of encode)?', default=False, action='store_true')
  154. parser.add_option('-t', '--text', dest='text', help='data is text, encoded format unix-compatible text?', default=False, action='store_true')
  155. (options, args) = parser.parse_args()
  156. if len(args) > 2:
  157. parser.error('incorrect number of arguments')
  158. sys.exit(1)
  159. # Use the binary streams underlying stdin/stdout
  160. input = sys.stdin.buffer
  161. output = sys.stdout.buffer
  162. if len(args) > 0:
  163. input = args[0]
  164. if len(args) > 1:
  165. output = args[1]
  166. if options.decode:
  167. if options.text:
  168. if isinstance(output, str):
  169. output = open(output, 'wb')
  170. else:
  171. print(sys.argv[0], ': cannot do -t to stdout')
  172. sys.exit(1)
  173. decode(input, output)
  174. else:
  175. if options.text:
  176. if isinstance(input, str):
  177. input = open(input, 'rb')
  178. else:
  179. print(sys.argv[0], ': cannot do -t from stdin')
  180. sys.exit(1)
  181. encode(input, output)
  182. if __name__ == '__main__':
  183. test()