【问题标题】:Is it possible to do async_handshake after reading from socket prior using Boost::asio?在使用 Boost::asio 之前从套接字读取后是否可以执行 async_handshake?
【发布时间】:2019-04-19 18:04:27
【问题描述】:

我有一个boost::asio::ssl::stream<boost::asio::ip::tcp::socket> 类型的套接字。当 boost 第一次接受到这个套接字的连接时,我想看看一些字节。但是,偷看不是您可以正确/安全地进行的事情。所以我读取了我需要的字节并将它们放在缓冲区中。

typedef socket_type boost::asio::ssl::stream<boost::asio::ip::tcp::socket>;
void OnAccept(std::shared_ptr<socket_type> socket)
{
    boost::asio::mutable_buffers_1 sslBuffer(m_Buffer.data(), m_Buffer.size());
    // I'm going to read 4 bytes from the socket.
    boost::system::error_code ec;
    std::size_t readBytes = boost::asio::read(socket->next_layer(), boost::asio::buffer(sslBuffer, 4), ec);
    if(ec) { Stop(); return; } // pseudo

    // Check the bytes I read in the buffer

    socket->async_handshake(boost::asio::ssl::stream_base::server, sslBuffer, &handler);
}

此时,async_handshake 的处理程序将被调用,但它会告诉我它从 ssl 获得了一个 unexpected message 错误代码。这是有道理的:与它进行握手的消息可能缺少前 4 个字节!

我可以做些什么来为async_handshake 提供适当的缓冲区,通知它其中已经有有效的 4 个字节?

【问题讨论】:

    标签: c++ ssl boost


    【解决方案1】:

    调查了async_handshake的buffer重载方法的实现,看来buffer肯定已经有握手读入了。

    我尝试过,但仍然遇到问题,我不断收到错误代码,提示 SSL 版本不正确。我知道这不是问题,因为不使用 async_handshake 的缓冲重载效果很好!

    解决方案是同时限制缓冲区参数的大小。

    typedef socket_type boost::asio::ssl::stream<boost::asio::ip::tcp::socket>;
    void OnAccept(std::shared_ptr<socket_type> socket)
    {
        const uint bytesToPeek = 4;
        boost::asio::mutable_buffers_1 sslBuffer(m_Buffer.data(), m_Buffer.size());
        // I'm going to read 4 bytes from the socket.
        boost::system::error_code ec;
        std::size_t readBytes = boost::asio::read(socket->next_layer(), boost::asio::buffer(sslBuffer, bytesToPeek), ec);
        if(ec) { Stop(); return; } // pseudo
    
        // Check the bytes I read in the buffer
    
        // Read in the rest of the handshake.
        std::size_t bytesOfHandshake = socket->next_layer().read_some(boost::asio::buffer(sslBuffer+bytesToPeek, 4000));
        bytesOfHandshake += bytesToPeek;
    
        // Finish the handshake.
        socket->async_handshake(boost::asio::ssl::stream_base::server, boost::asio::buffer(sslBuffer, bytesOfHandshake), &handler);
    }
    

    请注意,这里的readread_some 调用也应该是async。我只是想在没有处理程序的情况下演示答案。

    【讨论】:

    猜你喜欢
    • 2019-03-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-02-19
    • 2021-12-04
    • 1970-01-01
    • 2012-01-16
    相关资源
    最近更新 更多