source: azure_iot_hub_f767zi/trunk/azure_iot_sdk/umqtt/src/mqtt_codec.c

Last change on this file was 464, checked in by coas-nagasima, 3 years ago

WolfSSLとAzure IoT SDKを更新

  • Property svn:eol-style set to native
  • Property svn:mime-type set to text/x-csrc;charset=UTF-8
File size: 41.7 KB
Line 
1// Copyright (c) Microsoft. All rights reserved.
2// Licensed under the MIT license. See LICENSE file in the project root for full license information.
3
4#include <stdlib.h>
5#include <limits.h>
6#include "azure_c_shared_utility/optimize_size.h"
7#include "azure_c_shared_utility/gballoc.h"
8#include "azure_c_shared_utility/buffer_.h"
9#include "azure_c_shared_utility/strings.h"
10#include "azure_macro_utils/macro_utils.h"
11#include "azure_c_shared_utility/xlogging.h"
12#include "azure_umqtt_c/mqtt_codec.h"
13#include <inttypes.h>
14
15#define PAYLOAD_OFFSET 5
16#define PACKET_TYPE_BYTE(p) (CONTROL_PACKET_TYPE)((uint8_t)(((uint8_t)(p)) & 0xf0))
17#define FLAG_VALUE_BYTE(p) ((uint8_t)(((uint8_t)(p)) & 0xf))
18
19#define USERNAME_FLAG 0x80
20#define PASSWORD_FLAG 0x40
21#define WILL_RETAIN_FLAG 0x20
22#define WILL_QOS_FLAG_ 0x18
23#define WILL_FLAG_FLAG 0x04
24#define CLEAN_SESSION_FLAG 0x02
25
26#define NEXT_128_CHUNK 0x80
27#define PUBLISH_DUP_FLAG 0x8
28#define PUBLISH_QOS_EXACTLY_ONCE 0x4
29#define PUBLISH_QOS_AT_LEAST_ONCE 0x2
30#define PUBLISH_QOS_RETAIN 0x1
31
32#define PROTOCOL_NUMBER 4
33#define CONN_FLAG_BYTE_OFFSET 7
34
35#define CONNECT_FIXED_HEADER_SIZE 2
36#define CONNECT_VARIABLE_HEADER_SIZE 10
37#define SUBSCRIBE_FIXED_HEADER_FLAG 0x2
38#define UNSUBSCRIBE_FIXED_HEADER_FLAG 0x2
39
40#define MAX_SEND_SIZE 0xFFFFFF7F // 268435455
41
42// This captures the maximum packet size for 3 digits.
43// If it's above this value then we bail out of the loop
44#define MAX_3_DIGIT_PACKET_SIZE 2097152
45
46#define CODEC_STATE_VALUES \
47 CODEC_STATE_FIXED_HEADER, \
48 CODEC_STATE_VAR_HEADER, \
49 CODEC_STATE_PAYLOAD
50
51static const char* const TRUE_CONST = "true";
52static const char* const FALSE_CONST = "false";
53
54MU_DEFINE_ENUM(CODEC_STATE_RESULT, CODEC_STATE_VALUES);
55
56typedef struct MQTTCODEC_INSTANCE_TAG
57{
58 CONTROL_PACKET_TYPE currPacket;
59 CODEC_STATE_RESULT codecState;
60 size_t bufferOffset;
61 int headerFlags;
62 BUFFER_HANDLE headerData;
63 ON_PACKET_COMPLETE_CALLBACK packetComplete;
64 void* callContext;
65 uint8_t storeRemainLen[4];
66 size_t remainLenIndex;
67} MQTTCODEC_INSTANCE;
68
69typedef struct PUBLISH_HEADER_INFO_TAG
70{
71 const char* topicName;
72 uint16_t packetId;
73 const char* msgBuffer;
74 QOS_VALUE qualityOfServiceValue;
75} PUBLISH_HEADER_INFO;
76
77static const char* retrieve_qos_value(QOS_VALUE value)
78{
79 switch (value)
80 {
81 case DELIVER_AT_MOST_ONCE:
82 return "DELIVER_AT_MOST_ONCE";
83 case DELIVER_AT_LEAST_ONCE:
84 return "DELIVER_AT_LEAST_ONCE";
85 case DELIVER_EXACTLY_ONCE:
86 default:
87 return "DELIVER_EXACTLY_ONCE";
88 }
89}
90
91static void byteutil_writeByte(uint8_t** buffer, uint8_t value)
92{
93 if (buffer != NULL)
94 {
95 **buffer = value;
96 (*buffer)++;
97 }
98}
99
100static void byteutil_writeInt(uint8_t** buffer, uint16_t value)
101{
102 if (buffer != NULL)
103 {
104 **buffer = (char)(value / 256);
105 (*buffer)++;
106 **buffer = (char)(value % 256);
107 (*buffer)++;
108 }
109}
110
111static void byteutil_writeUTF(uint8_t** buffer, const char* stringData, uint16_t len)
112{
113 if (buffer != NULL)
114 {
115 byteutil_writeInt(buffer, len);
116 (void)memcpy(*buffer, stringData, len);
117 *buffer += len;
118 }
119}
120
121static CONTROL_PACKET_TYPE processControlPacketType(uint8_t pktByte, int* flags)
122{
123 CONTROL_PACKET_TYPE result;
124 result = PACKET_TYPE_BYTE(pktByte);
125 if (flags != NULL)
126 {
127 *flags = FLAG_VALUE_BYTE(pktByte);
128 }
129 return result;
130}
131
132static int addListItemsToUnsubscribePacket(BUFFER_HANDLE ctrlPacket, const char** payloadList, size_t payloadCount, STRING_HANDLE trace_log)
133{
134 int result = 0;
135 size_t index = 0;
136 for (index = 0; index < payloadCount && result == 0; index++)
137 {
138 // Add the Payload
139 size_t offsetLen = BUFFER_length(ctrlPacket);
140 size_t topicLen = strlen(payloadList[index]);
141 if (topicLen > USHRT_MAX)
142 {
143 result = MU_FAILURE;
144 }
145 else if (BUFFER_enlarge(ctrlPacket, topicLen + 2) != 0)
146 {
147 result = MU_FAILURE;
148 }
149 else
150 {
151 uint8_t* iterator = BUFFER_u_char(ctrlPacket);
152 iterator += offsetLen;
153 byteutil_writeUTF(&iterator, payloadList[index], (uint16_t)topicLen);
154 }
155 if (trace_log != NULL)
156 {
157 STRING_sprintf(trace_log, " | TOPIC_NAME: %s", payloadList[index]);
158 }
159 }
160 return result;
161}
162
163static int addListItemsToSubscribePacket(BUFFER_HANDLE ctrlPacket, SUBSCRIBE_PAYLOAD* payloadList, size_t payloadCount, STRING_HANDLE trace_log)
164{
165 int result = 0;
166 size_t index = 0;
167 for (index = 0; index < payloadCount && result == 0; index++)
168 {
169 // Add the Payload
170 size_t offsetLen = BUFFER_length(ctrlPacket);
171 size_t topicLen = strlen(payloadList[index].subscribeTopic);
172 if (topicLen > USHRT_MAX)
173 {
174 result = MU_FAILURE;
175 }
176 else if (BUFFER_enlarge(ctrlPacket, topicLen + 2 + 1) != 0)
177 {
178 result = MU_FAILURE;
179 }
180 else
181 {
182 uint8_t* iterator = BUFFER_u_char(ctrlPacket);
183 iterator += offsetLen;
184 byteutil_writeUTF(&iterator, payloadList[index].subscribeTopic, (uint16_t)topicLen);
185 *iterator = payloadList[index].qosReturn;
186
187 if (trace_log != NULL)
188 {
189 STRING_sprintf(trace_log, " | TOPIC_NAME: %s | QOS: %d", payloadList[index].subscribeTopic, (int)payloadList[index].qosReturn);
190 }
191 }
192 }
193 return result;
194}
195
196static int constructConnectVariableHeader(BUFFER_HANDLE ctrlPacket, const MQTT_CLIENT_OPTIONS* mqttOptions, STRING_HANDLE trace_log)
197{
198 int result = 0;
199 if (BUFFER_enlarge(ctrlPacket, CONNECT_VARIABLE_HEADER_SIZE) != 0)
200 {
201 result = MU_FAILURE;
202 }
203 else
204 {
205 uint8_t* iterator = BUFFER_u_char(ctrlPacket);
206 if (iterator == NULL)
207 {
208 result = MU_FAILURE;
209 }
210 else
211 {
212 if (trace_log != NULL)
213 {
214 STRING_sprintf(trace_log, " | VER: %d | KEEPALIVE: %d | FLAGS:", PROTOCOL_NUMBER, mqttOptions->keepAliveInterval);
215 }
216 byteutil_writeUTF(&iterator, "MQTT", 4);
217 byteutil_writeByte(&iterator, PROTOCOL_NUMBER);
218 byteutil_writeByte(&iterator, 0); // Flags will be entered later
219 byteutil_writeInt(&iterator, mqttOptions->keepAliveInterval);
220 result = 0;
221 }
222 }
223 return result;
224}
225
226static int constructPublishVariableHeader(BUFFER_HANDLE ctrlPacket, const PUBLISH_HEADER_INFO* publishHeader, STRING_HANDLE trace_log)
227{
228 int result = 0;
229 size_t topicLen = 0;
230 size_t spaceLen = 0;
231 size_t idLen = 0;
232
233 size_t currLen = BUFFER_length(ctrlPacket);
234
235 topicLen = strlen(publishHeader->topicName);
236 spaceLen += 2;
237
238 if (publishHeader->qualityOfServiceValue != DELIVER_AT_MOST_ONCE)
239 {
240 // Packet Id is only set if the QOS is not 0
241 idLen = 2;
242 }
243
244 if (topicLen > USHRT_MAX)
245 {
246 result = MU_FAILURE;
247 }
248 else if (BUFFER_enlarge(ctrlPacket, topicLen + idLen + spaceLen) != 0)
249 {
250 result = MU_FAILURE;
251 }
252 else
253 {
254 uint8_t* iterator = BUFFER_u_char(ctrlPacket);
255 if (iterator == NULL)
256 {
257 result = MU_FAILURE;
258 }
259 else
260 {
261 iterator += currLen;
262 /* The Topic Name MUST be present as the first field in the PUBLISH Packet Variable header.It MUST be 792 a UTF-8 encoded string [MQTT-3.3.2-1] as defined in section 1.5.3.*/
263 byteutil_writeUTF(&iterator, publishHeader->topicName, (uint16_t)topicLen);
264 if (trace_log != NULL)
265 {
266 STRING_sprintf(trace_log, " | TOPIC_NAME: %s", publishHeader->topicName);
267 }
268 if (idLen > 0)
269 {
270 if (trace_log != NULL)
271 {
272 STRING_sprintf(trace_log, " | PACKET_ID: %"PRIu16, publishHeader->packetId);
273 }
274 byteutil_writeInt(&iterator, publishHeader->packetId);
275 }
276 result = 0;
277 }
278 }
279 return result;
280}
281
282static int constructSubscibeTypeVariableHeader(BUFFER_HANDLE ctrlPacket, uint16_t packetId)
283{
284 int result = 0;
285 if (BUFFER_enlarge(ctrlPacket, 2) != 0)
286 {
287 result = MU_FAILURE;
288 }
289 else
290 {
291 uint8_t* iterator = BUFFER_u_char(ctrlPacket);
292 if (iterator == NULL)
293 {
294 result = MU_FAILURE;
295 }
296 else
297 {
298 byteutil_writeInt(&iterator, packetId);
299 result = 0;
300 }
301 }
302 return result;
303}
304
305static BUFFER_HANDLE constructPublishReply(CONTROL_PACKET_TYPE type, uint8_t flags, uint16_t packetId)
306{
307 BUFFER_HANDLE result = BUFFER_new();
308 if (result != NULL)
309 {
310 if (BUFFER_pre_build(result, 4) != 0)
311 {
312 BUFFER_delete(result);
313 result = NULL;
314 }
315 else
316 {
317 uint8_t* iterator = BUFFER_u_char(result);
318 if (iterator == NULL)
319 {
320 BUFFER_delete(result);
321 result = NULL;
322 }
323 else
324 {
325 *iterator = (uint8_t)type | flags;
326 iterator++;
327 *iterator = 0x2;
328 iterator++;
329 byteutil_writeInt(&iterator, packetId);
330 }
331 }
332 }
333 return result;
334}
335
336static int constructFixedHeader(BUFFER_HANDLE ctrlPacket, CONTROL_PACKET_TYPE packetType, uint8_t flags)
337{
338 int result;
339 size_t packetLen = BUFFER_length(ctrlPacket);
340 uint8_t remainSize[4] ={ 0 };
341 size_t index = 0;
342
343 // Calculate the length of packet
344 do
345 {
346 uint8_t encode = packetLen % 128;
347 packetLen /= 128;
348 // if there are more data to encode, set the top bit of this byte
349 if (packetLen > 0)
350 {
351 encode |= NEXT_128_CHUNK;
352 }
353 remainSize[index++] = encode;
354 } while (packetLen > 0);
355
356 BUFFER_HANDLE fixedHeader = BUFFER_new();
357 if (fixedHeader == NULL)
358 {
359 result = MU_FAILURE;
360 }
361 else if (BUFFER_pre_build(fixedHeader, index + 1) != 0)
362 {
363 BUFFER_delete(fixedHeader);
364 result = MU_FAILURE;
365 }
366 else
367 {
368 uint8_t* iterator = BUFFER_u_char(fixedHeader);
369 *iterator = (uint8_t)packetType | flags;
370 iterator++;
371 (void)memcpy(iterator, remainSize, index);
372
373 result = BUFFER_prepend(ctrlPacket, fixedHeader);
374 BUFFER_delete(fixedHeader);
375 }
376 return result;
377}
378
379static int constructConnPayload(BUFFER_HANDLE ctrlPacket, const MQTT_CLIENT_OPTIONS* mqttOptions, STRING_HANDLE trace_log)
380{
381 int result = 0;
382 size_t clientLen = 0;
383 size_t usernameLen = 0;
384 size_t passwordLen = 0;
385 size_t willMessageLen = 0;
386 size_t willTopicLen = 0;
387 size_t spaceLen = 0;
388 size_t currLen = 0;
389 size_t totalLen = 0;
390
391 if (mqttOptions->clientId != NULL)
392 {
393 spaceLen += 2;
394 clientLen = strlen(mqttOptions->clientId);
395 }
396 if (mqttOptions->username != NULL)
397 {
398 spaceLen += 2;
399 usernameLen = strlen(mqttOptions->username);
400 }
401 if (mqttOptions->password != NULL)
402 {
403 spaceLen += 2;
404 passwordLen = strlen(mqttOptions->password);
405 }
406 if (mqttOptions->willMessage != NULL)
407 {
408 spaceLen += 2;
409 willMessageLen = strlen(mqttOptions->willMessage);
410 }
411 if (mqttOptions->willTopic != NULL)
412 {
413 spaceLen += 2;
414 willTopicLen = strlen(mqttOptions->willTopic);
415 }
416
417 currLen = BUFFER_length(ctrlPacket);
418 totalLen = clientLen + usernameLen + passwordLen + willMessageLen + willTopicLen + spaceLen;
419
420 // Validate the Username & Password
421 if (clientLen > USHRT_MAX)
422 {
423 result = MU_FAILURE;
424 }
425 else if (usernameLen == 0 && passwordLen > 0)
426 {
427 result = MU_FAILURE;
428 }
429 else if ((willMessageLen > 0 && willTopicLen == 0) || (willTopicLen > 0 && willMessageLen == 0))
430 {
431 result = MU_FAILURE;
432 }
433 else if (BUFFER_enlarge(ctrlPacket, totalLen) != 0)
434 {
435 result = MU_FAILURE;
436 }
437 else
438 {
439 uint8_t* packet = BUFFER_u_char(ctrlPacket);
440 uint8_t* iterator = packet;
441
442 iterator += currLen;
443 byteutil_writeUTF(&iterator, mqttOptions->clientId, (uint16_t)clientLen);
444
445 // TODO: Read on the Will Topic
446 if (willMessageLen > USHRT_MAX || willTopicLen > USHRT_MAX || usernameLen > USHRT_MAX || passwordLen > USHRT_MAX)
447 {
448 result = MU_FAILURE;
449 }
450 else
451 {
452 STRING_HANDLE connect_payload_trace = NULL;
453 if (trace_log != NULL)
454 {
455 connect_payload_trace = STRING_new();
456 }
457 if (willMessageLen > 0 && willTopicLen > 0)
458 {
459 if (trace_log != NULL)
460 {
461 (void)STRING_sprintf(connect_payload_trace, " | WILL_TOPIC: %s", mqttOptions->willTopic);
462 }
463 packet[CONN_FLAG_BYTE_OFFSET] |= WILL_FLAG_FLAG;
464 byteutil_writeUTF(&iterator, mqttOptions->willTopic, (uint16_t)willTopicLen);
465 packet[CONN_FLAG_BYTE_OFFSET] |= (mqttOptions->qualityOfServiceValue << 3);
466 if (mqttOptions->messageRetain)
467 {
468 packet[CONN_FLAG_BYTE_OFFSET] |= WILL_RETAIN_FLAG;
469 }
470 byteutil_writeUTF(&iterator, mqttOptions->willMessage, (uint16_t)willMessageLen);
471 }
472 if (usernameLen > 0)
473 {
474 packet[CONN_FLAG_BYTE_OFFSET] |= USERNAME_FLAG;
475 byteutil_writeUTF(&iterator, mqttOptions->username, (uint16_t)usernameLen);
476 if (trace_log != NULL)
477 {
478 (void)STRING_sprintf(connect_payload_trace, " | USERNAME: %s", mqttOptions->username);
479 }
480 }
481 if (passwordLen > 0)
482 {
483 packet[CONN_FLAG_BYTE_OFFSET] |= PASSWORD_FLAG;
484 byteutil_writeUTF(&iterator, mqttOptions->password, (uint16_t)passwordLen);
485 if (trace_log != NULL)
486 {
487 (void)STRING_sprintf(connect_payload_trace, " | PWD: XXXX");
488 }
489 }
490 // TODO: Get the rest of the flags
491 if (trace_log != NULL)
492 {
493 (void)STRING_sprintf(connect_payload_trace, " | CLEAN: %s", mqttOptions->useCleanSession ? "1" : "0");
494 }
495 if (mqttOptions->useCleanSession)
496 {
497 packet[CONN_FLAG_BYTE_OFFSET] |= CLEAN_SESSION_FLAG;
498 }
499 if (trace_log != NULL)
500 {
501 (void)STRING_sprintf(trace_log, " %lu", packet[CONN_FLAG_BYTE_OFFSET]);
502 (void)STRING_concat_with_STRING(trace_log, connect_payload_trace);
503 STRING_delete(connect_payload_trace);
504 }
505 result = 0;
506 }
507 }
508 return result;
509}
510
511static int prepareheaderDataInfo(MQTTCODEC_INSTANCE* codecData, uint8_t remainLen)
512{
513 int result;
514 result = 0;
515 codecData->storeRemainLen[codecData->remainLenIndex++] = remainLen;
516 if (remainLen <= 0x7f)
517 {
518 int multiplier = 1;
519 int totalLen = 0;
520 size_t index = 0;
521 uint8_t encodeByte = 0;
522 do
523 {
524 encodeByte = codecData->storeRemainLen[index++];
525 totalLen += (encodeByte & 127) * multiplier;
526 multiplier *= NEXT_128_CHUNK;
527
528 if (multiplier > MAX_3_DIGIT_PACKET_SIZE)
529 {
530 result = MU_FAILURE;
531 break;
532 }
533 } while ((encodeByte & NEXT_128_CHUNK) != 0);
534
535 if (result != 0 || totalLen > MAX_SEND_SIZE)
536 {
537 LogError("Receive buffer too large for MQTT packet");
538 result = MU_FAILURE;
539 }
540 else
541 {
542 codecData->codecState = CODEC_STATE_VAR_HEADER;
543
544 // Reset remainLen Index
545 codecData->remainLenIndex = 0;
546 memset(codecData->storeRemainLen, 0, 4 * sizeof(uint8_t));
547
548 if (totalLen > 0)
549 {
550 codecData->bufferOffset = 0;
551 codecData->headerData = BUFFER_new();
552 if (codecData->headerData == NULL)
553 {
554 /* Codes_SRS_MQTT_CODEC_07_035: [ If any error is encountered then the packet state will be marked as error and mqtt_codec_bytesReceived shall return a non-zero value. ] */
555 LogError("Failed BUFFER_new");
556 result = MU_FAILURE;
557 }
558 else
559 {
560 if (BUFFER_pre_build(codecData->headerData, totalLen) != 0)
561 {
562 /* Codes_SRS_MQTT_CODEC_07_035: [ If any error is encountered then the packet state will be marked as error and mqtt_codec_bytesReceived shall return a non-zero value. ] */
563 LogError("Failed BUFFER_pre_build");
564 result = MU_FAILURE;
565 }
566
567 }
568 }
569 }
570 }
571 else if (codecData->remainLenIndex == (sizeof(codecData->storeRemainLen) / sizeof(codecData->storeRemainLen[0])))
572 {
573 // The maximum number of bytes in the Remaining Length field is four
574 // This allows applications to send Control Packets of size up to 268,435,455 (256 MB).
575 // The representation of this number on the wire is: 0xFF, 0xFF, 0xFF, 0x7F.
576
577 // The last byte has exceed the max value of 0x7F
578 LogError("MQTT packet len is invalid");
579 result = MU_FAILURE;
580 }
581 return result;
582}
583
584static void completePacketData(MQTTCODEC_INSTANCE* codecData)
585{
586 if (codecData->packetComplete != NULL)
587 {
588 codecData->packetComplete(codecData->callContext, codecData->currPacket, codecData->headerFlags, codecData->headerData);
589 }
590
591 // Clean up data
592 codecData->currPacket = UNKNOWN_TYPE;
593 codecData->codecState = CODEC_STATE_FIXED_HEADER;
594 codecData->headerFlags = 0;
595 BUFFER_delete(codecData->headerData);
596 codecData->headerData = NULL;
597}
598
599static void clear_codec_data(MQTTCODEC_INSTANCE* codec_data)
600{
601 // Clear the code instance data
602 codec_data->currPacket = UNKNOWN_TYPE;
603 codec_data->codecState = CODEC_STATE_FIXED_HEADER;
604 codec_data->headerFlags = 0;
605 codec_data->bufferOffset = 0;
606 codec_data->headerData = NULL;
607 memset(codec_data->storeRemainLen, 0, 4 * sizeof(uint8_t));
608 codec_data->remainLenIndex = 0;
609}
610
611void mqtt_codec_reset(MQTTCODEC_HANDLE handle)
612{
613 if (handle != NULL)
614 {
615 clear_codec_data(handle);
616 }
617}
618
619MQTTCODEC_HANDLE mqtt_codec_create(ON_PACKET_COMPLETE_CALLBACK packetComplete, void* callbackCtx)
620{
621 MQTTCODEC_HANDLE result;
622 result = malloc(sizeof(MQTTCODEC_INSTANCE));
623 /* Codes_SRS_MQTT_CODEC_07_001: [If a failure is encountered then mqtt_codec_create shall return NULL.] */
624 if (result != NULL)
625 {
626 /* Codes_SRS_MQTT_CODEC_07_002: [On success mqtt_codec_create shall return a MQTTCODEC_HANDLE value.] */
627 clear_codec_data(result);
628 result->packetComplete = packetComplete;
629 result->callContext = callbackCtx;
630 }
631 return result;
632}
633
634void mqtt_codec_destroy(MQTTCODEC_HANDLE handle)
635{
636 /* Codes_SRS_MQTT_CODEC_07_003: [If the handle parameter is NULL then mqtt_codec_destroy shall do nothing.] */
637 if (handle != NULL)
638 {
639 MQTTCODEC_INSTANCE* codecData = (MQTTCODEC_INSTANCE*)handle;
640 /* Codes_SRS_MQTT_CODEC_07_004: [mqtt_codec_destroy shall deallocate all memory that has been allocated by this object.] */
641 BUFFER_delete(codecData->headerData);
642 free(codecData);
643 }
644}
645
646BUFFER_HANDLE mqtt_codec_connect(const MQTT_CLIENT_OPTIONS* mqttOptions, STRING_HANDLE trace_log)
647{
648 BUFFER_HANDLE result;
649 /* Codes_SRS_MQTT_CODEC_07_008: [If the parameters mqttOptions is NULL then mqtt_codec_connect shall return a null value.] */
650 if (mqttOptions == NULL)
651 {
652 result = NULL;
653 }
654 else
655 {
656 /* Codes_SRS_MQTT_CODEC_07_009: [mqtt_codec_connect shall construct a BUFFER_HANDLE that represents a MQTT CONNECT packet.] */
657 result = BUFFER_new();
658 if (result != NULL)
659 {
660 STRING_HANDLE varible_header_log = NULL;
661 if (trace_log != NULL)
662 {
663 varible_header_log = STRING_new();
664 }
665 // Add Variable Header Information
666 if (constructConnectVariableHeader(result, mqttOptions, varible_header_log) != 0)
667 {
668 /* Codes_SRS_MQTT_CODEC_07_010: [If any error is encountered then mqtt_codec_connect shall return NULL.] */
669 BUFFER_delete(result);
670 result = NULL;
671 }
672 else
673 {
674 if (constructConnPayload(result, mqttOptions, varible_header_log) != 0)
675 {
676 /* Codes_SRS_MQTT_CODEC_07_010: [If any error is encountered then mqtt_codec_connect shall return NULL.] */
677 BUFFER_delete(result);
678 result = NULL;
679 }
680 else
681 {
682 if (trace_log != NULL)
683 {
684 (void)STRING_copy(trace_log, "CONNECT");
685 }
686 if (constructFixedHeader(result, CONNECT_TYPE, 0) != 0)
687 {
688 /* Codes_SRS_MQTT_CODEC_07_010: [If any error is encountered then mqtt_codec_connect shall return NULL.] */
689 BUFFER_delete(result);
690 result = NULL;
691 }
692 else
693 {
694 if (trace_log != NULL)
695 {
696 (void)STRING_concat_with_STRING(trace_log, varible_header_log);
697 }
698 }
699 }
700 if (varible_header_log != NULL)
701 {
702 STRING_delete(varible_header_log);
703 }
704 }
705 }
706 }
707 return result;
708}
709
710BUFFER_HANDLE mqtt_codec_disconnect()
711{
712 /* Codes_SRS_MQTT_CODEC_07_011: [On success mqtt_codec_disconnect shall construct a BUFFER_HANDLE that represents a MQTT DISCONNECT packet.] */
713 BUFFER_HANDLE result = BUFFER_new();
714 if (result != NULL)
715 {
716 if (BUFFER_enlarge(result, 2) != 0)
717 {
718 /* Codes_SRS_MQTT_CODEC_07_012: [If any error is encountered mqtt_codec_disconnect shall return NULL.] */
719 BUFFER_delete(result);
720 result = NULL;
721 }
722 else
723 {
724 uint8_t* iterator = BUFFER_u_char(result);
725 if (iterator == NULL)
726 {
727 /* Codes_SRS_MQTT_CODEC_07_012: [If any error is encountered mqtt_codec_disconnect shall return NULL.] */
728 BUFFER_delete(result);
729 result = NULL;
730 }
731 else
732 {
733 iterator[0] = DISCONNECT_TYPE;
734 iterator[1] = 0;
735 }
736 }
737 }
738 return result;
739}
740
741BUFFER_HANDLE mqtt_codec_publish(QOS_VALUE qosValue, bool duplicateMsg, bool serverRetain, uint16_t packetId, const char* topicName, const uint8_t* msgBuffer, size_t buffLen, STRING_HANDLE trace_log)
742{
743 BUFFER_HANDLE result;
744 /* Codes_SRS_MQTT_CODEC_07_005: [If the parameters topicName is NULL then mqtt_codec_publish shall return NULL.] */
745 if (topicName == NULL)
746 {
747 result = NULL;
748 }
749 /* Codes_SRS_MQTT_CODEC_07_036: [mqtt_codec_publish shall return NULL if the buffLen variable is greater than the MAX_SEND_SIZE (0xFFFFFF7F).] */
750 else if (buffLen > MAX_SEND_SIZE)
751 {
752 /* Codes_SRS_MQTT_CODEC_07_006: [If any error is encountered then mqtt_codec_publish shall return NULL.] */
753 result = NULL;
754 }
755 else
756 {
757 PUBLISH_HEADER_INFO publishInfo ={ 0 };
758 publishInfo.topicName = topicName;
759 publishInfo.packetId = packetId;
760 publishInfo.qualityOfServiceValue = qosValue;
761
762 uint8_t headerFlags = 0;
763 if (duplicateMsg) headerFlags |= PUBLISH_DUP_FLAG;
764 if (serverRetain) headerFlags |= PUBLISH_QOS_RETAIN;
765 if (qosValue != DELIVER_AT_MOST_ONCE)
766 {
767 if (qosValue == DELIVER_AT_LEAST_ONCE)
768 {
769 headerFlags |= PUBLISH_QOS_AT_LEAST_ONCE;
770 }
771 else
772 {
773 headerFlags |= PUBLISH_QOS_EXACTLY_ONCE;
774 }
775 }
776
777 /* Codes_SRS_MQTT_CODEC_07_007: [mqtt_codec_publish shall return a BUFFER_HANDLE that represents a MQTT PUBLISH message.] */
778 result = BUFFER_new();
779 if (result != NULL)
780 {
781 STRING_HANDLE varible_header_log = NULL;
782 if (trace_log != NULL)
783 {
784 varible_header_log = STRING_construct_sprintf(" | IS_DUP: %s | RETAIN: %d | QOS: %s", duplicateMsg ? TRUE_CONST : FALSE_CONST,
785 serverRetain ? 1 : 0,
786 retrieve_qos_value(publishInfo.qualityOfServiceValue) );
787 }
788
789 if (constructPublishVariableHeader(result, &publishInfo, varible_header_log) != 0)
790 {
791 /* Codes_SRS_MQTT_CODEC_07_006: [If any error is encountered then mqtt_codec_publish shall return NULL.] */
792 BUFFER_delete(result);
793 result = NULL;
794 }
795 else
796 {
797 size_t payloadOffset = BUFFER_length(result);
798 if (buffLen > 0)
799 {
800 if (BUFFER_enlarge(result, buffLen) != 0)
801 {
802 /* Codes_SRS_MQTT_CODEC_07_006: [If any error is encountered then mqtt_codec_publish shall return NULL.] */
803 BUFFER_delete(result);
804 result = NULL;
805 }
806 else
807 {
808 uint8_t* iterator = BUFFER_u_char(result);
809 if (iterator == NULL)
810 {
811 /* Codes_SRS_MQTT_CODEC_07_006: [If any error is encountered then mqtt_codec_publish shall return NULL.] */
812 BUFFER_delete(result);
813 result = NULL;
814 }
815 else
816 {
817 iterator += payloadOffset;
818 // Write Message
819 (void)memcpy(iterator, msgBuffer, buffLen);
820 if (trace_log)
821 {
822 STRING_sprintf(varible_header_log, " | PAYLOAD_LEN: %lu", (unsigned long)buffLen);
823 }
824 }
825 }
826 }
827
828 if (result != NULL)
829 {
830 if (trace_log != NULL)
831 {
832 (void)STRING_copy(trace_log, "PUBLISH");
833 }
834 if (constructFixedHeader(result, PUBLISH_TYPE, headerFlags) != 0)
835 {
836 /* Codes_SRS_MQTT_CODEC_07_006: [If any error is encountered then mqtt_codec_publish shall return NULL.] */
837 BUFFER_delete(result);
838 result = NULL;
839 }
840 else
841 {
842 if (trace_log != NULL)
843 {
844 (void)STRING_concat_with_STRING(trace_log, varible_header_log);
845 }
846 }
847 }
848 }
849 if (varible_header_log != NULL)
850 {
851 STRING_delete(varible_header_log);
852 }
853 }
854 }
855 return result;
856}
857
858BUFFER_HANDLE mqtt_codec_publishAck(uint16_t packetId)
859{
860 /* Codes_SRS_MQTT_CODEC_07_013: [On success mqtt_codec_publishAck shall return a BUFFER_HANDLE representation of a MQTT PUBACK packet.] */
861 /* Codes_SRS_MQTT_CODEC_07_014 : [If any error is encountered then mqtt_codec_publishAck shall return NULL.] */
862 BUFFER_HANDLE result = constructPublishReply(PUBACK_TYPE, 0, packetId);
863 return result;
864}
865
866BUFFER_HANDLE mqtt_codec_publishReceived(uint16_t packetId)
867{
868 /* Codes_SRS_MQTT_CODEC_07_015: [On success mqtt_codec_publishRecieved shall return a BUFFER_HANDLE representation of a MQTT PUBREC packet.] */
869 /* Codes_SRS_MQTT_CODEC_07_016 : [If any error is encountered then mqtt_codec_publishRecieved shall return NULL.] */
870 BUFFER_HANDLE result = constructPublishReply(PUBREC_TYPE, 0, packetId);
871 return result;
872}
873
874BUFFER_HANDLE mqtt_codec_publishRelease(uint16_t packetId)
875{
876 /* Codes_SRS_MQTT_CODEC_07_017: [On success mqtt_codec_publishRelease shall return a BUFFER_HANDLE representation of a MQTT PUBREL packet.] */
877 /* Codes_SRS_MQTT_CODEC_07_018 : [If any error is encountered then mqtt_codec_publishRelease shall return NULL.] */
878 BUFFER_HANDLE result = constructPublishReply(PUBREL_TYPE, 2, packetId);
879 return result;
880}
881
882BUFFER_HANDLE mqtt_codec_publishComplete(uint16_t packetId)
883{
884 /* Codes_SRS_MQTT_CODEC_07_019: [On success mqtt_codec_publishComplete shall return a BUFFER_HANDLE representation of a MQTT PUBCOMP packet.] */
885 /* Codes_SRS_MQTT_CODEC_07_020 : [If any error is encountered then mqtt_codec_publishComplete shall return NULL.] */
886 BUFFER_HANDLE result = constructPublishReply(PUBCOMP_TYPE, 0, packetId);
887 return result;
888}
889
890BUFFER_HANDLE mqtt_codec_ping()
891{
892 /* Codes_SRS_MQTT_CODEC_07_021: [On success mqtt_codec_ping shall construct a BUFFER_HANDLE that represents a MQTT PINGREQ packet.] */
893 BUFFER_HANDLE result = BUFFER_new();
894 if (result != NULL)
895 {
896 if (BUFFER_enlarge(result, 2) != 0)
897 {
898 /* Codes_SRS_MQTT_CODEC_07_022: [If any error is encountered mqtt_codec_ping shall return NULL.] */
899 BUFFER_delete(result);
900 result = NULL;
901 }
902 else
903 {
904 uint8_t* iterator = BUFFER_u_char(result);
905 if (iterator == NULL)
906 {
907 /* Codes_SRS_MQTT_CODEC_07_022: [If any error is encountered mqtt_codec_ping shall return NULL.] */
908 BUFFER_delete(result);
909 result = NULL;
910 }
911 else
912 {
913 iterator[0] = PINGREQ_TYPE;
914 iterator[1] = 0;
915 }
916 }
917 }
918 return result;
919}
920
921BUFFER_HANDLE mqtt_codec_subscribe(uint16_t packetId, SUBSCRIBE_PAYLOAD* subscribeList, size_t count, STRING_HANDLE trace_log)
922{
923 BUFFER_HANDLE result;
924 /* Codes_SRS_MQTT_CODEC_07_023: [If the parameters subscribeList is NULL or if count is 0 then mqtt_codec_subscribe shall return NULL.] */
925 if (subscribeList == NULL || count == 0)
926 {
927 result = NULL;
928 }
929 else
930 {
931 /* Codes_SRS_MQTT_CODEC_07_026: [mqtt_codec_subscribe shall return a BUFFER_HANDLE that represents a MQTT SUBSCRIBE message.]*/
932 result = BUFFER_new();
933 if (result != NULL)
934 {
935 if (constructSubscibeTypeVariableHeader(result, packetId) != 0)
936 {
937 /* Codes_SRS_MQTT_CODEC_07_025: [If any error is encountered then mqtt_codec_subscribe shall return NULL.] */
938 BUFFER_delete(result);
939 result = NULL;
940 }
941 else
942 {
943 STRING_HANDLE sub_trace = NULL;
944 if (trace_log != NULL)
945 {
946 sub_trace = STRING_construct_sprintf(" | PACKET_ID: %"PRIu16, packetId);
947 }
948 /* Codes_SRS_MQTT_CODEC_07_024: [mqtt_codec_subscribe shall iterate through count items in the subscribeList.] */
949 if (addListItemsToSubscribePacket(result, subscribeList, count, sub_trace) != 0)
950 {
951 /* Codes_SRS_MQTT_CODEC_07_025: [If any error is encountered then mqtt_codec_subscribe shall return NULL.] */
952 BUFFER_delete(result);
953 result = NULL;
954 }
955 else
956 {
957
958 if (trace_log != NULL)
959 {
960 STRING_concat(trace_log, "SUBSCRIBE");
961 }
962 if (constructFixedHeader(result, SUBSCRIBE_TYPE, SUBSCRIBE_FIXED_HEADER_FLAG) != 0)
963 {
964 /* Codes_SRS_MQTT_CODEC_07_025: [If any error is encountered then mqtt_codec_subscribe shall return NULL.] */
965 BUFFER_delete(result);
966 result = NULL;
967 }
968 else
969 {
970 if (trace_log != NULL)
971 {
972 (void)STRING_concat_with_STRING(trace_log, sub_trace);
973 }
974 }
975 }
976 if (sub_trace != NULL)
977 {
978 STRING_delete(sub_trace);
979 }
980 }
981 }
982 }
983 return result;
984}
985
986BUFFER_HANDLE mqtt_codec_unsubscribe(uint16_t packetId, const char** unsubscribeList, size_t count, STRING_HANDLE trace_log)
987{
988 BUFFER_HANDLE result;
989 /* Codes_SRS_MQTT_CODEC_07_027: [If the parameters unsubscribeList is NULL or if count is 0 then mqtt_codec_unsubscribe shall return NULL.] */
990 if (unsubscribeList == NULL || count == 0)
991 {
992 result = NULL;
993 }
994 else
995 {
996 /* Codes_SRS_MQTT_CODEC_07_030: [mqtt_codec_unsubscribe shall return a BUFFER_HANDLE that represents a MQTT SUBSCRIBE message.] */
997 result = BUFFER_new();
998 if (result != NULL)
999 {
1000 if (constructSubscibeTypeVariableHeader(result, packetId) != 0)
1001 {
1002 /* Codes_SRS_MQTT_CODEC_07_029: [If any error is encountered then mqtt_codec_unsubscribe shall return NULL.] */
1003 BUFFER_delete(result);
1004 result = NULL;
1005 }
1006 else
1007 {
1008 STRING_HANDLE unsub_trace = NULL;
1009 if (trace_log != NULL)
1010 {
1011 unsub_trace = STRING_construct_sprintf(" | PACKET_ID: %"PRIu16, packetId);
1012 }
1013 /* Codes_SRS_MQTT_CODEC_07_028: [mqtt_codec_unsubscribe shall iterate through count items in the unsubscribeList.] */
1014 if (addListItemsToUnsubscribePacket(result, unsubscribeList, count, unsub_trace) != 0)
1015 {
1016 /* Codes_SRS_MQTT_CODEC_07_029: [If any error is encountered then mqtt_codec_unsubscribe shall return NULL.] */
1017 BUFFER_delete(result);
1018 result = NULL;
1019 }
1020 else
1021 {
1022 if (trace_log != NULL)
1023 {
1024 (void)STRING_copy(trace_log, "UNSUBSCRIBE");
1025 }
1026 if (constructFixedHeader(result, UNSUBSCRIBE_TYPE, UNSUBSCRIBE_FIXED_HEADER_FLAG) != 0)
1027 {
1028 /* Codes_SRS_MQTT_CODEC_07_029: [If any error is encountered then mqtt_codec_unsubscribe shall return NULL.] */
1029 BUFFER_delete(result);
1030 result = NULL;
1031 }
1032 else
1033 {
1034 if (trace_log != NULL)
1035 {
1036 (void)STRING_concat_with_STRING(trace_log, unsub_trace);
1037 }
1038 }
1039 }
1040 if (unsub_trace != NULL)
1041 {
1042 STRING_delete(unsub_trace);
1043 }
1044 }
1045 }
1046 }
1047 return result;
1048}
1049
1050int mqtt_codec_bytesReceived(MQTTCODEC_HANDLE handle, const unsigned char* buffer, size_t size)
1051{
1052 int result;
1053 MQTTCODEC_INSTANCE* codec_Data = (MQTTCODEC_INSTANCE*)handle;
1054 /* Codes_SRS_MQTT_CODEC_07_031: [If the parameters handle or buffer is NULL then mqtt_codec_bytesReceived shall return a non-zero value.] */
1055 if (codec_Data == NULL)
1056 {
1057 result = MU_FAILURE;
1058 }
1059 /* Codes_SRS_MQTT_CODEC_07_031: [If the parameters handle or buffer is NULL then mqtt_codec_bytesReceived shall return a non-zero value.] */
1060 /* Codes_SRS_MQTT_CODEC_07_032: [If the parameters size is zero then mqtt_codec_bytesReceived shall return a non-zero value.] */
1061 else if (buffer == NULL || size == 0)
1062 {
1063 codec_Data->currPacket = PACKET_TYPE_ERROR;
1064 result = MU_FAILURE;
1065 }
1066 else
1067 {
1068 /* Codes_SRS_MQTT_CODEC_07_033: [mqtt_codec_bytesReceived constructs a sequence of bytes into the corresponding MQTT packets and on success returns zero.] */
1069 result = 0;
1070 size_t index = 0;
1071 for (index = 0; index < size && result == 0; index++)
1072 {
1073 uint8_t iterator = ((int8_t*)buffer)[index];
1074 if (codec_Data->codecState == CODEC_STATE_FIXED_HEADER)
1075 {
1076 if (codec_Data->currPacket == UNKNOWN_TYPE)
1077 {
1078 codec_Data->currPacket = processControlPacketType(iterator, &codec_Data->headerFlags);
1079
1080 // validate packet type and invalid reserved header flags
1081 switch (codec_Data->currPacket)
1082 {
1083 case PACKET_INVALID1_TYPE:
1084 case PACKET_INVALID2_TYPE:
1085 codec_Data->currPacket = PACKET_TYPE_ERROR;
1086 result = MU_FAILURE;
1087 break;
1088
1089 case CONNECT_TYPE:
1090 case CONNACK_TYPE:
1091 case PUBACK_TYPE:
1092 case PUBREC_TYPE:
1093 case PUBCOMP_TYPE:
1094 case SUBACK_TYPE:
1095 case UNSUBACK_TYPE:
1096 case PINGREQ_TYPE:
1097 case PINGRESP_TYPE:
1098 case DISCONNECT_TYPE:
1099 if (codec_Data->headerFlags & 0x0F) // flags must be all zeros
1100 {
1101 codec_Data->currPacket = PACKET_TYPE_ERROR;
1102 result = MU_FAILURE;
1103 }
1104 break;
1105
1106 case PUBREL_TYPE:
1107 case SUBSCRIBE_TYPE:
1108 case UNSUBSCRIBE_TYPE:
1109 if ((codec_Data->headerFlags & 0x0F) != 0x02) // only bit 1 must be set
1110 {
1111 codec_Data->currPacket = PACKET_TYPE_ERROR;
1112 result = MU_FAILURE;
1113 }
1114 break;
1115
1116 case PUBLISH_TYPE:
1117 case CONTROL_PACKET_TYPE_INVALID:
1118 case PACKET_TYPE_ERROR:
1119 case UNKNOWN_TYPE:
1120 break;
1121 }
1122 }
1123 else
1124 {
1125 if (prepareheaderDataInfo(codec_Data, iterator) != 0)
1126 {
1127 /* Codes_SRS_MQTT_CODEC_07_035: [If any error is encountered then the packet state will be marked as error and mqtt_codec_bytesReceived shall return a non-zero value.] */
1128 codec_Data->currPacket = PACKET_TYPE_ERROR;
1129 result = MU_FAILURE;
1130 }
1131 else if (codec_Data->currPacket == PINGRESP_TYPE)
1132 {
1133 // PINGRESP must not have a payload
1134 if (((int8_t*)buffer)[index] == 0)
1135 {
1136 /* Codes_SRS_MQTT_CODEC_07_034: [Upon a constructing a complete MQTT packet mqtt_codec_bytesReceived shall call the ON_PACKET_COMPLETE_CALLBACK function.] */
1137 completePacketData(codec_Data);
1138 }
1139 else
1140 {
1141 codec_Data->currPacket = PACKET_TYPE_ERROR;
1142 result = MU_FAILURE;
1143 }
1144 }
1145 }
1146 }
1147 else if (codec_Data->codecState == CODEC_STATE_VAR_HEADER)
1148 {
1149 if (codec_Data->headerData == NULL)
1150 {
1151 codec_Data->codecState = CODEC_STATE_PAYLOAD;
1152 }
1153 else
1154 {
1155 uint8_t* dataBytes = BUFFER_u_char(codec_Data->headerData);
1156 if (dataBytes == NULL)
1157 {
1158 /* Codes_SRS_MQTT_CODEC_07_035: [If any error is encountered then the packet state will be marked as error and mqtt_codec_bytesReceived shall return a non-zero value.] */
1159 codec_Data->currPacket = PACKET_TYPE_ERROR;
1160 result = MU_FAILURE;
1161 }
1162 else
1163 {
1164 // Increment the data
1165 dataBytes += codec_Data->bufferOffset++;
1166 *dataBytes = iterator;
1167
1168 size_t totalLen = BUFFER_length(codec_Data->headerData);
1169 if (codec_Data->bufferOffset >= totalLen)
1170 {
1171 /* Codes_SRS_MQTT_CODEC_07_034: [Upon a constructing a complete MQTT packet mqtt_codec_bytesReceived shall call the ON_PACKET_COMPLETE_CALLBACK function.] */
1172 completePacketData(codec_Data);
1173 }
1174 }
1175 }
1176 }
1177 else
1178 {
1179 /* Codes_SRS_MQTT_CODEC_07_035: [If any error is encountered then the packet state will be marked as error and mqtt_codec_bytesReceived shall return a non-zero value.] */
1180 codec_Data->currPacket = PACKET_TYPE_ERROR;
1181 result = MU_FAILURE;
1182 }
1183 }
1184 }
1185 return result;
1186}
Note: See TracBrowser for help on using the repository browser.