Coverage Report

Created: 2026-12-01 06:25

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