"""Offline network protocol verification lab for Chapter 09 (smtp-protocol)."""
import base64
import json
VERSION = "CPython 3.12.14 offline network protocol frame & state-machine verifier"
def case_smtp_envelope_and_data_fsm():
state = "GREET"
codes = [220]
envelope = {"from": None, "rcpts": [], "body": []}
transcript = [
"EHLO mail.sender.example",
"MAIL FROM:<alice@sender.example>",
"RCPT TO:<bob@receiver.example>",
"DATA",
"Subject: Protocol Test",
"",
"Hello Bob!",
".",
"QUIT",
]
for line in transcript:
if state == "DATA_BODY":
if line == ".":
state = "READY"
codes.append(250)
else:
envelope["body"].append(line)
continue
upper = line.upper()
if upper.startswith("EHLO ") or upper.startswith("HELO "):
state = "READY"
codes.append(250)
elif upper.startswith("MAIL FROM:") and state == "READY":
envelope["from"] = line[10:].strip("<>")
state = "MAIL"
codes.append(250)
elif upper.startswith("RCPT TO:") and state in ("MAIL", "RCPT"):
envelope["rcpts"].append(line[8:].strip("<>"))
state = "RCPT"
codes.append(250)
elif upper == "DATA" and state == "RCPT":
state = "DATA_BODY"
codes.append(354)
elif upper == "QUIT":
state = "CLOSED"
codes.append(221)
expected = {
"reply_codes": [220, 250, 250, 250, 354, 250, 221],
"mail_from": "alice@sender.example",
"rcpt_to": ["bob@receiver.example"],
"body_lines": 3,
"final_state": "CLOSED",
}
actual = {
"reply_codes": codes,
"mail_from": envelope["from"],
"rcpt_to": envelope["rcpts"],
"body_lines": len(envelope["body"]),
"final_state": state,
}
return {
"name": "smtp_envelope_and_data_fsm",
"summary": "模拟 RFC 5321 SMTP 25 端口 EHLO/MAIL FROM/RCPT TO/DATA/./QUIT 完整信封状态机",
"expected": expected,
"actual": actual,
"passed": actual == expected,
}
def case_smtp_dot_stuffing_codec():
# RFC 5321 Section 4.5.2 Transparency: leading '.' in body lines is doubled on wire
orig_lines = ["Line 1", ".hidden-dot-line", "..double-dot", "End"]
wire_lines = [("." + ln if ln.startswith(".") else ln) for ln in orig_lines] + ["."]
# Receiver stops at lone '.' and removes one leading '.' from stuffed lines
recovered = []
for ln in wire_lines:
if ln == ".":
break
recovered.append(ln[1:] if ln.startswith("..") else ln)
expected = {
"wire_stuffed_second_line": "..hidden-dot-line",
"wire_stuffed_third_line": "...double-dot",
"recovered_matches_original": True,
}
actual = {
"wire_stuffed_second_line": wire_lines[1],
"wire_stuffed_third_line": wire_lines[2],
"recovered_matches_original": recovered == orig_lines,
}
return {
"name": "smtp_dot_stuffing_codec",
"summary": "校验 SMTP DATA 阶段点填充(Dot-Stuffing)编码与接收端还原,防止正文句点误触发终止",
"expected": expected,
"actual": actual,
"passed": actual == expected,
}
def case_smtp_ehlo_starttls_and_auth_plain():
ehlo_resp = [
"250-smtp.example.com Hello",
"250-SIZE 35882577",
"250-STARTTLS",
"250 AUTH PLAIN LOGIN",
]
caps = {}
for line in ehlo_resp[1:]:
body = line[4:]
kw, _, val = body.partition(" ")
caps[kw] = val or True
# RFC 4616 AUTH PLAIN: base64(\x00authcid\x00passwd)
token = base64.b64encode(b"\x00alice\x00secret").decode("ascii")
decoded_parts = base64.b64decode(token).split(b"\x00")
expected = {
"supports_starttls": True,
"auth_mechs": ["PLAIN", "LOGIN"],
"auth_plain_user": "alice",
"max_size_bytes": 35882577,
}
actual = {
"supports_starttls": "STARTTLS" in caps,
"auth_mechs": caps["AUTH"].split(),
"auth_plain_user": decoded_parts[1].decode("ascii"),
"max_size_bytes": int(caps["SIZE"]),
}
return {
"name": "smtp_ehlo_starttls_and_auth_plain",
"summary": "解析 EHLO 多行扩展能力通告(STARTTLS/SIZE/AUTH)并校验 AUTH PLAIN Base64 编码格式",
"expected": expected,
"actual": actual,
"passed": actual == expected,
}
def case_smtp_reply_code_classification():
samples = {
220: "2xx_positive_completion",
354: "3xx_positive_intermediate",
421: "4xx_transient_negative_retry",
550: "5xx_permanent_negative_reject",
}
def classify(code):
cls = code // 100
return {
2: "2xx_positive_completion",
3: "3xx_positive_intermediate",
4: "4xx_transient_negative_retry",
5: "5xx_permanent_negative_reject",
}[cls]
actual = {str(k): classify(k) for k in samples}
expected = {str(k): v for k, v in samples.items()}
return {
"name": "smtp_reply_code_classification",
"summary": "验证 SMTP 三位数字状态码百位分类规则(成功、中间态、临时退信重试、永久拒绝)",
"expected": expected,
"actual": actual,
"passed": actual == expected,
}
def main():
cases = [
case_smtp_envelope_and_data_fsm(),
case_smtp_dot_stuffing_codec(),
case_smtp_ehlo_starttls_and_auth_plain(),
case_smtp_reply_code_classification(),
]
print(json.dumps({"version": VERSION, "cases": cases}, ensure_ascii=False, indent=2))
if __name__ == "__main__":
main()
本例需在 Windows x64、CPython 3.12.14 离线网络协议帧编解码与状态机验证脚本(纯本地内存执行,未发起外部网络连接)。 中运行,请复制源码、保存文件或下载工程包后在本地执行验证。
运行说明与环境独立工程
运行环境:Windows x64、CPython 3.12.14 离线网络协议帧编解码与状态机验证脚本(纯本地内存执行,未发起外部网络连接)。
入口文件:projects/np-smtp-protocol-lab/explore-smtp-protocol.py
本地运行步骤快速上手
- 点击上方“保存源码”保存为
explore-smtp-protocol.py,或下载右侧课程工程包。 - 确认本地已准备 Windows x64、CPython 3.12.14 离线网络协议帧编解码与状态机验证脚本(纯本地内存执行,未发起外部网络连接)。。
- 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载
课程关联工程包(登记关联29章) · 含当前章节或实例 · mbskycom202612a2722.zip
课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a2744.zip