blob: 109ff5f7c773659a090f85c574b26a17f118b4a5 [file] [log] [blame]
Barry Warsaw602426e2006-02-03 04:44:52 +00001# Copyright (C) 2002-2006 Python Software Foundation
Barry Warsawbb113862004-10-03 03:16:19 +00002# Contact: email-sig@python.org
Barry Warsaw030ddf72002-11-05 19:54:52 +00003
4"""Email address parsing code.
5
6Lifted directly from rfc822.py. This should eventually be rewritten.
7"""
8
Barry Warsaw40ef0062006-03-18 15:41:53 +00009__all__ = [
10 'mktime_tz',
11 'parsedate',
12 'parsedate_tz',
13 'quote',
14 ]
15
Barry Warsaw030ddf72002-11-05 19:54:52 +000016import time
Barry Warsaw5c8fef92002-12-30 16:43:42 +000017
18SPACE = ' '
19EMPTYSTRING = ''
20COMMASPACE = ', '
Barry Warsaw030ddf72002-11-05 19:54:52 +000021
22# Parse a date field
23_monthnames = ['jan', 'feb', 'mar', 'apr', 'may', 'jun', 'jul',
24 'aug', 'sep', 'oct', 'nov', 'dec',
25 'january', 'february', 'march', 'april', 'may', 'june', 'july',
26 'august', 'september', 'october', 'november', 'december']
27
28_daynames = ['mon', 'tue', 'wed', 'thu', 'fri', 'sat', 'sun']
29
30# The timezone table does not include the military time zones defined
31# in RFC822, other than Z. According to RFC1123, the description in
32# RFC822 gets the signs wrong, so we can't rely on any such time
33# zones. RFC1123 recommends that numeric timezone indicators be used
34# instead of timezone names.
35
36_timezones = {'UT':0, 'UTC':0, 'GMT':0, 'Z':0,
37 'AST': -400, 'ADT': -300, # Atlantic (used in Canada)
38 'EST': -500, 'EDT': -400, # Eastern
39 'CST': -600, 'CDT': -500, # Central
40 'MST': -700, 'MDT': -600, # Mountain
41 'PST': -800, 'PDT': -700 # Pacific
42 }
43
44
45def parsedate_tz(data):
46 """Convert a date string to a time tuple.
47
48 Accounts for military timezones.
49 """
50 data = data.split()
Barry Warsawba976592002-12-30 17:21:36 +000051 # The FWS after the comma after the day-of-week is optional, so search and
52 # adjust for this.
53 if data[0].endswith(',') or data[0].lower() in _daynames:
Barry Warsaw030ddf72002-11-05 19:54:52 +000054 # There's a dayname here. Skip it
55 del data[0]
Barry Warsawba976592002-12-30 17:21:36 +000056 else:
57 i = data[0].rfind(',')
Barry Warsawb5dc39f2003-05-08 03:33:15 +000058 if i >= 0:
59 data[0] = data[0][i+1:]
Barry Warsaw030ddf72002-11-05 19:54:52 +000060 if len(data) == 3: # RFC 850 date, deprecated
61 stuff = data[0].split('-')
62 if len(stuff) == 3:
63 data = stuff + data[1:]
64 if len(data) == 4:
65 s = data[3]
66 i = s.find('+')
67 if i > 0:
68 data[3:] = [s[:i], s[i+1:]]
69 else:
70 data.append('') # Dummy tz
71 if len(data) < 5:
72 return None
73 data = data[:5]
74 [dd, mm, yy, tm, tz] = data
75 mm = mm.lower()
Barry Warsaw5c8fef92002-12-30 16:43:42 +000076 if mm not in _monthnames:
Barry Warsaw030ddf72002-11-05 19:54:52 +000077 dd, mm = mm, dd.lower()
Barry Warsaw5c8fef92002-12-30 16:43:42 +000078 if mm not in _monthnames:
Barry Warsaw030ddf72002-11-05 19:54:52 +000079 return None
Barry Warsaw5c8fef92002-12-30 16:43:42 +000080 mm = _monthnames.index(mm) + 1
81 if mm > 12:
82 mm -= 12
Barry Warsaw030ddf72002-11-05 19:54:52 +000083 if dd[-1] == ',':
84 dd = dd[:-1]
85 i = yy.find(':')
86 if i > 0:
87 yy, tm = tm, yy
88 if yy[-1] == ',':
89 yy = yy[:-1]
90 if not yy[0].isdigit():
91 yy, tz = tz, yy
92 if tm[-1] == ',':
93 tm = tm[:-1]
94 tm = tm.split(':')
95 if len(tm) == 2:
96 [thh, tmm] = tm
97 tss = '0'
98 elif len(tm) == 3:
99 [thh, tmm, tss] = tm
100 else:
101 return None
102 try:
103 yy = int(yy)
104 dd = int(dd)
105 thh = int(thh)
106 tmm = int(tmm)
107 tss = int(tss)
108 except ValueError:
109 return None
110 tzoffset = None
111 tz = tz.upper()
112 if _timezones.has_key(tz):
113 tzoffset = _timezones[tz]
114 else:
115 try:
116 tzoffset = int(tz)
117 except ValueError:
118 pass
119 # Convert a timezone offset into seconds ; -0500 -> -18000
120 if tzoffset:
121 if tzoffset < 0:
122 tzsign = -1
123 tzoffset = -tzoffset
124 else:
125 tzsign = 1
Barry Warsawbb113862004-10-03 03:16:19 +0000126 tzoffset = tzsign * ( (tzoffset//100)*3600 + (tzoffset % 100)*60)
Barry Warsaw602426e2006-02-03 04:44:52 +0000127 return yy, mm, dd, thh, tmm, tss, 0, 1, 0, tzoffset
Barry Warsaw030ddf72002-11-05 19:54:52 +0000128
129
130def parsedate(data):
131 """Convert a time string to a time tuple."""
132 t = parsedate_tz(data)
Barry Warsaw24f79762004-05-09 03:55:11 +0000133 if isinstance(t, tuple):
Barry Warsaw030ddf72002-11-05 19:54:52 +0000134 return t[:9]
Barry Warsaw5c8fef92002-12-30 16:43:42 +0000135 else:
136 return t
Barry Warsaw030ddf72002-11-05 19:54:52 +0000137
138
139def mktime_tz(data):
140 """Turn a 10-tuple as returned by parsedate_tz() into a UTC timestamp."""
141 if data[9] is None:
142 # No zone info, so localtime is better assumption than GMT
143 return time.mktime(data[:8] + (-1,))
144 else:
145 t = time.mktime(data[:8] + (0,))
146 return t - data[9] - time.timezone
147
148
149def quote(str):
150 """Add quotes around a string."""
151 return str.replace('\\', '\\\\').replace('"', '\\"')
152
153
154class AddrlistClass:
155 """Address parser class by Ben Escoto.
156
Barry Warsaw1fb22bb2002-12-30 16:21:07 +0000157 To understand what this class does, it helps to have a copy of RFC 2822 in
158 front of you.
Barry Warsaw030ddf72002-11-05 19:54:52 +0000159
160 Note: this class interface is deprecated and may be removed in the future.
161 Use rfc822.AddressList instead.
162 """
163
164 def __init__(self, field):
165 """Initialize a new instance.
166
167 `field' is an unparsed address header field, containing
168 one or more addresses.
169 """
170 self.specials = '()<>@,:;.\"[]'
171 self.pos = 0
172 self.LWS = ' \t'
173 self.CR = '\r\n'
174 self.atomends = self.specials + self.LWS + self.CR
Barry Warsaw1fb22bb2002-12-30 16:21:07 +0000175 # Note that RFC 2822 now specifies `.' as obs-phrase, meaning that it
176 # is obsolete syntax. RFC 2822 requires that we recognize obsolete
177 # syntax, so allow dots in phrases.
178 self.phraseends = self.atomends.replace('.', '')
Barry Warsaw030ddf72002-11-05 19:54:52 +0000179 self.field = field
180 self.commentlist = []
181
182 def gotonext(self):
183 """Parse up to the start of the next address."""
184 while self.pos < len(self.field):
185 if self.field[self.pos] in self.LWS + '\n\r':
Barry Warsaw5c8fef92002-12-30 16:43:42 +0000186 self.pos += 1
Barry Warsaw030ddf72002-11-05 19:54:52 +0000187 elif self.field[self.pos] == '(':
188 self.commentlist.append(self.getcomment())
Barry Warsaw5c8fef92002-12-30 16:43:42 +0000189 else:
190 break
Barry Warsaw030ddf72002-11-05 19:54:52 +0000191
192 def getaddrlist(self):
193 """Parse all addresses.
194
195 Returns a list containing all of the addresses.
196 """
Barry Warsaw1fb22bb2002-12-30 16:21:07 +0000197 result = []
Barry Warsawfa348c82003-03-17 18:35:42 +0000198 while self.pos < len(self.field):
Barry Warsaw1fb22bb2002-12-30 16:21:07 +0000199 ad = self.getaddress()
200 if ad:
201 result += ad
202 else:
Barry Warsawfa348c82003-03-17 18:35:42 +0000203 result.append(('', ''))
Barry Warsaw1fb22bb2002-12-30 16:21:07 +0000204 return result
Barry Warsaw030ddf72002-11-05 19:54:52 +0000205
206 def getaddress(self):
207 """Parse the next address."""
208 self.commentlist = []
209 self.gotonext()
210
211 oldpos = self.pos
212 oldcl = self.commentlist
213 plist = self.getphraselist()
214
215 self.gotonext()
216 returnlist = []
217
218 if self.pos >= len(self.field):
219 # Bad email address technically, no domain.
220 if plist:
Barry Warsaw5c8fef92002-12-30 16:43:42 +0000221 returnlist = [(SPACE.join(self.commentlist), plist[0])]
Barry Warsaw030ddf72002-11-05 19:54:52 +0000222
223 elif self.field[self.pos] in '.@':
224 # email address is just an addrspec
225 # this isn't very efficient since we start over
226 self.pos = oldpos
227 self.commentlist = oldcl
228 addrspec = self.getaddrspec()
Barry Warsaw5c8fef92002-12-30 16:43:42 +0000229 returnlist = [(SPACE.join(self.commentlist), addrspec)]
Barry Warsaw030ddf72002-11-05 19:54:52 +0000230
231 elif self.field[self.pos] == ':':
232 # address is a group
233 returnlist = []
234
235 fieldlen = len(self.field)
Barry Warsaw5c8fef92002-12-30 16:43:42 +0000236 self.pos += 1
Barry Warsaw030ddf72002-11-05 19:54:52 +0000237 while self.pos < len(self.field):
238 self.gotonext()
239 if self.pos < fieldlen and self.field[self.pos] == ';':
Barry Warsaw5c8fef92002-12-30 16:43:42 +0000240 self.pos += 1
Barry Warsaw030ddf72002-11-05 19:54:52 +0000241 break
242 returnlist = returnlist + self.getaddress()
243
244 elif self.field[self.pos] == '<':
245 # Address is a phrase then a route addr
246 routeaddr = self.getrouteaddr()
247
248 if self.commentlist:
Barry Warsaw5c8fef92002-12-30 16:43:42 +0000249 returnlist = [(SPACE.join(plist) + ' (' +
250 ' '.join(self.commentlist) + ')', routeaddr)]
251 else:
252 returnlist = [(SPACE.join(plist), routeaddr)]
Barry Warsaw030ddf72002-11-05 19:54:52 +0000253
254 else:
255 if plist:
Barry Warsaw5c8fef92002-12-30 16:43:42 +0000256 returnlist = [(SPACE.join(self.commentlist), plist[0])]
Barry Warsaw030ddf72002-11-05 19:54:52 +0000257 elif self.field[self.pos] in self.specials:
Barry Warsaw5c8fef92002-12-30 16:43:42 +0000258 self.pos += 1
Barry Warsaw030ddf72002-11-05 19:54:52 +0000259
260 self.gotonext()
261 if self.pos < len(self.field) and self.field[self.pos] == ',':
Barry Warsaw5c8fef92002-12-30 16:43:42 +0000262 self.pos += 1
Barry Warsaw030ddf72002-11-05 19:54:52 +0000263 return returnlist
264
265 def getrouteaddr(self):
266 """Parse a route address (Return-path value).
267
268 This method just skips all the route stuff and returns the addrspec.
269 """
270 if self.field[self.pos] != '<':
271 return
272
Barry Warsaw5c8fef92002-12-30 16:43:42 +0000273 expectroute = False
274 self.pos += 1
Barry Warsaw030ddf72002-11-05 19:54:52 +0000275 self.gotonext()
Barry Warsaw5c8fef92002-12-30 16:43:42 +0000276 adlist = ''
Barry Warsaw030ddf72002-11-05 19:54:52 +0000277 while self.pos < len(self.field):
278 if expectroute:
279 self.getdomain()
Barry Warsaw5c8fef92002-12-30 16:43:42 +0000280 expectroute = False
Barry Warsaw030ddf72002-11-05 19:54:52 +0000281 elif self.field[self.pos] == '>':
Barry Warsaw5c8fef92002-12-30 16:43:42 +0000282 self.pos += 1
Barry Warsaw030ddf72002-11-05 19:54:52 +0000283 break
284 elif self.field[self.pos] == '@':
Barry Warsaw5c8fef92002-12-30 16:43:42 +0000285 self.pos += 1
286 expectroute = True
Barry Warsaw030ddf72002-11-05 19:54:52 +0000287 elif self.field[self.pos] == ':':
Barry Warsaw5c8fef92002-12-30 16:43:42 +0000288 self.pos += 1
Barry Warsaw030ddf72002-11-05 19:54:52 +0000289 else:
290 adlist = self.getaddrspec()
Barry Warsaw5c8fef92002-12-30 16:43:42 +0000291 self.pos += 1
Barry Warsaw030ddf72002-11-05 19:54:52 +0000292 break
293 self.gotonext()
294
295 return adlist
296
297 def getaddrspec(self):
Barry Warsaw1fb22bb2002-12-30 16:21:07 +0000298 """Parse an RFC 2822 addr-spec."""
Barry Warsaw030ddf72002-11-05 19:54:52 +0000299 aslist = []
300
301 self.gotonext()
302 while self.pos < len(self.field):
303 if self.field[self.pos] == '.':
304 aslist.append('.')
Barry Warsaw5c8fef92002-12-30 16:43:42 +0000305 self.pos += 1
Barry Warsaw030ddf72002-11-05 19:54:52 +0000306 elif self.field[self.pos] == '"':
307 aslist.append('"%s"' % self.getquote())
308 elif self.field[self.pos] in self.atomends:
309 break
Barry Warsaw5c8fef92002-12-30 16:43:42 +0000310 else:
311 aslist.append(self.getatom())
Barry Warsaw030ddf72002-11-05 19:54:52 +0000312 self.gotonext()
313
314 if self.pos >= len(self.field) or self.field[self.pos] != '@':
Barry Warsaw5c8fef92002-12-30 16:43:42 +0000315 return EMPTYSTRING.join(aslist)
Barry Warsaw030ddf72002-11-05 19:54:52 +0000316
317 aslist.append('@')
Barry Warsaw5c8fef92002-12-30 16:43:42 +0000318 self.pos += 1
Barry Warsaw030ddf72002-11-05 19:54:52 +0000319 self.gotonext()
Barry Warsaw5c8fef92002-12-30 16:43:42 +0000320 return EMPTYSTRING.join(aslist) + self.getdomain()
Barry Warsaw030ddf72002-11-05 19:54:52 +0000321
322 def getdomain(self):
323 """Get the complete domain name from an address."""
324 sdlist = []
325 while self.pos < len(self.field):
326 if self.field[self.pos] in self.LWS:
Barry Warsaw5c8fef92002-12-30 16:43:42 +0000327 self.pos += 1
Barry Warsaw030ddf72002-11-05 19:54:52 +0000328 elif self.field[self.pos] == '(':
329 self.commentlist.append(self.getcomment())
330 elif self.field[self.pos] == '[':
331 sdlist.append(self.getdomainliteral())
332 elif self.field[self.pos] == '.':
Barry Warsaw5c8fef92002-12-30 16:43:42 +0000333 self.pos += 1
Barry Warsaw030ddf72002-11-05 19:54:52 +0000334 sdlist.append('.')
335 elif self.field[self.pos] in self.atomends:
336 break
Barry Warsaw5c8fef92002-12-30 16:43:42 +0000337 else:
338 sdlist.append(self.getatom())
339 return EMPTYSTRING.join(sdlist)
Barry Warsaw030ddf72002-11-05 19:54:52 +0000340
Barry Warsaw5c8fef92002-12-30 16:43:42 +0000341 def getdelimited(self, beginchar, endchars, allowcomments=True):
Barry Warsaw030ddf72002-11-05 19:54:52 +0000342 """Parse a header fragment delimited by special characters.
343
344 `beginchar' is the start character for the fragment.
345 If self is not looking at an instance of `beginchar' then
346 getdelimited returns the empty string.
347
348 `endchars' is a sequence of allowable end-delimiting characters.
349 Parsing stops when one of these is encountered.
350
Barry Warsaw1fb22bb2002-12-30 16:21:07 +0000351 If `allowcomments' is non-zero, embedded RFC 2822 comments are allowed
352 within the parsed fragment.
Barry Warsaw030ddf72002-11-05 19:54:52 +0000353 """
354 if self.field[self.pos] != beginchar:
355 return ''
356
357 slist = ['']
Barry Warsaw5c8fef92002-12-30 16:43:42 +0000358 quote = False
359 self.pos += 1
Barry Warsaw030ddf72002-11-05 19:54:52 +0000360 while self.pos < len(self.field):
Barry Warsaw5c8fef92002-12-30 16:43:42 +0000361 if quote:
Barry Warsaw030ddf72002-11-05 19:54:52 +0000362 slist.append(self.field[self.pos])
Barry Warsaw5c8fef92002-12-30 16:43:42 +0000363 quote = False
Barry Warsaw030ddf72002-11-05 19:54:52 +0000364 elif self.field[self.pos] in endchars:
Barry Warsaw5c8fef92002-12-30 16:43:42 +0000365 self.pos += 1
Barry Warsaw030ddf72002-11-05 19:54:52 +0000366 break
367 elif allowcomments and self.field[self.pos] == '(':
368 slist.append(self.getcomment())
369 elif self.field[self.pos] == '\\':
Barry Warsaw5c8fef92002-12-30 16:43:42 +0000370 quote = True
Barry Warsaw030ddf72002-11-05 19:54:52 +0000371 else:
372 slist.append(self.field[self.pos])
Barry Warsaw5c8fef92002-12-30 16:43:42 +0000373 self.pos += 1
Barry Warsaw030ddf72002-11-05 19:54:52 +0000374
Barry Warsaw5c8fef92002-12-30 16:43:42 +0000375 return EMPTYSTRING.join(slist)
Barry Warsaw030ddf72002-11-05 19:54:52 +0000376
377 def getquote(self):
378 """Get a quote-delimited fragment from self's field."""
Barry Warsaw5c8fef92002-12-30 16:43:42 +0000379 return self.getdelimited('"', '"\r', False)
Barry Warsaw030ddf72002-11-05 19:54:52 +0000380
381 def getcomment(self):
382 """Get a parenthesis-delimited fragment from self's field."""
Barry Warsaw5c8fef92002-12-30 16:43:42 +0000383 return self.getdelimited('(', ')\r', True)
Barry Warsaw030ddf72002-11-05 19:54:52 +0000384
385 def getdomainliteral(self):
Barry Warsaw1fb22bb2002-12-30 16:21:07 +0000386 """Parse an RFC 2822 domain-literal."""
Barry Warsaw5c8fef92002-12-30 16:43:42 +0000387 return '[%s]' % self.getdelimited('[', ']\r', False)
Barry Warsaw030ddf72002-11-05 19:54:52 +0000388
Barry Warsaw1fb22bb2002-12-30 16:21:07 +0000389 def getatom(self, atomends=None):
390 """Parse an RFC 2822 atom.
391
392 Optional atomends specifies a different set of end token delimiters
393 (the default is to use self.atomends). This is used e.g. in
394 getphraselist() since phrase endings must not include the `.' (which
395 is legal in phrases)."""
Barry Warsaw030ddf72002-11-05 19:54:52 +0000396 atomlist = ['']
Barry Warsaw1fb22bb2002-12-30 16:21:07 +0000397 if atomends is None:
398 atomends = self.atomends
Barry Warsaw030ddf72002-11-05 19:54:52 +0000399
400 while self.pos < len(self.field):
Barry Warsaw1fb22bb2002-12-30 16:21:07 +0000401 if self.field[self.pos] in atomends:
Barry Warsaw030ddf72002-11-05 19:54:52 +0000402 break
Barry Warsaw5c8fef92002-12-30 16:43:42 +0000403 else:
404 atomlist.append(self.field[self.pos])
405 self.pos += 1
Barry Warsaw030ddf72002-11-05 19:54:52 +0000406
Barry Warsaw5c8fef92002-12-30 16:43:42 +0000407 return EMPTYSTRING.join(atomlist)
Barry Warsaw030ddf72002-11-05 19:54:52 +0000408
409 def getphraselist(self):
Barry Warsaw1fb22bb2002-12-30 16:21:07 +0000410 """Parse a sequence of RFC 2822 phrases.
Barry Warsaw030ddf72002-11-05 19:54:52 +0000411
Barry Warsaw1fb22bb2002-12-30 16:21:07 +0000412 A phrase is a sequence of words, which are in turn either RFC 2822
413 atoms or quoted-strings. Phrases are canonicalized by squeezing all
414 runs of continuous whitespace into one space.
Barry Warsaw030ddf72002-11-05 19:54:52 +0000415 """
416 plist = []
417
418 while self.pos < len(self.field):
419 if self.field[self.pos] in self.LWS:
Barry Warsaw5c8fef92002-12-30 16:43:42 +0000420 self.pos += 1
Barry Warsaw030ddf72002-11-05 19:54:52 +0000421 elif self.field[self.pos] == '"':
422 plist.append(self.getquote())
423 elif self.field[self.pos] == '(':
424 self.commentlist.append(self.getcomment())
Barry Warsaw1fb22bb2002-12-30 16:21:07 +0000425 elif self.field[self.pos] in self.phraseends:
Barry Warsaw030ddf72002-11-05 19:54:52 +0000426 break
Barry Warsaw5c8fef92002-12-30 16:43:42 +0000427 else:
428 plist.append(self.getatom(self.phraseends))
Barry Warsaw030ddf72002-11-05 19:54:52 +0000429
430 return plist
431
432class AddressList(AddrlistClass):
Barry Warsaw1fb22bb2002-12-30 16:21:07 +0000433 """An AddressList encapsulates a list of parsed RFC 2822 addresses."""
Barry Warsaw030ddf72002-11-05 19:54:52 +0000434 def __init__(self, field):
435 AddrlistClass.__init__(self, field)
436 if field:
437 self.addresslist = self.getaddrlist()
438 else:
439 self.addresslist = []
440
441 def __len__(self):
442 return len(self.addresslist)
443
Barry Warsaw030ddf72002-11-05 19:54:52 +0000444 def __add__(self, other):
445 # Set union
446 newaddr = AddressList(None)
447 newaddr.addresslist = self.addresslist[:]
448 for x in other.addresslist:
449 if not x in self.addresslist:
450 newaddr.addresslist.append(x)
451 return newaddr
452
453 def __iadd__(self, other):
454 # Set union, in-place
455 for x in other.addresslist:
456 if not x in self.addresslist:
457 self.addresslist.append(x)
458 return self
459
460 def __sub__(self, other):
461 # Set difference
462 newaddr = AddressList(None)
463 for x in self.addresslist:
464 if not x in other.addresslist:
465 newaddr.addresslist.append(x)
466 return newaddr
467
468 def __isub__(self, other):
469 # Set difference, in-place
470 for x in other.addresslist:
471 if x in self.addresslist:
472 self.addresslist.remove(x)
473 return self
474
475 def __getitem__(self, index):
476 # Make indexing, slices, and 'in' work
477 return self.addresslist[index]