emqx_frame.erl 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749
  1. %%--------------------------------------------------------------------
  2. %% Copyright (c) 2020 EMQ Technologies Co., Ltd. All Rights Reserved.
  3. %%
  4. %% Licensed under the Apache License, Version 2.0 (the "License");
  5. %% you may not use this file except in compliance with the License.
  6. %% You may obtain a copy of the License at
  7. %%
  8. %% http://www.apache.org/licenses/LICENSE-2.0
  9. %%
  10. %% Unless required by applicable law or agreed to in writing, software
  11. %% distributed under the License is distributed on an "AS IS" BASIS,
  12. %% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. %% See the License for the specific language governing permissions and
  14. %% limitations under the License.
  15. %%--------------------------------------------------------------------
  16. -module(emqx_frame).
  17. -include_lib("emqx_libs/include/emqx.hrl").
  18. -include_lib("emqx_libs/include/emqx_mqtt.hrl").
  19. -export([ initial_parse_state/0
  20. , initial_parse_state/1
  21. ]).
  22. -export([ parse/1
  23. , parse/2
  24. , serialize_fun/0
  25. , serialize_fun/1
  26. , serialize/1
  27. , serialize/2
  28. ]).
  29. -export_type([ options/0
  30. , parse_state/0
  31. , parse_result/0
  32. , serialize_fun/0
  33. ]).
  34. -type(options() :: #{strict_mode => boolean(),
  35. max_size => 1..?MAX_PACKET_SIZE,
  36. version => emqx_types:version()
  37. }).
  38. -type(parse_state() :: {none, options()} | cont_fun()).
  39. -type(parse_result() :: {more, cont_fun()}
  40. | {ok, emqx_types:packet(), binary(), parse_state()}).
  41. -type(cont_fun() :: fun((binary()) -> parse_result())).
  42. -type(serialize_fun() :: fun((emqx_types:packet()) -> iodata())).
  43. -define(none(Options), {none, Options}).
  44. -define(DEFAULT_OPTIONS,
  45. #{strict_mode => false,
  46. max_size => ?MAX_PACKET_SIZE,
  47. version => ?MQTT_PROTO_V4
  48. }).
  49. -dialyzer({no_match, [serialize_utf8_string/2]}).
  50. %%--------------------------------------------------------------------
  51. %% Init Parse State
  52. %%--------------------------------------------------------------------
  53. -spec(initial_parse_state() -> {none, options()}).
  54. initial_parse_state() ->
  55. initial_parse_state(#{}).
  56. -spec(initial_parse_state(options()) -> {none, options()}).
  57. initial_parse_state(Options) when is_map(Options) ->
  58. ?none(merge_opts(Options)).
  59. %% @pivate
  60. merge_opts(Options) ->
  61. maps:merge(?DEFAULT_OPTIONS, Options).
  62. %%--------------------------------------------------------------------
  63. %% Parse MQTT Frame
  64. %%--------------------------------------------------------------------
  65. -spec(parse(binary()) -> parse_result()).
  66. parse(Bin) ->
  67. parse(Bin, initial_parse_state()).
  68. -spec(parse(binary(), parse_state()) -> parse_result()).
  69. parse(<<>>, {none, Options}) ->
  70. {more, fun(Bin) -> parse(Bin, {none, Options}) end};
  71. parse(<<Type:4, Dup:1, QoS:2, Retain:1, Rest/binary>>,
  72. {none, Options = #{strict_mode := StrictMode}}) ->
  73. %% Validate header if strict mode.
  74. StrictMode andalso validate_header(Type, Dup, QoS, Retain),
  75. Header = #mqtt_packet_header{type = Type,
  76. dup = bool(Dup),
  77. qos = QoS,
  78. retain = bool(Retain)
  79. },
  80. Header1 = case fixqos(Type, QoS) of
  81. QoS -> Header;
  82. FixedQoS -> Header#mqtt_packet_header{qos = FixedQoS}
  83. end,
  84. parse_remaining_len(Rest, Header1, Options);
  85. parse(Bin, Cont) when is_binary(Bin), is_function(Cont) ->
  86. Cont(Bin).
  87. parse_remaining_len(<<>>, Header, Options) ->
  88. {more, fun(Bin) -> parse_remaining_len(Bin, Header, Options) end};
  89. parse_remaining_len(Rest, Header, Options) ->
  90. parse_remaining_len(Rest, Header, 1, 0, Options).
  91. parse_remaining_len(_Bin, _Header, _Multiplier, Length, #{max_size := MaxSize})
  92. when Length > MaxSize ->
  93. error(frame_too_large);
  94. parse_remaining_len(<<>>, Header, Multiplier, Length, Options) ->
  95. {more, fun(Bin) -> parse_remaining_len(Bin, Header, Multiplier, Length, Options) end};
  96. %% Match DISCONNECT without payload
  97. parse_remaining_len(<<0:8, Rest/binary>>, Header = #mqtt_packet_header{type = ?DISCONNECT}, 1, 0, Options) ->
  98. Packet = packet(Header, #mqtt_packet_disconnect{reason_code = ?RC_SUCCESS}),
  99. {ok, Packet, Rest, ?none(Options)};
  100. %% Match PINGREQ.
  101. parse_remaining_len(<<0:8, Rest/binary>>, Header, 1, 0, Options) ->
  102. parse_frame(Rest, Header, 0, Options);
  103. %% Match PUBACK, PUBREC, PUBREL, PUBCOMP, UNSUBACK...
  104. parse_remaining_len(<<0:1, 2:7, Rest/binary>>, Header, 1, 0, Options) ->
  105. parse_frame(Rest, Header, 2, Options);
  106. parse_remaining_len(<<1:1, Len:7, Rest/binary>>, Header, Multiplier, Value, Options) ->
  107. parse_remaining_len(Rest, Header, Multiplier * ?HIGHBIT, Value + Len * Multiplier, Options);
  108. parse_remaining_len(<<0:1, Len:7, Rest/binary>>, Header, Multiplier, Value,
  109. Options = #{max_size := MaxSize}) ->
  110. FrameLen = Value + Len * Multiplier,
  111. if
  112. FrameLen > MaxSize -> error(frame_too_large);
  113. true -> parse_frame(Rest, Header, FrameLen, Options)
  114. end.
  115. parse_frame(Bin, Header, 0, Options) ->
  116. {ok, packet(Header), Bin, ?none(Options)};
  117. parse_frame(Bin, Header, Length, Options) ->
  118. case Bin of
  119. <<FrameBin:Length/binary, Rest/binary>> ->
  120. case parse_packet(Header, FrameBin, Options) of
  121. {Variable, Payload} ->
  122. {ok, packet(Header, Variable, Payload), Rest, ?none(Options)};
  123. Variable = #mqtt_packet_connect{proto_ver = Ver} ->
  124. {ok, packet(Header, Variable), Rest, ?none(Options#{version := Ver})};
  125. Variable ->
  126. {ok, packet(Header, Variable), Rest, ?none(Options)}
  127. end;
  128. TooShortBin ->
  129. {more, fun(BinMore) ->
  130. parse_frame(<<TooShortBin/binary, BinMore/binary>>, Header, Length, Options)
  131. end}
  132. end.
  133. -compile({inline, [packet/1, packet/2, packet/3]}).
  134. packet(Header) ->
  135. #mqtt_packet{header = Header}.
  136. packet(Header, Variable) ->
  137. #mqtt_packet{header = Header, variable = Variable}.
  138. packet(Header, Variable, Payload) ->
  139. #mqtt_packet{header = Header, variable = Variable, payload = Payload}.
  140. parse_packet(#mqtt_packet_header{type = ?CONNECT}, FrameBin, _Options) ->
  141. {ProtoName, Rest} = parse_utf8_string(FrameBin),
  142. <<BridgeTag:4, ProtoVer:4, Rest1/binary>> = Rest,
  143. % Note: Crash when reserved flag doesn't equal to 0, there is no strict
  144. % compliance with the MQTT5.0.
  145. <<UsernameFlag : 1,
  146. PasswordFlag : 1,
  147. WillRetain : 1,
  148. WillQoS : 2,
  149. WillFlag : 1,
  150. CleanStart : 1,
  151. 0 : 1,
  152. KeepAlive : 16/big,
  153. Rest2/binary>> = Rest1,
  154. {Properties, Rest3} = parse_properties(Rest2, ProtoVer),
  155. {ClientId, Rest4} = parse_utf8_string(Rest3),
  156. ConnPacket = #mqtt_packet_connect{proto_name = ProtoName,
  157. proto_ver = ProtoVer,
  158. is_bridge = (BridgeTag =:= 8),
  159. clean_start = bool(CleanStart),
  160. will_flag = bool(WillFlag),
  161. will_qos = WillQoS,
  162. will_retain = bool(WillRetain),
  163. keepalive = KeepAlive,
  164. properties = Properties,
  165. clientid = ClientId
  166. },
  167. {ConnPacket1, Rest5} = parse_will_message(ConnPacket, Rest4),
  168. {Username, Rest6} = parse_utf8_string(Rest5, bool(UsernameFlag)),
  169. {Passsword, <<>>} = parse_utf8_string(Rest6, bool(PasswordFlag)),
  170. ConnPacket1#mqtt_packet_connect{username = Username, password = Passsword};
  171. parse_packet(#mqtt_packet_header{type = ?CONNACK},
  172. <<AckFlags:8, ReasonCode:8, Rest/binary>>, #{version := Ver}) ->
  173. {Properties, <<>>} = parse_properties(Rest, Ver),
  174. #mqtt_packet_connack{ack_flags = AckFlags,
  175. reason_code = ReasonCode,
  176. properties = Properties
  177. };
  178. parse_packet(#mqtt_packet_header{type = ?PUBLISH, qos = QoS}, Bin,
  179. #{strict_mode := StrictMode, version := Ver}) ->
  180. {TopicName, Rest} = parse_utf8_string(Bin),
  181. {PacketId, Rest1} = case QoS of
  182. ?QOS_0 -> {undefined, Rest};
  183. _ -> parse_packet_id(Rest)
  184. end,
  185. (PacketId =/= undefined) andalso
  186. StrictMode andalso validate_packet_id(PacketId),
  187. {Properties, Payload} = parse_properties(Rest1, Ver),
  188. Publish = #mqtt_packet_publish{topic_name = TopicName,
  189. packet_id = PacketId,
  190. properties = Properties
  191. },
  192. {Publish, Payload};
  193. parse_packet(#mqtt_packet_header{type = PubAck}, <<PacketId:16/big>>, #{strict_mode := StrictMode})
  194. when ?PUBACK =< PubAck, PubAck =< ?PUBCOMP ->
  195. StrictMode andalso validate_packet_id(PacketId),
  196. #mqtt_packet_puback{packet_id = PacketId, reason_code = 0};
  197. parse_packet(#mqtt_packet_header{type = PubAck}, <<PacketId:16/big, ReasonCode, Rest/binary>>,
  198. #{strict_mode := StrictMode, version := Ver = ?MQTT_PROTO_V5})
  199. when ?PUBACK =< PubAck, PubAck =< ?PUBCOMP ->
  200. StrictMode andalso validate_packet_id(PacketId),
  201. {Properties, <<>>} = parse_properties(Rest, Ver),
  202. #mqtt_packet_puback{packet_id = PacketId,
  203. reason_code = ReasonCode,
  204. properties = Properties
  205. };
  206. parse_packet(#mqtt_packet_header{type = ?SUBSCRIBE}, <<PacketId:16/big, Rest/binary>>,
  207. #{strict_mode := StrictMode, version := Ver}) ->
  208. StrictMode andalso validate_packet_id(PacketId),
  209. {Properties, Rest1} = parse_properties(Rest, Ver),
  210. TopicFilters = parse_topic_filters(subscribe, Rest1),
  211. ok = validate_subqos([QoS || {_, #{qos := QoS}} <- TopicFilters]),
  212. #mqtt_packet_subscribe{packet_id = PacketId,
  213. properties = Properties,
  214. topic_filters = TopicFilters
  215. };
  216. parse_packet(#mqtt_packet_header{type = ?SUBACK}, <<PacketId:16/big, Rest/binary>>,
  217. #{strict_mode := StrictMode, version := Ver}) ->
  218. StrictMode andalso validate_packet_id(PacketId),
  219. {Properties, Rest1} = parse_properties(Rest, Ver),
  220. ReasonCodes = parse_reason_codes(Rest1),
  221. #mqtt_packet_suback{packet_id = PacketId,
  222. properties = Properties,
  223. reason_codes = ReasonCodes
  224. };
  225. parse_packet(#mqtt_packet_header{type = ?UNSUBSCRIBE}, <<PacketId:16/big, Rest/binary>>,
  226. #{strict_mode := StrictMode, version := Ver}) ->
  227. StrictMode andalso validate_packet_id(PacketId),
  228. {Properties, Rest1} = parse_properties(Rest, Ver),
  229. TopicFilters = parse_topic_filters(unsubscribe, Rest1),
  230. #mqtt_packet_unsubscribe{packet_id = PacketId,
  231. properties = Properties,
  232. topic_filters = TopicFilters
  233. };
  234. parse_packet(#mqtt_packet_header{type = ?UNSUBACK}, <<PacketId:16/big>>,
  235. #{strict_mode := StrictMode}) ->
  236. StrictMode andalso validate_packet_id(PacketId),
  237. #mqtt_packet_unsuback{packet_id = PacketId};
  238. parse_packet(#mqtt_packet_header{type = ?UNSUBACK}, <<PacketId:16/big, Rest/binary>>,
  239. #{strict_mode := StrictMode, version := Ver}) ->
  240. StrictMode andalso validate_packet_id(PacketId),
  241. {Properties, Rest1} = parse_properties(Rest, Ver),
  242. ReasonCodes = parse_reason_codes(Rest1),
  243. #mqtt_packet_unsuback{packet_id = PacketId,
  244. properties = Properties,
  245. reason_codes = ReasonCodes
  246. };
  247. parse_packet(#mqtt_packet_header{type = ?DISCONNECT}, <<ReasonCode, Rest/binary>>,
  248. #{version := ?MQTT_PROTO_V5}) ->
  249. {Properties, <<>>} = parse_properties(Rest, ?MQTT_PROTO_V5),
  250. #mqtt_packet_disconnect{reason_code = ReasonCode,
  251. properties = Properties
  252. };
  253. parse_packet(#mqtt_packet_header{type = ?AUTH}, <<ReasonCode, Rest/binary>>,
  254. #{version := ?MQTT_PROTO_V5}) ->
  255. {Properties, <<>>} = parse_properties(Rest, ?MQTT_PROTO_V5),
  256. #mqtt_packet_auth{reason_code = ReasonCode, properties = Properties}.
  257. parse_will_message(Packet = #mqtt_packet_connect{will_flag = true,
  258. proto_ver = Ver}, Bin) ->
  259. {Props, Rest} = parse_properties(Bin, Ver),
  260. {Topic, Rest1} = parse_utf8_string(Rest),
  261. {Payload, Rest2} = parse_binary_data(Rest1),
  262. {Packet#mqtt_packet_connect{will_props = Props,
  263. will_topic = Topic,
  264. will_payload = Payload
  265. }, Rest2};
  266. parse_will_message(Packet, Bin) -> {Packet, Bin}.
  267. -compile({inline, [parse_packet_id/1]}).
  268. parse_packet_id(<<PacketId:16/big, Rest/binary>>) ->
  269. {PacketId, Rest}.
  270. parse_properties(Bin, Ver) when Ver =/= ?MQTT_PROTO_V5 ->
  271. {#{}, Bin};
  272. %% TODO: version mess?
  273. parse_properties(<<>>, ?MQTT_PROTO_V5) ->
  274. {#{}, <<>>};
  275. parse_properties(<<0, Rest/binary>>, ?MQTT_PROTO_V5) ->
  276. {#{}, Rest};
  277. parse_properties(Bin, ?MQTT_PROTO_V5) ->
  278. {Len, Rest} = parse_variable_byte_integer(Bin),
  279. <<PropsBin:Len/binary, Rest1/binary>> = Rest,
  280. {parse_property(PropsBin, #{}), Rest1}.
  281. parse_property(<<>>, Props) ->
  282. Props;
  283. parse_property(<<16#01, Val, Bin/binary>>, Props) ->
  284. parse_property(Bin, Props#{'Payload-Format-Indicator' => Val});
  285. parse_property(<<16#02, Val:32/big, Bin/binary>>, Props) ->
  286. parse_property(Bin, Props#{'Message-Expiry-Interval' => Val});
  287. parse_property(<<16#03, Bin/binary>>, Props) ->
  288. {Val, Rest} = parse_utf8_string(Bin),
  289. parse_property(Rest, Props#{'Content-Type' => Val});
  290. parse_property(<<16#08, Bin/binary>>, Props) ->
  291. {Val, Rest} = parse_utf8_string(Bin),
  292. parse_property(Rest, Props#{'Response-Topic' => Val});
  293. parse_property(<<16#09, Len:16/big, Val:Len/binary, Bin/binary>>, Props) ->
  294. parse_property(Bin, Props#{'Correlation-Data' => Val});
  295. parse_property(<<16#0B, Bin/binary>>, Props) ->
  296. {Val, Rest} = parse_variable_byte_integer(Bin),
  297. parse_property(Rest, Props#{'Subscription-Identifier' => Val});
  298. parse_property(<<16#11, Val:32/big, Bin/binary>>, Props) ->
  299. parse_property(Bin, Props#{'Session-Expiry-Interval' => Val});
  300. parse_property(<<16#12, Bin/binary>>, Props) ->
  301. {Val, Rest} = parse_utf8_string(Bin),
  302. parse_property(Rest, Props#{'Assigned-Client-Identifier' => Val});
  303. parse_property(<<16#13, Val:16, Bin/binary>>, Props) ->
  304. parse_property(Bin, Props#{'Server-Keep-Alive' => Val});
  305. parse_property(<<16#15, Bin/binary>>, Props) ->
  306. {Val, Rest} = parse_utf8_string(Bin),
  307. parse_property(Rest, Props#{'Authentication-Method' => Val});
  308. parse_property(<<16#16, Len:16/big, Val:Len/binary, Bin/binary>>, Props) ->
  309. parse_property(Bin, Props#{'Authentication-Data' => Val});
  310. parse_property(<<16#17, Val, Bin/binary>>, Props) ->
  311. parse_property(Bin, Props#{'Request-Problem-Information' => Val});
  312. parse_property(<<16#18, Val:32, Bin/binary>>, Props) ->
  313. parse_property(Bin, Props#{'Will-Delay-Interval' => Val});
  314. parse_property(<<16#19, Val, Bin/binary>>, Props) ->
  315. parse_property(Bin, Props#{'Request-Response-Information' => Val});
  316. parse_property(<<16#1A, Bin/binary>>, Props) ->
  317. {Val, Rest} = parse_utf8_string(Bin),
  318. parse_property(Rest, Props#{'Response-Information' => Val});
  319. parse_property(<<16#1C, Bin/binary>>, Props) ->
  320. {Val, Rest} = parse_utf8_string(Bin),
  321. parse_property(Rest, Props#{'Server-Reference' => Val});
  322. parse_property(<<16#1F, Bin/binary>>, Props) ->
  323. {Val, Rest} = parse_utf8_string(Bin),
  324. parse_property(Rest, Props#{'Reason-String' => Val});
  325. parse_property(<<16#21, Val:16/big, Bin/binary>>, Props) ->
  326. parse_property(Bin, Props#{'Receive-Maximum' => Val});
  327. parse_property(<<16#22, Val:16/big, Bin/binary>>, Props) ->
  328. parse_property(Bin, Props#{'Topic-Alias-Maximum' => Val});
  329. parse_property(<<16#23, Val:16/big, Bin/binary>>, Props) ->
  330. parse_property(Bin, Props#{'Topic-Alias' => Val});
  331. parse_property(<<16#24, Val, Bin/binary>>, Props) ->
  332. parse_property(Bin, Props#{'Maximum-QoS' => Val});
  333. parse_property(<<16#25, Val, Bin/binary>>, Props) ->
  334. parse_property(Bin, Props#{'Retain-Available' => Val});
  335. parse_property(<<16#26, Bin/binary>>, Props) ->
  336. {Pair, Rest} = parse_utf8_pair(Bin),
  337. case maps:find('User-Property', Props) of
  338. {ok, UserProps} ->
  339. UserProps1 = lists:append(UserProps, [Pair]),
  340. parse_property(Rest, Props#{'User-Property' := UserProps1});
  341. error ->
  342. parse_property(Rest, Props#{'User-Property' => [Pair]})
  343. end;
  344. parse_property(<<16#27, Val:32, Bin/binary>>, Props) ->
  345. parse_property(Bin, Props#{'Maximum-Packet-Size' => Val});
  346. parse_property(<<16#28, Val, Bin/binary>>, Props) ->
  347. parse_property(Bin, Props#{'Wildcard-Subscription-Available' => Val});
  348. parse_property(<<16#29, Val, Bin/binary>>, Props) ->
  349. parse_property(Bin, Props#{'Subscription-Identifier-Available' => Val});
  350. parse_property(<<16#2A, Val, Bin/binary>>, Props) ->
  351. parse_property(Bin, Props#{'Shared-Subscription-Available' => Val}).
  352. parse_variable_byte_integer(Bin) ->
  353. parse_variable_byte_integer(Bin, 1, 0).
  354. parse_variable_byte_integer(<<1:1, Len:7, Rest/binary>>, Multiplier, Value) ->
  355. parse_variable_byte_integer(Rest, Multiplier * ?HIGHBIT, Value + Len * Multiplier);
  356. parse_variable_byte_integer(<<0:1, Len:7, Rest/binary>>, Multiplier, Value) ->
  357. {Value + Len * Multiplier, Rest}.
  358. parse_topic_filters(subscribe, Bin) ->
  359. [{Topic, #{rh => Rh, rap => Rap, nl => Nl, qos => QoS}}
  360. || <<Len:16/big, Topic:Len/binary, _:2, Rh:2, Rap:1, Nl:1, QoS:2>> <= Bin];
  361. parse_topic_filters(unsubscribe, Bin) ->
  362. [Topic || <<Len:16/big, Topic:Len/binary>> <= Bin].
  363. parse_reason_codes(Bin) ->
  364. [Code || <<Code>> <= Bin].
  365. parse_utf8_pair(<<Len1:16/big, Key:Len1/binary,
  366. Len2:16/big, Val:Len2/binary, Rest/binary>>) ->
  367. {{Key, Val}, Rest}.
  368. parse_utf8_string(Bin, false) ->
  369. {undefined, Bin};
  370. parse_utf8_string(Bin, true) ->
  371. parse_utf8_string(Bin).
  372. parse_utf8_string(<<Len:16/big, Str:Len/binary, Rest/binary>>) ->
  373. {Str, Rest}.
  374. parse_binary_data(<<Len:16/big, Data:Len/binary, Rest/binary>>) ->
  375. {Data, Rest}.
  376. %%--------------------------------------------------------------------
  377. %% Serialize MQTT Packet
  378. %%--------------------------------------------------------------------
  379. serialize_fun() -> serialize_fun(?DEFAULT_OPTIONS).
  380. serialize_fun(#mqtt_packet_connect{proto_ver = ProtoVer, properties = ConnProps}) ->
  381. MaxSize = get_property('Maximum-Packet-Size', ConnProps, ?MAX_PACKET_SIZE),
  382. serialize_fun(#{version => ProtoVer, max_size => MaxSize});
  383. serialize_fun(#{version := Ver, max_size := MaxSize}) ->
  384. fun(Packet) ->
  385. IoData = serialize(Packet, Ver),
  386. case is_too_large(IoData, MaxSize) of
  387. true -> <<>>;
  388. false -> IoData
  389. end
  390. end.
  391. -spec(serialize(emqx_types:packet()) -> iodata()).
  392. serialize(Packet) -> serialize(Packet, ?MQTT_PROTO_V4).
  393. -spec(serialize(emqx_types:packet(), emqx_types:version()) -> iodata()).
  394. serialize(#mqtt_packet{header = Header,
  395. variable = Variable,
  396. payload = Payload}, Ver) ->
  397. serialize(Header, serialize_variable(Variable, Ver), serialize_payload(Payload)).
  398. serialize(#mqtt_packet_header{type = Type,
  399. dup = Dup,
  400. qos = QoS,
  401. retain = Retain
  402. }, VariableBin, PayloadBin)
  403. when ?CONNECT =< Type andalso Type =< ?AUTH ->
  404. Len = iolist_size(VariableBin) + iolist_size(PayloadBin),
  405. [<<Type:4, (flag(Dup)):1, (flag(QoS)):2, (flag(Retain)):1>>,
  406. serialize_remaining_len(Len), VariableBin, PayloadBin].
  407. serialize_variable(#mqtt_packet_connect{
  408. proto_name = ProtoName,
  409. proto_ver = ProtoVer,
  410. is_bridge = IsBridge,
  411. clean_start = CleanStart,
  412. will_flag = WillFlag,
  413. will_qos = WillQoS,
  414. will_retain = WillRetain,
  415. keepalive = KeepAlive,
  416. properties = Properties,
  417. clientid = ClientId,
  418. will_props = WillProps,
  419. will_topic = WillTopic,
  420. will_payload = WillPayload,
  421. username = Username,
  422. password = Password}, _Ver) ->
  423. [serialize_binary_data(ProtoName),
  424. <<(case IsBridge of
  425. true -> 16#80 + ProtoVer;
  426. false -> ProtoVer
  427. end):8,
  428. (flag(Username)):1,
  429. (flag(Password)):1,
  430. (flag(WillRetain)):1,
  431. WillQoS:2,
  432. (flag(WillFlag)):1,
  433. (flag(CleanStart)):1,
  434. 0:1,
  435. KeepAlive:16/big-unsigned-integer>>,
  436. serialize_properties(Properties, ProtoVer),
  437. serialize_utf8_string(ClientId),
  438. case WillFlag of
  439. true -> [serialize_properties(WillProps, ProtoVer),
  440. serialize_utf8_string(WillTopic),
  441. serialize_binary_data(WillPayload)];
  442. false -> <<>>
  443. end,
  444. serialize_utf8_string(Username, true),
  445. serialize_utf8_string(Password, true)];
  446. serialize_variable(#mqtt_packet_connack{ack_flags = AckFlags,
  447. reason_code = ReasonCode,
  448. properties = Properties}, Ver) ->
  449. [AckFlags, ReasonCode, serialize_properties(Properties, Ver)];
  450. serialize_variable(#mqtt_packet_publish{topic_name = TopicName,
  451. packet_id = PacketId,
  452. properties = Properties}, Ver) ->
  453. [serialize_utf8_string(TopicName),
  454. if
  455. PacketId =:= undefined -> <<>>;
  456. true -> <<PacketId:16/big-unsigned-integer>>
  457. end,
  458. serialize_properties(Properties, Ver)];
  459. serialize_variable(#mqtt_packet_puback{packet_id = PacketId}, Ver)
  460. when Ver == ?MQTT_PROTO_V3; Ver == ?MQTT_PROTO_V4 ->
  461. <<PacketId:16/big-unsigned-integer>>;
  462. serialize_variable(#mqtt_packet_puback{packet_id = PacketId,
  463. reason_code = ReasonCode,
  464. properties = Properties
  465. },
  466. Ver = ?MQTT_PROTO_V5) ->
  467. [<<PacketId:16/big-unsigned-integer>>, ReasonCode,
  468. serialize_properties(Properties, Ver)];
  469. serialize_variable(#mqtt_packet_subscribe{packet_id = PacketId,
  470. properties = Properties,
  471. topic_filters = TopicFilters}, Ver) ->
  472. [<<PacketId:16/big-unsigned-integer>>, serialize_properties(Properties, Ver),
  473. serialize_topic_filters(subscribe, TopicFilters, Ver)];
  474. serialize_variable(#mqtt_packet_suback{packet_id = PacketId,
  475. properties = Properties,
  476. reason_codes = ReasonCodes}, Ver) ->
  477. [<<PacketId:16/big-unsigned-integer>>, serialize_properties(Properties, Ver),
  478. serialize_reason_codes(ReasonCodes)];
  479. serialize_variable(#mqtt_packet_unsubscribe{packet_id = PacketId,
  480. properties = Properties,
  481. topic_filters = TopicFilters}, Ver) ->
  482. [<<PacketId:16/big-unsigned-integer>>, serialize_properties(Properties, Ver),
  483. serialize_topic_filters(unsubscribe, TopicFilters, Ver)];
  484. serialize_variable(#mqtt_packet_unsuback{packet_id = PacketId,
  485. properties = Properties,
  486. reason_codes = ReasonCodes}, Ver) ->
  487. [<<PacketId:16/big-unsigned-integer>>, serialize_properties(Properties, Ver),
  488. serialize_reason_codes(ReasonCodes)];
  489. serialize_variable(#mqtt_packet_disconnect{}, Ver)
  490. when Ver == ?MQTT_PROTO_V3; Ver == ?MQTT_PROTO_V4 ->
  491. <<>>;
  492. serialize_variable(#mqtt_packet_disconnect{reason_code = ReasonCode,
  493. properties = Properties},
  494. Ver = ?MQTT_PROTO_V5) ->
  495. [ReasonCode, serialize_properties(Properties, Ver)];
  496. serialize_variable(#mqtt_packet_disconnect{}, _Ver) ->
  497. <<>>;
  498. serialize_variable(#mqtt_packet_auth{reason_code = ReasonCode,
  499. properties = Properties},
  500. Ver = ?MQTT_PROTO_V5) ->
  501. [ReasonCode, serialize_properties(Properties, Ver)];
  502. serialize_variable(PacketId, ?MQTT_PROTO_V3) when is_integer(PacketId) ->
  503. <<PacketId:16/big-unsigned-integer>>;
  504. serialize_variable(PacketId, ?MQTT_PROTO_V4) when is_integer(PacketId) ->
  505. <<PacketId:16/big-unsigned-integer>>;
  506. serialize_variable(undefined, _Ver) ->
  507. <<>>.
  508. serialize_payload(undefined) -> <<>>;
  509. serialize_payload(Bin) -> Bin.
  510. serialize_properties(_Props, Ver) when Ver =/= ?MQTT_PROTO_V5 ->
  511. <<>>;
  512. serialize_properties(Props, ?MQTT_PROTO_V5) ->
  513. serialize_properties(Props).
  514. serialize_properties(undefined) ->
  515. <<0>>;
  516. serialize_properties(Props) when map_size(Props) == 0 ->
  517. <<0>>;
  518. serialize_properties(Props) when is_map(Props) ->
  519. Bin = << <<(serialize_property(Prop, Val))/binary>> || {Prop, Val} <- maps:to_list(Props) >>,
  520. [serialize_variable_byte_integer(byte_size(Bin)), Bin].
  521. serialize_property(_, undefined) ->
  522. <<>>;
  523. serialize_property('Payload-Format-Indicator', Val) ->
  524. <<16#01, Val>>;
  525. serialize_property('Message-Expiry-Interval', Val) ->
  526. <<16#02, Val:32/big>>;
  527. serialize_property('Content-Type', Val) ->
  528. <<16#03, (serialize_utf8_string(Val))/binary>>;
  529. serialize_property('Response-Topic', Val) ->
  530. <<16#08, (serialize_utf8_string(Val))/binary>>;
  531. serialize_property('Correlation-Data', Val) ->
  532. <<16#09, (byte_size(Val)):16, Val/binary>>;
  533. serialize_property('Subscription-Identifier', Val) ->
  534. <<16#0B, (serialize_variable_byte_integer(Val))/binary>>;
  535. serialize_property('Session-Expiry-Interval', Val) ->
  536. <<16#11, Val:32/big>>;
  537. serialize_property('Assigned-Client-Identifier', Val) ->
  538. <<16#12, (serialize_utf8_string(Val))/binary>>;
  539. serialize_property('Server-Keep-Alive', Val) ->
  540. <<16#13, Val:16/big>>;
  541. serialize_property('Authentication-Method', Val) ->
  542. <<16#15, (serialize_utf8_string(Val))/binary>>;
  543. serialize_property('Authentication-Data', Val) ->
  544. <<16#16, (iolist_size(Val)):16, Val/binary>>;
  545. serialize_property('Request-Problem-Information', Val) ->
  546. <<16#17, Val>>;
  547. serialize_property('Will-Delay-Interval', Val) ->
  548. <<16#18, Val:32/big>>;
  549. serialize_property('Request-Response-Information', Val) ->
  550. <<16#19, Val>>;
  551. serialize_property('Response-Information', Val) ->
  552. <<16#1A, (serialize_utf8_string(Val))/binary>>;
  553. serialize_property('Server-Reference', Val) ->
  554. <<16#1C, (serialize_utf8_string(Val))/binary>>;
  555. serialize_property('Reason-String', Val) ->
  556. <<16#1F, (serialize_utf8_string(Val))/binary>>;
  557. serialize_property('Receive-Maximum', Val) ->
  558. <<16#21, Val:16/big>>;
  559. serialize_property('Topic-Alias-Maximum', Val) ->
  560. <<16#22, Val:16/big>>;
  561. serialize_property('Topic-Alias', Val) ->
  562. <<16#23, Val:16/big>>;
  563. serialize_property('Maximum-QoS', Val) ->
  564. <<16#24, Val>>;
  565. serialize_property('Retain-Available', Val) ->
  566. <<16#25, Val>>;
  567. serialize_property('User-Property', {Key, Val}) ->
  568. <<16#26, (serialize_utf8_pair({Key, Val}))/binary>>;
  569. serialize_property('User-Property', Props) when is_list(Props) ->
  570. << <<(serialize_property('User-Property', {Key, Val}))/binary>>
  571. || {Key, Val} <- Props >>;
  572. serialize_property('Maximum-Packet-Size', Val) ->
  573. <<16#27, Val:32/big>>;
  574. serialize_property('Wildcard-Subscription-Available', Val) ->
  575. <<16#28, Val>>;
  576. serialize_property('Subscription-Identifier-Available', Val) ->
  577. <<16#29, Val>>;
  578. serialize_property('Shared-Subscription-Available', Val) ->
  579. <<16#2A, Val>>.
  580. serialize_topic_filters(subscribe, TopicFilters, ?MQTT_PROTO_V5) ->
  581. << <<(serialize_utf8_string(Topic))/binary,
  582. ?RESERVED:2, Rh:2, (flag(Rap)):1,(flag(Nl)):1, QoS:2 >>
  583. || {Topic, #{rh := Rh, rap := Rap, nl := Nl, qos := QoS}} <- TopicFilters >>;
  584. serialize_topic_filters(subscribe, TopicFilters, _Ver) ->
  585. << <<(serialize_utf8_string(Topic))/binary, ?RESERVED:6, QoS:2>>
  586. || {Topic, #{qos := QoS}} <- TopicFilters >>;
  587. serialize_topic_filters(unsubscribe, TopicFilters, _Ver) ->
  588. << <<(serialize_utf8_string(Topic))/binary>> || Topic <- TopicFilters >>.
  589. serialize_reason_codes(undefined) ->
  590. <<>>;
  591. serialize_reason_codes(ReasonCodes) when is_list(ReasonCodes) ->
  592. << <<Code>> || Code <- ReasonCodes >>.
  593. serialize_utf8_pair({Name, Value}) ->
  594. << (serialize_utf8_string(Name))/binary, (serialize_utf8_string(Value))/binary >>.
  595. serialize_binary_data(Bin) ->
  596. [<<(byte_size(Bin)):16/big-unsigned-integer>>, Bin].
  597. serialize_utf8_string(undefined, false) ->
  598. error(utf8_string_undefined);
  599. serialize_utf8_string(undefined, true) ->
  600. <<>>;
  601. serialize_utf8_string(String, _AllowNull) ->
  602. serialize_utf8_string(String).
  603. serialize_utf8_string(String) ->
  604. StringBin = unicode:characters_to_binary(String),
  605. Len = byte_size(StringBin),
  606. true = (Len =< 16#ffff),
  607. <<Len:16/big, StringBin/binary>>.
  608. serialize_remaining_len(I) ->
  609. serialize_variable_byte_integer(I).
  610. serialize_variable_byte_integer(N) when N =< ?LOWBITS ->
  611. <<0:1, N:7>>;
  612. serialize_variable_byte_integer(N) ->
  613. <<1:1, (N rem ?HIGHBIT):7, (serialize_variable_byte_integer(N div ?HIGHBIT))/binary>>.
  614. %% Is the frame too large?
  615. -spec(is_too_large(iodata(), pos_integer()) -> boolean()).
  616. is_too_large(IoData, MaxSize) ->
  617. iolist_size(IoData) >= MaxSize.
  618. get_property(_Key, undefined, Default) ->
  619. Default;
  620. get_property(Key, Props, Default) ->
  621. maps:get(Key, Props, Default).
  622. %% Validate header if sctrict mode. See: mqtt-v5.0: 2.1.3 Flags
  623. validate_header(?CONNECT, 0, 0, 0) -> ok;
  624. validate_header(?CONNACK, 0, 0, 0) -> ok;
  625. validate_header(?PUBLISH, 0, ?QOS_0, _) -> ok;
  626. validate_header(?PUBLISH, _, ?QOS_1, _) -> ok;
  627. validate_header(?PUBLISH, 0, ?QOS_2, _) -> ok;
  628. validate_header(?PUBACK, 0, 0, 0) -> ok;
  629. validate_header(?PUBREC, 0, 0, 0) -> ok;
  630. validate_header(?PUBREL, 0, 1, 0) -> ok;
  631. validate_header(?PUBCOMP, 0, 0, 0) -> ok;
  632. validate_header(?SUBSCRIBE, 0, 1, 0) -> ok;
  633. validate_header(?SUBACK, 0, 0, 0) -> ok;
  634. validate_header(?UNSUBSCRIBE, 0, 1, 0) -> ok;
  635. validate_header(?UNSUBACK, 0, 0, 0) -> ok;
  636. validate_header(?PINGREQ, 0, 0, 0) -> ok;
  637. validate_header(?PINGRESP, 0, 0, 0) -> ok;
  638. validate_header(?DISCONNECT, 0, 0, 0) -> ok;
  639. validate_header(?AUTH, 0, 0, 0) -> ok;
  640. validate_header(_Type, _Dup, _QoS, _Rt) -> error(bad_frame_header).
  641. -compile({inline, [validate_packet_id/1]}).
  642. validate_packet_id(0) -> error(bad_packet_id);
  643. validate_packet_id(_) -> ok.
  644. validate_subqos([3|_]) -> error(bad_subqos);
  645. validate_subqos([_|T]) -> validate_subqos(T);
  646. validate_subqos([]) -> ok.
  647. bool(0) -> false;
  648. bool(1) -> true.
  649. flag(undefined) -> ?RESERVED;
  650. flag(false) -> 0;
  651. flag(true) -> 1;
  652. flag(X) when is_integer(X) -> X;
  653. flag(B) when is_binary(B) -> 1.
  654. fixqos(?PUBREL, 0) -> 1;
  655. fixqos(?SUBSCRIBE, 0) -> 1;
  656. fixqos(?UNSUBSCRIBE, 0) -> 1;
  657. fixqos(_Type, QoS) -> QoS.