python / python/cpython

logging: `SMTPHandler.emit()` leaks the SMTP connection when sending fails

オープン
#155,946 コメント 0 件 リアクション 0 件 担当者 0 名 GitHub で見る

まだ誰も着手していません。

stdlib type-bug
主要言語
Python
スター
77.2k
フォーク
35.9k
PR マージ指標
PR 指標を取得中

説明

Bug report

Bug description:

SMTPHandler.emit() only closes its SMTP connection on the success path: smtp.quit() is the last statement of the try block (Lib/logging/handlers.py#L1109-L1154).

If starttls(), login() or send_message() raises, control jumps to except Exception: self.handleError(record) and the connection is never closed — cleanup is left to the garbage collector.

Reproducer
import gc, logging, logging.handlers, socket, threading, time

logging.raiseExceptions = False
open_conns = []

def handle(conn):
    conn.sendall(b"220 fake ESMTP\r\n")
    for line in conn.makefile("rb"):
        cmd = line.strip().upper()
        if cmd.startswith(b"EHLO"):
            conn.sendall(b"250-fake\r\n250 AUTH PLAIN LOGIN\r\n")
        elif cmd.startswith(b"AUTH"):
            conn.sendall(b"535 authentication failed\r\n")
        else:
            conn.sendall(b"250 ok\r\n")
    open_conns.remove(conn)  # reached when the client closes the connection
    conn.close()

def serve(listener):
    while True:
        conn, _ = listener.accept()
        open_conns.append(conn)
        threading.Thread(target=handle, args=(conn,), daemon=True).start()

listener = socket.create_server(("127.0.0.1", 0))
threading.Thread(target=serve, args=(listener,), daemon=True).start()

h = logging.handlers.SMTPHandler(("127.0.0.1", listener.getsockname()[1]),
                                 "me@example.com", "you@example.com", "subject",
                                 credentials=("user", "wrong-password"))
for i in range(5):
    h.emit(logging.makeLogRecord({"msg": "hello"}))  # SMTPAuthenticationError
time.sleep(0.5)
print("open connections after 5 failed emits:", len(open_conns))
gc.collect(); time.sleep(0.5)
print("after gc.collect():", len(open_conns))

Output on main:

open connections after 5 failed emits: 5
after gc.collect(): 0
CPython versions tested on:

CPython main branch

Operating systems tested on:

macOS

Linked PRs
  • gh-155950

コントリビューションガイド

コントリビューションガイドを開く

はじめの一歩

  1. issue を最後まで読み、次にプロジェクトのコントリビューションガイドを読みます。
  2. 着手することを issue にコメントします — 二人が同じ作業をするのを防げます。
  3. リポジトリをフォークし、ブランチを切って変更します。
  4. issue 番号を参照したプルリクエストを送ります。

調査の方向性

Lib/logging/handlers.py の SMTPHandler.emit() から始め、提供されている認証失敗の再現手順を実行してください。starttls()、login()、または send_message() が失敗するパスで SMTP 接続が開いたままにならなくなり、再現手順に対して動作が確認できれば完了です。リンクされている PR gh-155950 は、すでに作業が進行中であることを示しています。

索引モデルが issue の本文から書いたものです。

評価

技術スタック
python
領域
backend
issue の種類
バグ
難易度
2/5
見積もり時間
1〜3時間
活発さ
停滞
明瞭さ
明確に書かれている
初心者へのやさしさ
25/100

新しい issue をメールで受け取る

初心者向けの GitHub issue を短くまとめたダイジェスト。