blob: 6d7cdd613fd71392961836388637bfe1117d7f24 [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
Martin v. Löwis16dc7f42001-09-30 20:32:11 +000016except:
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)
64 else:
65 output.write(s + lineEnd)
66
67 prevline = None
Jeremy Hylton77249442000-10-05 17:24:33 +000068 while 1:
69 line = input.readline()
70 if not line:
71 break
Barry Warsaw9b630a52001-06-19 19:07:46 +000072 outline = []
73 # Strip off any readline induced trailing newline
74 stripped = ''
75 if line[-1:] == '\n':
Jeremy Hylton77249442000-10-05 17:24:33 +000076 line = line[:-1]
Barry Warsaw9b630a52001-06-19 19:07:46 +000077 stripped = '\n'
Barry Warsawdac67ac2001-06-19 22:48:10 +000078 # Calculate the un-length-limited encoded line
Jeremy Hylton77249442000-10-05 17:24:33 +000079 for c in line:
Martin v. Löwis16dc7f42001-09-30 20:32:11 +000080 if needsquoting(c, quotetabs, header):
Jeremy Hylton77249442000-10-05 17:24:33 +000081 c = quote(c)
Martin v. Löwis16dc7f42001-09-30 20:32:11 +000082 if header and c == ' ':
83 outline.append('_')
84 else:
85 outline.append(c)
Barry Warsawdac67ac2001-06-19 22:48:10 +000086 # First, write out the previous line
Barry Warsaw9b630a52001-06-19 19:07:46 +000087 if prevline is not None:
88 write(prevline)
Barry Warsawdac67ac2001-06-19 22:48:10 +000089 # Now see if we need any soft line breaks because of RFC-imposed
90 # length limitations. Then do the thisline->prevline dance.
91 thisline = EMPTYSTRING.join(outline)
92 while len(thisline) > MAXLINESIZE:
93 # Don't forget to include the soft line break `=' sign in the
94 # length calculation!
95 write(thisline[:MAXLINESIZE-1], lineEnd='=\n')
96 thisline = thisline[MAXLINESIZE-1:]
97 # Write out the current line
98 prevline = thisline
Barry Warsaw9b630a52001-06-19 19:07:46 +000099 # Write out the last line, without a trailing newline
100 if prevline is not None:
101 write(prevline, lineEnd=stripped)
Guido van Rossumf1945461995-06-14 23:43:44 +0000102
Martin v. Löwis16dc7f42001-09-30 20:32:11 +0000103def encodestring(s, quotetabs = 0, header = 0):
104 if b2a_qp is not None:
105 return b2a_qp(s, quotetabs = quotetabs, header = header)
Barry Warsaw9b630a52001-06-19 19:07:46 +0000106 from cStringIO import StringIO
107 infp = StringIO(s)
108 outfp = StringIO()
Martin v. Löwis16dc7f42001-09-30 20:32:11 +0000109 encode(infp, outfp, quotetabs, header)
Barry Warsaw9b630a52001-06-19 19:07:46 +0000110 return outfp.getvalue()
111
112
Tim Petersd1c29652001-07-02 04:57:30 +0000113
Martin v. Löwis16dc7f42001-09-30 20:32:11 +0000114def decode(input, output, header = 0):
Jeremy Hylton77249442000-10-05 17:24:33 +0000115 """Read 'input', apply quoted-printable decoding, and write to 'output'.
Martin v. Löwis16dc7f42001-09-30 20:32:11 +0000116 'input' and 'output' are files with readline() and write() methods.
117 If 'header' is true, decode underscore as space (per RFC 1522)."""
Guido van Rossume7b146f2000-02-04 15:28:42 +0000118
Martin v. Löwis16dc7f42001-09-30 20:32:11 +0000119 if a2b_qp is not None:
120 data = input.read()
121 odata = a2b_qp(data, header = header)
122 output.write(odata)
123 return
124
Jeremy Hylton77249442000-10-05 17:24:33 +0000125 new = ''
126 while 1:
127 line = input.readline()
128 if not line: break
129 i, n = 0, len(line)
130 if n > 0 and line[n-1] == '\n':
131 partial = 0; n = n-1
132 # Strip trailing whitespace
Guido van Rossum14b90a42001-03-22 22:30:21 +0000133 while n > 0 and line[n-1] in " \t\r":
Jeremy Hylton77249442000-10-05 17:24:33 +0000134 n = n-1
135 else:
136 partial = 1
137 while i < n:
138 c = line[i]
Martin v. Löwis16dc7f42001-09-30 20:32:11 +0000139 if c == '_' and header:
140 new = new + ' '; i = i+1
141 elif c != ESCAPE:
Jeremy Hylton77249442000-10-05 17:24:33 +0000142 new = new + c; i = i+1
143 elif i+1 == n and not partial:
144 partial = 1; break
145 elif i+1 < n and line[i+1] == ESCAPE:
146 new = new + ESCAPE; i = i+2
147 elif i+2 < n and ishex(line[i+1]) and ishex(line[i+2]):
148 new = new + chr(unhex(line[i+1:i+3])); i = i+3
149 else: # Bad escape sequence -- leave it in
150 new = new + c; i = i+1
151 if not partial:
152 output.write(new + '\n')
153 new = ''
154 if new:
155 output.write(new)
Guido van Rossumf1945461995-06-14 23:43:44 +0000156
Martin v. Löwis16dc7f42001-09-30 20:32:11 +0000157def decodestring(s, header = 0):
158 if a2b_qp is not None:
159 return a2b_qp(s, header = header)
Barry Warsaw9b630a52001-06-19 19:07:46 +0000160 from cStringIO import StringIO
161 infp = StringIO(s)
162 outfp = StringIO()
Martin v. Löwis16dc7f42001-09-30 20:32:11 +0000163 decode(infp, outfp, header = header)
Barry Warsaw9b630a52001-06-19 19:07:46 +0000164 return outfp.getvalue()
165
166
Tim Petersd1c29652001-07-02 04:57:30 +0000167
Barry Warsaw9b630a52001-06-19 19:07:46 +0000168# Other helper functions
Guido van Rossumf1945461995-06-14 23:43:44 +0000169def ishex(c):
Jeremy Hylton77249442000-10-05 17:24:33 +0000170 """Return true if the character 'c' is a hexadecimal digit."""
171 return '0' <= c <= '9' or 'a' <= c <= 'f' or 'A' <= c <= 'F'
Guido van Rossumf1945461995-06-14 23:43:44 +0000172
173def unhex(s):
Jeremy Hylton77249442000-10-05 17:24:33 +0000174 """Get the integer value of a hexadecimal number."""
175 bits = 0
176 for c in s:
177 if '0' <= c <= '9':
178 i = ord('0')
179 elif 'a' <= c <= 'f':
180 i = ord('a')-10
181 elif 'A' <= c <= 'F':
182 i = ord('A')-10
183 else:
184 break
185 bits = bits*16 + (ord(c) - i)
186 return bits
Guido van Rossumf1945461995-06-14 23:43:44 +0000187
Barry Warsaw9b630a52001-06-19 19:07:46 +0000188
Tim Petersd1c29652001-07-02 04:57:30 +0000189
Barry Warsaw9b630a52001-06-19 19:07:46 +0000190def main():
Jeremy Hylton77249442000-10-05 17:24:33 +0000191 import sys
192 import getopt
193 try:
194 opts, args = getopt.getopt(sys.argv[1:], 'td')
195 except getopt.error, msg:
196 sys.stdout = sys.stderr
197 print msg
198 print "usage: quopri [-t | -d] [file] ..."
199 print "-t: quote tabs"
200 print "-d: decode; default encode"
201 sys.exit(2)
202 deco = 0
203 tabs = 0
204 for o, a in opts:
205 if o == '-t': tabs = 1
206 if o == '-d': deco = 1
207 if tabs and deco:
208 sys.stdout = sys.stderr
209 print "-t and -d are mutually exclusive"
210 sys.exit(2)
211 if not args: args = ['-']
212 sts = 0
213 for file in args:
214 if file == '-':
215 fp = sys.stdin
216 else:
217 try:
218 fp = open(file)
219 except IOError, msg:
220 sys.stderr.write("%s: can't open (%s)\n" % (file, msg))
221 sts = 1
222 continue
223 if deco:
224 decode(fp, sys.stdout)
225 else:
226 encode(fp, sys.stdout, tabs)
227 if fp is not sys.stdin:
228 fp.close()
229 if sts:
230 sys.exit(sts)
Guido van Rossumf1945461995-06-14 23:43:44 +0000231
Barry Warsaw9b630a52001-06-19 19:07:46 +0000232
Tim Petersd1c29652001-07-02 04:57:30 +0000233
Guido van Rossumf1945461995-06-14 23:43:44 +0000234if __name__ == '__main__':
Barry Warsaw9b630a52001-06-19 19:07:46 +0000235 main()