50
  /   ˆ{‹„„-i[D<†ªoZƒ›Ù«Ä491_‘I|¥‰ÓMdœv ©ƒ†ü+=ÃÂ ë    ‹      ¥”O�Ú0Åïû)¦>ôF†úG¬“jK�ŠÊb©ªªêÁ‰MlmbG¶YÊ~úB»´‚–UO™8ožßo‡¾HgÃå—ù>,o'0ÿô~2é ~îÓeÚ>èÝq4%@¤÷õ q³Ù›^`l�ËJ_•}tÞªÜÜs’\ÑÝZrT
Æ›+P¯|)’±æâ;˜ Y{§¸èãÚYt’Y�ÜäXËúmu*£Ã3Šm[c„'š¾Ým>ß¬éÙGaÙÞsWÚ„z	¬T…Ž‰75I¨ª
p6�	ªÜh‡YÉô}P¨Vú˜|gßz¹ëN(iÅ*&ï†ñôzß�dÊ*A‘�ÖÜ¶š	s*ÃÕJ	~V|×ˆS’Ü©Çó†ik˜
—[U{eô“ÄcÔÜ”®fë«†@ÚcU+áÿšËÆüf1š.Óñ¢	ßY<¥;÷jH2oJí!UVäÞØí!rÛÿRg®¾þy‡@VÒ“ '•Ï ÈMU[áœàÇ,ÍœNRä’éB”¦R‘)¦ƒâ‘$'�þu£×�0ìD!„ýA/8'Þ|ü_ºµ¾×f£/B3õö°ó¯òBŒî Û?‹aôŒ?H<UŠûSO±ý­ü M#g“¹    C   ˆl–äY>”JeJe@†à¸Û*bÑ¿�þZd¬Ü¡p¬ˆ$‘¦�üÿÇ„¡m¿Æ_ŠI|¥�+Wé3ž¯ÅÄ ?÷     # mail.py - mail sending bits for mercurial
#
# Copyright 2006 Olivia Mackall <olivia@selenic.com>
#
# This software may be used and distributed according to the terms of the
# GNU General Public License version 2 or any later version.


import email
import email.charset
import email.generator
import email.header
import email.message
import email.parser
import io
import os
import smtplib
import socket
import time

from .i18n import _
from .pycompat import (
    getattr,
    open,
)
from . import (
    encoding,
    error,
    pycompat,
    sslutil,
    util,
)
from .utils import (
    procutil,
    stringutil,
    urlutil,
)

if pycompat.TYPE_CHECKING:
    from typing import Any, List, Tuple, Union

    # keep pyflakes happy
    assert all((Any, List, Tuple, Union))


class STARTTLS(smtplib.SMTP):
    """Derived class to verify the peer certificate for STARTTLS.

    This class allows to pass any keyword arguments to SSL socket creation.
    """

    def __init__(self, ui, host=None, **kwargs):
        smtplib.SMTP.__init__(self, **kwargs)
        self._ui = ui
        self._host = host

    def starttls(self, keyfile=None, certfile=None):
        if not self.has_extn("starttls"):
            msg = b"STARTTLS extension not supported by server"
            raise smtplib.SMTPException(msg)
        (resp, reply) = self.docmd("STARTTLS")
        if resp == 220:
            self.sock = sslutil.wrapsocket(
                self.sock,
                keyfile,
                certfile,
                ui=self._ui,
                serverhostname=self._host,
            )
            self.file = self.sock.makefile("rb")
            self.helo_resp = None
            self.ehlo_resp = None
            self.esmtp_features = {}
            self.does_esmtp = 0
        return (resp, reply)


class SMTPS(smtplib.SMTP):
    """Derived class to verify the peer certificate for SMTPS.

    This class allows to pass any keyword arguments to SSL socket creation.
    """

    def __init__(self, ui, keyfile=None, certfile=None, host=None, **kwargs):
        self.keyfile = keyfile
        self.certfile = certfile
        smtplib.SMTP.__init__(self, **kwargs)
        self._host = host
        self.default_port = smtplib.SMTP_SSL_PORT
        self._ui = ui

    def _get_socket(self, host, port, timeout):
        if self.debuglevel > 0:
            self._ui.debug(b'connect: %r\n' % ((host, port),))
        new_socket = socket.create_connection((host, port), timeout)
        new_socket = sslutil.wrapsocket(
            new_socket,
            self.keyfile,
            self.certfile,
            ui=self._ui,
            serverhostname=self._host,
        )
        self.file = new_socket.makefile('rb')
        return new_socket


def _pyhastls():
    # type: () -> bool
    """Returns true iff Python has TLS support, false otherwise."""
    try:
        import ssl

        getattr(ssl, 'HAS_TLS', False)
        return True
    except ImportError:
        return False


def _smtp(ui):
    '''build an smtp connection and return a function to send mail'''
    local_hostname = ui.config(b'smtp', b'local_hostname')
    tls = ui.config(b'smtp', b'tls')
    # backward compatible: when tls = true, we use starttls.
    starttls = tls == b'starttls' or stringutil.parsebool(tls)
    smtps = tls == b'smtps'
    if (starttls or smtps) and not _pyhastls():
        raise error.Abort(_(b"can't use TLS: Python SSL support not installed"))
 