// McpTlsProxy.h — MCP 端口的 TLS 前端(同端口嗅探:TLS 解密 / 明文直通) // // 背景:CMcpServer 用的 httplib::Server 是明文 HTTP。要让 MCP 客户端经公网用 https // 访问,又不引入 OpenSSL 依赖,这里在 MCP 前面加一层基于 Schannel 的 TLS 前端: // // 客户端 → :McpPort(本类)→ 127.0.0.1:<内部端口>(httplib) // // 首字节嗅探与设备端口(IOCPServer.cpp §5.2)同一套路:首字节 0x16 且次字节 0x03 // 视为 TLS ClientHello,走 ServerTlsSession 入站握手;否则按明文原样转发。因此本机 // 现有的 http://127.0.0.1:6544 用法不需要改动,远端可同时用 https。 // // 身份:独立于设备端口的 [tls] 证书(MCP 面向公网客户端,需公共 CA 证书), // 由 ServerTlsLoadIdentityFromPem 加载,CNG 键名 YamaMcpTlsKey,与设备端口互不覆盖。 #pragma once #include #include #include #include #include #include #include #include "ServerTlsSession.h" class ServerTlsSession; class McpTlsProxy { public: McpTlsProxy() {} ~McpTlsProxy() { Stop(); } McpTlsProxy(const McpTlsProxy&) = delete; McpTlsProxy& operator=(const McpTlsProxy&) = delete; // 监听 bind:listenPort,把解密后的字节转发到 127.0.0.1:backendPort。 // certPath/keyPath 为 PEM(证书 + PKCS#8 私钥)。任一环节失败返回 false(fail-closed)。 bool Start(const std::string& bind, int listenPort, int backendPort, const std::string& certPath, const std::string& keyPath); void Stop(); bool IsRunning() const { return m_running.load(); } private: // 单条前端连接:客户端套接字 + 连到 httplib 的后端套接字。 // Stop() 需要能打断正在 select/recv 的线程,故后端套接字放在原子量里随时可取。 struct Conn { std::atomic client{ INVALID_SOCKET }; std::atomic backend{ INVALID_SOCKET }; std::atomic done{ false }; std::thread th; }; void AcceptLoop(); void ServeConn(std::shared_ptr c); void PumpRaw(Conn& c); void PumpTls(Conn& c, ServerTlsSession& sess); void SweepFinished(); void CloseConn(Conn& c); static SOCKET ConnectLoopback(int port); static bool WaitReady(SOCKET sock, bool forRead, int timeoutMs); static bool SendAll(SOCKET sock, const void* data, int len); SOCKET m_listen = INVALID_SOCKET; std::thread m_acceptThread; std::atomic m_running{ false }; int m_backendPort = 0; ServerTlsExtraIdentity m_identity; bool m_identityLoaded = false; std::mutex m_connMtx; std::vector> m_conns; };