-
Notifications
You must be signed in to change notification settings - Fork 110
/
Copy pathbroker.hpp
2277 lines (2128 loc) · 91.6 KB
/
broker.hpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright Takatoshi Kondo 2017
//
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
#if !defined(MQTT_BROKER_BROKER_HPP)
#define MQTT_BROKER_BROKER_HPP
#include <mqtt/config.hpp>
#include <set>
#include <boost/lexical_cast.hpp>
#include <mqtt/broker/broker_namespace.hpp>
#include <mqtt/optional.hpp>
#include <mqtt/property.hpp>
#include <mqtt/visitor_util.hpp>
#include <mqtt/broker/session_state.hpp>
#include <mqtt/broker/sub_con_map.hpp>
#include <mqtt/broker/retained_messages.hpp>
#include <mqtt/broker/retained_topic_map.hpp>
#include <mqtt/broker/shared_target_impl.hpp>
#include <mqtt/broker/mutex.hpp>
#include <mqtt/broker/uuid.hpp>
MQTT_BROKER_NS_BEGIN
namespace mi = boost::multi_index;
namespace as = boost::asio;
#if defined(MQTT_STD_STRING_VIEW)
#define MQTT_STRING_VIEW_CONSTEXPR constexpr
#else // defined(MQTT_STD_STRING_VIEW)
#define MQTT_STRING_VIEW_CONSTEXPR
#endif // defined(MQTT_STD_STRING_VIEW)
// TODO: Technically this function is simply wrong, since it's treating the
// topic pattern as if it were an ASCII sequence.
// To make this function correct per the standard, it would be necessary
// to conduct the search for the wildcard characters using a proper
// UTF-8 API to avoid problems of interpreting parts of multi-byte characters
// as if they were individual ASCII characters
MQTT_STRING_VIEW_CONSTEXPR
bool validate_topic_filter(string_view topic_filter) {
/*
* Confirm the topic pattern is valid before registering it.
* Use rules from http://docs.oasis-open.org/mqtt/mqtt/v3.1.1/os/mqtt-v3.1.1-os.html#_Toc398718106
*/
// All Topic Names and Topic Filters MUST be at least one character long
// Topic Names and Topic Filters are UTF-8 Encoded Strings; they MUST NOT encode to more than 65,535 bytes
if (topic_filter.empty() || (topic_filter.size() > std::numeric_limits<std::uint16_t>::max())) {
return false;
}
for (string_view::size_type idx = topic_filter.find_first_of(string_view("\0+#", 3));
string_view::npos != idx;
idx = topic_filter.find_first_of(string_view("\0+#", 3), idx+1)) {
BOOST_ASSERT(
('\0' == topic_filter[idx])
|| ('+' == topic_filter[idx])
|| ('#' == topic_filter[idx])
);
if ('\0' == topic_filter[idx]) {
// Topic Names and Topic Filters MUST NOT include the null character (Unicode U+0000)
return false;
}
else if ('+' == topic_filter[idx]) {
/*
* Either must be the first character,
* or be preceeded by a topic seperator.
*/
if ((0 != idx) && ('/' != topic_filter[idx-1])) {
return false;
}
/*
* Either must be the last character,
* or be followed by a topic seperator.
*/
if ((topic_filter.size()-1 != idx) && ('/' != topic_filter[idx+1])) {
return false;
}
}
// multilevel wildcard
else if ('#' == topic_filter[idx]) {
/*
* Must be absolute last character.
* Must only be one multi level wild card.
*/
if (idx != topic_filter.size()-1) {
return false;
}
/*
* If not the first character, then the
* immediately preceeding character must
* be a topic level separator.
*/
if ((0 != idx) && ('/' != topic_filter[idx-1])) {
return false;
}
}
else {
return false;
}
}
return true;
}
#if defined(MQTT_STD_STRING_VIEW)
// The following rules come from https://docs.oasis-open.org/mqtt/mqtt/v5.0/os/mqtt-v5.0-os.html#_Toc3901247
static_assert( ! validate_topic_filter(""), "All Topic Names and Topic Filters MUST be at least one character long");
static_assert(validate_topic_filter("/"), "A Topic Name or Topic Filter consisting only of the ‘/’ character is valid");
static_assert( ! validate_topic_filter(string_view("\0", 1)), "Topic Names and Topic Filters MUST NOT include the null character (Unicode U+0000)");
static_assert(validate_topic_filter(" "), "Topic Names and Topic Filters can include the space character");
static_assert(validate_topic_filter("/////"), "Topic level separators can appear anywhere in a Topic Filter or Topic Name. Adjacent Topic level separators indicate a zero-length topic level");
static_assert(validate_topic_filter("#"), "The multi-level wildcard character MUST be specified either on its own or following a topic level separator");
static_assert(validate_topic_filter("/#"), "The multi-level wildcard character MUST be specified either on its own or following a topic level separator");
static_assert(validate_topic_filter("+/#"), "The multi-level wildcard character MUST be specified either on its own or following a topic level separator");
static_assert( ! validate_topic_filter("+#"), "The multi-level wildcard character MUST be specified either on its own or following a topic level separator");
static_assert( ! validate_topic_filter("++"), "The multi-level wildcard character MUST be specified either on its own or following a topic level separator");
static_assert( ! validate_topic_filter("f#"), "The multi-level wildcard character MUST be specified either on its own or following a topic level separator");
static_assert( ! validate_topic_filter("#/"), "In either case the multi-level wildcard character MUST be the last character specified in the Topic Filter");
static_assert(validate_topic_filter("+"), "The single-level wildcard can be used at any level in the Topic Filter, including first and last levels");
static_assert(validate_topic_filter("+/bob/alice/sue"), "The single-level wildcard can be used at any level in the Topic Filter, including first and last levels");
static_assert(validate_topic_filter("bob/alice/sue/+"), "The single-level wildcard can be used at any level in the Topic Filter, including first and last levels");
static_assert(validate_topic_filter("+/bob/alice/sue/+"), "The single-level wildcard can be used at any level in the Topic Filter, including first and last levels");
static_assert(validate_topic_filter("+/bob/+/sue/+"), "The single-level wildcard can be used at any level in the Topic Filter, including first and last levels");
static_assert(validate_topic_filter("+/bob/+/sue/#"), "The single-level wildcard can be used at more than one level in the Topic Filter and can be used in conjunction with the multi-level wildcard");
static_assert( ! validate_topic_filter("+a"), "Where it is used, the single-level wildcard MUST occupy an entire level of the filter.");
static_assert( ! validate_topic_filter("a+"), "Where it is used, the single-level wildcard MUST occupy an entire level of the filter.");
static_assert( ! validate_topic_filter("/a+"), "Where it is used, the single-level wildcard MUST occupy an entire level of the filter.");
static_assert( ! validate_topic_filter("a+/"), "Where it is used, the single-level wildcard MUST occupy an entire level of the filter.");
static_assert( ! validate_topic_filter("/a+/"), "Where it is used, the single-level wildcard MUST occupy an entire level of the filter.");
#endif // defined(MQTT_STD_STRING_VIEW)
MQTT_STRING_VIEW_CONSTEXPR
bool validate_topic_name(string_view topic_name) {
/*
* Confirm the topic name is valid
* Use rules from https://docs.oasis-open.org/mqtt/mqtt/v5.0/os/mqtt-v5.0-os.html#_Toc3901247
*/
// All Topic Names and Topic Filters MUST be at least one character long
// Topic Names and Topic Filters are UTF-8 Encoded Strings; they MUST NOT encode to more than 65,535 bytes
// The wildcard characters can be used in Topic Filters, but MUST NOT be used within a Topic Name
// Topic Names and Topic Filters MUST NOT include the null character (Unicode U+0000)
return
! topic_name.empty()
&& (topic_name.size() <= std::numeric_limits<std::uint16_t>::max())
&& (string_view::npos == topic_name.find_first_of(string_view("\0+#", 3)));
}
#if defined(MQTT_STD_STRING_VIEW)
// The following rules come from https://docs.oasis-open.org/mqtt/mqtt/v5.0/os/mqtt-v5.0-os.html#_Toc3901247
static_assert( ! validate_topic_name(""), "All Topic Names and Topic Filters MUST be at least one character long");
static_assert(validate_topic_name("/"), "A Topic Name or Topic Filter consisting only of the ‘/’ character is valid");
static_assert( ! validate_topic_name(string_view("\0", 1)), "Topic Names and Topic Filters MUST NOT include the null character (Unicode U+0000)");
static_assert(validate_topic_name(" "), "Topic Names and Topic Filters can include the space character");
static_assert(validate_topic_name("/////"), "Topic level separators can appear anywhere in a Topic Filter or Topic Name. Adjacent Topic level separators indicate a zero-length topic level");
static_assert( ! validate_topic_name("#"), "The wildcard characters can be used in Topic Filters, but MUST NOT be used within a Topic Name");
static_assert( ! validate_topic_name("+"), "The wildcard characters can be used in Topic Filters, but MUST NOT be used within a Topic Name");
static_assert( ! validate_topic_name("/#"), "The wildcard characters can be used in Topic Filters, but MUST NOT be used within a Topic Name");
static_assert( ! validate_topic_name("+/#"), "The wildcard characters can be used in Topic Filters, but MUST NOT be used within a Topic Name");
static_assert( ! validate_topic_name("f#"), "The wildcard characters can be used in Topic Filters, but MUST NOT be used within a Topic Name");
static_assert( ! validate_topic_name("#/"), "The wildcard characters can be used in Topic Filters, but MUST NOT be used within a Topic Name");
#endif // defined(MQTT_STD_STRING_VIEW)
MQTT_STRING_VIEW_CONSTEXPR
bool compare_topic_filter(string_view topic_filter, string_view topic_name) {
if ( ! validate_topic_filter(topic_filter)) {
BOOST_ASSERT(validate_topic_filter(topic_filter));
return false;
}
if ( ! validate_topic_name(topic_name)) {
BOOST_ASSERT(validate_topic_name(topic_name));
return false;
}
// TODO: The Server MUST NOT match Topic Filters starting with a wildcard character (# or +) with Topic Names beginning with a $ character
for (string_view::size_type idx = topic_filter.find_first_of("+#");
string_view::npos != idx;
idx = topic_filter.find_first_of("+#")) {
BOOST_ASSERT(
('+' == topic_filter[idx])
|| ('#' == topic_filter[idx])
);
if ('+' == topic_filter[idx]) {
// Compare everything up to the first +
if (topic_filter.substr(0, idx) == topic_name.substr(0, idx)) {
/*
* We already know thanks to the topic filter being validated
* that the + symbol is directly touching '/'s on both sides
* (if not the first or last character), so we don't need to
* double check that.
*
* By simply removing the prefix that we've compared and letting
* the loop continue, we get the proper comparison of the '/'s
* automatically when the loop continues.
*/
topic_filter.remove_prefix(idx+1);
/*
* It's a bit more complicated for the incoming topic though
* as we need to remove everything up to the next seperator.
*/
topic_name.remove_prefix(topic_name.find('/', idx));
}
else {
return false;
}
}
// multilevel wildcard
else {
/*
* Compare up to where the multilevel wild card is found
* and then anything after that matches the wildcard.
*/
return topic_filter.substr(0, idx) == topic_name.substr(0, idx);
}
}
// No + or # found in the remaining topic filter. Just do a string compare.
return topic_filter == topic_name;
}
#if defined(MQTT_STD_STRING_VIEW)
static_assert(compare_topic_filter("bob", "bob"), "Topic Names and Topic Filters are case sensitive");
static_assert( ! compare_topic_filter("Bob", "bob"), "Topic Names and Topic Filters are case sensitive");
static_assert( ! compare_topic_filter("bob", "boB"), "Topic Names and Topic Filters are case sensitive");
static_assert( ! compare_topic_filter("/bob", "bob"), "A leading or trailing ‘/’ creates a distinct Topic Name or Topic Filter");
static_assert( ! compare_topic_filter("bob/", "bob"), "A leading or trailing ‘/’ creates a distinct Topic Name or Topic Filter");
static_assert( ! compare_topic_filter("bob", "/bob"), "A leading or trailing ‘/’ creates a distinct Topic Name or Topic Filter");
static_assert( ! compare_topic_filter("bob", "bob/"), "A leading or trailing ‘/’ creates a distinct Topic Name or Topic Filter");
static_assert(compare_topic_filter("bob/alice", "bob/alice"), "Each non-wildcarded level in the Topic Filter has to match the corresponding level in the Topic Name character for character for the match to succeed");
static_assert(compare_topic_filter("bob/alice/sue", "bob/alice/sue"), "Each non-wildcarded level in the Topic Filter has to match the corresponding level in the Topic Name character for character for the match to succeed");
static_assert(compare_topic_filter("bob//////sue", "bob//////sue"), "Each non-wildcarded level in the Topic Filter has to match the corresponding level in the Topic Name character for character for the match to succeed");
static_assert(compare_topic_filter("bob/#", "bob//////sue"), "Each non-wildcarded level in the Topic Filter has to match the corresponding level in the Topic Name character for character for the match to succeed");
static_assert( ! compare_topic_filter("bob///#", "bob/sue"), "Each non-wildcarded level in the Topic Filter has to match the corresponding level in the Topic Name character for character for the match to succeed");
static_assert(compare_topic_filter("bob/+/sue", "bob/alice/sue"), "Each non-wildcarded level in the Topic Filter has to match the corresponding level in the Topic Name character for character for the match to succeed");
static_assert( ! compare_topic_filter("bob/+/sue", "bob/alice/mary/sue"), "Each non-wildcarded level in the Topic Filter has to match the corresponding level in the Topic Name character for character for the match to succeed");
static_assert(compare_topic_filter("#", "bob/alice/mary/sue"), "Each non-wildcarded level in the Topic Filter has to match the corresponding level in the Topic Name character for character for the match to succeed");
static_assert(compare_topic_filter("bob/#", "bob/alice/mary/sue"), "Each non-wildcarded level in the Topic Filter has to match the corresponding level in the Topic Name character for character for the match to succeed");
static_assert(compare_topic_filter("bob/alice/#", "bob/alice/mary/sue"), "Each non-wildcarded level in the Topic Filter has to match the corresponding level in the Topic Name character for character for the match to succeed");
static_assert(compare_topic_filter("bob/alice/mary/#", "bob/alice/mary/sue"), "Each non-wildcarded level in the Topic Filter has to match the corresponding level in the Topic Name character for character for the match to succeed");
static_assert( ! compare_topic_filter("bob/alice/mary/sue/#", "bob/alice/mary/sue"), "Each non-wildcarded level in the Topic Filter has to match the corresponding level in the Topic Name character for character for the match to succeed");
#endif // defined(MQTT_STD_STRING_VIEW)
class broker_t {
public:
broker_t(as::io_context& timer_ioc)
:timer_ioc_(timer_ioc),
tim_disconnect_(timer_ioc_)
{}
// [begin] for test setting
/**
* @brief set_disconnect_delay adds a delay to disconnect operations.
*
* This makes the broker wait the specified amount between when a disconnect
* is received from a client, and when the connection is actually closed in
* the broker.
*
* @param delay - the amount to delay by
*/
void set_disconnect_delay(std::chrono::steady_clock::duration delay) {
delay_disconnect_ = force_move(delay);
}
/**
* @brief set pingresp send operaton
*
* @param b - if true, send pingresp when pingreq is received.
* if false, doesn't send pingresp for test.
*/
void set_pingresp(bool b) {
pingresp_ = b;
}
/**
* @brief set pingresp send operaton
*
* @param b - if true, send connack when connect is received.
* if false, doesn't send connack for test.
*/
void set_connack(bool b) {
connack_ = b;
}
// [end] for test setting
/**
* @brief handle_accept
*
* Call this function when an server (of whatever kind) has accepted a raw
* connection from an MQTT client. By 'raw connection', this might be raw TCP sockets
* or websockets, or completed a TLS handshake, or any other underlying transport
* type, but what is not meant is that the mqtt client on the other end of the endpoint
* has initiated the MQTT application protocol connection sequence with CONNECT or CONACK
* messages being sent or received.
*
* This function will assign several event handlers into server (of whatever kind)
* that is provided as a parameter. This includes connection handlers, disconnection handlers
* and various handlers for a variety of of MQTT message types.
*
* @param ep - The server (of whichever kind) to accept a connection on.
*/
void handle_accept(con_sp_t spep) {
con_wp_t wp(spep);
endpoint_t& ep = *spep;
ep.socket().lowest_layer().set_option(as::ip::tcp::no_delay(true));
ep.set_auto_pub_response(false);
ep.set_async_operation(true);
ep.set_topic_alias_maximum(MQTT_NS::topic_alias_max);
// set connection (lower than MQTT) level handlers
ep.set_close_handler(
[this, wp]
(){
con_sp_t sp = wp.lock();
BOOST_ASSERT(sp);
close_proc(force_move(sp), true);
});
ep.set_error_handler(
[this, wp]
(error_code ec){
con_sp_t sp = wp.lock();
BOOST_ASSERT(sp);
auto ver = sp->get_protocol_version();
MQTT_LOG("mqtt_broker", info)
<< MQTT_ADD_VALUE(address, this)
<< " error_handler is called. ec:" << ec.message() << " protocol_version:" << ver;
auto send_response =
[&](auto ec) {
if (sp->connected()) {
auto rc =
[&] () -> MQTT_NS::optional<v5::disconnect_reason_code> {
if (ec == boost::system::errc::protocol_error) {
return MQTT_NS::v5::disconnect_reason_code::protocol_error;
}
else if (ec == boost::system::errc::bad_message) {
return MQTT_NS::v5::disconnect_reason_code::malformed_packet;
}
return MQTT_NS::nullopt;
}();
if (rc) {
MQTT_LOG("mqtt_broker", trace)
<< MQTT_ADD_VALUE(address, this)
<< "send DISCONNECT reason_code:" << rc.value();
sp->async_disconnect(
rc.value(),
v5::properties{},
[sp]
(error_code ec) {
if (ec) {
MQTT_LOG("mqtt_broker", info)
<< MQTT_ADD_VALUE(address, sp.get())
<< ec.message();
}
}
);
}
}
else if (sp->underlying_connected()){
// underlying layer connected, mqtt connecting
// and protocol_version has already been determind as v5
auto rc =
[&] () -> MQTT_NS::optional<v5::connect_reason_code> {
if (ec ==boost::system::errc::protocol_error) {
return MQTT_NS::v5::connect_reason_code::protocol_error;
}
else if (ec == boost::system::errc::bad_message) {
return MQTT_NS::v5::connect_reason_code::malformed_packet;
}
return MQTT_NS::nullopt;
}();
if (rc) {
MQTT_LOG("mqtt_broker", trace)
<< MQTT_ADD_VALUE(address, this)
<< "send CONNACK reason_code:" << rc.value();
if (connack_) sp->async_connack(
false,
rc.value(),
[sp]
(error_code ec) {
if (ec) {
MQTT_LOG("mqtt_broker", info)
<< MQTT_ADD_VALUE(address, sp.get())
<< ec.message();
}
}
);
}
}
};
switch (ver) {
case MQTT_NS::protocol_version::v5:
// https://docs.oasis-open.org/mqtt/mqtt/v5.0/os/mqtt-v5.0-os.html#S4_13_Errors
// https://docs.oasis-open.org/mqtt/mqtt/v5.0/os/mqtt-v5.0-os.html#_Toc3901205
//
// The DISCONNECT packet is the final MQTT Control Packet sent from the Client or
// the Server.
send_response(ec);
break;
case MQTT_NS::protocol_version::v3_1_1:
// DISCONNECT can't be sent by broker on v3.1.1
//
// http://docs.oasis-open.org/mqtt/mqtt/v3.1.1/os/mqtt-v3.1.1-os.html#_Toc398718090
//
// The DISCONNECT Packet is the final Control Packet sent from the Client to the Server.
// It indicates that the Client is disconnecting cleanly.
//
// At the MQTT connecting, there is no appropriate Connect Return Code on v3.1.1
// http://docs.oasis-open.org/mqtt/mqtt/v3.1.1/os/mqtt-v3.1.1-os.html#_Toc398718035
break;
default:
// The protocol_version is in the CONNECT packet.
// Protocol error could happen before the protocol_version is parsed.
break;
}
close_proc(force_move(sp), true);
}
);
// set MQTT level handlers
ep.set_connect_handler(
[this, wp]
(buffer client_id,
optional<buffer> username,
optional<buffer> password,
optional<will> will,
bool clean_session,
std::uint16_t keep_alive) {
con_sp_t sp = wp.lock();
BOOST_ASSERT(sp);
auto p = sp.get();
try {
return connect_handler(
force_move(sp),
force_move(client_id),
force_move(username),
force_move(password),
force_move(will),
clean_session,
keep_alive,
v5::properties{}
);
}
catch (std::exception const& ex) {
MQTT_LOG("mqtt_broker", error)
<< MQTT_ADD_VALUE(address, p)
<< ex.what();
return true;
}
}
);
ep.set_v5_connect_handler(
[this, wp]
(buffer client_id,
optional<buffer> username,
optional<buffer> password,
optional<will> will,
bool clean_start,
std::uint16_t keep_alive,
v5::properties props) {
con_sp_t sp = wp.lock();
BOOST_ASSERT(sp);
auto p = sp.get();
try {
return connect_handler(
force_move(sp),
force_move(client_id),
force_move(username),
force_move(password),
force_move(will),
clean_start,
keep_alive,
force_move(props)
);
}
catch (std::exception const& ex) {
MQTT_LOG("mqtt_broker", error)
<< MQTT_ADD_VALUE(address, p)
<< ex.what();
return true;
}
}
);
ep.set_disconnect_handler(
[this, wp]
(){
con_sp_t sp = wp.lock();
BOOST_ASSERT(sp);
auto p = sp.get();
try {
disconnect_handler(force_move(sp));
}
catch (std::exception const& ex) {
MQTT_LOG("mqtt_broker", error)
<< MQTT_ADD_VALUE(address, p)
<< ex.what();
}
}
);
ep.set_v5_disconnect_handler(
[this, wp]
(v5::disconnect_reason_code /*reason_code*/, v5::properties props) {
if (h_disconnect_props_) h_disconnect_props_(force_move(props));
con_sp_t sp = wp.lock();
BOOST_ASSERT(sp);
auto p = sp.get();
try {
disconnect_handler(force_move(sp));
}
catch (std::exception const& ex) {
MQTT_LOG("mqtt_broker", error)
<< MQTT_ADD_VALUE(address, p)
<< ex.what();
}
}
);
ep.set_puback_handler(
[this, wp]
(packet_id_t packet_id){
con_sp_t sp = wp.lock();
BOOST_ASSERT(sp);
auto p = sp.get();
try {
return puback_handler(
force_move(sp),
packet_id,
v5::puback_reason_code::success,
v5::properties{}
);
}
catch (std::exception const& ex) {
MQTT_LOG("mqtt_broker", error)
<< MQTT_ADD_VALUE(address, p)
<< ex.what();
return true;
}
}
);
ep.set_v5_puback_handler(
[this, wp]
(packet_id_t packet_id,
v5::puback_reason_code reason_code,
v5::properties props){
con_sp_t sp = wp.lock();
BOOST_ASSERT(sp);
auto p = sp.get();
try {
return puback_handler(
force_move(sp),
packet_id,
reason_code,
force_move(props)
);
}
catch (std::exception const& ex) {
MQTT_LOG("mqtt_broker", error)
<< MQTT_ADD_VALUE(address, p)
<< ex.what();
return true;
}
}
);
ep.set_pubrec_handler(
[this, wp]
(packet_id_t packet_id){
con_sp_t sp = wp.lock();
BOOST_ASSERT(sp);
auto p = sp.get();
try {
return pubrec_handler(
force_move(sp),
packet_id,
v5::pubrec_reason_code::success,
v5::properties{}
);
}
catch (std::exception const& ex) {
MQTT_LOG("mqtt_broker", error)
<< MQTT_ADD_VALUE(address, p)
<< ex.what();
return true;
}
}
);
ep.set_v5_pubrec_handler(
[this, wp]
(packet_id_t packet_id,
v5::pubrec_reason_code reason_code,
v5::properties props){
con_sp_t sp = wp.lock();
BOOST_ASSERT(sp);
auto p = sp.get();
try {
return pubrec_handler(
force_move(sp),
packet_id,
reason_code,
force_move(props)
);
}
catch (std::exception const& ex) {
MQTT_LOG("mqtt_broker", error)
<< MQTT_ADD_VALUE(address, p)
<< ex.what();
return true;
}
}
);
ep.set_pubrel_handler(
[this, wp]
(packet_id_t packet_id){
con_sp_t sp = wp.lock();
BOOST_ASSERT(sp);
auto p = sp.get();
try {
return pubrel_handler(
force_move(sp),
packet_id,
v5::pubrel_reason_code::success,
v5::properties{}
);
}
catch (std::exception const& ex) {
MQTT_LOG("mqtt_broker", error)
<< MQTT_ADD_VALUE(address, p)
<< ex.what();
return true;
}
}
);
ep.set_v5_pubrel_handler(
[this, wp]
(packet_id_t packet_id,
v5::pubrel_reason_code reason_code,
v5::properties props){
con_sp_t sp = wp.lock();
BOOST_ASSERT(sp);
auto p = sp.get();
try {
return pubrel_handler(
force_move(sp),
packet_id,
reason_code,
force_move(props)
);
}
catch (std::exception const& ex) {
MQTT_LOG("mqtt_broker", error)
<< MQTT_ADD_VALUE(address, p)
<< ex.what();
return true;
}
}
);
ep.set_pubcomp_handler(
[this, wp]
(packet_id_t packet_id){
con_sp_t sp = wp.lock();
BOOST_ASSERT(sp);
auto p = sp.get();
try {
return pubcomp_handler(
force_move(sp),
packet_id,
v5::pubcomp_reason_code::success,
v5::properties{}
);
}
catch (std::exception const& ex) {
MQTT_LOG("mqtt_broker", error)
<< MQTT_ADD_VALUE(address, p)
<< ex.what();
return true;
}
}
);
ep.set_v5_pubcomp_handler(
[this, wp]
(packet_id_t packet_id,
v5::pubcomp_reason_code reason_code,
v5::properties props){
con_sp_t sp = wp.lock();
BOOST_ASSERT(sp);
auto p = sp.get();
try {
return pubcomp_handler(
force_move(sp),
packet_id,
reason_code,
force_move(props)
);
}
catch (std::exception const& ex) {
MQTT_LOG("mqtt_broker", error)
<< MQTT_ADD_VALUE(address, p)
<< ex.what();
return true;
}
}
);
ep.set_publish_handler(
[this, wp]
(optional<packet_id_t> packet_id,
publish_options pubopts,
buffer topic_name,
buffer contents){
con_sp_t sp = wp.lock();
BOOST_ASSERT(sp);
auto p = sp.get();
try {
return publish_handler(
force_move(sp),
packet_id,
pubopts,
force_move(topic_name),
force_move(contents),
v5::properties{}
);
}
catch (std::exception const& ex) {
MQTT_LOG("mqtt_broker", error)
<< MQTT_ADD_VALUE(address, p)
<< ex.what();
return true;
}
}
);
ep.set_v5_publish_handler(
[this, wp]
(optional<packet_id_t> packet_id,
publish_options pubopts,
buffer topic_name,
buffer contents,
v5::properties props
) {
if (h_publish_props_) h_publish_props_(props);
con_sp_t sp = wp.lock();
BOOST_ASSERT(sp);
auto p = sp.get();
try {
return publish_handler(
force_move(sp),
packet_id,
pubopts,
force_move(topic_name),
force_move(contents),
force_move(props)
);
}
catch (std::exception const& ex) {
MQTT_LOG("mqtt_broker", error)
<< MQTT_ADD_VALUE(address, p)
<< ex.what();
return true;
}
}
);
ep.set_subscribe_handler(
[this, wp]
(packet_id_t packet_id,
std::vector<subscribe_entry> entries) {
con_sp_t sp = wp.lock();
BOOST_ASSERT(sp);
auto p = sp.get();
try {
return subscribe_handler(
force_move(sp),
packet_id,
force_move(entries),
v5::properties{}
);
}
catch (std::exception const& ex) {
MQTT_LOG("mqtt_broker", error)
<< MQTT_ADD_VALUE(address, p)
<< ex.what();
return true;
}
}
);
ep.set_v5_subscribe_handler(
[this, wp]
(packet_id_t packet_id,
std::vector<subscribe_entry> entries,
v5::properties props
) {
con_sp_t sp = wp.lock();
BOOST_ASSERT(sp);
auto p = sp.get();
try {
return subscribe_handler(
force_move(sp),
packet_id,
force_move(entries),
force_move(props)
);
}
catch (std::exception const& ex) {
MQTT_LOG("mqtt_broker", error)
<< MQTT_ADD_VALUE(address, p)
<< ex.what();
return true;
}
}
);
ep.set_unsubscribe_handler(
[this, wp]
(packet_id_t packet_id,
std::vector<unsubscribe_entry> entries) {
con_sp_t sp = wp.lock();
BOOST_ASSERT(sp);
auto p = sp.get();
try {
return unsubscribe_handler(
force_move(sp),
packet_id,
force_move(entries),
v5::properties{}
);
}
catch (std::exception const& ex) {
MQTT_LOG("mqtt_broker", error)
<< MQTT_ADD_VALUE(address, p)
<< ex.what();
return true;
}
}
);
ep.set_v5_unsubscribe_handler(
[this, wp]
(packet_id_t packet_id,
std::vector<unsubscribe_entry> entries,
v5::properties props
) {
con_sp_t sp = wp.lock();
BOOST_ASSERT(sp);
auto p = sp.get();
try {
return unsubscribe_handler(
force_move(sp),
packet_id,
force_move(entries),
force_move(props)
);
}
catch (std::exception const& ex) {
MQTT_LOG("mqtt_broker", error)
<< MQTT_ADD_VALUE(address, p)
<< ex.what();
return true;
}
}
);
ep.set_pingreq_handler(
[this, wp] {
con_sp_t sp = wp.lock();
BOOST_ASSERT(sp);
if (pingresp_) {
auto p = sp.get();
p->async_pingresp(
[sp = force_move(sp)]
(error_code ec) {
if (ec) {
MQTT_LOG("mqtt_broker", info)
<< MQTT_ADD_VALUE(address, sp.get())
<< ec.message();
}
}
);
}
return true;
}
);
ep.set_v5_auth_handler(
[this]
(v5::auth_reason_code /*reason_code*/,
v5::properties props
) {
if (h_auth_props_) h_auth_props_(force_move(props));
return true;
}
);
// Pass spep to keep lifetime.
// It makes sure wp.lock() never return nullptr in the handlers below
// including close_handler and error_handler.
ep.start_session(spep);
}
void set_connack_props(v5::properties props) {
connack_props_ = force_move(props);
}
void set_suback_props(v5::properties props) {
suback_props_ = force_move(props);
}
void set_unsuback_props(v5::properties props) {
unsuback_props_ = force_move(props);
}
void set_puback_props(v5::properties props) {
puback_props_ = force_move(props);
}
void set_pubrec_props(v5::properties props) {
pubrec_props_ = force_move(props);
}
void set_pubrel_props(v5::properties props) {
pubrel_props_ = force_move(props);
}
void set_pubcomp_props(v5::properties props) {
pubcomp_props_ = force_move(props);
}
void set_connect_props_handler(std::function<void(v5::properties const&)> h) {
h_connect_props_ = force_move(h);
}
void set_disconnect_props_handler(std::function<void(v5::properties const&)> h) {
h_disconnect_props_ = force_move(h);
}
void set_publish_props_handler(std::function<void(v5::properties const&)> h) {
h_publish_props_ = force_move(h);
}
void set_puback_props_handler(std::function<void(v5::properties const&)> h) {
h_puback_props_ = force_move(h);
}
void set_pubrec_props_handler(std::function<void(v5::properties const&)> h) {
h_pubrec_props_ = force_move(h);
}
void set_pubrel_props_handler(std::function<void(v5::properties const&)> h) {
h_pubrel_props_ = force_move(h);
}
void set_pubcomp_props_handler(std::function<void(v5::properties const&)> h) {
h_pubcomp_props_ = force_move(h);
}
void set_subscribe_props_handler(std::function<void(v5::properties const&)> h) {
h_subscribe_props_ = force_move(h);
}
void set_unsubscribe_props_handler(std::function<void(v5::properties const&)> h) {
h_unsubscribe_props_ = force_move(h);
}
void set_auth_props_handler(std::function<void(v5::properties const&)> h) {
h_auth_props_ = force_move(h);
}
void clear_all_sessions() {
std::lock_guard<mutex> g(mtx_sessions_);
sessions_.clear();
}
void clear_all_retained_topics() {
std::lock_guard<mutex> g(mtx_retains_);
retains_.clear();
}
private:
/**
* @brief connect_proc Process an incoming CONNECT packet
*
* This is called by the connect_handler function, which is registered
* on mqtt connections where the raw transport (tcp / tls / websocket / etc)
* is established, but the CONNECT message has not been sent / received by
* the mqtt client on the other end of the connection.
*
* When the CONNECT message is received, this function is called after some
* basic pre-connection logic, to setup the record keeping that this broker
* class needs to handle the connection and process subscriptions and publishing.
*
* @param clean_start - if the clean-start flag is set on the CONNECT message.
* @param spep - varient of shared pointers to underlying connection type.
* @param client_id - the id that the client wants to use