aws-iot-device-sdk-cpp-v2: AWS_ERROR_SYS_CALL_FAILURE when building the MqttClientConnectionConfigBuilder

Describe the bug

Hi, I’m upgrading our thing’s SDK version from 1 to 2 and trying to set up the MQTT Client connection similar to the pub sub sample. We are getting the client config ready with the following:

  • Certificate and private key (sent as byte cursors)
  • Endpoint
  • Root certificate (sent as byte cursors) I might have a problem with function.

Aws::Iot::MqttClientConnectionConfigBuilder::Build() On debugging and stepping into the build function, we found it errors out here:

auto tlsContext = Crt::Io::TlsContext(m_contextOptions, Crt::Io::TlsMode::CLIENT, m_allocator);

            if (!tlsContext)

            {

                return MqttClientConnectionConfig::CreateInvalid(tlsContext.GetInitializationError());

            }

We dont use BYO_CRYPTO and Metrics collection is set to false. We stepped into the TLSOptions.cpp to see what is the exact error and here is where we get AWS_ERROR_SYS_CALL_FAILURE:

 if (mode == TlsMode::CLIENT)
                {
                    aws_tls_ctx *underlying_tls_ctx = aws_tls_client_ctx_new(allocator, &options.m_options);
                    if (underlying_tls_ctx != nullptr)
                    {
                        m_ctx.reset(underlying_tls_ctx, aws_tls_ctx_release);
                    }
                }
                else
                {
                    aws_tls_ctx *underlying_tls_ctx = aws_tls_server_ctx_new(allocator, &options.m_options);
                    if (underlying_tls_ctx != nullptr)
                    {
                        m_ctx.reset(underlying_tls_ctx, aws_tls_ctx_release);
                    }
                }
                if (!m_ctx)
                {
                    m_initializationError = Aws::Crt::LastErrorOrUnknown();
                }

the mode is CLIENT but it never enters m_ctx.reset(), we get an error with code 46 in the last if block for checking m_ctx. Can you please advise? thanks

Expected Behavior

I expected the MQTTClientCOnfigBuilder to build successfully and establish a TLS connection

Current Behavior

On building the MQTTClientCOnfigBuilder using the build(), it errors out with AWS_ERROR_SYS_CALL_FAILURE.

Reproduction Steps

Here’s the code snippet for the MQTT connection for our device:

IMqttClient::ResponseCode MqttClient::Connect(const string &endpoint, const vector<uint8_t> &privateKey,
   const vector<uint8_t> &certificate, const string &clientId, const boost::shared_ptr<LastWill_t> &lastWill,
   const Time &timeout)
{
   // Do the global initialization for the API move to MQTTInitilization
   ApiHandle apiHandle;
   ResponseCode result = MQTT_SUCCESS;
   Aws::Crt::String cert_pem = convertDerToPem(certificate);
   Aws::Crt::String key_pem = convertPrivateKeyDerToPem(privateKey);
   // convert certificate using ByteCursorFromString
   ByteCursor cert_b = ByteCursorFromString(cert_pem);
   ByteCursor key_b = ByteCursorFromString(key_pem);
   ByteCursor root_b = ByteCursorFromCString(ROOT_CERTIFICATES);
   auto stdTimeout = milliseconds(timeout.Convert(Time::MILLISECONDS));
      if (!m_certificate->Exists() || !m_key->Exists() || !m_root_certificates->Exists())
   {
      return MQTT_FAILURE;
   }


   // Create the MQTT builder and populate it
   Aws::Iot::MqttClientConnectionConfigBuilder clientConfigBuilder(cert_b, key_b);
   clientConfigBuilder.WithEndpoint(endpoint.c_str());
   clientConfigBuilder.WithMetricsCollection(false);
   // override port
  // clientConfigBuilder.WithPortOverride(443);
   clientConfigBuilder.WithCertificateAuthority(root_b);
   boost::optional<Aws::Iot::MqttClientConnectionConfig> clientConfig = clientConfigBuilder.Build();

   if (!clientConfig.get())
   {
      fprintf(
         stderr,
         "Client Configuration initialization failed with error %s\n",
         Aws::Crt::ErrorDebugString(clientConfig.get().LastError()));
      return MQTT_FAILURE;
   }
   Aws::Iot::MqttClient client = Aws::Iot::MqttClient();
   auto connection = client.NewConnection(clientConfig.get());
   if (!*connection)
   {
      fprintf(stderr, "Connection creation failed with error %s\n", Aws::Crt::ErrorDebugString(connection->LastError()));
      return MQTT_FAILURE;
   }        
  

   if(lastWill != nullptr)
   {
      
      bool retained = lastWill->retained;
      IOT::IMqttClient::QoS qos = lastWill->qos;
      const char* topic = lastWill->topic.c_str();
      Aws::Crt::ByteBuf payload = Aws::Crt::ByteBufFromArray(lastWill->payload.data(), lastWill->payload.size() );
      connection->SetWill(topic, ConvertFromQos(qos), retained, payload);
   }
std::promise<bool> connectionCompletedPromise;
 // Invoke when MQTT connection was interrupted
 auto onInterrupted = [&](Aws::Crt::Mqtt::MqttConnection &, int error) {
    //fprintf(stdout, "Connection interrupted with error %s\n", Aws::Crt::ErrorDebugString(error));
    HandleDisconnect(error);

 };
 // Invoked when a MQTT connection was interrupted/lost, but then reconnected successfully
    auto onResumed = [&](Aws::Crt::Mqtt::MqttConnection &, Aws::Crt::Mqtt::ReturnCode, bool) {
      result =  MQTT_SUCCESS;
    };

 // Invoked when a MQTT connect has completed or failed
 auto onConnectionCompleted =
        [&](Aws::Crt::Mqtt::MqttConnection &, int errorCode, Aws::Crt::Mqtt::ReturnCode returnCode, bool) {
            if (errorCode == AWS_ERROR_SUCCESS && returnCode == AWS_MQTT_CONNECT_ACCEPTED)
            {
              
                connectionCompletedPromise.set_value(true);
            }
            else
            {
              
                connectionCompletedPromise.set_value(false);
            }
        };
  // Assign callbacks
   connection->OnConnectionInterrupted = std::move(onInterrupted);
   connection->OnConnectionResumed = std::move(onResumed);
 connection->OnConnectionCompleted = std::move(onConnectionCompleted);

   
// connect 
  
   if(!connection->Connect(clientId.c_str(), true, uint16_t(stdTimeout.count())))
   {
      printf("Failed to connect\n");
      return MQTT_FAILURE;
   }
   
 // wait for the OnConnectionCompleted callback to fire, which sets connectionCompletedPromise...
   if (connectionCompletedPromise.get_future().wait_for(stdTimeout) != std::future_status::ready)
   {
      printf("Timed out waiting for connection\n");
      return MQTT_FAILURE;
   }
    if (connectionCompletedPromise.get_future().get() == false)
    {
        fprintf(stderr, "Connection failed\n");
      return MQTT_FAILURE;
    }
  if (result != MQTT_SUCCESS)
  {
 
   connection->Disconnect();

  }


   return result;
}

Error is thrown in this segment:

boost::optional<Aws::Iot::MqttClientConnectionConfig> clientConfig = clientConfigBuilder.Build();
   if (!clientConfig.get())
   {
      fprintf(
         stderr,
         "Client Configuration initialization failed with error %s\n",
         Aws::Crt::ErrorDebugString(clientConfig.get().LastError()));
      return MQTT_FAILURE;
   }


Possible Solution

No response

Additional Information/Context

No response

SDK version used

2

Environment details (OS name and version, etc.)

Windows

About this issue

  • Original URL
  • State: closed
  • Created 3 years ago
  • Comments: 15 (3 by maintainers)

Most upvoted comments

Hello @sweta98 ,

Thank you very much for providing this information. We do support for Windows ECC key import (see PR).

I’ll bring this up to the team, this is unexpected behavior. Thank you very much for your time and collaboration.

Sincerely,

Yasmine

Hello @sweta98 ,

Thank you very much for your submission.

From a first guess, I think this might be an issue with the way you are providing certificate.

Could you please provide the following information:

  1. The log associated with the behavior. To enable the log, you will need to call InitializeLogging. You can look at our integration test for a good example of how this function works.

  2. SDK version being used (I am assuming that you are using the latest version of the aws-iot-device-sdk-cpp-v2 released as of today: v1.24.3) In the meantime, I’ll attempt to reproduce the issue.

Thank you very much for your time and collaboration. Sincerely, Best regards,

Yasmine