Programming Tips - How do I use OpenSSL to turn an unencrypted connection into a secure one when doing STARTTLS ?

Date: 2010jan27 Library: OpenSSL Language: C/C++ Q. How do I use OpenSSL to turn an unencrypted connection into a secure one when doing STARTTLS ? A. This worked for me in an XMPP (Jabber) client that did that. But should be the same for POP3 or SMTP which also do STARTTLS.
bool become_secure(BIO* &bio, SSL* &ssl) { ssl = SSL_new(ctx); SSL_set_bio(ssl, bio, bio); SSL_set_connect_state(ssl); if (SSL_do_handshake(ssl) <= 0) return false; return true; } void example_use() { BIO *bio; SSL *ssl; create_a_bio_unencrypted_connection(bio); // Code not shown here send_starttls_command_to_server(bio); // Code not shown here become_secure(bio, ssl); // This function is above // Now, use ssl for the remainder of the session. // But do NOT free bio. send_password_and_have_rest_of_the_session(ssl); // Code not show here }