28 const char* cert_file,
31 *ssl_ctx = SSL_CTX_new(SSLv23_client_method());
35 if (!SSL_CTX_load_verify_locations(*ssl_ctx, ca_file, ca_path)) {
36 printf(
"error: failed to load ca certificate\n");
40 if (cert_file && key_file)
42 if (!SSL_CTX_use_certificate_file(*ssl_ctx, cert_file, SSL_FILETYPE_PEM))
44 printf(
"error: failed to load client certificate\n");
48 if (!SSL_CTX_use_PrivateKey_file(*ssl_ctx, key_file, SSL_FILETYPE_PEM))
50 printf(
"error: failed to load client key\n");
56 char * addr_copy = (
char*)malloc(strlen(addr) + 1);
57 strcpy(addr_copy,addr);
58 char * port_copy = (
char*)malloc(strlen(port) + 1);
59 strcpy(port_copy,port);
61 *bio = BIO_new_ssl_connect(*ssl_ctx);
62 BIO_get_ssl(*bio, &ssl);
63 SSL_set_mode(ssl, SSL_MODE_AUTO_RETRY);
64 BIO_set_conn_hostname(*bio, addr_copy);
65 BIO_set_nbio(*bio, 1);
66 BIO_set_conn_port(*bio, port_copy);
72 int start_time = (int)time(NULL);
73 int do_connect_rv = (int)BIO_do_connect(*bio);
74 while(do_connect_rv <= 0 && BIO_should_retry(*bio) && (int)time(NULL) - start_time < 10) {
75 do_connect_rv = (int)BIO_do_connect(*bio);
77 if (do_connect_rv <= 0) {
78 printf(
"error: %s\n", ERR_reason_error_string(ERR_get_error()));
80 SSL_CTX_free(*ssl_ctx);
87 if (SSL_get_verify_result(ssl) != X509_V_OK) {
89 printf(
"error: x509 certificate verification failed\n");
void open_nb_socket(BIO **bio, SSL_CTX **ssl_ctx, const char *addr, const char *port, const char *ca_file, const char *ca_path, const char *cert_file, const char *key_file)