uu.py 5.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191
  1. #! /usr/bin/env python
  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. from types import StringType
  33. __all__ = ["Error", "encode", "decode"]
  34. class Error(Exception):
  35. pass
  36. def encode(in_file, out_file, name=None, mode=None):
  37. """Uuencode file"""
  38. #
  39. # If in_file is a pathname open it and change defaults
  40. #
  41. if in_file == '-':
  42. in_file = sys.stdin
  43. elif isinstance(in_file, StringType):
  44. if name is None:
  45. name = os.path.basename(in_file)
  46. if mode is None:
  47. try:
  48. mode = os.stat(in_file).st_mode
  49. except AttributeError:
  50. pass
  51. in_file = open(in_file, 'rb')
  52. #
  53. # Open out_file if it is a pathname
  54. #
  55. if out_file == '-':
  56. out_file = sys.stdout
  57. elif isinstance(out_file, StringType):
  58. out_file = open(out_file, 'w')
  59. #
  60. # Set defaults for name and mode
  61. #
  62. if name is None:
  63. name = '-'
  64. if mode is None:
  65. mode = 0666
  66. #
  67. # Write the data
  68. #
  69. out_file.write('begin %o %s\n' % ((mode&0777),name))
  70. str = in_file.read(45)
  71. while len(str) > 0:
  72. out_file.write(binascii.b2a_uu(str))
  73. str = in_file.read(45)
  74. out_file.write(' \nend\n')
  75. def decode(in_file, out_file=None, mode=None, quiet=0):
  76. """Decode uuencoded file"""
  77. #
  78. # Open the input file, if needed.
  79. #
  80. if in_file == '-':
  81. in_file = sys.stdin
  82. elif isinstance(in_file, StringType):
  83. in_file = open(in_file)
  84. #
  85. # Read until a begin is encountered or we've exhausted the file
  86. #
  87. while 1:
  88. hdr = in_file.readline()
  89. if not hdr:
  90. raise Error, 'No valid begin line found in input file'
  91. if hdr[:5] != 'begin':
  92. continue
  93. hdrfields = hdr.split(" ", 2)
  94. if len(hdrfields) == 3 and hdrfields[0] == 'begin':
  95. try:
  96. int(hdrfields[1], 8)
  97. break
  98. except ValueError:
  99. pass
  100. if out_file is None:
  101. out_file = hdrfields[2].rstrip()
  102. if os.path.exists(out_file):
  103. raise Error, 'Cannot overwrite existing file: %s' % out_file
  104. if mode is None:
  105. mode = int(hdrfields[1], 8)
  106. #
  107. # Open the output file
  108. #
  109. if out_file == '-':
  110. out_file = sys.stdout
  111. elif isinstance(out_file, StringType):
  112. fp = open(out_file, 'wb')
  113. try:
  114. os.path.chmod(out_file, mode)
  115. except AttributeError:
  116. pass
  117. out_file = fp
  118. #
  119. # Main decoding loop
  120. #
  121. s = in_file.readline()
  122. while s and s.strip() != 'end':
  123. try:
  124. data = binascii.a2b_uu(s)
  125. except binascii.Error, v:
  126. # Workaround for broken uuencoders by /Fredrik Lundh
  127. nbytes = (((ord(s[0])-32) & 63) * 4 + 5) / 3
  128. data = binascii.a2b_uu(s[:nbytes])
  129. if not quiet:
  130. sys.stderr.write("Warning: %s\n" % str(v))
  131. out_file.write(data)
  132. s = in_file.readline()
  133. if not s:
  134. raise Error, 'Truncated input file'
  135. def test():
  136. """uuencode/uudecode main program"""
  137. import getopt
  138. dopt = 0
  139. topt = 0
  140. input = sys.stdin
  141. output = sys.stdout
  142. ok = 1
  143. try:
  144. optlist, args = getopt.getopt(sys.argv[1:], 'dt')
  145. except getopt.error:
  146. ok = 0
  147. if not ok or len(args) > 2:
  148. print 'Usage:', sys.argv[0], '[-d] [-t] [input [output]]'
  149. print ' -d: Decode (in stead of encode)'
  150. print ' -t: data is text, encoded format unix-compatible text'
  151. sys.exit(1)
  152. for o, a in optlist:
  153. if o == '-d': dopt = 1
  154. if o == '-t': topt = 1
  155. if len(args) > 0:
  156. input = args[0]
  157. if len(args) > 1:
  158. output = args[1]
  159. if dopt:
  160. if topt:
  161. if isinstance(output, StringType):
  162. output = open(output, 'w')
  163. else:
  164. print sys.argv[0], ': cannot do -t to stdout'
  165. sys.exit(1)
  166. decode(input, output)
  167. else:
  168. if topt:
  169. if isinstance(input, StringType):
  170. input = open(input, 'r')
  171. else:
  172. print sys.argv[0], ': cannot do -t from stdin'
  173. sys.exit(1)
  174. encode(input, output)
  175. if __name__ == '__main__':
  176. test()