blob: 8788afc2f188faeb357442e130431dfa569ff571 [file] [log] [blame]
Guido van Rossum105bd981997-07-11 18:39:03 +00001#! /usr/bin/env python
2
Barry Warsaw9b630a52001-06-19 19:07:46 +00003"""Conversions to/from quoted-printable transport encoding as per RFC 1521."""
Guido van Rossume7b146f2000-02-04 15:28:42 +00004
Guido van Rossumf1945461995-06-14 23:43:44 +00005# (Dec 1991 version).
6
Barry Warsaw9b630a52001-06-19 19:07:46 +00007__all__ = ["encode", "decode", "encodestring", "decodestring"]
Skip Montanaroc62c81e2001-02-12 02:00:42 +00008
Guido van Rossumf1945461995-06-14 23:43:44 +00009ESCAPE = '='
10MAXLINESIZE = 76
11HEX = '0123456789ABCDEF'
Barry Warsaw9b630a52001-06-19 19:07:46 +000012EMPTYSTRING = ''
Guido van Rossumf1945461995-06-14 23:43:44 +000013
Martin v. Löwis16dc7f42001-09-30 20:32:11 +000014try:
Tim Peters527e64f2001-10-04 05:36:56 +000015 from binascii import a2b_qp, b2a_qp
Skip Montanaro3c4a6292002-03-23 05:55:18 +000016except ImportError:
Tim Peters527e64f2001-10-04 05:36:56 +000017 a2b_qp = None
18 b2a_qp = None
Barry Warsaw9b630a52001-06-19 19:07:46 +000019
Tim Petersd1c29652001-07-02 04:57:30 +000020
Martin v. Löwis16dc7f42001-09-30 20:32:11 +000021def needsquoting(c, quotetabs, header):
Jeremy Hylton77249442000-10-05 17:24:33 +000022 """Decide whether a particular character needs to be quoted.
Guido van Rossume7b146f2000-02-04 15:28:42 +000023
Barry Warsaw9b630a52001-06-19 19:07:46 +000024 The 'quotetabs' flag indicates whether embedded tabs and spaces should be
25 quoted. Note that line-ending tabs and spaces are always encoded, as per
26 RFC 1521.
27 """
28 if c in ' \t':
29 return quotetabs
Martin v. Löwis16dc7f42001-09-30 20:32:11 +000030 # if header, we have to escape _ because _ is used to escape space
Tim Peters527e64f2001-10-04 05:36:56 +000031 if c == '_':
Martin v. Löwis16dc7f42001-09-30 20:32:11 +000032 return header
Barry Warsaw9b630a52001-06-19 19:07:46 +000033 return c == ESCAPE or not (' ' <= c <= '~')
Guido van Rossumf1945461995-06-14 23:43:44 +000034
35def quote(c):
Jeremy Hylton77249442000-10-05 17:24:33 +000036 """Quote a single character."""
37 i = ord(c)
Guido van Rossum54e54c62001-09-04 19:14:14 +000038 return ESCAPE + HEX[i//16] + HEX[i%16]
Guido van Rossumf1945461995-06-14 23:43:44 +000039
Barry Warsaw9b630a52001-06-19 19:07:46 +000040
Tim Petersd1c29652001-07-02 04:57:30 +000041
Martin v. Löwis16dc7f42001-09-30 20:32:11 +000042def encode(input, output, quotetabs, header = 0):
Jeremy Hylton77249442000-10-05 17:24:33 +000043 """Read 'input', apply quoted-printable encoding, and write to 'output'.
Guido van Rossume7b146f2000-02-04 15:28:42 +000044
Jeremy Hylton77249442000-10-05 17:24:33 +000045 'input' and 'output' are files with readline() and write() methods.
Barry Warsaw9b630a52001-06-19 19:07:46 +000046 The 'quotetabs' flag indicates whether embedded tabs and spaces should be
47 quoted. Note that line-ending tabs and spaces are always encoded, as per
48 RFC 1521.
Martin v. Löwis16dc7f42001-09-30 20:32:11 +000049 The 'header' flag indicates whether we are encoding spaces as _ as per
50 RFC 1522.
Barry Warsaw9b630a52001-06-19 19:07:46 +000051 """
Martin v. Löwis16dc7f42001-09-30 20:32:11 +000052
53 if b2a_qp is not None:
54 data = input.read()
55 odata = b2a_qp(data, quotetabs = quotetabs, header = header)
56 output.write(odata)
57 return
Tim Peters527e64f2001-10-04 05:36:56 +000058
Barry Warsaw9b630a52001-06-19 19:07:46 +000059 def write(s, output=output, lineEnd='\n'):
60 # RFC 1521 requires that the line ending in a space or tab must have
61 # that trailing character encoded.
62 if s and s[-1:] in ' \t':
63 output.write(s[:-1] + quote(s[-1]) + lineEnd)
Guido van Rossum1346e832001-10-15 18:44:26 +000064 elif s == '.':
65 output.write(quote(s) + lineEnd)
Barry Warsaw9b630a52001-06-19 19:07:46 +000066 else:
67 output.write(s + lineEnd)
68
69 prevline = None
Jeremy Hylton77249442000-10-05 17:24:33 +000070 while 1:
71 line = input.readline()
72 if not line:
73 break
Barry Warsaw9b630a52001-06-19 19:07:46 +000074 outline = []
75 # Strip off any readline induced trailing newline
76 stripped = ''
77 if line[-1:] == '\n':
Jeremy Hylton77249442000-10-05 17:24:33 +000078 line = line[:-1]
Barry Warsaw9b630a52001-06-19 19:07:46 +000079 stripped = '\n'
Barry Warsawdac67ac2001-06-19 22:48:10 +000080 # Calculate the un-length-limited encoded line
Jeremy Hylton77249442000-10-05 17:24:33 +000081 for c in line:
Martin v. Löwis16dc7f42001-09-30 20:32:11 +000082 if needsquoting(c, quotetabs, header):
Jeremy Hylton77249442000-10-05 17:24:33 +000083 c = quote(c)
Martin v. Löwis16dc7f42001-09-30 20:32:11 +000084 if header and c == ' ':
85 outline.append('_')
86 else:
87 outline.append(c)
Barry Warsawdac67ac2001-06-19 22:48:10 +000088 # First, write out the previous line
Barry Warsaw9b630a52001-06-19 19:07:46 +000089 if prevline is not None:
90 write(prevline)
Barry Warsawdac67ac2001-06-19 22:48:10 +000091 # Now see if we need any soft line breaks because of RFC-imposed
92 # length limitations. Then do the thisline->prevline dance.
93 thisline = EMPTYSTRING.join(outline)
94 while len(thisline) > MAXLINESIZE:
95 # Don't forget to include the soft line break `=' sign in the
96 # length calculation!
97 write(thisline[:MAXLINESIZE-1], lineEnd='=\n')
98 thisline = thisline[MAXLINESIZE-1:]
99 # Write out the current line
100 prevline = thisline
Barry Warsaw9b630a52001-06-19 19:07:46 +0000101 # Write out the last line, without a trailing newline
102 if prevline is not None:
103 write(prevline, lineEnd=stripped)
Guido van Rossumf1945461995-06-14 23:43:44 +0000104
Martin v. Löwis16dc7f42001-09-30 20:32:11 +0000105def encodestring(s, quotetabs = 0, header = 0):
106 if b2a_qp is not None:
107 return b2a_qp(s, quotetabs = quotetabs, header = header)
Barry Warsaw9b630a52001-06-19 19:07:46 +0000108 from cStringIO import StringIO
109 infp = StringIO(s)
110 outfp = StringIO()
Martin v. Löwis16dc7f42001-09-30 20:32:11 +0000111 encode(infp, outfp, quotetabs, header)
Barry Warsaw9b630a52001-06-19 19:07:46 +0000112 return outfp.getvalue()
113
114
Tim Petersd1c29652001-07-02 04:57:30 +0000115
Martin v. Löwis16dc7f42001-09-30 20:32:11 +0000116def decode(input, output, header = 0):
Jeremy Hylton77249442000-10-05 17:24:33 +0000117 """Read 'input', apply quoted-printable decoding, and write to 'output'.
Martin v. Löwis16dc7f42001-09-30 20:32:11 +0000118 'input' and 'output' are files with readline() and write() methods.
119 If 'header' is true, decode underscore as space (per RFC 1522)."""
Guido van Rossume7b146f2000-02-04 15:28:42 +0000120
Martin v. Löwis16dc7f42001-09-30 20:32:11 +0000121 if a2b_qp is not None:
122 data = input.read()
123 odata = a2b_qp(data, header = header)
124 output.write(odata)
125 return
126
Jeremy Hylton77249442000-10-05 17:24:33 +0000127 new = ''
128 while 1:
129 line = input.readline()
130 if not line: break
131 i, n = 0, len(line)
132 if n > 0 and line[n-1] == '\n':
133 partial = 0; n = n-1
134 # Strip trailing whitespace
Guido van Rossum14b90a42001-03-22 22:30:21 +0000135 while n > 0 and line[n-1] in " \t\r":
Jeremy Hylton77249442000-10-05 17:24:33 +0000136 n = n-1
137 else:
138 partial = 1
139 while i < n:
140 c = line[i]
Martin v. Löwis16dc7f42001-09-30 20:32:11 +0000141 if c == '_' and header:
142 new = new + ' '; i = i+1
143 elif c != ESCAPE:
Jeremy Hylton77249442000-10-05 17:24:33 +0000144 new = new + c; i = i+1
145 elif i+1 == n and not partial:
146 partial = 1; break
147 elif i+1 < n and line[i+1] == ESCAPE:
148 new = new + ESCAPE; i = i+2
149 elif i+2 < n and ishex(line[i+1]) and ishex(line[i+2]):
150 new = new + chr(unhex(line[i+1:i+3])); i = i+3
151 else: # Bad escape sequence -- leave it in
152 new = new + c; i = i+1
153 if not partial:
154 output.write(new + '\n')
155 new = ''
156 if new:
157 output.write(new)
Guido van Rossumf1945461995-06-14 23:43:44 +0000158
Martin v. Löwis16dc7f42001-09-30 20:32:11 +0000159def decodestring(s, header = 0):
160 if a2b_qp is not None:
161 return a2b_qp(s, header = header)
Barry Warsaw9b630a52001-06-19 19:07:46 +0000162 from cStringIO import StringIO
163 infp = StringIO(s)
164 outfp = StringIO()
Martin v. Löwis16dc7f42001-09-30 20:32:11 +0000165 decode(infp, outfp, header = header)
Barry Warsaw9b630a52001-06-19 19:07:46 +0000166 return outfp.getvalue()
167
168
Tim Petersd1c29652001-07-02 04:57:30 +0000169
Barry Warsaw9b630a52001-06-19 19:07:46 +0000170# Other helper functions
Guido van Rossumf1945461995-06-14 23:43:44 +0000171def ishex(c):
Jeremy Hylton77249442000-10-05 17:24:33 +0000172 """Return true if the character 'c' is a hexadecimal digit."""
173 return '0' <= c <= '9' or 'a' <= c <= 'f' or 'A' <= c <= 'F'
Guido van Rossumf1945461995-06-14 23:43:44 +0000174
175def unhex(s):
Jeremy Hylton77249442000-10-05 17:24:33 +0000176 """Get the integer value of a hexadecimal number."""
177 bits = 0
178 for c in s:
179 if '0' <= c <= '9':
180 i = ord('0')
181 elif 'a' <= c <= 'f':
182 i = ord('a')-10
183 elif 'A' <= c <= 'F':
184 i = ord('A')-10
185 else:
186 break
187 bits = bits*16 + (ord(c) - i)
188 return bits
Guido van Rossumf1945461995-06-14 23:43:44 +0000189
Barry Warsaw9b630a52001-06-19 19:07:46 +0000190
Tim Petersd1c29652001-07-02 04:57:30 +0000191
Barry Warsaw9b630a52001-06-19 19:07:46 +0000192def main():
Jeremy Hylton77249442000-10-05 17:24:33 +0000193 import sys
194 import getopt
195 try:
196 opts, args = getopt.getopt(sys.argv[1:], 'td')
197 except getopt.error, msg:
198 sys.stdout = sys.stderr
199 print msg
200 print "usage: quopri [-t | -d] [file] ..."
201 print "-t: quote tabs"
202 print "-d: decode; default encode"
203 sys.exit(2)
204 deco = 0
205 tabs = 0
206 for o, a in opts:
207 if o == '-t': tabs = 1
208 if o == '-d': deco = 1
209 if tabs and deco:
210 sys.stdout = sys.stderr
211 print "-t and -d are mutually exclusive"
212 sys.exit(2)
213 if not args: args = ['-']
214 sts = 0
215 for file in args:
216 if file == '-':
217 fp = sys.stdin
218 else:
219 try:
220 fp = open(file)
221 except IOError, msg:
222 sys.stderr.write("%s: can't open (%s)\n" % (file, msg))
223 sts = 1
224 continue
225 if deco:
226 decode(fp, sys.stdout)
227 else:
228 encode(fp, sys.stdout, tabs)
229 if fp is not sys.stdin:
230 fp.close()
231 if sts:
232 sys.exit(sts)
Guido van Rossumf1945461995-06-14 23:43:44 +0000233
Barry Warsaw9b630a52001-06-19 19:07:46 +0000234
Tim Petersd1c29652001-07-02 04:57:30 +0000235
Guido van Rossumf1945461995-06-14 23:43:44 +0000236if __name__ == '__main__':
Barry Warsaw9b630a52001-06-19 19:07:46 +0000237 main()