0
  8   sˆl–Ðz¾”d
eJe@
à�q¦ÔÅ£�þYh/,Ü¬ºI_} ?ô„,²çóÅ¿ð 4    s# Copyright (C) 2000-2014 Bastian Kleineidam
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License along
# with this program; if not, write to the Free Software Foundation, Inc.,
# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
"""
Handler for mailto: links.
"""

import re
import urllib.parse
from email._parseaddr import AddressList

from . import urlbase
from .. import log, LOG_CHECK, strformat, url as urlutil
from dns import resolver
from ..network import iputil
from .const import WARN_MAIL_NO_MX_HOST


def getaddresses(addr):
    """Return list of email addresses from given field value."""
    parsed = [mail for name, mail in AddressList(addr).addresslist if mail]
    if parsed:
        addresses = parsed
    elif addr:
        # we could not parse any mail addresses, so try with the raw string
        addresses = [addr]
    else:
        addresses = []
    return addresses


def is_quoted(addr):
    """Return True iff mail address string is quoted."""
    return addr.startswith('"') and addr.endswith('"')


def is_literal(domain):
    """Return True iff domain string is a literal."""
    return domain.startswith('[') and domain.endswith(']')


_remove_quoted = re.compile(r'\\.').sub
_quotes = re.compile(r'["\\]')


def is_missing_quote(addr):
    """Return True iff mail address is not correctly quoted."""
    return _quotes.match(_remove_quoted("", addr[1:-1]))


# list of CGI keys to search for email addresses
EMAIL_CGI_ADDRESS = ("to", "cc", "bcc")
EMAIL_CGI_SUBJECT = "subject"


class MailtoUrl(urlbase.UrlBase):
    """
    Url link with mailto scheme.
    """

    def build_url(self):
        """Call super.build_url(), extract list of mail addresses from URL,
        and check their syntax.
        """
        super().build_url()
        self.addresses = set()
        self.subject = None
        self.parse_addresses()
        if self.addresses:
            for addr in sorted(self.addresses):
                self.check_email_syntax(addr)
                if not self.valid:
                    break
        elif not self.subject:
            self.add_warning(
                _("No mail addresses or email subject found in `%(url)s'.")
                % {"url": self.url}
            )

    def parse_addresses(self):
        """Parse all mail addresses out of the URL target. Also parses
        optional CGI headers like "?to=foo@example.org".
        Stores parsed addresses in the self.addresses set.
        """
        # cut off leading mailto: and unquote
        url = urllib.parse.unquote(self.base_url[7:], self.encoding)
        # search for cc, bcc, to and store in headers
        mode = 0  # 0=default, 1=quote, 2=esc
        quote = None
        i = 0
        for i, c in enumerate(url):
            if mode == 0:
                if c == '?':
                    break
                elif c in '<"':
                    quote = c
                    mode = 1
                elif c == '\\':
                    mode = 2
            elif mode == 1:
                if c == '"' and quote == '"':
                    mode = 0
                elif c == '>' and quote == '<':
                    mode = 0
            elif mode == 2:
                mode = 0
        if i < (len(url) - 1):
            self.addresses.update(getaddresses(url[:i]))
            try:
                headers = urllib.parse.parse_qs(url[(i + 1):], strict_parsing=True)
                for key, vals in headers.items():
                    if key.lower() in EMAIL_CGI_