Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

boost::asio with SSL - problems after SSL error

I use synchronous boost::asio SSL sockets in my application. I initialize all parameters and then connect to some hosts (one after another) and do a GET request for each host.

Everything works until I get a "404 - Not Found" error for one of the hosts. After this error, all new connections fail with some unspecified SSL error.

Do I have to reset the ssl::stream somehow? Is it possible to re-initialize the ssl::stream after each connection?

In the following code snippets I removed error handling and all non asio related things.

Main:

asio::io_service ioservice;
asio::ssl::context ctx(ioservice, asio::ssl::context::sslv23);
ctx.set_verify_mode(asio::ssl::context::verify_none);

Connector *con = new Connector(ioservice, ctx);

while (!iplist.empty())
{
    ...
    con->ssl_connect(ipaddress, port);
    ...
}

Connector:

Connector::Connector(asio::io_service& io_service, asio::ssl::context &ctx) 
    : sslSock(io_service, ctx)
{
}

Connector::ssl_connect(std::string ipAdr, std::string port)
{
    ...
    tcp::resolver resolver(ioserv);
    tcp::resolver::query query(ipAdr, port);
    endpoint_iterator = resolver.resolve(query);
    ...

    asio::error_code errorcode = asio::error::host_not_found;
    tcp::resolver::iterator end;

    // Establish connection
    while (errorcode && endpoint_iterator != end)
    {
        sslSock.lowest_layer().close();
        sslSock.lowest_layer().connect(*endpoint_iterator++, errorcode);
    }
    sslSock.handshake(asio::ssl::stream_base::client, errorcode);
    ...
    asio::write(...);
    ...
    asio::read(...);
    ...
    sslSock.lowest_layer().close();
    ...
    return;
}
like image 879
mspoerr Avatar asked Jan 21 '23 03:01

mspoerr


1 Answers

I got the answer from the asio mailing list (many thanks to Marsh Ray). Sam Miller was correct in that the asio::ssl::context has to be created each time. To achieve this, std::auto_ptr is used.

Connector.h:

std::auto_ptr<asio::ssl::stream<tcp::socket>> sslSock;

Connector.cpp:

asio::ssl::context ctx(ioserv, asio::ssl::context::sslv23);
ctx.set_verify_mode(asio::ssl::context::verify_none);
sslSock.reset(new asio::ssl::stream<tcp::socket>(ioserv, ctx));
like image 108
mspoerr Avatar answered Jan 29 '23 05:01

mspoerr