Search code examples
c++httpsopensslboost-beast

Beast SSL Connection Graceful Shutdown


I am implementing an HTTPS client that tries to read information from the server. During its work the shutdown can be requested. It can be expresses in the following code:

        http::async_read( stream_, buffer_, res_,
                          beast::bind_front_handler(
                                  &session::on_read,
                                  shared_from_this()));
        beast::get_lowest_layer( stream_ ).cancel();

As soon as the read is cancelled (on_read is called with operation cancel error) I call

stream_.async_shutdown([t = shared_from_this()] ( beast::error_code ec ) {
            t->on_shutdown(ec);
        });

The shutdown finishes with the following error:

application data after close notify

The question is whether it is safe to ignore this error?


Solution

  • You can ignore this error. It happens if a server sends data concurrently - started sending an application data chunk asynchronousely right before has received close notify.

    stream_.async_shutdown([t = shared_from_this()] ( beast::error_code ec ) {
        if (ec ...)  // add proper condition here
            ec = beast::error_code(success);
        t->on_shutdown(ec);
    });
    

    I would also add some flag to session and set it before cancel, so session::on_read is not unexpected, can be ignored after shutdown.