Coverage Report

Created: 2026-01-10 06:51

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