1 |
|
2 |
|
3 |
|
4 |
|
5 |
|
6 |
|
7 |
|
8 |
|
9 |
|
10 |
|
11 |
|
12 |
|
13 |
|
14 |
|
15 |
|
16 |
|
17 |
|
18 |
|
19 |
|
20 |
|
21 |
|
22 |
|
23 |
|
24 |
|
25 |
|
26 |
|
27 |
|
28 |
|
29 |
|
30 | #ifdef WITH_SRV
|
31 | # include <ares.h>
|
32 |
|
33 | # include <arpa/nameser.h>
|
34 | # include <stdio.h>
|
35 | # include <string.h>
|
36 | #endif
|
37 |
|
38 | #include "logging_mosq.h"
|
39 | #include "memory_mosq.h"
|
40 | #include "mosquitto_internal.h"
|
41 | #include "mosquitto.h"
|
42 |
|
43 | #ifdef WITH_SRV
|
44 | static void srv_callback(void *arg, int status, int timeouts, unsigned char *abuf, int alen)
|
45 | {
|
46 | struct mosquitto *mosq = arg;
|
47 | struct ares_srv_reply *reply = NULL;
|
48 | if(status == ARES_SUCCESS){
|
49 | status = ares_parse_srv_reply(abuf, alen, &reply);
|
50 | if(status == ARES_SUCCESS){
|
51 |
|
52 | mosquitto_connect(mosq, reply->host, reply->port, mosq->keepalive);
|
53 | }
|
54 | }else{
|
55 | _mosquitto_log_printf(mosq, MOSQ_LOG_ERR, "Error: SRV lookup failed (%d).", status);
|
56 | exit(1);
|
57 | }
|
58 | }
|
59 | #endif
|
60 |
|
61 | int mosquitto_connect_srv(struct mosquitto *mosq, const char *host, int keepalive, const char *bind_address)
|
62 | {
|
63 | #ifdef WITH_SRV
|
64 | char *h;
|
65 | int rc;
|
66 | if(!mosq) return MOSQ_ERR_INVAL;
|
67 |
|
68 | rc = ares_init(&mosq->achan);
|
69 | if(rc != ARES_SUCCESS){
|
70 | return MOSQ_ERR_UNKNOWN;
|
71 | }
|
72 |
|
73 | if(!host){
|
74 |
|
75 | }else{
|
76 | #ifdef WITH_TLS
|
77 | if(mosq->tls_cafile || mosq->tls_capath || mosq->tls_psk){
|
78 | h = _mosquitto_malloc(strlen(host) + strlen("_secure-mqtt._tcp.") + 1);
|
79 | if(!h) return MOSQ_ERR_NOMEM;
|
80 | sprintf(h, "_secure-mqtt._tcp.%s", host);
|
81 | }else{
|
82 | #endif
|
83 | h = _mosquitto_malloc(strlen(host) + strlen("_mqtt._tcp.") + 1);
|
84 | if(!h) return MOSQ_ERR_NOMEM;
|
85 | sprintf(h, "_mqtt._tcp.%s", host);
|
86 | #ifdef WITH_TLS
|
87 | }
|
88 | #endif
|
89 | ares_search(mosq->achan, h, ns_c_in, ns_t_srv, srv_callback, mosq);
|
90 | _mosquitto_free(h);
|
91 | }
|
92 |
|
93 | pthread_mutex_lock(&mosq->state_mutex);
|
94 | mosq->state = mosq_cs_connect_srv;
|
95 | pthread_mutex_unlock(&mosq->state_mutex);
|
96 |
|
97 | mosq->keepalive = keepalive;
|
98 |
|
99 | return MOSQ_ERR_SUCCESS;
|
100 |
|
101 | #else
|
102 | return MOSQ_ERR_NOT_SUPPORTED;
|
103 | #endif
|
104 | }
|
105 |
|
106 |
|