使用接口 mosquitto_tls_set 使客户端支持 SSL/TLS,接口说明:https://mosquitto.org/api/files/mosquitto-h.html#mosquitto_tls_set
int mosquitto_tls_set(struct mosquitto *mosq, const char *cafile, const char *capath, const char *certfile, const char *keyfile, int (*pw_callback)(char *buf, int size, int rwflag, void *userdata))
{
#ifdef WITH_TLS
FILE *fptr;
if(!mosq || (!cafile && !capath) || (certfile && !keyfile) || (!certfile && keyfile)) return MOSQ_ERR_INVAL;
mosquitto__free(mosq->tls_cafile);
mosq->tls_cafile = NULL;
if(cafile){
fptr = mosquitto__fopen(cafile, "rt", false);
if(fptr){
fclose(fptr);
}else{
return MOSQ_ERR_INVAL;
}
mosq->tls_cafile = mosquitto__strdup(cafile);
if(!mosq->tls_cafile){
return MOSQ_ERR_NOMEM;
}
}
mosquitto__free(mosq->tls_capath);
mosq->tls_capath = NULL;
if(capath){
mosq->tls_capath = mosquitto__strdup(capath);
if(!mosq->tls_capath){
return MOSQ_ERR_NOMEM;
}
}
mosquitto__free(mosq->tls_certfile);
mosq->tls_certfile = NULL;
if(certfile){
fptr = mosquitto__fopen(certfile, "rt", false);
if(fptr){
fclose(fptr);
}else{
mosquitto__free(mosq->tls_cafile);
mosq->tls_cafile = NULL;
mosquitto__free(mosq->tls_capath);
mosq->tls_capath = NULL;
return MOSQ_ERR_INVAL;
}
mosq->tls_certfile = mosquitto__strdup(certfile);
if(!mosq->tls_certfile){
return MOSQ_ERR_NOMEM;
}
}
mosquitto__free(mosq->tls_keyfile);
mosq->tls_keyfile = NULL;
if(keyfile){
fptr = mosquitto__fopen(keyfile, "rt", false);
if(fptr){
fclose(fptr);
}else{
mosquitto__free(mosq->tls_cafile);
mosq->tls_cafile = NULL;
mosquitto__free(mosq->tls_capath);
mosq->tls_capath = NULL;
mosquitto__free(mosq->tls_certfile);
mosq->tls_certfile = NULL;
return MOSQ_ERR_INVAL;
}
mosq->tls_keyfile = mosquitto__strdup(keyfile);
if(!mosq->tls_keyfile){
return MOSQ_ERR_NOMEM;
}
}
mosq->tls_pw_callback = pw_callback;
return MOSQ_ERR_SUCCESS;
#else
UNUSED(mosq);
UNUSED(cafile);
UNUSED(capath);
UNUSED(certfile);
UNUSED(keyfile);
UNUSED(pw_callback);
return MOSQ_ERR_NOT_SUPPORTED;
#endif
}
虽然目的是单向无证书验证,但是从源代码看,必须传入一个存在的 cafile ,我是自己创建了证书,这个是任意的,只是为了让函数返回正确状态。
接着配置SSL/TLS选项,不去验证服务器,否则肯定无法通过,使用接口mosquitto_tls_opts_set,第二参数传入 0即可,接口说明:https://mosquitto.org/api/files/mosquitto-h.html#mosquitto_tls_opts_set
总结:
在 mosquitto_connect 之前插入下面两句即可:
mosquitto_tls_set(mosq,"/userdata/server.crt",NULL,NULL,NULL,NULL);
mosquitto_tls_opts_set(mosq,0,NULL,NULL);