| 1 |
|
| 2 |
|
| 3 |
|
| 4 |
|
| 5 |
"""Miscellaneous utilities.""" |
| 6 |
|
| 7 |
__all__ = [ |
| 8 |
'collapse_rfc2231_value', |
| 9 |
'decode_params', |
| 10 |
'decode_rfc2231', |
| 11 |
'encode_rfc2231', |
| 12 |
'formataddr', |
| 13 |
'formatdate', |
| 14 |
'format_datetime', |
| 15 |
'getaddresses', |
| 16 |
'make_msgid', |
| 17 |
'mktime_tz', |
| 18 |
'parseaddr', |
| 19 |
'parsedate', |
| 20 |
'parsedate_tz', |
| 21 |
'parsedate_to_datetime', |
| 22 |
'unquote', |
| 23 |
] |
| 24 |
|
| 25 |
import os |
| 26 |
import re |
| 27 |
import time |
| 28 |
import random |
| 29 |
import socket |
| 30 |
import datetime |
| 31 |
import urllib.parse |
| 32 |
|
| 33 |
from email._parseaddr import quote |
| 34 |
from email._parseaddr import AddressList as _AddressList |
| 35 |
from email._parseaddr import mktime_tz |
| 36 |
|
| 37 |
from email._parseaddr import parsedate, parsedate_tz, _parsedate_tz |
| 38 |
|
| 39 |
|
| 40 |
from email.charset import Charset |
| 41 |
|
| 42 |
COMMASPACE = ', ' |
| 43 |
EMPTYSTRING = '' |
| 44 |
UEMPTYSTRING = '' |
| 45 |
CRLF = '\r\n' |
| 46 |
TICK = "'" |
| 47 |
|
| 48 |
specialsre = re.compile(r'[][\\()<>@,:;".]') |
| 49 |
escapesre = re.compile(r'[\\"]') |
| 50 |
|
| 51 |
|
| 52 |
def _has_surrogates(s): |
| 53 |
"""Return True if s may contain surrogate-escaped binary data.""" |
| 54 |
|
| 55 |
|
| 56 |
|
| 57 |
try: |
| 58 |
s.encode() |
| 59 |
return False |
| 60 |
except UnicodeEncodeError: |
| 61 |
return True |
| 62 |
|
| 63 |
|
| 64 |
|
| 65 |
def _sanitize(string): |
| 66 |
|
| 67 |
|
| 68 |
|
| 69 |
|
| 70 |
original_bytes = string.encode('utf-8', 'surrogateescape') |
| 71 |
return original_bytes.decode('utf-8', 'replace') |
| 72 |
|
| 73 |
|
| 74 |
|
| 75 |
|
| 76 |
|
| 77 |
def formataddr(pair, charset='utf-8'): |
| 78 |
"""The inverse of parseaddr(), this takes a 2-tuple of the form |
| 79 |
(realname, email_address) and returns the string value suitable |
| 80 |
for an RFC 2822 From, To or Cc header. |
| 81 |
|
| 82 |
If the first element of pair is false, then the second element is |
| 83 |
returned unmodified. |
| 84 |
|
| 85 |
The optional charset is the character set that is used to encode |
| 86 |
realname in case realname is not ASCII safe. Can be an instance of str or |
| 87 |
a Charset-like object which has a header_encode method. Default is |
| 88 |
'utf-8'. |
| 89 |
""" |
| 90 |
name, address = pair |
| 91 |
|
| 92 |
address.encode('ascii') |
| 93 |
if name: |
| 94 |
try: |
| 95 |
name.encode('ascii') |
| 96 |
except UnicodeEncodeError: |
| 97 |
if isinstance(charset, str): |
| 98 |
charset = Charset(charset) |
| 99 |
encoded_name = charset.header_encode(name) |
| 100 |
return "%s <%s>" % (encoded_name, address) |
| 101 |
else: |
| 102 |
quotes = '' |
| 103 |
if specialsre.search(name): |
| 104 |
quotes = '"' |
| 105 |
name = escapesre.sub(r'\\\g<0>', name) |
| 106 |
return '%s%s%s <%s>' % (quotes, name, quotes, address) |
| 107 |
return address |
| 108 |
|
| 109 |
|
| 110 |
def _iter_escaped_chars(addr): |
| 111 |
pos = 0 |
| 112 |
escape = False |
| 113 |
for pos, ch in enumerate(addr): |
| 114 |
if escape: |
| 115 |
yield (pos, '\\' + ch) |
| 116 |
escape = False |
| 117 |
elif ch == '\\': |
| 118 |
escape = True |
| 119 |
else: |
| 120 |
yield (pos, ch) |
| 121 |
if escape: |
| 122 |
yield (pos, '\\') |
| 123 |
|
| 124 |
|
| 125 |
def _strip_quoted_realnames(addr): |
| 126 |
"""Strip real names between quotes.""" |
| 127 |
if '"' not in addr: |
| 128 |
|
| 129 |
return addr |
| 130 |
|
| 131 |
start = 0 |
| 132 |
open_pos = None |
| 133 |
result = [] |
| 134 |
for pos, ch in _iter_escaped_chars(addr): |
| 135 |
if ch == '"': |
| 136 |
if open_pos is None: |
| 137 |
open_pos = pos |
| 138 |
else: |
| 139 |
if start != open_pos: |
| 140 |
result.append(addr[start:open_pos]) |
| 141 |
start = pos + 1 |
| 142 |
open_pos = None |
| 143 |
|
| 144 |
if start < len(addr): |
| 145 |
result.append(addr[start:]) |
| 146 |
|
| 147 |
return ''.join(result) |
| 148 |
|
| 149 |
|
| 150 |
supports_strict_parsing = True |
| 151 |
|
| 152 |
def getaddresses(fieldvalues, *, strict=True): |
| 153 |
"""Return a list of (REALNAME, EMAIL) or ('','') for each fieldvalue. |
| 154 |
|
| 155 |
When parsing fails for a fieldvalue, a 2-tuple of ('', '') is returned in |
| 156 |
its place. |
| 157 |
|
| 158 |
If strict is true, use a strict parser which rejects malformed inputs. |
| 159 |
""" |
| 160 |
|
| 161 |
|
| 162 |
|
| 163 |
|
| 164 |
|
| 165 |
|
| 166 |
|
| 167 |
|
| 168 |
|
| 169 |
|
| 170 |
if not strict: |
| 171 |
all = COMMASPACE.join(str(v) for v in fieldvalues) |
| 172 |
a = _AddressList(all) |
| 173 |
return a.addresslist |
| 174 |
|
| 175 |
fieldvalues = [str(v) for v in fieldvalues] |
| 176 |
fieldvalues = _pre_parse_validation(fieldvalues) |
| 177 |
addr = COMMASPACE.join(fieldvalues) |
| 178 |
a = _AddressList(addr) |
| 179 |
result = _post_parse_validation(a.addresslist) |
| 180 |
|
| 181 |
|
| 182 |
|
| 183 |
n = 0 |
| 184 |
for v in fieldvalues: |
| 185 |
|
| 186 |
|
| 187 |
v = _strip_quoted_realnames(v) |
| 188 |
|
| 189 |
n += 1 + v.count(',') |
| 190 |
if len(result) != n: |
| 191 |
return [('', '')] |
| 192 |
|
| 193 |
return result |
| 194 |
|
| 195 |
|
| 196 |
def _check_parenthesis(addr): |
| 197 |
|
| 198 |
addr = _strip_quoted_realnames(addr) |
| 199 |
|
| 200 |
opens = 0 |
| 201 |
for pos, ch in _iter_escaped_chars(addr): |
| 202 |
if ch == '(': |
| 203 |
opens += 1 |
| 204 |
elif ch == ')': |
| 205 |
opens -= 1 |
| 206 |
if opens < 0: |
| 207 |
return False |
| 208 |
return (opens == 0) |
| 209 |
|
| 210 |
|
| 211 |
def _pre_parse_validation(email_header_fields): |
| 212 |
accepted_values = [] |
| 213 |
for v in email_header_fields: |
| 214 |
if not _check_parenthesis(v): |
| 215 |
v = "('', '')" |
| 216 |
accepted_values.append(v) |
| 217 |
|
| 218 |
return accepted_values |
| 219 |
|
| 220 |
|
| 221 |
def _post_parse_validation(parsed_email_header_tuples): |
| 222 |
accepted_values = [] |
| 223 |
|
| 224 |
|
| 225 |
for v in parsed_email_header_tuples: |
| 226 |
if '[' in v[1]: |
| 227 |
v = ('', '') |
| 228 |
accepted_values.append(v) |
| 229 |
|
| 230 |
return accepted_values |
| 231 |
|
| 232 |
|
| 233 |
def _format_timetuple_and_zone(timetuple, zone): |
| 234 |
return '%s, %02d %s %04d %02d:%02d:%02d %s' % ( |
| 235 |
['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun'][timetuple[6]], |
| 236 |
timetuple[2], |
| 237 |
['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', |
| 238 |
'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'][timetuple[1] - 1], |
| 239 |
timetuple[0], timetuple[3], timetuple[4], timetuple[5], |
| 240 |
zone) |
| 241 |
|
| 242 |
def formatdate(timeval=None, localtime=False, usegmt=False): |
| 243 |
"""Returns a date string as specified by RFC 2822, e.g.: |
| 244 |
|
| 245 |
Fri, 09 Nov 2001 01:08:47 -0000 |
| 246 |
|
| 247 |
Optional timeval if given is a floating point time value as accepted by |
| 248 |
gmtime() and localtime(), otherwise the current time is used. |
| 249 |
|
| 250 |
Optional localtime is a flag that when True, interprets timeval, and |
| 251 |
returns a date relative to the local timezone instead of UTC, properly |
| 252 |
taking daylight savings time into account. |
| 253 |
|
| 254 |
Optional argument usegmt means that the timezone is written out as |
| 255 |
an ascii string, not numeric one (so "GMT" instead of "+0000"). This |
| 256 |
is needed for HTTP, and is only used when localtime==False. |
| 257 |
""" |
| 258 |
|
| 259 |
|
| 260 |
if timeval is None: |
| 261 |
timeval = time.time() |
| 262 |
if localtime or usegmt: |
| 263 |
dt = datetime.datetime.fromtimestamp(timeval, datetime.timezone.utc) |
| 264 |
else: |
| 265 |
dt = datetime.datetime.utcfromtimestamp(timeval) |
| 266 |
if localtime: |
| 267 |
dt = dt.astimezone() |
| 268 |
usegmt = False |
| 269 |
return format_datetime(dt, usegmt) |
| 270 |
|
| 271 |
def format_datetime(dt, usegmt=False): |
| 272 |
"""Turn a datetime into a date string as specified in RFC 2822. |
| 273 |
|
| 274 |
If usegmt is True, dt must be an aware datetime with an offset of zero. In |
| 275 |
this case 'GMT' will be rendered instead of the normal +0000 required by |
| 276 |
RFC2822. This is to support HTTP headers involving date stamps. |
| 277 |
""" |
| 278 |
now = dt.timetuple() |
| 279 |
if usegmt: |
| 280 |
if dt.tzinfo is None or dt.tzinfo != datetime.timezone.utc: |
| 281 |
raise ValueError("usegmt option requires a UTC datetime") |
| 282 |
zone = 'GMT' |
| 283 |
elif dt.tzinfo is None: |
| 284 |
zone = '-0000' |
| 285 |
else: |
| 286 |
zone = dt.strftime("%z") |
| 287 |
return _format_timetuple_and_zone(now, zone) |
| 288 |
|
| 289 |
|
| 290 |
def make_msgid(idstring=None, domain=None): |
| 291 |
"""Returns a string suitable for RFC 2822 compliant Message-ID, e.g: |
| 292 |
|
| 293 |
<142480216486.20800.16526388040877946887@nightshade.la.mastaler.com> |
| 294 |
|
| 295 |
Optional idstring if given is a string used to strengthen the |
| 296 |
uniqueness of the message id. Optional domain if given provides the |
| 297 |
portion of the message id after the '@'. It defaults to the locally |
| 298 |
defined hostname. |
| 299 |
""" |
| 300 |
timeval = int(time.time()*100) |
| 301 |
pid = os.getpid() |
| 302 |
randint = random.getrandbits(64) |
| 303 |
if idstring is None: |
| 304 |
idstring = '' |
| 305 |
else: |
| 306 |
idstring = '.' + idstring |
| 307 |
if domain is None: |
| 308 |
domain = socket.getfqdn() |
| 309 |
msgid = '<%d.%d.%d%s@%s>' % (timeval, pid, randint, idstring, domain) |
| 310 |
return msgid |
| 311 |
|
| 312 |
|
| 313 |
def parsedate_to_datetime(data): |
| 314 |
parsed_date_tz = _parsedate_tz(data) |
| 315 |
if parsed_date_tz is None: |
| 316 |
raise ValueError('Invalid date value or format "%s"' % str(data)) |
| 317 |
*dtuple, tz = parsed_date_tz |
| 318 |
if tz is None: |
| 319 |
return datetime.datetime(*dtuple[:6]) |
| 320 |
return datetime.datetime(*dtuple[:6], |
| 321 |
tzinfo=datetime.timezone(datetime.timedelta(seconds=tz))) |
| 322 |
|
| 323 |
|
| 324 |
def parseaddr(addr, *, strict=True): |
| 325 |
""" |
| 326 |
Parse addr into its constituent realname and email address parts. |
| 327 |
|
| 328 |
Return a tuple of realname and email address, unless the parse fails, in |
| 329 |
which case return a 2-tuple of ('', ''). |
| 330 |
|
| 331 |
If strict is True, use a strict parser which rejects malformed inputs. |
| 332 |
""" |
| 333 |
if not strict: |
| 334 |
addrs = _AddressList(addr).addresslist |
| 335 |
if not addrs: |
| 336 |
return ('', '') |
| 337 |
return addrs[0] |
| 338 |
|
| 339 |
if isinstance(addr, list): |
| 340 |
addr = addr[0] |
| 341 |
|
| 342 |
if not isinstance(addr, str): |
| 343 |
return ('', '') |
| 344 |
|
| 345 |
addr = _pre_parse_validation([addr])[0] |
| 346 |
addrs = _post_parse_validation(_AddressList(addr).addresslist) |
| 347 |
|
| 348 |
if not addrs or len(addrs) > 1: |
| 349 |
return ('', '') |
| 350 |
|
| 351 |
return addrs[0] |
| 352 |
|
| 353 |
|
| 354 |
|
| 355 |
def unquote(str): |
| 356 |
"""Remove quotes from a string.""" |
| 357 |
if len(str) > 1: |
| 358 |
if str.startswith('"') and str.endswith('"'): |
| 359 |
return str[1:-1].replace('\\\\', '\\').replace('\\"', '"') |
| 360 |
if str.startswith('<') and str.endswith('>'): |
| 361 |
return str[1:-1] |
| 362 |
return str |
| 363 |
|
| 364 |
|
| 365 |
|
| 366 |
|
| 367 |
def decode_rfc2231(s): |
| 368 |
"""Decode string according to RFC 2231""" |
| 369 |
parts = s.split(TICK, 2) |
| 370 |
if len(parts) <= 2: |
| 371 |
return None, None, s |
| 372 |
return parts |
| 373 |
|
| 374 |
|
| 375 |
def encode_rfc2231(s, charset=None, language=None): |
| 376 |
"""Encode string according to RFC 2231. |
| 377 |
|
| 378 |
If neither charset nor language is given, then s is returned as-is. If |
| 379 |
charset is given but not language, the string is encoded using the empty |
| 380 |
string for language. |
| 381 |
""" |
| 382 |
s = urllib.parse.quote(s, safe='', encoding=charset or 'ascii') |
| 383 |
if charset is None and language is None: |
| 384 |
return s |
| 385 |
if language is None: |
| 386 |
language = '' |
| 387 |
return "%s'%s'%s" % (charset, language, s) |
| 388 |
|
| 389 |
|
| 390 |
rfc2231_continuation = re.compile(r'^(?P<name>\w+)\*((?P<num>[0-9]+)\*?)?$', |
| 391 |
re.ASCII) |
| 392 |
|
| 393 |
def decode_params(params): |
| 394 |
"""Decode parameters list according to RFC 2231. |
| 395 |
|
| 396 |
params is a sequence of 2-tuples containing (param name, string value). |
| 397 |
""" |
| 398 |
new_params = [params[0]] |
| 399 |
|
| 400 |
|
| 401 |
|
| 402 |
rfc2231_params = {} |
| 403 |
for name, value in params[1:]: |
| 404 |
encoded = name.endswith('*') |
| 405 |
value = unquote(value) |
| 406 |
mo = rfc2231_continuation.match(name) |
| 407 |
if mo: |
| 408 |
name, num = mo.group('name', 'num') |
| 409 |
if num is not None: |
| 410 |
num = int(num) |
| 411 |
rfc2231_params.setdefault(name, []).append((num, value, encoded)) |
| 412 |
else: |
| 413 |
new_params.append((name, '"%s"' % quote(value))) |
| 414 |
if rfc2231_params: |
| 415 |
for name, continuations in rfc2231_params.items(): |
| 416 |
value = [] |
| 417 |
extended = False |
| 418 |
|
| 419 |
continuations.sort() |
| 420 |
|
| 421 |
|
| 422 |
|
| 423 |
|
| 424 |
|
| 425 |
for num, s, encoded in continuations: |
| 426 |
if encoded: |
| 427 |
|
| 428 |
|
| 429 |
|
| 430 |
s = urllib.parse.unquote(s, encoding="latin-1") |
| 431 |
extended = True |
| 432 |
value.append(s) |
| 433 |
value = quote(EMPTYSTRING.join(value)) |
| 434 |
if extended: |
| 435 |
charset, language, value = decode_rfc2231(value) |
| 436 |
new_params.append((name, (charset, language, '"%s"' % value))) |
| 437 |
else: |
| 438 |
new_params.append((name, '"%s"' % value)) |
| 439 |
return new_params |
| 440 |
|
| 441 |
def collapse_rfc2231_value(value, errors='replace', |
| 442 |
fallback_charset='us-ascii'): |
| 443 |
if not isinstance(value, tuple) or len(value) != 3: |
| 444 |
return unquote(value) |
| 445 |
|
| 446 |
|
| 447 |
|
| 448 |
charset, language, text = value |
| 449 |
if charset is None: |
| 450 |
|
| 451 |
|
| 452 |
charset = fallback_charset |
| 453 |
rawbytes = bytes(text, 'raw-unicode-escape') |
| 454 |
try: |
| 455 |
return str(rawbytes, charset, errors) |
| 456 |
except LookupError: |
| 457 |
|
| 458 |
return unquote(text) |
| 459 |
|
| 460 |
|
| 461 |
|
| 462 |
|
| 463 |
|
| 464 |
|
| 465 |
|
| 466 |
|
| 467 |
def localtime(dt=None, isdst=-1): |
| 468 |
"""Return local time as an aware datetime object. |
| 469 |
|
| 470 |
If called without arguments, return current time. Otherwise *dt* |
| 471 |
argument should be a datetime instance, and it is converted to the |
| 472 |
local time zone according to the system time zone database. If *dt* is |
| 473 |
naive (that is, dt.tzinfo is None), it is assumed to be in local time. |
| 474 |
In this case, a positive or zero value for *isdst* causes localtime to |
| 475 |
presume initially that summer time (for example, Daylight Saving Time) |
| 476 |
is or is not (respectively) in effect for the specified time. A |
| 477 |
negative value for *isdst* causes the localtime() function to attempt |
| 478 |
to divine whether summer time is in effect for the specified time. |
| 479 |
|
| 480 |
""" |
| 481 |
if dt is None: |
| 482 |
return datetime.datetime.now(datetime.timezone.utc).astimezone() |
| 483 |
if dt.tzinfo is not None: |
| 484 |
return dt.astimezone() |
| 485 |
|
| 486 |
|
| 487 |
|
| 488 |
tm = dt.timetuple()[:-1] + (isdst,) |
| 489 |
seconds = time.mktime(tm) |
| 490 |
localtm = time.localtime(seconds) |
| 491 |
try: |
| 492 |
delta = datetime.timedelta(seconds=localtm.tm_gmtoff) |
| 493 |
tz = datetime.timezone(delta, localtm.tm_zone) |
| 494 |
except AttributeError: |
| 495 |
|
| 496 |
|
| 497 |
delta = dt - datetime.datetime(*time.gmtime(seconds)[:6]) |
| 498 |
dst = time.daylight and localtm.tm_isdst > 0 |
| 499 |
gmtoff = -(time.altzone if dst else time.timezone) |
| 500 |
if delta == datetime.timedelta(seconds=gmtoff): |
| 501 |
tz = datetime.timezone(delta, time.tzname[dst]) |
| 502 |
else: |
| 503 |
tz = datetime.timezone(delta) |
| 504 |
return dt.replace(tzinfo=tz) |