uu.py 7.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216
  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], *, backtick=False)
  27. decode(in_file [, out_file, mode, quiet])
  28. """
  29. import binascii
  30. import os
  31. import sys
  32. import warnings
  33. warnings._deprecated(__name__, remove=(3, 13))
  34. __all__ = ["Error", "encode", "decode"]
  35. class Error(Exception):
  36. pass
  37. def encode(in_file, out_file, name=None, mode=None, *, backtick=False):
  38. """Uuencode file"""
  39. #
  40. # If in_file is a pathname open it and change defaults
  41. #
  42. opened_files = []
  43. try:
  44. if in_file == '-':
  45. in_file = sys.stdin.buffer
  46. elif isinstance(in_file, str):
  47. if name is None:
  48. name = os.path.basename(in_file)
  49. if mode is None:
  50. try:
  51. mode = os.stat(in_file).st_mode
  52. except AttributeError:
  53. pass
  54. in_file = open(in_file, 'rb')
  55. opened_files.append(in_file)
  56. #
  57. # Open out_file if it is a pathname
  58. #
  59. if out_file == '-':
  60. out_file = sys.stdout.buffer
  61. elif isinstance(out_file, str):
  62. out_file = open(out_file, 'wb')
  63. opened_files.append(out_file)
  64. #
  65. # Set defaults for name and mode
  66. #
  67. if name is None:
  68. name = '-'
  69. if mode is None:
  70. mode = 0o666
  71. #
  72. # Remove newline chars from name
  73. #
  74. name = name.replace('\n','\\n')
  75. name = name.replace('\r','\\r')
  76. #
  77. # Write the data
  78. #
  79. out_file.write(('begin %o %s\n' % ((mode & 0o777), name)).encode("ascii"))
  80. data = in_file.read(45)
  81. while len(data) > 0:
  82. out_file.write(binascii.b2a_uu(data, backtick=backtick))
  83. data = in_file.read(45)
  84. if backtick:
  85. out_file.write(b'`\nend\n')
  86. else:
  87. out_file.write(b' \nend\n')
  88. finally:
  89. for f in opened_files:
  90. f.close()
  91. def decode(in_file, out_file=None, mode=None, quiet=False):
  92. """Decode uuencoded file"""
  93. #
  94. # Open the input file, if needed.
  95. #
  96. opened_files = []
  97. if in_file == '-':
  98. in_file = sys.stdin.buffer
  99. elif isinstance(in_file, str):
  100. in_file = open(in_file, 'rb')
  101. opened_files.append(in_file)
  102. try:
  103. #
  104. # Read until a begin is encountered or we've exhausted the file
  105. #
  106. while True:
  107. hdr = in_file.readline()
  108. if not hdr:
  109. raise Error('No valid begin line found in input file')
  110. if not hdr.startswith(b'begin'):
  111. continue
  112. hdrfields = hdr.split(b' ', 2)
  113. if len(hdrfields) == 3 and hdrfields[0] == b'begin':
  114. try:
  115. int(hdrfields[1], 8)
  116. break
  117. except ValueError:
  118. pass
  119. if out_file is None:
  120. # If the filename isn't ASCII, what's up with that?!?
  121. out_file = hdrfields[2].rstrip(b' \t\r\n\f').decode("ascii")
  122. if os.path.exists(out_file):
  123. raise Error(f'Cannot overwrite existing file: {out_file}')
  124. if (out_file.startswith(os.sep) or
  125. f'..{os.sep}' in out_file or (
  126. os.altsep and
  127. (out_file.startswith(os.altsep) or
  128. f'..{os.altsep}' in out_file))
  129. ):
  130. raise Error(f'Refusing to write to {out_file} due to directory traversal')
  131. if mode is None:
  132. mode = int(hdrfields[1], 8)
  133. #
  134. # Open the output file
  135. #
  136. if out_file == '-':
  137. out_file = sys.stdout.buffer
  138. elif isinstance(out_file, str):
  139. fp = open(out_file, 'wb')
  140. os.chmod(out_file, mode)
  141. out_file = fp
  142. opened_files.append(out_file)
  143. #
  144. # Main decoding loop
  145. #
  146. s = in_file.readline()
  147. while s and s.strip(b' \t\r\n\f') != b'end':
  148. try:
  149. data = binascii.a2b_uu(s)
  150. except binascii.Error as v:
  151. # Workaround for broken uuencoders by /Fredrik Lundh
  152. nbytes = (((s[0]-32) & 63) * 4 + 5) // 3
  153. data = binascii.a2b_uu(s[:nbytes])
  154. if not quiet:
  155. sys.stderr.write("Warning: %s\n" % v)
  156. out_file.write(data)
  157. s = in_file.readline()
  158. if not s:
  159. raise Error('Truncated input file')
  160. finally:
  161. for f in opened_files:
  162. f.close()
  163. def test():
  164. """uuencode/uudecode main program"""
  165. import optparse
  166. parser = optparse.OptionParser(usage='usage: %prog [-d] [-t] [input [output]]')
  167. parser.add_option('-d', '--decode', dest='decode', help='Decode (instead of encode)?', default=False, action='store_true')
  168. parser.add_option('-t', '--text', dest='text', help='data is text, encoded format unix-compatible text?', default=False, action='store_true')
  169. (options, args) = parser.parse_args()
  170. if len(args) > 2:
  171. parser.error('incorrect number of arguments')
  172. sys.exit(1)
  173. # Use the binary streams underlying stdin/stdout
  174. input = sys.stdin.buffer
  175. output = sys.stdout.buffer
  176. if len(args) > 0:
  177. input = args[0]
  178. if len(args) > 1:
  179. output = args[1]
  180. if options.decode:
  181. if options.text:
  182. if isinstance(output, str):
  183. output = open(output, 'wb')
  184. else:
  185. print(sys.argv[0], ': cannot do -t to stdout')
  186. sys.exit(1)
  187. decode(input, output)
  188. else:
  189. if options.text:
  190. if isinstance(input, str):
  191. input = open(input, 'rb')
  192. else:
  193. print(sys.argv[0], ': cannot do -t from stdin')
  194. sys.exit(1)
  195. encode(input, output)
  196. if __name__ == '__main__':
  197. test()