Coverage Report

Created: 2023-06-07 07:02

/src/curl/lib/mqtt.c
Line
Count
Source (jump to first uncovered line)
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
26
#include "curl_setup.h"
27
28
#ifndef CURL_DISABLE_MQTT
29
30
#include "urldata.h"
31
#include <curl/curl.h>
32
#include "transfer.h"
33
#include "sendf.h"
34
#include "progress.h"
35
#include "mqtt.h"
36
#include "select.h"
37
#include "strdup.h"
38
#include "url.h"
39
#include "escape.h"
40
#include "warnless.h"
41
#include "curl_printf.h"
42
#include "curl_memory.h"
43
#include "multiif.h"
44
#include "rand.h"
45
46
/* The last #include file should be: */
47
#include "memdebug.h"
48
49
0
#define MQTT_MSG_CONNECT   0x10
50
#define MQTT_MSG_CONNACK   0x20
51
0
#define MQTT_MSG_PUBLISH   0x30
52
0
#define MQTT_MSG_SUBSCRIBE 0x82
53
0
#define MQTT_MSG_SUBACK    0x90
54
0
#define MQTT_MSG_DISCONNECT 0xe0
55
56
0
#define MQTT_CONNACK_LEN 2
57
0
#define MQTT_SUBACK_LEN 3
58
0
#define MQTT_CLIENTID_LEN 12 /* "curl0123abcd" */
59
60
/*
61
 * Forward declarations.
62
 */
63
64
static CURLcode mqtt_do(struct Curl_easy *data, bool *done);
65
static CURLcode mqtt_done(struct Curl_easy *data,
66
                          CURLcode status, bool premature);
67
static CURLcode mqtt_doing(struct Curl_easy *data, bool *done);
68
static int mqtt_getsock(struct Curl_easy *data, struct connectdata *conn,
69
                        curl_socket_t *sock);
70
static CURLcode mqtt_setup_conn(struct Curl_easy *data,
71
                                struct connectdata *conn);
72
73
/*
74
 * MQTT protocol handler.
75
 */
76
77
const struct Curl_handler Curl_handler_mqtt = {
78
  "MQTT",                             /* scheme */
79
  mqtt_setup_conn,                    /* setup_connection */
80
  mqtt_do,                            /* do_it */
81
  mqtt_done,                          /* done */
82
  ZERO_NULL,                          /* do_more */
83
  ZERO_NULL,                          /* connect_it */
84
  ZERO_NULL,                          /* connecting */
85
  mqtt_doing,                         /* doing */
86
  ZERO_NULL,                          /* proto_getsock */
87
  mqtt_getsock,                       /* doing_getsock */
88
  ZERO_NULL,                          /* domore_getsock */
89
  ZERO_NULL,                          /* perform_getsock */
90
  ZERO_NULL,                          /* disconnect */
91
  ZERO_NULL,                          /* readwrite */
92
  ZERO_NULL,                          /* connection_check */
93
  ZERO_NULL,                          /* attach connection */
94
  PORT_MQTT,                          /* defport */
95
  CURLPROTO_MQTT,                     /* protocol */
96
  CURLPROTO_MQTT,                     /* family */
97
  PROTOPT_NONE                        /* flags */
98
};
99
100
static CURLcode mqtt_setup_conn(struct Curl_easy *data,
101
                                struct connectdata *conn)
102
0
{
103
  /* allocate the HTTP-specific struct for the Curl_easy, only to survive
104
     during this request */
105
0
  struct MQTT *mq;
106
0
  (void)conn;
107
0
  DEBUGASSERT(data->req.p.mqtt == NULL);
108
109
0
  mq = calloc(1, sizeof(struct MQTT));
110
0
  if(!mq)
111
0
    return CURLE_OUT_OF_MEMORY;
112
0
  data->req.p.mqtt = mq;
113
0
  return CURLE_OK;
114
0
}
115
116
static CURLcode mqtt_send(struct Curl_easy *data,
117
                          char *buf, size_t len)
118
0
{
119
0
  CURLcode result = CURLE_OK;
120
0
  struct connectdata *conn = data->conn;
121
0
  curl_socket_t sockfd = conn->sock[FIRSTSOCKET];
122
0
  struct MQTT *mq = data->req.p.mqtt;
123
0
  ssize_t n;
124
0
  result = Curl_write(data, sockfd, buf, len, &n);
125
0
  if(result)
126
0
    return result;
127
0
  Curl_debug(data, CURLINFO_HEADER_OUT, buf, (size_t)n);
128
0
  if(len != (size_t)n) {
129
0
    size_t nsend = len - n;
130
0
    char *sendleftovers = Curl_memdup(&buf[n], nsend);
131
0
    if(!sendleftovers)
132
0
      return CURLE_OUT_OF_MEMORY;
133
0
    mq->sendleftovers = sendleftovers;
134
0
    mq->nsend = nsend;
135
0
  }
136
0
  else {
137
0
    mq->sendleftovers = NULL;
138
0
    mq->nsend = 0;
139
0
  }
140
0
  return result;
141
0
}
142
143
/* Generic function called by the multi interface to figure out what socket(s)
144
   to wait for and for what actions during the DOING and PROTOCONNECT
145
   states */
146
static int mqtt_getsock(struct Curl_easy *data,
147
                        struct connectdata *conn,
148
                        curl_socket_t *sock)
149
0
{
150
0
  (void)data;
151
0
  sock[0] = conn->sock[FIRSTSOCKET];
152
0
  return GETSOCK_READSOCK(FIRSTSOCKET);
153
0
}
154
155
static int mqtt_encode_len(char *buf, size_t len)
156
0
{
157
0
  unsigned char encoded;
158
0
  int i;
159
160
0
  for(i = 0; (len > 0) && (i<4); i++) {
161
0
    encoded = len % 0x80;
162
0
    len /= 0x80;
163
0
    if(len)
164
0
      encoded |= 0x80;
165
0
    buf[i] = encoded;
166
0
  }
167
168
0
  return i;
169
0
}
170
171
/* add the passwd to the CONNECT packet */
172
static int add_passwd(const char *passwd, const size_t plen,
173
                       char *pkt, const size_t start, int remain_pos)
174
0
{
175
  /* magic number that need to be set properly */
176
0
  const size_t conn_flags_pos = remain_pos + 8;
177
0
  if(plen > 0xffff)
178
0
    return 1;
179
180
  /* set password flag */
181
0
  pkt[conn_flags_pos] |= 0x40;
182
183
  /* length of password provided */
184
0
  pkt[start] = (char)((plen >> 8) & 0xFF);
185
0
  pkt[start + 1] = (char)(plen & 0xFF);
186
0
  memcpy(&pkt[start + 2], passwd, plen);
187
0
  return 0;
188
0
}
189
190
/* add user to the CONNECT packet */
191
static int add_user(const char *username, const size_t ulen,
192
                    unsigned char *pkt, const size_t start, int remain_pos)
193
0
{
194
  /* magic number that need to be set properly */
195
0
  const size_t conn_flags_pos = remain_pos + 8;
196
0
  if(ulen > 0xffff)
197
0
    return 1;
198
199
  /* set username flag */
200
0
  pkt[conn_flags_pos] |= 0x80;
201
  /* length of username provided */
202
0
  pkt[start] = (unsigned char)((ulen >> 8) & 0xFF);
203
0
  pkt[start + 1] = (unsigned char)(ulen & 0xFF);
204
0
  memcpy(&pkt[start + 2], username, ulen);
205
0
  return 0;
206
0
}
207
208
/* add client ID to the CONNECT packet */
209
static int add_client_id(const char *client_id, const size_t client_id_len,
210
                         char *pkt, const size_t start)
211
0
{
212
0
  if(client_id_len != MQTT_CLIENTID_LEN)
213
0
    return 1;
214
0
  pkt[start] = 0x00;
215
0
  pkt[start + 1] = MQTT_CLIENTID_LEN;
216
0
  memcpy(&pkt[start + 2], client_id, MQTT_CLIENTID_LEN);
217
0
  return 0;
218
0
}
219
220
/* Set initial values of CONNECT packet */
221
static int init_connpack(char *packet, char *remain, int remain_pos)
222
0
{
223
  /* Fixed header starts */
224
  /* packet type */
225
0
  packet[0] = MQTT_MSG_CONNECT;
226
  /* remaining length field */
227
0
  memcpy(&packet[1], remain, remain_pos);
228
  /* Fixed header ends */
229
230
  /* Variable header starts */
231
  /* protocol length */
232
0
  packet[remain_pos + 1] = 0x00;
233
0
  packet[remain_pos + 2] = 0x04;
234
  /* protocol name */
235
0
  packet[remain_pos + 3] = 'M';
236
0
  packet[remain_pos + 4] = 'Q';
237
0
  packet[remain_pos + 5] = 'T';
238
0
  packet[remain_pos + 6] = 'T';
239
  /* protocol level */
240
0
  packet[remain_pos + 7] = 0x04;
241
  /* CONNECT flag: CleanSession */
242
0
  packet[remain_pos + 8] = 0x02;
243
  /* keep-alive 0 = disabled */
244
0
  packet[remain_pos + 9] = 0x00;
245
0
  packet[remain_pos + 10] = 0x3c;
246
  /* end of variable header */
247
0
  return remain_pos + 10;
248
0
}
249
250
static CURLcode mqtt_connect(struct Curl_easy *data)
251
0
{
252
0
  CURLcode result = CURLE_OK;
253
0
  int pos = 0;
254
0
  int rc = 0;
255
  /* remain length */
256
0
  int remain_pos = 0;
257
0
  char remain[4] = {0};
258
0
  size_t packetlen = 0;
259
0
  size_t payloadlen = 0;
260
0
  size_t start_user = 0;
261
0
  size_t start_pwd = 0;
262
0
  char client_id[MQTT_CLIENTID_LEN + 1] = "curl";
263
0
  const size_t clen = strlen("curl");
264
0
  char *packet = NULL;
265
266
  /* extracting username from request */
267
0
  const char *username = data->state.aptr.user ?
268
0
    data->state.aptr.user : "";
269
0
  const size_t ulen = strlen(username);
270
  /* extracting password from request */
271
0
  const char *passwd = data->state.aptr.passwd ?
272
0
    data->state.aptr.passwd : "";
273
0
  const size_t plen = strlen(passwd);
274
275
0
  payloadlen = ulen + plen + MQTT_CLIENTID_LEN + 2;
276
  /* The plus 2 are for the MSB and LSB describing the length of the string to
277
   * be added on the payload. Refer to spec 1.5.2 and 1.5.4 */
278
0
  if(ulen)
279
0
    payloadlen += 2;
280
0
  if(plen)
281
0
    payloadlen += 2;
282
283
  /* getting how much occupy the remain length */
284
0
  remain_pos = mqtt_encode_len(remain, payloadlen + 10);
285
286
  /* 10 length of variable header and 1 the first byte of the fixed header */
287
0
  packetlen = payloadlen + 10 + remain_pos + 1;
288
289
  /* allocating packet */
290
0
  if(packetlen > 268435455)
291
0
    return CURLE_WEIRD_SERVER_REPLY;
292
0
  packet = malloc(packetlen);
293
0
  if(!packet)
294
0
    return CURLE_OUT_OF_MEMORY;
295
0
  memset(packet, 0, packetlen);
296
297
  /* set initial values for the CONNECT packet */
298
0
  pos = init_connpack(packet, remain, remain_pos);
299
300
0
  result = Curl_rand_hex(data, (unsigned char *)&client_id[clen],
301
0
                         MQTT_CLIENTID_LEN - clen + 1);
302
  /* add client id */
303
0
  rc = add_client_id(client_id, strlen(client_id), packet, pos + 1);
304
0
  if(rc) {
305
0
    failf(data, "Client ID length mismatched: [%lu]", strlen(client_id));
306
0
    result = CURLE_WEIRD_SERVER_REPLY;
307
0
    goto end;
308
0
  }
309
0
  infof(data, "Using client id '%s'", client_id);
310
311
  /* position where starts the user payload */
312
0
  start_user = pos + 3 + MQTT_CLIENTID_LEN;
313
  /* position where starts the password payload */
314
0
  start_pwd = start_user + ulen;
315
  /* if user name was provided, add it to the packet */
316
0
  if(ulen) {
317
0
    start_pwd += 2;
318
319
0
    rc = add_user(username, ulen,
320
0
                  (unsigned char *)packet, start_user, remain_pos);
321
0
    if(rc) {
322
0
      failf(data, "Username is too large: [%lu]", ulen);
323
0
      result = CURLE_WEIRD_SERVER_REPLY;
324
0
      goto end;
325
0
    }
326
0
  }
327
328
  /* if passwd was provided, add it to the packet */
329
0
  if(plen) {
330
0
    rc = add_passwd(passwd, plen, packet, start_pwd, remain_pos);
331
0
    if(rc) {
332
0
      failf(data, "Password is too large: [%lu]", plen);
333
0
      result = CURLE_WEIRD_SERVER_REPLY;
334
0
      goto end;
335
0
    }
336
0
  }
337
338
0
  if(!result)
339
0
    result = mqtt_send(data, packet, packetlen);
340
341
0
end:
342
0
  if(packet)
343
0
    free(packet);
344
0
  Curl_safefree(data->state.aptr.user);
345
0
  Curl_safefree(data->state.aptr.passwd);
346
0
  return result;
347
0
}
348
349
static CURLcode mqtt_disconnect(struct Curl_easy *data)
350
0
{
351
0
  CURLcode result = CURLE_OK;
352
0
  struct MQTT *mq = data->req.p.mqtt;
353
0
  result = mqtt_send(data, (char *)"\xe0\x00", 2);
354
0
  Curl_safefree(mq->sendleftovers);
355
0
  return result;
356
0
}
357
358
static CURLcode mqtt_verify_connack(struct Curl_easy *data)
359
0
{
360
0
  CURLcode result;
361
0
  struct connectdata *conn = data->conn;
362
0
  curl_socket_t sockfd = conn->sock[FIRSTSOCKET];
363
0
  unsigned char readbuf[MQTT_CONNACK_LEN];
364
0
  ssize_t nread;
365
366
0
  result = Curl_read(data, sockfd, (char *)readbuf, MQTT_CONNACK_LEN, &nread);
367
0
  if(result)
368
0
    goto fail;
369
370
0
  Curl_debug(data, CURLINFO_HEADER_IN, (char *)readbuf, (size_t)nread);
371
372
  /* fixme */
373
0
  if(nread < MQTT_CONNACK_LEN) {
374
0
    result = CURLE_WEIRD_SERVER_REPLY;
375
0
    goto fail;
376
0
  }
377
378
  /* verify CONNACK */
379
0
  if(readbuf[0] != 0x00 || readbuf[1] != 0x00) {
380
0
    failf(data, "Expected %02x%02x but got %02x%02x",
381
0
          0x00, 0x00, readbuf[0], readbuf[1]);
382
0
    result = CURLE_WEIRD_SERVER_REPLY;
383
0
  }
384
385
0
fail:
386
0
  return result;
387
0
}
388
389
static CURLcode mqtt_get_topic(struct Curl_easy *data,
390
                               char **topic, size_t *topiclen)
391
0
{
392
0
  char *path = data->state.up.path;
393
0
  CURLcode result = CURLE_URL_MALFORMAT;
394
0
  if(strlen(path) > 1) {
395
0
    result = Curl_urldecode(path + 1, 0, topic, topiclen, REJECT_NADA);
396
0
    if(!result && (*topiclen > 0xffff)) {
397
0
      failf(data, "Too long MQTT topic");
398
0
      result = CURLE_URL_MALFORMAT;
399
0
    }
400
0
  }
401
0
  else
402
0
    failf(data, "No MQTT topic found. Forgot to URL encode it?");
403
404
0
  return result;
405
0
}
406
407
static CURLcode mqtt_subscribe(struct Curl_easy *data)
408
0
{
409
0
  CURLcode result = CURLE_OK;
410
0
  char *topic = NULL;
411
0
  size_t topiclen;
412
0
  unsigned char *packet = NULL;
413
0
  size_t packetlen;
414
0
  char encodedsize[4];
415
0
  size_t n;
416
0
  struct connectdata *conn = data->conn;
417
418
0
  result = mqtt_get_topic(data, &topic, &topiclen);
419
0
  if(result)
420
0
    goto fail;
421
422
0
  conn->proto.mqtt.packetid++;
423
424
0
  packetlen = topiclen + 5; /* packetid + topic (has a two byte length field)
425
                               + 2 bytes topic length + QoS byte */
426
0
  n = mqtt_encode_len((char *)encodedsize, packetlen);
427
0
  packetlen += n + 1; /* add one for the control packet type byte */
428
429
0
  packet = malloc(packetlen);
430
0
  if(!packet) {
431
0
    result = CURLE_OUT_OF_MEMORY;
432
0
    goto fail;
433
0
  }
434
435
0
  packet[0] = MQTT_MSG_SUBSCRIBE;
436
0
  memcpy(&packet[1], encodedsize, n);
437
0
  packet[1 + n] = (conn->proto.mqtt.packetid >> 8) & 0xff;
438
0
  packet[2 + n] = conn->proto.mqtt.packetid & 0xff;
439
0
  packet[3 + n] = (topiclen >> 8) & 0xff;
440
0
  packet[4 + n ] = topiclen & 0xff;
441
0
  memcpy(&packet[5 + n], topic, topiclen);
442
0
  packet[5 + n + topiclen] = 0; /* QoS zero */
443
444
0
  result = mqtt_send(data, (char *)packet, packetlen);
445
446
0
fail:
447
0
  free(topic);
448
0
  free(packet);
449
0
  return result;
450
0
}
451
452
/*
453
 * Called when the first byte was already read.
454
 */
455
static CURLcode mqtt_verify_suback(struct Curl_easy *data)
456
0
{
457
0
  CURLcode result;
458
0
  struct connectdata *conn = data->conn;
459
0
  curl_socket_t sockfd = conn->sock[FIRSTSOCKET];
460
0
  unsigned char readbuf[MQTT_SUBACK_LEN];
461
0
  ssize_t nread;
462
0
  struct mqtt_conn *mqtt = &conn->proto.mqtt;
463
464
0
  result = Curl_read(data, sockfd, (char *)readbuf, MQTT_SUBACK_LEN, &nread);
465
0
  if(result)
466
0
    goto fail;
467
468
0
  Curl_debug(data, CURLINFO_HEADER_IN, (char *)readbuf, (size_t)nread);
469
470
  /* fixme */
471
0
  if(nread < MQTT_SUBACK_LEN) {
472
0
    result = CURLE_WEIRD_SERVER_REPLY;
473
0
    goto fail;
474
0
  }
475
476
  /* verify SUBACK */
477
0
  if(readbuf[0] != ((mqtt->packetid >> 8) & 0xff) ||
478
0
     readbuf[1] != (mqtt->packetid & 0xff) ||
479
0
     readbuf[2] != 0x00)
480
0
    result = CURLE_WEIRD_SERVER_REPLY;
481
482
0
fail:
483
0
  return result;
484
0
}
485
486
static CURLcode mqtt_publish(struct Curl_easy *data)
487
0
{
488
0
  CURLcode result;
489
0
  char *payload = data->set.postfields;
490
0
  size_t payloadlen;
491
0
  char *topic = NULL;
492
0
  size_t topiclen;
493
0
  unsigned char *pkt = NULL;
494
0
  size_t i = 0;
495
0
  size_t remaininglength;
496
0
  size_t encodelen;
497
0
  char encodedbytes[4];
498
0
  curl_off_t postfieldsize = data->set.postfieldsize;
499
500
0
  if(!payload)
501
0
    return CURLE_BAD_FUNCTION_ARGUMENT;
502
0
  if(postfieldsize < 0)
503
0
    payloadlen = strlen(payload);
504
0
  else
505
0
    payloadlen = (size_t)postfieldsize;
506
507
0
  result = mqtt_get_topic(data, &topic, &topiclen);
508
0
  if(result)
509
0
    goto fail;
510
511
0
  remaininglength = payloadlen + 2 + topiclen;
512
0
  encodelen = mqtt_encode_len(encodedbytes, remaininglength);
513
514
  /* add the control byte and the encoded remaining length */
515
0
  pkt = malloc(remaininglength + 1 + encodelen);
516
0
  if(!pkt) {
517
0
    result = CURLE_OUT_OF_MEMORY;
518
0
    goto fail;
519
0
  }
520
521
  /* assemble packet */
522
0
  pkt[i++] = MQTT_MSG_PUBLISH;
523
0
  memcpy(&pkt[i], encodedbytes, encodelen);
524
0
  i += encodelen;
525
0
  pkt[i++] = (topiclen >> 8) & 0xff;
526
0
  pkt[i++] = (topiclen & 0xff);
527
0
  memcpy(&pkt[i], topic, topiclen);
528
0
  i += topiclen;
529
0
  memcpy(&pkt[i], payload, payloadlen);
530
0
  i += payloadlen;
531
0
  result = mqtt_send(data, (char *)pkt, i);
532
533
0
fail:
534
0
  free(pkt);
535
0
  free(topic);
536
0
  return result;
537
0
}
538
539
static size_t mqtt_decode_len(unsigned char *buf,
540
                              size_t buflen, size_t *lenbytes)
541
0
{
542
0
  size_t len = 0;
543
0
  size_t mult = 1;
544
0
  size_t i;
545
0
  unsigned char encoded = 128;
546
547
0
  for(i = 0; (i < buflen) && (encoded & 128); i++) {
548
0
    encoded = buf[i];
549
0
    len += (encoded & 127) * mult;
550
0
    mult *= 128;
551
0
  }
552
553
0
  if(lenbytes)
554
0
    *lenbytes = i;
555
556
0
  return len;
557
0
}
558
559
#ifdef CURLDEBUG
560
static const char *statenames[]={
561
  "MQTT_FIRST",
562
  "MQTT_REMAINING_LENGTH",
563
  "MQTT_CONNACK",
564
  "MQTT_SUBACK",
565
  "MQTT_SUBACK_COMING",
566
  "MQTT_PUBWAIT",
567
  "MQTT_PUB_REMAIN",
568
569
  "NOT A STATE"
570
};
571
#endif
572
573
/* The only way to change state */
574
static void mqstate(struct Curl_easy *data,
575
                    enum mqttstate state,
576
                    enum mqttstate nextstate) /* used if state == FIRST */
577
0
{
578
0
  struct connectdata *conn = data->conn;
579
0
  struct mqtt_conn *mqtt = &conn->proto.mqtt;
580
0
#ifdef CURLDEBUG
581
0
  infof(data, "%s (from %s) (next is %s)",
582
0
        statenames[state],
583
0
        statenames[mqtt->state],
584
0
        (state == MQTT_FIRST)? statenames[nextstate] : "");
585
0
#endif
586
0
  mqtt->state = state;
587
0
  if(state == MQTT_FIRST)
588
0
    mqtt->nextstate = nextstate;
589
0
}
590
591
592
/* for the publish packet */
593
#define MQTT_HEADER_LEN 5    /* max 5 bytes */
594
595
static CURLcode mqtt_read_publish(struct Curl_easy *data, bool *done)
596
0
{
597
0
  CURLcode result = CURLE_OK;
598
0
  struct connectdata *conn = data->conn;
599
0
  curl_socket_t sockfd = conn->sock[FIRSTSOCKET];
600
0
  ssize_t nread;
601
0
  unsigned char *pkt = (unsigned char *)data->state.buffer;
602
0
  size_t remlen;
603
0
  struct mqtt_conn *mqtt = &conn->proto.mqtt;
604
0
  struct MQTT *mq = data->req.p.mqtt;
605
0
  unsigned char packet;
606
607
0
  switch(mqtt->state) {
608
0
MQTT_SUBACK_COMING:
609
0
  case MQTT_SUBACK_COMING:
610
0
    result = mqtt_verify_suback(data);
611
0
    if(result)
612
0
      break;
613
614
0
    mqstate(data, MQTT_FIRST, MQTT_PUBWAIT);
615
0
    break;
616
617
0
  case MQTT_SUBACK:
618
0
  case MQTT_PUBWAIT:
619
    /* we are expecting PUBLISH or SUBACK */
620
0
    packet = mq->firstbyte & 0xf0;
621
0
    if(packet == MQTT_MSG_PUBLISH)
622
0
      mqstate(data, MQTT_PUB_REMAIN, MQTT_NOSTATE);
623
0
    else if(packet == MQTT_MSG_SUBACK) {
624
0
      mqstate(data, MQTT_SUBACK_COMING, MQTT_NOSTATE);
625
0
      goto MQTT_SUBACK_COMING;
626
0
    }
627
0
    else if(packet == MQTT_MSG_DISCONNECT) {
628
0
      infof(data, "Got DISCONNECT");
629
0
      *done = TRUE;
630
0
      goto end;
631
0
    }
632
0
    else {
633
0
      result = CURLE_WEIRD_SERVER_REPLY;
634
0
      goto end;
635
0
    }
636
637
    /* -- switched state -- */
638
0
    remlen = mq->remaining_length;
639
0
    infof(data, "Remaining length: %zd bytes", remlen);
640
0
    if(data->set.max_filesize &&
641
0
       (curl_off_t)remlen > data->set.max_filesize) {
642
0
      failf(data, "Maximum file size exceeded");
643
0
      result = CURLE_FILESIZE_EXCEEDED;
644
0
      goto end;
645
0
    }
646
0
    Curl_pgrsSetDownloadSize(data, remlen);
647
0
    data->req.bytecount = 0;
648
0
    data->req.size = remlen;
649
0
    mq->npacket = remlen; /* get this many bytes */
650
    /* FALLTHROUGH */
651
0
  case MQTT_PUB_REMAIN: {
652
    /* read rest of packet, but no more. Cap to buffer size */
653
0
    struct SingleRequest *k = &data->req;
654
0
    size_t rest = mq->npacket;
655
0
    if(rest > (size_t)data->set.buffer_size)
656
0
      rest = (size_t)data->set.buffer_size;
657
0
    result = Curl_read(data, sockfd, (char *)pkt, rest, &nread);
658
0
    if(result) {
659
0
      if(CURLE_AGAIN == result) {
660
0
        infof(data, "EEEE AAAAGAIN");
661
0
      }
662
0
      goto end;
663
0
    }
664
0
    if(!nread) {
665
0
      infof(data, "server disconnected");
666
0
      result = CURLE_PARTIAL_FILE;
667
0
      goto end;
668
0
    }
669
0
    Curl_debug(data, CURLINFO_DATA_IN, (char *)pkt, (size_t)nread);
670
671
0
    mq->npacket -= nread;
672
0
    k->bytecount += nread;
673
0
    Curl_pgrsSetDownloadCounter(data, k->bytecount);
674
675
    /* if QoS is set, message contains packet id */
676
677
0
    result = Curl_client_write(data, CLIENTWRITE_BODY, (char *)pkt, nread);
678
0
    if(result)
679
0
      goto end;
680
681
0
    if(!mq->npacket)
682
      /* no more PUBLISH payload, back to subscribe wait state */
683
0
      mqstate(data, MQTT_FIRST, MQTT_PUBWAIT);
684
0
    break;
685
0
  }
686
0
  default:
687
0
    DEBUGASSERT(NULL); /* illegal state */
688
0
    result = CURLE_WEIRD_SERVER_REPLY;
689
0
    goto end;
690
0
  }
691
0
end:
692
0
  return result;
693
0
}
694
695
static CURLcode mqtt_do(struct Curl_easy *data, bool *done)
696
0
{
697
0
  CURLcode result = CURLE_OK;
698
0
  *done = FALSE; /* unconditionally */
699
700
0
  result = mqtt_connect(data);
701
0
  if(result) {
702
0
    failf(data, "Error %d sending MQTT CONNECT request", result);
703
0
    return result;
704
0
  }
705
0
  mqstate(data, MQTT_FIRST, MQTT_CONNACK);
706
0
  return CURLE_OK;
707
0
}
708
709
static CURLcode mqtt_done(struct Curl_easy *data,
710
                          CURLcode status, bool premature)
711
0
{
712
0
  struct MQTT *mq = data->req.p.mqtt;
713
0
  (void)status;
714
0
  (void)premature;
715
0
  Curl_safefree(mq->sendleftovers);
716
0
  return CURLE_OK;
717
0
}
718
719
static CURLcode mqtt_doing(struct Curl_easy *data, bool *done)
720
0
{
721
0
  CURLcode result = CURLE_OK;
722
0
  struct connectdata *conn = data->conn;
723
0
  struct mqtt_conn *mqtt = &conn->proto.mqtt;
724
0
  struct MQTT *mq = data->req.p.mqtt;
725
0
  ssize_t nread;
726
0
  curl_socket_t sockfd = conn->sock[FIRSTSOCKET];
727
0
  unsigned char *pkt = (unsigned char *)data->state.buffer;
728
0
  unsigned char byte;
729
730
0
  *done = FALSE;
731
732
0
  if(mq->nsend) {
733
    /* send the remainder of an outgoing packet */
734
0
    char *ptr = mq->sendleftovers;
735
0
    result = mqtt_send(data, mq->sendleftovers, mq->nsend);
736
0
    free(ptr);
737
0
    if(result)
738
0
      return result;
739
0
  }
740
741
0
  infof(data, "mqtt_doing: state [%d]", (int) mqtt->state);
742
0
  switch(mqtt->state) {
743
0
  case MQTT_FIRST:
744
    /* Read the initial byte only */
745
0
    result = Curl_read(data, sockfd, (char *)&mq->firstbyte, 1, &nread);
746
0
    if(result)
747
0
      break;
748
0
    else if(!nread) {
749
0
      failf(data, "Connection disconnected");
750
0
      *done = TRUE;
751
0
      result = CURLE_RECV_ERROR;
752
0
      break;
753
0
    }
754
0
    Curl_debug(data, CURLINFO_HEADER_IN, (char *)&mq->firstbyte, 1);
755
    /* remember the first byte */
756
0
    mq->npacket = 0;
757
0
    mqstate(data, MQTT_REMAINING_LENGTH, MQTT_NOSTATE);
758
    /* FALLTHROUGH */
759
0
  case MQTT_REMAINING_LENGTH:
760
0
    do {
761
0
      result = Curl_read(data, sockfd, (char *)&byte, 1, &nread);
762
0
      if(!nread)
763
0
        break;
764
0
      Curl_debug(data, CURLINFO_HEADER_IN, (char *)&byte, 1);
765
0
      pkt[mq->npacket++] = byte;
766
0
    } while((byte & 0x80) && (mq->npacket < 4));
767
0
    if(nread && (byte & 0x80))
768
      /* MQTT supports up to 127 * 128^0 + 127 * 128^1 + 127 * 128^2 +
769
         127 * 128^3 bytes. server tried to send more */
770
0
      result = CURLE_WEIRD_SERVER_REPLY;
771
0
    if(result)
772
0
      break;
773
0
    mq->remaining_length = mqtt_decode_len(&pkt[0], mq->npacket, NULL);
774
0
    mq->npacket = 0;
775
0
    if(mq->remaining_length) {
776
0
      mqstate(data, mqtt->nextstate, MQTT_NOSTATE);
777
0
      break;
778
0
    }
779
0
    mqstate(data, MQTT_FIRST, MQTT_FIRST);
780
781
0
    if(mq->firstbyte == MQTT_MSG_DISCONNECT) {
782
0
      infof(data, "Got DISCONNECT");
783
0
      *done = TRUE;
784
0
    }
785
0
    break;
786
0
  case MQTT_CONNACK:
787
0
    result = mqtt_verify_connack(data);
788
0
    if(result)
789
0
      break;
790
791
0
    if(data->state.httpreq == HTTPREQ_POST) {
792
0
      result = mqtt_publish(data);
793
0
      if(!result) {
794
0
        result = mqtt_disconnect(data);
795
0
        *done = TRUE;
796
0
      }
797
0
      mqtt->nextstate = MQTT_FIRST;
798
0
    }
799
0
    else {
800
0
      result = mqtt_subscribe(data);
801
0
      if(!result) {
802
0
        mqstate(data, MQTT_FIRST, MQTT_SUBACK);
803
0
      }
804
0
    }
805
0
    break;
806
807
0
  case MQTT_SUBACK:
808
0
  case MQTT_PUBWAIT:
809
0
  case MQTT_PUB_REMAIN:
810
0
    result = mqtt_read_publish(data, done);
811
0
    break;
812
813
0
  default:
814
0
    failf(data, "State not handled yet");
815
0
    *done = TRUE;
816
0
    break;
817
0
  }
818
819
0
  if(result == CURLE_AGAIN)
820
0
    result = CURLE_OK;
821
0
  return result;
822
0
}
823
824
#endif /* CURL_DISABLE_MQTT */