ResponseCode OpenSSLConnection::ConnectInternal()

in network/OpenSSL/OpenSSLConnection.cpp [446:507]


        ResponseCode OpenSSLConnection::ConnectInternal() {
            ResponseCode networkResponse = ResponseCode::SUCCESS;
            const unsigned char alpn_protocol_list[] = {
                    14, 'x', '-', 'a', 'm', 'z', 'n', '-', 'm', 'q', 't', 't', '-', 'c', 'a'
            };
            const unsigned int alpn_protocol_list_length = sizeof(alpn_protocol_list);

            X509_VERIFY_PARAM *param = nullptr;

            if (!certificates_read_flag_) {
                networkResponse = LoadCerts();
                if (ResponseCode::SUCCESS != networkResponse) {
                    return networkResponse;
                }
            }

            if (nullptr == p_ssl_handle_) {
                p_ssl_handle_ = SSL_new(p_ssl_context_);
            }

            // Requires OpenSSL v1.0.2 and above
            if (server_verification_flag_) {
                param = SSL_get0_param(p_ssl_handle_);
                // Enable automatic hostname checks
                X509_VERIFY_PARAM_set_hostflags(param, X509_CHECK_FLAG_NO_PARTIAL_WILDCARDS);

                // Check if it is an IPv4 or an IPv6 address to enable ip checking
                // Enable host name check otherwise
                char dst[INET6_ADDRSTRLEN];
                if (inet_pton(AF_INET, endpoint_.c_str(), (void *) dst) ||
                    inet_pton(AF_INET6, endpoint_.c_str(), (void *) dst)) {
                    X509_VERIFY_PARAM_set1_ip_asc(param, endpoint_.c_str());
                } else {
                    X509_VERIFY_PARAM_set1_host(param, endpoint_.c_str(), 0);
                }
            }

            if (enable_alpn_) {
                if (0 != SSL_set_alpn_protos(p_ssl_handle_, alpn_protocol_list, alpn_protocol_list_length)) {
                    AWS_LOG_ERROR(OPENSSL_WRAPPER_LOG_TAG, " SSL INIT Failed - Unable to set ALPN options");
                    return ResponseCode::NETWORK_SSL_INIT_ERROR;
                }
            }

            networkResponse = PerformSSLConnect();
            if (ResponseCode::SUCCESS != networkResponse && address_family_ == AF_INET6) {
                // IPv6 connection unsucessful retry with IPv4
                address_family_ = AF_INET;
                networkResponse = PerformSSLConnect();
            }

            if (ResponseCode::SUCCESS != networkResponse) {
                SSL_free(p_ssl_handle_);
                p_ssl_handle_ = nullptr;
            }

            if (ResponseCode::SUCCESS == networkResponse) {
                is_connected_ = true;
            }

            return networkResponse;
        }