Debian Codegraph @

extra/curl/curl-8.14.1/lib/mqtt.c

raw symbols SCIP
1 /***************************************************************************
2 * _ _ ____ _
3 * Project ___| | | | _ \| |
4 * / __| | | | |_) | |
5 * | (__| |_| | _ <| |___
6 * \___|\___/|_| \_\_____|
7 *
8 * Copyright (C) Daniel Stenberg, <[email protected]>, et al.
9 * Copyright (C) Björn Stenberg, <[email protected]>
10 *
11 * This software is licensed as described in the file COPYING, which
12 * you should have received as part of this distribution. The terms
13 * are also available at https://curl.se/docs/copyright.html.
14 *
15 * You may opt to use, copy, modify, merge, publish, distribute and/or sell
16 * copies of the Software, and permit persons to whom the Software is
17 * furnished to do so, under the terms of the COPYING file.
18 *
19 * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
20 * KIND, either express or implied.
21 *
22 * SPDX-License-Identifier: curl
23 *
24 ***************************************************************************/
25
26 #include "curl_setup.h"
27
28 #ifndef CURL_DISABLE_MQTT
29
30 #include "urldata.h"
31 #include <curl/curl.h>
32 #include "transfer.h"
33 #include "sendf.h"
34 #include "progress.h"
35 #include "mqtt.h"
36 #include "select.h"
37 #include "strdup.h"
38 #include "url.h"
39 #include "escape.h"
40 #include "curlx/warnless.h"
41 #include "curl_printf.h"
42 #include "curl_memory.h"
43 #include "multiif.h"
44 #include "rand.h"
45
46 /* The last #include file should be: */
47 #include "memdebug.h"
48
49 /* first byte is command.
50 second byte is for flags. */
51 #define MQTT_MSG_CONNECT 0x10
52 /* #define MQTT_MSG_CONNACK 0x20 */
53 #define MQTT_MSG_PUBLISH 0x30
54 #define MQTT_MSG_SUBSCRIBE 0x82
55 #define MQTT_MSG_SUBACK 0x90
56 #define MQTT_MSG_DISCONNECT 0xe0
57 #define MQTT_MSG_PINGREQ 0xC0
58 #define MQTT_MSG_PINGRESP 0xD0
59
60 #define MQTT_CONNACK_LEN 2
61 #define MQTT_SUBACK_LEN 3
62 #define MQTT_CLIENTID_LEN 12 /* "curl0123abcd" */
63
64 /* meta key for storing protocol meta at easy handle */
65 #define CURL_META_MQTT_EASY "meta:proto:mqtt:easy"
66 /* meta key for storing protocol meta at connection */
67 #define CURL_META_MQTT_CONN "meta:proto:mqtt:conn"
68
69 enum mqttstate {
70 MQTT_FIRST, /* 0 */
71 MQTT_REMAINING_LENGTH, /* 1 */
72 MQTT_CONNACK, /* 2 */
73 MQTT_SUBACK, /* 3 */
74 MQTT_SUBACK_COMING, /* 4 - the SUBACK remainder */
75 MQTT_PUBWAIT, /* 5 - wait for publish */
76 MQTT_PUB_REMAIN, /* 6 - wait for the remainder of the publish */
77
78 MQTT_NOSTATE /* 7 - never used an actual state */
79 };
80
81 struct mqtt_conn {
82 enum mqttstate state;
83 enum mqttstate nextstate; /* switch to this after remaining length is
84 done */
85 unsigned int packetid;
86 };
87
88 /* protocol-specific transfer-related data */
89 struct MQTT {
90 struct dynbuf sendbuf;
91 /* when receiving */
92 struct dynbuf recvbuf;
93 size_t npacket; /* byte counter */
94 size_t remaining_length;
95 unsigned char pkt_hd[4]; /* for decoding the arriving packet length */
96 struct curltime lastTime; /* last time we sent or received data */
97 unsigned char firstbyte;
98 BIT(pingsent); /* 1 while we wait for ping response */
99 };
100
101
102 /*
103 * Forward declarations.
104 */
105
106 static CURLcode mqtt_do(struct Curl_easy *data, bool *done);
107 static CURLcode mqtt_done(struct Curl_easy *data,
108 CURLcode status, bool premature);
109 static CURLcode mqtt_doing(struct Curl_easy *data, bool *done);
110 static int mqtt_getsock(struct Curl_easy *data, struct connectdata *conn,
111 curl_socket_t *sock);
112 static CURLcode mqtt_setup_conn(struct Curl_easy *data,
113 struct connectdata *conn);
114
115 /*
116 * MQTT protocol handler.
117 */
118
119 const struct Curl_handler Curl_handler_mqtt = {
120 "mqtt", /* scheme */
121 mqtt_setup_conn, /* setup_connection */
122 mqtt_do, /* do_it */
123 mqtt_done, /* done */
124 ZERO_NULL, /* do_more */
125 ZERO_NULL, /* connect_it */
126 ZERO_NULL, /* connecting */
127 mqtt_doing, /* doing */
128 ZERO_NULL, /* proto_getsock */
129 mqtt_getsock, /* doing_getsock */
130 ZERO_NULL, /* domore_getsock */
131 ZERO_NULL, /* perform_getsock */
132 ZERO_NULL, /* disconnect */
133 ZERO_NULL, /* write_resp */
134 ZERO_NULL, /* write_resp_hd */
135 ZERO_NULL, /* connection_check */
136 ZERO_NULL, /* attach connection */
137 ZERO_NULL, /* follow */
138 PORT_MQTT, /* defport */
139 CURLPROTO_MQTT, /* protocol */
140 CURLPROTO_MQTT, /* family */
141 PROTOPT_NONE /* flags */
142 };
143
144 static void mqtt_easy_dtor(void *key, size_t klen, void *entry)
145 {
146 struct MQTT *mq = entry;
147 (void)key;
148 (void)klen;
149 curlx_dyn_free(&mq->sendbuf);
150 curlx_dyn_free(&mq->recvbuf);
151 free(mq);
152 }
153
154 static void mqtt_conn_dtor(void *key, size_t klen, void *entry)
155 {
156 (void)key;
157 (void)klen;
158 free(entry);
159 }
160
161 static CURLcode mqtt_setup_conn(struct Curl_easy *data,
162 struct connectdata *conn)
163 {
164 /* setup MQTT specific meta data at easy handle and connection */
165 struct mqtt_conn *mqtt;
166 struct MQTT *mq;
167
168 mqtt = calloc(1, sizeof(*mqtt));
169 if(!mqtt ||
170 Curl_conn_meta_set(conn, CURL_META_MQTT_CONN, mqtt, mqtt_conn_dtor))
171 return CURLE_OUT_OF_MEMORY;
172
173 mq = calloc(1, sizeof(struct MQTT));
174 if(!mq)
175 return CURLE_OUT_OF_MEMORY;
176 curlx_dyn_init(&mq->recvbuf, DYN_MQTT_RECV);
177 curlx_dyn_init(&mq->sendbuf, DYN_MQTT_SEND);
178 if(Curl_meta_set(data, CURL_META_MQTT_EASY, mq, mqtt_easy_dtor))
179 return CURLE_OUT_OF_MEMORY;
180 return CURLE_OK;
181 }
182
183 static CURLcode mqtt_send(struct Curl_easy *data,
184 const char *buf, size_t len)
185 {
186 size_t n;
187 CURLcode result;
188 struct MQTT *mq = Curl_meta_get(data, CURL_META_MQTT_EASY);
189
190 if(!mq)
191 return CURLE_FAILED_INIT;
192
193 result = Curl_xfer_send(data, buf, len, FALSE, &n);
194 if(result)
195 return result;
196 mq->lastTime = curlx_now();
197 Curl_debug(data, CURLINFO_HEADER_OUT, buf, (size_t)n);
198 if(len != n) {
199 size_t nsend = len - n;
200 if(curlx_dyn_len(&mq->sendbuf)) {
201 DEBUGASSERT(curlx_dyn_len(&mq->sendbuf) >= nsend);
202 result = curlx_dyn_tail(&mq->sendbuf, nsend); /* keep this much */
203 }
204 else {
205 result = curlx_dyn_addn(&mq->sendbuf, &buf[n], nsend);
206 }
207 }
208 else
209 curlx_dyn_reset(&mq->sendbuf);
210 return result;
211 }
212
213 /* Generic function called by the multi interface to figure out what socket(s)
214 to wait for and for what actions during the DOING and PROTOCONNECT
215 states */
216 static int mqtt_getsock(struct Curl_easy *data,
217 struct connectdata *conn,
218 curl_socket_t *sock)
219 {
220 (void)data;
221 sock[0] = conn->sock[FIRSTSOCKET];
222 return GETSOCK_READSOCK(FIRSTSOCKET);
223 }
224
225 static int mqtt_encode_len(char *buf, size_t len)
226 {
227 int i;
228
229 for(i = 0; (len > 0) && (i < 4); i++) {
230 unsigned char encoded;
231 encoded = len % 0x80;
232 len /= 0x80;
233 if(len)
234 encoded |= 0x80;
235 buf[i] = (char)encoded;
236 }
237
238 return i;
239 }
240
241 /* add the passwd to the CONNECT packet */
242 static int add_passwd(const char *passwd, const size_t plen,
243 char *pkt, const size_t start, int remain_pos)
244 {
245 /* magic number that need to be set properly */
246 const size_t conn_flags_pos = remain_pos + 8;
247 if(plen > 0xffff)
248 return 1;
249
250 /* set password flag */
251 pkt[conn_flags_pos] |= 0x40;
252
253 /* length of password provided */
254 pkt[start] = (char)((plen >> 8) & 0xFF);
255 pkt[start + 1] = (char)(plen & 0xFF);
256 memcpy(&pkt[start + 2], passwd, plen);
257 return 0;
258 }
259
260 /* add user to the CONNECT packet */
261 static int add_user(const char *username, const size_t ulen,
262 unsigned char *pkt, const size_t start, int remain_pos)
263 {
264 /* magic number that need to be set properly */
265 const size_t conn_flags_pos = remain_pos + 8;
266 if(ulen > 0xffff)
267 return 1;
268
269 /* set username flag */
270 pkt[conn_flags_pos] |= 0x80;
271 /* length of username provided */
272 pkt[start] = (unsigned char)((ulen >> 8) & 0xFF);
273 pkt[start + 1] = (unsigned char)(ulen & 0xFF);
274 memcpy(&pkt[start + 2], username, ulen);
275 return 0;
276 }
277
278 /* add client ID to the CONNECT packet */
279 static int add_client_id(const char *client_id, const size_t client_id_len,
280 char *pkt, const size_t start)
281 {
282 if(client_id_len != MQTT_CLIENTID_LEN)
283 return 1;
284 pkt[start] = 0x00;
285 pkt[start + 1] = MQTT_CLIENTID_LEN;
286 memcpy(&pkt[start + 2], client_id, MQTT_CLIENTID_LEN);
287 return 0;
288 }
289
290 /* Set initial values of CONNECT packet */
291 static int init_connpack(char *packet, char *remain, int remain_pos)
292 {
293 /* Fixed header starts */
294 /* packet type */
295 packet[0] = MQTT_MSG_CONNECT;
296 /* remaining length field */
297 memcpy(&packet[1], remain, remain_pos);
298 /* Fixed header ends */
299
300 /* Variable header starts */
301 /* protocol length */
302 packet[remain_pos + 1] = 0x00;
303 packet[remain_pos + 2] = 0x04;
304 /* protocol name */
305 packet[remain_pos + 3] = 'M';
306 packet[remain_pos + 4] = 'Q';
307 packet[remain_pos + 5] = 'T';
308 packet[remain_pos + 6] = 'T';
309 /* protocol level */
310 packet[remain_pos + 7] = 0x04;
311 /* CONNECT flag: CleanSession */
312 packet[remain_pos + 8] = 0x02;
313 /* keep-alive 0 = disabled */
314 packet[remain_pos + 9] = 0x00;
315 packet[remain_pos + 10] = 0x3c;
316 /* end of variable header */
317 return remain_pos + 10;
318 }
319
320 static CURLcode mqtt_connect(struct Curl_easy *data)
321 {
322 CURLcode result = CURLE_OK;
323 int pos = 0;
324 int rc = 0;
325 /* remain length */
326 int remain_pos = 0;
327 char remain[4] = {0};
328 size_t packetlen = 0;
329 size_t start_user = 0;
330 size_t start_pwd = 0;
331 char client_id[MQTT_CLIENTID_LEN + 1] = "curl";
332 const size_t clen = strlen("curl");
333 char *packet = NULL;
334
335 /* extracting username from request */
336 const char *username = data->state.aptr.user ?
337 data->state.aptr.user : "";
338 const size_t ulen = strlen(username);
339 /* extracting password from request */
340 const char *passwd = data->state.aptr.passwd ?
341 data->state.aptr.passwd : "";
342 const size_t plen = strlen(passwd);
343 const size_t payloadlen = ulen + plen + MQTT_CLIENTID_LEN + 2 +
344 /* The plus 2s below are for the MSB and LSB describing the length of the
345 string to be added on the payload. Refer to spec 1.5.2 and 1.5.4 */
346 (ulen ? 2 : 0) +
347 (plen ? 2 : 0);
348
349 /* getting how much occupy the remain length */
350 remain_pos = mqtt_encode_len(remain, payloadlen + 10);
351
352 /* 10 length of variable header and 1 the first byte of the fixed header */
353 packetlen = payloadlen + 10 + remain_pos + 1;
354
355 /* allocating packet */
356 if(packetlen > 0xFFFFFFF)
357 return CURLE_WEIRD_SERVER_REPLY;
358 packet = calloc(1, packetlen);
359 if(!packet)
360 return CURLE_OUT_OF_MEMORY;
361
362 /* set initial values for the CONNECT packet */
363 pos = init_connpack(packet, remain, remain_pos);
364
365 result = Curl_rand_alnum(data, (unsigned char *)&client_id[clen],
366 MQTT_CLIENTID_LEN - clen + 1);
367 /* add client id */
368 rc = add_client_id(client_id, strlen(client_id), packet, pos + 1);
369 if(rc) {
370 failf(data, "Client ID length mismatched: [%zu]", strlen(client_id));
371 result = CURLE_WEIRD_SERVER_REPLY;
372 goto end;
373 }
374 infof(data, "Using client id '%s'", client_id);
375
376 /* position where the user payload starts */
377 start_user = pos + 3 + MQTT_CLIENTID_LEN;
378 /* position where the password payload starts */
379 start_pwd = start_user + ulen;
380 /* if username was provided, add it to the packet */
381 if(ulen) {
382 start_pwd += 2;
383
384 rc = add_user(username, ulen,
385 (unsigned char *)packet, start_user, remain_pos);
386 if(rc) {
387 failf(data, "Username too long: [%zu]", ulen);
388 result = CURLE_WEIRD_SERVER_REPLY;
389 goto end;
390 }
391 }
392
393 /* if passwd was provided, add it to the packet */
394 if(plen) {
395 rc = add_passwd(passwd, plen, packet, start_pwd, remain_pos);
396 if(rc) {
397 failf(data, "Password too long: [%zu]", plen);
398 result = CURLE_WEIRD_SERVER_REPLY;
399 goto end;
400 }
401 }
402
403 if(!result)
404 result = mqtt_send(data, packet, packetlen);
405
406 end:
407 if(packet)
408 free(packet);
409 Curl_safefree(data->state.aptr.user);
410 Curl_safefree(data->state.aptr.passwd);
411 return result;
412 }
413
414 static CURLcode mqtt_disconnect(struct Curl_easy *data)
415 {
416 return mqtt_send(data, "\xe0\x00", 2);
417 }
418
419 static CURLcode mqtt_recv_atleast(struct Curl_easy *data, size_t nbytes)
420 {
421 struct MQTT *mq = Curl_meta_get(data, CURL_META_MQTT_EASY);
422 size_t rlen;
423 CURLcode result;
424
425 if(!mq)
426 return CURLE_FAILED_INIT;
427 rlen = curlx_dyn_len(&mq->recvbuf);
428
429 if(rlen < nbytes) {
430 unsigned char readbuf[1024];
431 ssize_t nread;
432
433 DEBUGASSERT(nbytes - rlen < sizeof(readbuf));
434 result = Curl_xfer_recv(data, (char *)readbuf, nbytes - rlen, &nread);
435 if(result)
436 return result;
437 DEBUGASSERT(nread >= 0);
438 if(curlx_dyn_addn(&mq->recvbuf, readbuf, (size_t)nread))
439 return CURLE_OUT_OF_MEMORY;
440 rlen = curlx_dyn_len(&mq->recvbuf);
441 }
442 return (rlen >= nbytes) ? CURLE_OK : CURLE_AGAIN;
443 }
444
445 static void mqtt_recv_consume(struct Curl_easy *data, size_t nbytes)
446 {
447 struct MQTT *mq = Curl_meta_get(data, CURL_META_MQTT_EASY);
448 DEBUGASSERT(mq);
449 if(mq) {
450 size_t rlen = curlx_dyn_len(&mq->recvbuf);
451 if(rlen <= nbytes)
452 curlx_dyn_reset(&mq->recvbuf);
453 else
454 curlx_dyn_tail(&mq->recvbuf, rlen - nbytes);
455 }
456 }
457
458 static CURLcode mqtt_verify_connack(struct Curl_easy *data)
459 {
460 struct MQTT *mq = Curl_meta_get(data, CURL_META_MQTT_EASY);
461 CURLcode result;
462 char *ptr;
463
464 DEBUGASSERT(mq);
465 if(!mq)
466 return CURLE_FAILED_INIT;
467
468 result = mqtt_recv_atleast(data, MQTT_CONNACK_LEN);
469 if(result)
470 goto fail;
471
472 /* verify CONNACK */
473 DEBUGASSERT(curlx_dyn_len(&mq->recvbuf) >= MQTT_CONNACK_LEN);
474 ptr = curlx_dyn_ptr(&mq->recvbuf);
475 Curl_debug(data, CURLINFO_HEADER_IN, ptr, MQTT_CONNACK_LEN);
476
477 if(ptr[0] != 0x00 || ptr[1] != 0x00) {
478 failf(data, "Expected %02x%02x but got %02x%02x",
479 0x00, 0x00, ptr[0], ptr[1]);
480 curlx_dyn_reset(&mq->recvbuf);
481 result = CURLE_WEIRD_SERVER_REPLY;
482 goto fail;
483 }
484 mqtt_recv_consume(data, MQTT_CONNACK_LEN);
485 fail:
486 return result;
487 }
488
489 static CURLcode mqtt_get_topic(struct Curl_easy *data,
490 char **topic, size_t *topiclen)
491 {
492 char *path = data->state.up.path;
493 CURLcode result = CURLE_URL_MALFORMAT;
494 if(strlen(path) > 1) {
495 result = Curl_urldecode(path + 1, 0, topic, topiclen, REJECT_NADA);
496 if(!result && (*topiclen > 0xffff)) {
497 failf(data, "Too long MQTT topic");
498 result = CURLE_URL_MALFORMAT;
499 }
500 }
501 else
502 failf(data, "No MQTT topic found. Forgot to URL encode it?");
503
504 return result;
505 }
506
507 static CURLcode mqtt_subscribe(struct Curl_easy *data)
508 {
509 CURLcode result = CURLE_OK;
510 char *topic = NULL;
511 size_t topiclen;
512 unsigned char *packet = NULL;
513 size_t packetlen;
514 char encodedsize[4];
515 size_t n;
516 struct connectdata *conn = data->conn;
517 struct mqtt_conn *mqtt = Curl_conn_meta_get(conn, CURL_META_MQTT_CONN);
518
519 if(!mqtt)
520 return CURLE_FAILED_INIT;
521
522 result = mqtt_get_topic(data, &topic, &topiclen);
523 if(result)
524 goto fail;
525
526 mqtt->packetid++;
527
528 packetlen = topiclen + 5; /* packetid + topic (has a two byte length field)
529 + 2 bytes topic length + QoS byte */
530 n = mqtt_encode_len((char *)encodedsize, packetlen);
531 packetlen += n + 1; /* add one for the control packet type byte */
532
533 packet = malloc(packetlen);
534 if(!packet) {
535 result = CURLE_OUT_OF_MEMORY;
536 goto fail;
537 }
538
539 packet[0] = MQTT_MSG_SUBSCRIBE;
540 memcpy(&packet[1], encodedsize, n);
541 packet[1 + n] = (mqtt->packetid >> 8) & 0xff;
542 packet[2 + n] = mqtt->packetid & 0xff;
543 packet[3 + n] = (topiclen >> 8) & 0xff;
544 packet[4 + n ] = topiclen & 0xff;
545 memcpy(&packet[5 + n], topic, topiclen);
546 packet[5 + n + topiclen] = 0; /* QoS zero */
547
548 result = mqtt_send(data, (const char *)packet, packetlen);
549
550 fail:
551 free(topic);
552 free(packet);
553 return result;
554 }
555
556 /*
557 * Called when the first byte was already read.
558 */
559 static CURLcode mqtt_verify_suback(struct Curl_easy *data)
560 {
561 struct MQTT *mq = Curl_meta_get(data, CURL_META_MQTT_EASY);
562 struct connectdata *conn = data->conn;
563 struct mqtt_conn *mqtt = Curl_conn_meta_get(conn, CURL_META_MQTT_CONN);
564 CURLcode result;
565 char *ptr;
566
567 if(!mqtt || !mq)
568 return CURLE_FAILED_INIT;
569
570 result = mqtt_recv_atleast(data, MQTT_SUBACK_LEN);
571 if(result)
572 goto fail;
573
574 /* verify SUBACK */
575 DEBUGASSERT(curlx_dyn_len(&mq->recvbuf) >= MQTT_SUBACK_LEN);
576 ptr = curlx_dyn_ptr(&mq->recvbuf);
577 Curl_debug(data, CURLINFO_HEADER_IN, ptr, MQTT_SUBACK_LEN);
578
579 if(((unsigned char)ptr[0]) != ((mqtt->packetid >> 8) & 0xff) ||
580 ((unsigned char)ptr[1]) != (mqtt->packetid & 0xff) ||
581 ptr[2] != 0x00) {
582 curlx_dyn_reset(&mq->recvbuf);
583 result = CURLE_WEIRD_SERVER_REPLY;
584 goto fail;
585 }
586 mqtt_recv_consume(data, MQTT_SUBACK_LEN);
587 fail:
588 return result;
589 }
590
591 static CURLcode mqtt_publish(struct Curl_easy *data)
592 {
593 CURLcode result;
594 char *payload = data->set.postfields;
595 size_t payloadlen;
596 char *topic = NULL;
597 size_t topiclen;
598 unsigned char *pkt = NULL;
599 size_t i = 0;
600 size_t remaininglength;
601 size_t encodelen;
602 char encodedbytes[4];
603 curl_off_t postfieldsize = data->set.postfieldsize;
604
605 if(!payload) {
606 DEBUGF(infof(data, "mqtt_publish without payload, return bad arg"));
607 return CURLE_BAD_FUNCTION_ARGUMENT;
608 }
609 if(postfieldsize < 0)
610 payloadlen = strlen(payload);
611 else
612 payloadlen = (size_t)postfieldsize;
613
614 result = mqtt_get_topic(data, &topic, &topiclen);
615 if(result)
616 goto fail;
617
618 remaininglength = payloadlen + 2 + topiclen;
619 encodelen = mqtt_encode_len(encodedbytes, remaininglength);
620
621 /* add the control byte and the encoded remaining length */
622 pkt = malloc(remaininglength + 1 + encodelen);
623 if(!pkt) {
624 result = CURLE_OUT_OF_MEMORY;
625 goto fail;
626 }
627
628 /* assemble packet */
629 pkt[i++] = MQTT_MSG_PUBLISH;
630 memcpy(&pkt[i], encodedbytes, encodelen);
631 i += encodelen;
632 pkt[i++] = (topiclen >> 8) & 0xff;
633 pkt[i++] = (topiclen & 0xff);
634 memcpy(&pkt[i], topic, topiclen);
635 i += topiclen;
636 memcpy(&pkt[i], payload, payloadlen);
637 i += payloadlen;
638 result = mqtt_send(data, (const char *)pkt, i);
639
640 fail:
641 free(pkt);
642 free(topic);
643 return result;
644 }
645
646 static size_t mqtt_decode_len(unsigned char *buf,
647 size_t buflen, size_t *lenbytes)
648 {
649 size_t len = 0;
650 size_t mult = 1;
651 size_t i;
652 unsigned char encoded = 128;
653
654 for(i = 0; (i < buflen) && (encoded & 128); i++) {
655 encoded = buf[i];
656 len += (encoded & 127) * mult;
657 mult *= 128;
658 }
659
660 if(lenbytes)
661 *lenbytes = i;
662
663 return len;
664 }
665
666 #ifdef DEBUGBUILD
667 static const char *statenames[]={
668 "MQTT_FIRST",
669 "MQTT_REMAINING_LENGTH",
670 "MQTT_CONNACK",
671 "MQTT_SUBACK",
672 "MQTT_SUBACK_COMING",
673 "MQTT_PUBWAIT",
674 "MQTT_PUB_REMAIN",
675
676 "NOT A STATE"
677 };
678 #endif
679
680 /* The only way to change state */
681 static void mqstate(struct Curl_easy *data,
682 enum mqttstate state,
683 enum mqttstate nextstate) /* used if state == FIRST */
684 {
685 struct connectdata *conn = data->conn;
686 struct mqtt_conn *mqtt = Curl_conn_meta_get(conn, CURL_META_MQTT_CONN);
687 DEBUGASSERT(mqtt);
688 if(!mqtt)
689 return;
690 #ifdef DEBUGBUILD
691 infof(data, "%s (from %s) (next is %s)",
692 statenames[state],
693 statenames[mqtt->state],
694 (state == MQTT_FIRST) ? statenames[nextstate] : "");
695 #endif
696 mqtt->state = state;
697 if(state == MQTT_FIRST)
698 mqtt->nextstate = nextstate;
699 }
700
701
702 static CURLcode mqtt_read_publish(struct Curl_easy *data, bool *done)
703 {
704 CURLcode result = CURLE_OK;
705 struct connectdata *conn = data->conn;
706 ssize_t nread;
707 size_t remlen;
708 struct mqtt_conn *mqtt = Curl_conn_meta_get(conn, CURL_META_MQTT_CONN);
709 struct MQTT *mq = Curl_meta_get(data, CURL_META_MQTT_EASY);
710 unsigned char packet;
711
712 DEBUGASSERT(mqtt);
713 if(!mqtt || !mq)
714 return CURLE_FAILED_INIT;
715
716 switch(mqtt->state) {
717 MQTT_SUBACK_COMING:
718 case MQTT_SUBACK_COMING:
719 result = mqtt_verify_suback(data);
720 if(result)
721 break;
722
723 mqstate(data, MQTT_FIRST, MQTT_PUBWAIT);
724 break;
725
726 case MQTT_SUBACK:
727 case MQTT_PUBWAIT:
728 /* we are expecting PUBLISH or SUBACK */
729 packet = mq->firstbyte & 0xf0;
730 if(packet == MQTT_MSG_PUBLISH)
731 mqstate(data, MQTT_PUB_REMAIN, MQTT_NOSTATE);
732 else if(packet == MQTT_MSG_SUBACK) {
733 mqstate(data, MQTT_SUBACK_COMING, MQTT_NOSTATE);
734 goto MQTT_SUBACK_COMING;
735 }
736 else if(packet == MQTT_MSG_DISCONNECT) {
737 infof(data, "Got DISCONNECT");
738 *done = TRUE;
739 goto end;
740 }
741 else {
742 result = CURLE_WEIRD_SERVER_REPLY;
743 goto end;
744 }
745
746 /* -- switched state -- */
747 remlen = mq->remaining_length;
748 infof(data, "Remaining length: %zu bytes", remlen);
749 if(data->set.max_filesize &&
750 (curl_off_t)remlen > data->set.max_filesize) {
751 failf(data, "Maximum file size exceeded");
752 result = CURLE_FILESIZE_EXCEEDED;
753 goto end;
754 }
755 Curl_pgrsSetDownloadSize(data, remlen);
756 data->req.bytecount = 0;
757 data->req.size = remlen;
758 mq->npacket = remlen; /* get this many bytes */
759 FALLTHROUGH();
760 case MQTT_PUB_REMAIN: {
761 /* read rest of packet, but no more. Cap to buffer size */
762 char buffer[4*1024];
763 size_t rest = mq->npacket;
764 if(rest > sizeof(buffer))
765 rest = sizeof(buffer);
766 result = Curl_xfer_recv(data, buffer, rest, &nread);
767 if(result) {
768 if(CURLE_AGAIN == result) {
769 infof(data, "EEEE AAAAGAIN");
770 }
771 goto end;
772 }
773 if(!nread) {
774 infof(data, "server disconnected");
775 result = CURLE_PARTIAL_FILE;
776 goto end;
777 }
778
779 /* we received something */
780 mq->lastTime = curlx_now();
781
782 /* if QoS is set, message contains packet id */
783 result = Curl_client_write(data, CLIENTWRITE_BODY, buffer, nread);
784 if(result)
785 goto end;
786
787 mq->npacket -= nread;
788 if(!mq->npacket)
789 /* no more PUBLISH payload, back to subscribe wait state */
790 mqstate(data, MQTT_FIRST, MQTT_PUBWAIT);
791 break;
792 }
793 default:
794 DEBUGASSERT(NULL); /* illegal state */
795 result = CURLE_WEIRD_SERVER_REPLY;
796 goto end;
797 }
798 end:
799 return result;
800 }
801
802 static CURLcode mqtt_do(struct Curl_easy *data, bool *done)
803 {
804 struct MQTT *mq = Curl_meta_get(data, CURL_META_MQTT_EASY);
805 CURLcode result = CURLE_OK;
806 *done = FALSE; /* unconditionally */
807
808 if(!mq)
809 return CURLE_FAILED_INIT;
810 mq->lastTime = curlx_now();
811 mq->pingsent = FALSE;
812
813 result = mqtt_connect(data);
814 if(result) {
815 failf(data, "Error %d sending MQTT CONNECT request", result);
816 return result;
817 }
818 mqstate(data, MQTT_FIRST, MQTT_CONNACK);
819 return CURLE_OK;
820 }
821
822 static CURLcode mqtt_done(struct Curl_easy *data,
823 CURLcode status, bool premature)
824 {
825 struct MQTT *mq = Curl_meta_get(data, CURL_META_MQTT_EASY);
826 (void)status;
827 (void)premature;
828 if(mq) {
829 curlx_dyn_free(&mq->sendbuf);
830 curlx_dyn_free(&mq->recvbuf);
831 }
832 return CURLE_OK;
833 }
834
835 /* we ping regularly to avoid being disconnected by the server */
836 static CURLcode mqtt_ping(struct Curl_easy *data)
837 {
838 struct MQTT *mq = Curl_meta_get(data, CURL_META_MQTT_EASY);
839 CURLcode result = CURLE_OK;
840 struct connectdata *conn = data->conn;
841 struct mqtt_conn *mqtt = Curl_conn_meta_get(conn, CURL_META_MQTT_CONN);
842
843 if(!mqtt || !mq)
844 return CURLE_FAILED_INIT;
845
846 if(mqtt->state == MQTT_FIRST &&
847 !mq->pingsent &&
848 data->set.upkeep_interval_ms > 0) {
849 struct curltime t = curlx_now();
850 timediff_t diff = curlx_timediff(t, mq->lastTime);
851
852 if(diff > data->set.upkeep_interval_ms) {
853 /* 0xC0 is PINGREQ, and 0x00 is remaining length */
854 unsigned char packet[2] = { 0xC0, 0x00 };
855 size_t packetlen = sizeof(packet);
856
857 result = mqtt_send(data, (char *)packet, packetlen);
858 if(!result) {
859 mq->pingsent = TRUE;
860 }
861 infof(data, "mqtt_ping: sent ping request.");
862 }
863 }
864 return result;
865 }
866
867 static CURLcode mqtt_doing(struct Curl_easy *data, bool *done)
868 {
869 struct MQTT *mq = Curl_meta_get(data, CURL_META_MQTT_EASY);
870 CURLcode result = CURLE_OK;
871 ssize_t nread;
872 unsigned char recvbyte;
873 struct mqtt_conn *mqtt = Curl_conn_meta_get(data->conn, CURL_META_MQTT_CONN);
874
875 if(!mqtt || !mq)
876 return CURLE_FAILED_INIT;
877
878 *done = FALSE;
879
880 if(curlx_dyn_len(&mq->sendbuf)) {
881 /* send the remainder of an outgoing packet */
882 result = mqtt_send(data, curlx_dyn_ptr(&mq->sendbuf),
883 curlx_dyn_len(&mq->sendbuf));
884 if(result)
885 return result;
886 }
887
888 result = mqtt_ping(data);
889 if(result)
890 return result;
891
892 infof(data, "mqtt_doing: state [%d]", (int) mqtt->state);
893 switch(mqtt->state) {
894 case MQTT_FIRST:
895 /* Read the initial byte only */
896 result = Curl_xfer_recv(data, (char *)&mq->firstbyte, 1, &nread);
897 if(result)
898 break;
899 else if(!nread) {
900 failf(data, "Connection disconnected");
901 *done = TRUE;
902 result = CURLE_RECV_ERROR;
903 break;
904 }
905 Curl_debug(data, CURLINFO_HEADER_IN, (const char *)&mq->firstbyte, 1);
906
907 /* we received something */
908 mq->lastTime = curlx_now();
909
910 /* remember the first byte */
911 mq->npacket = 0;
912 mqstate(data, MQTT_REMAINING_LENGTH, MQTT_NOSTATE);
913 FALLTHROUGH();
914 case MQTT_REMAINING_LENGTH:
915 do {
916 result = Curl_xfer_recv(data, (char *)&recvbyte, 1, &nread);
917 if(result || !nread)
918 break;
919 Curl_debug(data, CURLINFO_HEADER_IN, (const char *)&recvbyte, 1);
920 mq->pkt_hd[mq->npacket++] = recvbyte;
921 } while((recvbyte & 0x80) && (mq->npacket < 4));
922 if(!result && nread && (recvbyte & 0x80))
923 /* MQTT supports up to 127 * 128^0 + 127 * 128^1 + 127 * 128^2 +
924 127 * 128^3 bytes. server tried to send more */
925 result = CURLE_WEIRD_SERVER_REPLY;
926 if(result)
927 break;
928 mq->remaining_length = mqtt_decode_len(mq->pkt_hd, mq->npacket, NULL);
929 mq->npacket = 0;
930 if(mq->remaining_length) {
931 mqstate(data, mqtt->nextstate, MQTT_NOSTATE);
932 break;
933 }
934 mqstate(data, MQTT_FIRST, MQTT_FIRST);
935
936 if(mq->firstbyte == MQTT_MSG_DISCONNECT) {
937 infof(data, "Got DISCONNECT");
938 *done = TRUE;
939 }
940
941 /* ping response */
942 if(mq->firstbyte == MQTT_MSG_PINGRESP) {
943 infof(data, "Received ping response.");
944 mq->pingsent = FALSE;
945 mqstate(data, MQTT_FIRST, MQTT_PUBWAIT);
946 }
947 break;
948 case MQTT_CONNACK:
949 result = mqtt_verify_connack(data);
950 if(result)
951 break;
952
953 if(data->state.httpreq == HTTPREQ_POST) {
954 result = mqtt_publish(data);
955 if(!result) {
956 result = mqtt_disconnect(data);
957 *done = TRUE;
958 }
959 mqtt->nextstate = MQTT_FIRST;
960 }
961 else {
962 result = mqtt_subscribe(data);
963 if(!result) {
964 mqstate(data, MQTT_FIRST, MQTT_SUBACK);
965 }
966 }
967 break;
968
969 case MQTT_SUBACK:
970 case MQTT_PUBWAIT:
971 case MQTT_PUB_REMAIN:
972 result = mqtt_read_publish(data, done);
973 break;
974
975 default:
976 failf(data, "State not handled yet");
977 *done = TRUE;
978 break;
979 }
980
981 if(result == CURLE_AGAIN)
982 result = CURLE_OK;
983 return result;
984 }
985
986 #endif /* CURL_DISABLE_MQTT */