66 const char *ca_file) {
67 const unsigned char *additional = (
const unsigned char *)
"MQTT-C";
68 size_t additional_len = 6;
71 mbedtls_net_context *net_ctx = &ctx->
net_ctx;
72 mbedtls_ssl_context *ssl_ctx = &ctx->
ssl_ctx;
73 mbedtls_ssl_config *ssl_conf = &ctx->
ssl_conf;
74 mbedtls_x509_crt *ca_crt = &ctx->
ca_crt;
75 mbedtls_entropy_context *entropy = &ctx->
entropy;
76 mbedtls_ctr_drbg_context *ctr_drbg = &ctx->
ctr_drbg;
78 mbedtls_entropy_init(entropy);
79 mbedtls_ctr_drbg_init(ctr_drbg);
80 rv = mbedtls_ctr_drbg_seed(ctr_drbg, mbedtls_entropy_func, entropy,
81 additional, additional_len);
83 failed(
"mbedtls_ctr_drbg_seed", rv);
86 mbedtls_x509_crt_init(ca_crt);
87 rv = mbedtls_x509_crt_parse_file(ca_crt, ca_file);
89 failed(
"mbedtls_x509_crt_parse_file", rv);
92 mbedtls_ssl_config_init(ssl_conf);
93 rv = mbedtls_ssl_config_defaults(ssl_conf, MBEDTLS_SSL_IS_CLIENT,
94 MBEDTLS_SSL_TRANSPORT_STREAM,
95 MBEDTLS_SSL_PRESET_DEFAULT);
97 failed(
"mbedtls_ssl_config_defaults", rv);
99 mbedtls_ssl_conf_ca_chain(ssl_conf, ca_crt, NULL);
100 mbedtls_ssl_conf_authmode(ssl_conf, MBEDTLS_SSL_VERIFY_OPTIONAL);
101 mbedtls_ssl_conf_rng(ssl_conf, mbedtls_ctr_drbg_random, ctr_drbg);
103 mbedtls_net_init(net_ctx);
104 rv = mbedtls_net_connect(net_ctx, hostname, port, MBEDTLS_NET_PROTO_TCP);
106 failed(
"mbedtls_net_connect", rv);
108 rv = mbedtls_net_set_nonblock(net_ctx);
110 failed(
"mbedtls_net_set_nonblock", rv);
113 mbedtls_ssl_init(ssl_ctx);
114 rv = mbedtls_ssl_setup(ssl_ctx, ssl_conf);
116 failed(
"mbedtls_ssl_setup", rv);
118 rv = mbedtls_ssl_set_hostname(ssl_ctx, hostname);
120 failed(
"mbedtls_ssl_set_hostname", rv);
122 mbedtls_ssl_set_bio(ssl_ctx, net_ctx,
123 mbedtls_net_send, mbedtls_net_recv, NULL);
126 rv = mbedtls_ssl_handshake(ssl_ctx);
128 if (rv == MBEDTLS_ERR_SSL_WANT_READ) {
130 }
else if (rv == MBEDTLS_ERR_SSL_WANT_WRITE) {
137 failed(
"mbedtls_net_poll", rv);
141 failed(
"mbedtls_ssl_handshake", rv);
143 uint32_t result = mbedtls_ssl_get_verify_result(ssl_ctx);
145 if (result == (uint32_t)-1) {
146 failed(
"mbedtls_ssl_get_verify_result", (
int)result);
mbedtls_ssl_context ssl_ctx
mbedtls_entropy_context entropy
mbedtls_ctr_drbg_context ctr_drbg
mbedtls_net_context net_ctx
mbedtls_ssl_config ssl_conf