Coverage Report

Created: 2026-08-31 06:46

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