blob: cb2869a4a5daf144f9f94e958e3a050bbc40da31 [file] [log] [blame]
Barry Warsaw030ddf72002-11-05 19:54:52 +00001# Copyright (C) 2002 Python Software Foundation
2
3"""Email address parsing code.
4
5Lifted directly from rfc822.py. This should eventually be rewritten.
6"""
7
8import time
9
10# Parse a date field
11_monthnames = ['jan', 'feb', 'mar', 'apr', 'may', 'jun', 'jul',
12 'aug', 'sep', 'oct', 'nov', 'dec',
13 'january', 'february', 'march', 'april', 'may', 'june', 'july',
14 'august', 'september', 'october', 'november', 'december']
15
16_daynames = ['mon', 'tue', 'wed', 'thu', 'fri', 'sat', 'sun']
17
18# The timezone table does not include the military time zones defined
19# in RFC822, other than Z. According to RFC1123, the description in
20# RFC822 gets the signs wrong, so we can't rely on any such time
21# zones. RFC1123 recommends that numeric timezone indicators be used
22# instead of timezone names.
23
24_timezones = {'UT':0, 'UTC':0, 'GMT':0, 'Z':0,
25 'AST': -400, 'ADT': -300, # Atlantic (used in Canada)
26 'EST': -500, 'EDT': -400, # Eastern
27 'CST': -600, 'CDT': -500, # Central
28 'MST': -700, 'MDT': -600, # Mountain
29 'PST': -800, 'PDT': -700 # Pacific
30 }
31
32
33def parsedate_tz(data):
34 """Convert a date string to a time tuple.
35
36 Accounts for military timezones.
37 """
38 data = data.split()
39 if data[0][-1] in (',', '.') or data[0].lower() in _daynames:
40 # There's a dayname here. Skip it
41 del data[0]
42 if len(data) == 3: # RFC 850 date, deprecated
43 stuff = data[0].split('-')
44 if len(stuff) == 3:
45 data = stuff + data[1:]
46 if len(data) == 4:
47 s = data[3]
48 i = s.find('+')
49 if i > 0:
50 data[3:] = [s[:i], s[i+1:]]
51 else:
52 data.append('') # Dummy tz
53 if len(data) < 5:
54 return None
55 data = data[:5]
56 [dd, mm, yy, tm, tz] = data
57 mm = mm.lower()
58 if not mm in _monthnames:
59 dd, mm = mm, dd.lower()
60 if not mm in _monthnames:
61 return None
62 mm = _monthnames.index(mm)+1
63 if mm > 12: mm = mm - 12
64 if dd[-1] == ',':
65 dd = dd[:-1]
66 i = yy.find(':')
67 if i > 0:
68 yy, tm = tm, yy
69 if yy[-1] == ',':
70 yy = yy[:-1]
71 if not yy[0].isdigit():
72 yy, tz = tz, yy
73 if tm[-1] == ',':
74 tm = tm[:-1]
75 tm = tm.split(':')
76 if len(tm) == 2:
77 [thh, tmm] = tm
78 tss = '0'
79 elif len(tm) == 3:
80 [thh, tmm, tss] = tm
81 else:
82 return None
83 try:
84 yy = int(yy)
85 dd = int(dd)
86 thh = int(thh)
87 tmm = int(tmm)
88 tss = int(tss)
89 except ValueError:
90 return None
91 tzoffset = None
92 tz = tz.upper()
93 if _timezones.has_key(tz):
94 tzoffset = _timezones[tz]
95 else:
96 try:
97 tzoffset = int(tz)
98 except ValueError:
99 pass
100 # Convert a timezone offset into seconds ; -0500 -> -18000
101 if tzoffset:
102 if tzoffset < 0:
103 tzsign = -1
104 tzoffset = -tzoffset
105 else:
106 tzsign = 1
107 tzoffset = tzsign * ( (tzoffset/100)*3600 + (tzoffset % 100)*60)
108 tuple = (yy, mm, dd, thh, tmm, tss, 0, 0, 0, tzoffset)
109 return tuple
110
111
112def parsedate(data):
113 """Convert a time string to a time tuple."""
114 t = parsedate_tz(data)
115 if type(t) == type( () ):
116 return t[:9]
117 else: return t
118
119
120def mktime_tz(data):
121 """Turn a 10-tuple as returned by parsedate_tz() into a UTC timestamp."""
122 if data[9] is None:
123 # No zone info, so localtime is better assumption than GMT
124 return time.mktime(data[:8] + (-1,))
125 else:
126 t = time.mktime(data[:8] + (0,))
127 return t - data[9] - time.timezone
128
129
130def quote(str):
131 """Add quotes around a string."""
132 return str.replace('\\', '\\\\').replace('"', '\\"')
133
134
135class AddrlistClass:
136 """Address parser class by Ben Escoto.
137
138 To understand what this class does, it helps to have a copy of
139 RFC-822 in front of you.
140
141 Note: this class interface is deprecated and may be removed in the future.
142 Use rfc822.AddressList instead.
143 """
144
145 def __init__(self, field):
146 """Initialize a new instance.
147
148 `field' is an unparsed address header field, containing
149 one or more addresses.
150 """
151 self.specials = '()<>@,:;.\"[]'
152 self.pos = 0
153 self.LWS = ' \t'
154 self.CR = '\r\n'
155 self.atomends = self.specials + self.LWS + self.CR
156 self.field = field
157 self.commentlist = []
158
159 def gotonext(self):
160 """Parse up to the start of the next address."""
161 while self.pos < len(self.field):
162 if self.field[self.pos] in self.LWS + '\n\r':
163 self.pos = self.pos + 1
164 elif self.field[self.pos] == '(':
165 self.commentlist.append(self.getcomment())
166 else: break
167
168 def getaddrlist(self):
169 """Parse all addresses.
170
171 Returns a list containing all of the addresses.
172 """
173 ad = self.getaddress()
174 if ad:
175 return ad + self.getaddrlist()
176 else: return []
177
178 def getaddress(self):
179 """Parse the next address."""
180 self.commentlist = []
181 self.gotonext()
182
183 oldpos = self.pos
184 oldcl = self.commentlist
185 plist = self.getphraselist()
186
187 self.gotonext()
188 returnlist = []
189
190 if self.pos >= len(self.field):
191 # Bad email address technically, no domain.
192 if plist:
193 returnlist = [(' '.join(self.commentlist), plist[0])]
194
195 elif self.field[self.pos] in '.@':
196 # email address is just an addrspec
197 # this isn't very efficient since we start over
198 self.pos = oldpos
199 self.commentlist = oldcl
200 addrspec = self.getaddrspec()
201 returnlist = [(' '.join(self.commentlist), addrspec)]
202
203 elif self.field[self.pos] == ':':
204 # address is a group
205 returnlist = []
206
207 fieldlen = len(self.field)
208 self.pos = self.pos + 1
209 while self.pos < len(self.field):
210 self.gotonext()
211 if self.pos < fieldlen and self.field[self.pos] == ';':
212 self.pos = self.pos + 1
213 break
214 returnlist = returnlist + self.getaddress()
215
216 elif self.field[self.pos] == '<':
217 # Address is a phrase then a route addr
218 routeaddr = self.getrouteaddr()
219
220 if self.commentlist:
221 returnlist = [(' '.join(plist) + ' (' + \
222 ' '.join(self.commentlist) + ')', routeaddr)]
223 else: returnlist = [(' '.join(plist), routeaddr)]
224
225 else:
226 if plist:
227 returnlist = [(' '.join(self.commentlist), plist[0])]
228 elif self.field[self.pos] in self.specials:
229 self.pos = self.pos + 1
230
231 self.gotonext()
232 if self.pos < len(self.field) and self.field[self.pos] == ',':
233 self.pos = self.pos + 1
234 return returnlist
235
236 def getrouteaddr(self):
237 """Parse a route address (Return-path value).
238
239 This method just skips all the route stuff and returns the addrspec.
240 """
241 if self.field[self.pos] != '<':
242 return
243
244 expectroute = 0
245 self.pos = self.pos + 1
246 self.gotonext()
247 adlist = ""
248 while self.pos < len(self.field):
249 if expectroute:
250 self.getdomain()
251 expectroute = 0
252 elif self.field[self.pos] == '>':
253 self.pos = self.pos + 1
254 break
255 elif self.field[self.pos] == '@':
256 self.pos = self.pos + 1
257 expectroute = 1
258 elif self.field[self.pos] == ':':
259 self.pos = self.pos + 1
260 expectaddrspec = 1
261 else:
262 adlist = self.getaddrspec()
263 self.pos = self.pos + 1
264 break
265 self.gotonext()
266
267 return adlist
268
269 def getaddrspec(self):
270 """Parse an RFC-822 addr-spec."""
271 aslist = []
272
273 self.gotonext()
274 while self.pos < len(self.field):
275 if self.field[self.pos] == '.':
276 aslist.append('.')
277 self.pos = self.pos + 1
278 elif self.field[self.pos] == '"':
279 aslist.append('"%s"' % self.getquote())
280 elif self.field[self.pos] in self.atomends:
281 break
282 else: aslist.append(self.getatom())
283 self.gotonext()
284
285 if self.pos >= len(self.field) or self.field[self.pos] != '@':
286 return ''.join(aslist)
287
288 aslist.append('@')
289 self.pos = self.pos + 1
290 self.gotonext()
291 return ''.join(aslist) + self.getdomain()
292
293 def getdomain(self):
294 """Get the complete domain name from an address."""
295 sdlist = []
296 while self.pos < len(self.field):
297 if self.field[self.pos] in self.LWS:
298 self.pos = self.pos + 1
299 elif self.field[self.pos] == '(':
300 self.commentlist.append(self.getcomment())
301 elif self.field[self.pos] == '[':
302 sdlist.append(self.getdomainliteral())
303 elif self.field[self.pos] == '.':
304 self.pos = self.pos + 1
305 sdlist.append('.')
306 elif self.field[self.pos] in self.atomends:
307 break
308 else: sdlist.append(self.getatom())
309 return ''.join(sdlist)
310
311 def getdelimited(self, beginchar, endchars, allowcomments = 1):
312 """Parse a header fragment delimited by special characters.
313
314 `beginchar' is the start character for the fragment.
315 If self is not looking at an instance of `beginchar' then
316 getdelimited returns the empty string.
317
318 `endchars' is a sequence of allowable end-delimiting characters.
319 Parsing stops when one of these is encountered.
320
321 If `allowcomments' is non-zero, embedded RFC-822 comments
322 are allowed within the parsed fragment.
323 """
324 if self.field[self.pos] != beginchar:
325 return ''
326
327 slist = ['']
328 quote = 0
329 self.pos = self.pos + 1
330 while self.pos < len(self.field):
331 if quote == 1:
332 slist.append(self.field[self.pos])
333 quote = 0
334 elif self.field[self.pos] in endchars:
335 self.pos = self.pos + 1
336 break
337 elif allowcomments and self.field[self.pos] == '(':
338 slist.append(self.getcomment())
339 elif self.field[self.pos] == '\\':
340 quote = 1
341 else:
342 slist.append(self.field[self.pos])
343 self.pos = self.pos + 1
344
345 return ''.join(slist)
346
347 def getquote(self):
348 """Get a quote-delimited fragment from self's field."""
349 return self.getdelimited('"', '"\r', 0)
350
351 def getcomment(self):
352 """Get a parenthesis-delimited fragment from self's field."""
353 return self.getdelimited('(', ')\r', 1)
354
355 def getdomainliteral(self):
356 """Parse an RFC-822 domain-literal."""
357 return '[%s]' % self.getdelimited('[', ']\r', 0)
358
359 def getatom(self):
360 """Parse an RFC-822 atom."""
361 atomlist = ['']
362
363 while self.pos < len(self.field):
364 if self.field[self.pos] in self.atomends:
365 break
366 else: atomlist.append(self.field[self.pos])
367 self.pos = self.pos + 1
368
369 return ''.join(atomlist)
370
371 def getphraselist(self):
372 """Parse a sequence of RFC-822 phrases.
373
374 A phrase is a sequence of words, which are in turn either
375 RFC-822 atoms or quoted-strings. Phrases are canonicalized
376 by squeezing all runs of continuous whitespace into one space.
377 """
378 plist = []
379
380 while self.pos < len(self.field):
381 if self.field[self.pos] in self.LWS:
382 self.pos = self.pos + 1
383 elif self.field[self.pos] == '"':
384 plist.append(self.getquote())
385 elif self.field[self.pos] == '(':
386 self.commentlist.append(self.getcomment())
387 elif self.field[self.pos] in self.atomends:
388 break
389 else: plist.append(self.getatom())
390
391 return plist
392
393class AddressList(AddrlistClass):
394 """An AddressList encapsulates a list of parsed RFC822 addresses."""
395 def __init__(self, field):
396 AddrlistClass.__init__(self, field)
397 if field:
398 self.addresslist = self.getaddrlist()
399 else:
400 self.addresslist = []
401
402 def __len__(self):
403 return len(self.addresslist)
404
405 def __str__(self):
406 return ", ".join(map(dump_address_pair, self.addresslist))
407
408 def __add__(self, other):
409 # Set union
410 newaddr = AddressList(None)
411 newaddr.addresslist = self.addresslist[:]
412 for x in other.addresslist:
413 if not x in self.addresslist:
414 newaddr.addresslist.append(x)
415 return newaddr
416
417 def __iadd__(self, other):
418 # Set union, in-place
419 for x in other.addresslist:
420 if not x in self.addresslist:
421 self.addresslist.append(x)
422 return self
423
424 def __sub__(self, other):
425 # Set difference
426 newaddr = AddressList(None)
427 for x in self.addresslist:
428 if not x in other.addresslist:
429 newaddr.addresslist.append(x)
430 return newaddr
431
432 def __isub__(self, other):
433 # Set difference, in-place
434 for x in other.addresslist:
435 if x in self.addresslist:
436 self.addresslist.remove(x)
437 return self
438
439 def __getitem__(self, index):
440 # Make indexing, slices, and 'in' work
441 return self.addresslist[index]