Commit Graph

59 Commits

Author SHA1 Message Date
Aayush Atharva
fe7b18ee83
Make variables final (#11548)
Motivation:
We should make variables `final` which are not reinstated again in code to match the code style and makes the code look better.

Modification:
Made couples of variables as `final`.

Result:
Variables marked as `final`.
2021-08-06 09:27:12 +02:00
Aayush Atharva
6e387e2f5d
Remove unnecessary toString calls (#11550)
Motivation:
We should get rid of the unnecessary toString calls because they're redundant in nature.

Modification:
Removed unnecessary toString calls.

Result:
Better code
2021-08-05 14:17:00 +02:00
Aayush Atharva
1ce28e80d1
Remove Unused Imports (#11546)
Motivation:
There are lots of imports which are unused. We should get rid of them to make the code look better,

Modification:
Removed unused imports.

Result:
No unused imports.
2021-08-05 13:54:48 +02:00
Norman Maurer
043e9e309e
Remove rest of junit4 usage (#11484)
Motivation:

We did migrate all these modules to junit5 before but missed a few usages of junit4

Modifications:

Replace all junit4 imports by junit5 apis

Result:

Part of  https://github.com/netty/netty/issues/10757
2021-07-13 20:59:57 +02:00
Norman Maurer
94a4880358
Migrate codec-mqtt to junit5 (#11431)
Motivation:

We should update to use junit5 in all modules.

Modifications:

Adjust codec-mqtt tests to use junit5

Result:

Part of https://github.com/netty/netty/issues/10757
2021-06-30 15:32:16 +02:00
Hylke van der Schaaf
2f4f7135fb
Validate fixed header bits in MQTT (#11389)
Motivation:
The MQTT spec states that the bits in the fixed header must be set to specific values depending on message type. If a client sends a message with the wrong bits, the server must treat the message as malformed. Netty did not check the value of the reserved bits in the fixed header.

See:
MQTT3.1.1: http://docs.oasis-open.org/mqtt/mqtt/v3.1.1/errata01/os/mqtt-v3.1.1-errata01-os-complete.html#_Toc442180835
MQTT 5.0: https://docs.oasis-open.org/mqtt/mqtt/v5.0/os/mqtt-v5.0-os.html#_Toc3901023


Modification:
Add validation checks to MqttDecoder.java
Add unit tests to MqttCodecTest.java 
Fixed two instances where messages were generated for other unit tests with an incorrect fixed header.

Result:
Fixes #11379.
2021-06-16 14:59:15 +02:00
Julien Viet
06f7deb030
The MqttDecoder incorrectly skip bytes before throwing TooLongFrameException (#11362)
Motivation:

Commit c32c520edd incorrectly skip the bytes of the replay decoder buffer. The number of bytes to skip is determined by ByteBuf#readableBytes() instead of using ByteToMessageDecoder#actualReadableBytes(). As result it throws an exception because the ByteBuf provided will return a too large value (Integer.MAX_VALUE - reader index) causing a bound check error in the skipBytes method. This is not detected by the tests because most tests are calling the decode(...) method with a regular ByteBuf. In practice when this method is called with a specialized ByteBuf when channelRead(...) is called. Such tests should actually use channelRead with proper mocking of the ChannelHandlerContext

Modification:

- Rewrite the MqttCodecTest to use channelRead(...) instead of decode(...) and use proper mocking of ChannelHandlerContext to get the message emitted by the decoder.
- Use actualReadableBytes() instead of buff.readableBytes() to compute the number of bytes to skip

Result:

Skip correctly the number of bytes when a too large message is found and improve testing. See #11361

Signed-off-by: Julien Viet <julien@julienviet.com>
2021-06-10 15:05:25 +02:00
terrarier2111
2bcd03f788
Improved exception messages in MqttVersion (#11228)
Motivation:
When checking the latest commit i saw some bad exception messages in MqttVersion hence i improved them.

Modification:

Improved exception messages in MqttVersion.

Result:

Better exception messages in MqttVersion.
2021-05-06 11:28:00 +02:00
skyguard1
84356bbeb0
Add default block in MqttVersion (#11226)
Motivation:

Fix switch case fall through, add default block in MqttVersion

Modification:

Fix switch case fall through, add default block in MqttVersion

Result:

Code cleanup


Signed-off-by: xingrufei <xingrufei@sogou-inc.com>

Co-authored-by: xingrufei <xingrufei@sogou-inc.com>
2021-05-06 08:09:27 +02:00
skyguard1
c32c520edd
Before throwing TooLongFrameException,should skip the bytes to be read in MqttDecoder (#11204)
Motivation:

Before throwing TooLongFrameException, should call the skipBytes method to skip the bytes to be read

Modification:
- skip bytes before throw

Result:
Actually skip the bytes when we detect too much data

Signed-off-by: xingrufei <xingrufei@sogou-inc.com>

Co-authored-by: xingrufei <xingrufei@sogou-inc.com>
2021-04-29 08:13:11 +02:00
skyguard1
d22a35628d
Give a choice for app to extend the length limitation of clientId even in mqtt v3.1 on the server side (#11205)
Motivation:

In the mqtt v3.1 protocol, the default maximum Client Identifier length is 23.However, in (#11114), there are many cases, the server may still receive a client ID with a length greater than 23. Perhaps should consider letting the user decide whether accept client id greater than 23 on the server side

Modification:

- Allow to specify max length.

Result:

Give a choice for app to extend the length limitation of clientId even in mqtt v3.1 on the server side.

Signed-off-by: xingrufei <xingrufei@sogou-inc.com>

Co-authored-by: xingrufei <xingrufei@sogou-inc.com>
2021-04-28 16:20:59 +02:00
Boris Unckel
d3fa33058d
Utilize i.n.u.internal.ObjectUtil to assert Preconditions (codec*) (#11170) (#11185)
Motivation:

NullChecks resulting in a NullPointerException or IllegalArgumentException, numeric ranges (>0, >=0) checks, not empty strings/arrays checks must never be anonymous but with the parameter or variable name which is checked. They must be specific and should not be done with an "OR-Logic" (if a == null || b == null) throw new NullPointerEx.

Modifications:

* import static relevant checks
* Replace manual checks with ObjectUtil methods

Result:

All checks needed are done with ObjectUtil, some exception texts are improved.
Fixes #11170
2021-04-22 16:01:28 +02:00
strugcoder
bb9370f2a2
Simplity some code (#11000)
Motivation:

There was some code that could be simplified.

Modification:

Simplify code.

Result:

Code cleanup
2021-02-11 08:42:01 +01:00
Duke Bartholomew
f54bf7aeb0
Allow to use int while build MqttMessageIdVariableHeader (#10930)
Motivation:

Exception occurs in the MQTT message builder class (`io.netty.handler.codec.mqtt.MqttMessageBuilders`) when trying to create a message with packetId > 32767

Modification:

-add method that takes int
- deprecate old methods that take short. 

Result:


Fixes #10929 .
2021-01-21 14:40:45 +01:00
Andrea Selva
01d44ff592
Add ConnAck message builder method to handle the creation of related properties. (#10812)
Motivation:
The CONNACK message builder `ConnAckBuilder` doesn't provide a smooth way to assign the message properties. This PR try to provide an simpler way to create them, in a lazy way.

Modification:
This PR permit to store properties in the ConnAck message, collecting them and inserting during the build phase. The syntax this PR introduces is:
```java
 MqttMessageBuilders.connAck().properties(new MqttMessageBuilders.PropertiesInitializer<MqttMessageBuilders.ConnAckPropertiesBuilder>() {
        @Override
        public void apply(MqttMessageBuilders.ConnAckPropertiesBuilder builder) {
            builder.assignedClientId("client1234");
            builder.userProperty("custom_property", "value");
         }
 }).build()
```
The name of the properties are defined in the `ConnAckPropertiesBuilder` so that is can be easily used by autocompletion tools.

Result:
This PR adds the builder class `ConnAckPropertiesBuilder`which is used by newly introduced method `properties` inside the message builder class `ConnAckBuilder`.
2020-12-23 10:50:09 +01:00
Paul Lysak
9c0c996729
MQTT: foolproof SUBSCRIBE QoS encoding (#10874)
Motivation:

If the MQTT client specifies Subscribe Options parameters only available in MQTT v5 and tries to encode the message as MQTT v3 then an invalid QoS value is encoded

Modification:

Check MQTT version when encoding SUBSCRIBE message options, if it's 3.1 or 3.1.1 - only encode QoS, skip other options.

Result:

MqttEncoder produces a valid SUBSCRIBE message even if the client has specified options not available in the current MQTT version.
2020-12-18 10:40:15 +01:00
Paul Lysak
7b736a3ae4
MQTT5: support multiple Subscription ID properties (#10734)
Motivation:

Subscription ID property of the PUBLISH message may be repeated multiple times, which wasn't taken into account when developing `MqttProperties` API.

Modification:

Store Subscription ID properties separately from others - in `MqttProperties.subscriptionIds`. 
Add `MqttProperties.getProperties` method to retrieve properties that may be repeated.
Change internal representation of User Properties for uniformity with Subscription ID - now they're stored in `MqttProperties.userProperties` rather than the common hash map.

Result:

Multiple Subscription ID properties can be set or retrieved.
2020-10-30 11:17:46 +01:00
Artem Smotrakov
e5951d46fc
Enable nohttp check during the build (#10708)
Motivation:

HTTP is a plaintext protocol which means that someone may be able
to eavesdrop the data. To prevent this, HTTPS should be used whenever
possible. However, maintaining using https:// in all URLs may be
difficult. The nohttp tool can help here. The tool scans all the files
in a repository and reports where http:// is used.

Modifications:

- Added nohttp (via checkstyle) into the build process.
- Suppressed findings for the websites
  that don't support HTTPS or that are not reachable

Result:

- Prevent using HTTP in the future.
- Encourage users to use HTTPS when they follow the links they found in
  the code.
2020-10-23 14:44:18 +02:00
Artem Smotrakov
1ca7d5db81
Fix or suppress LGTM findings (#10689)
Motivation:

LGTM reports multiple issues. They need to be triaged,
and real ones should be fixed.

Modifications:
- Fixed multiple issues reported by LGTM, such as redundant conditions,
  resource leaks, typos, possible integer overflows.
- Suppressed false-positives.
- Added a few testcases.

Result:

Fixed several possible issues, get rid of false alarms in the LGTM report.
2020-10-17 09:49:44 +02:00
Paul Lysak
b112483799
Not truncate MQTT SUBACK reason codes (#10584)
Motivation:

Reason code for MQTT SUBACK messages is truncated, thus not allowing to get new codes supported by MQTT v.5

Modification:

Changed `MqttCodecTest.testUnsubAckMessageForMqtt5` to catch it then, removed truncation in `MqttDecoder.decodeSubackPayload` to make it pass.

Result:

Codec users can get all reason codes supported by MQTT5 now.
2020-09-22 08:58:49 +02:00
Paul Lysak
aa85ea9947
Make MQTT property value publicly accessible (#10577)
Motivation:

There was no way to read MQTT properties outside of `io.netty.handler.codec.mqtt` package

Modification:

Expose `MqttProperties.MqttProperty` fields `value` and `propertyId` via public methods

Result:

It's possible to read MQTT properties now
2020-09-16 07:56:17 +02:00
Paul Lysak
3b47427cf7
Fix NPE with MqttUnsubAckMessage - regression of MQTT5 support (#10557)
Recent changes for MQTT5 may cause NPE if UNSUBACK message is created with `MqttMessageFactory`
and client code isn't up-to-date.

Modifications:

Added default body in `MqttUnsubAckMessage` constructor if null body is passed,
added null checks in `encodeUnsubAckMessage`

Result:

`MqttUnsubAckMessage` created with `MqttMessageFactory` doesn't cause NPE
even if null body is supplied.
2020-09-14 12:04:55 +02:00
Paul Lysak
8c1db6ccb8
Make RetainedHandlingPolicy enum public (#10565)
Motivation:

Impossible to specify retained messages handling policy because the corresponding enum
isn't public (https://github.com/netty/netty/issues/10562)

Modification:

Made `RetainedHandlingPolicy` public

Result:

Fixes #10562.
2020-09-11 08:32:16 +02:00
Francesco Nigro
38f01e0840
Reduce garbage on MQTT (#10509)
Reduce garbage on MQTT encoding

Motivation:

MQTT encoding and decoding is doing unnecessary object allocation in a number of places:
- MqttEncoder create many byte[] to encode Strings into UTF-8 bytes
- MqttProperties uses Integer keys instead of int
- Some enums valueOf create unnecessary arrays on the hot paths
- MqttDecoder was using unecessary Result<T>

Modification:

- ByteBufUtil::utf8Bytes and ByteBufUtil::reserveAndWriteUtf8 allows to perform the same operation GC-free
- MqttProperties uses a primitive key map
- Implemented GC free const table lookup/switch valueOf
- Use some bit-tricks to pack 2 ints into a single primitive long to store both result and numberOfBytesConsumed and use byte[].length to compute numberOfByteConsumed on fly. These changes allowed to save creating Result<T>.

Result:
Significantly less garbage produced in MQTT encoding/decoding
2020-09-04 18:27:22 +02:00
Francesco Nigro
d2c03c9a29
Improve MqttMessageType::valueOf cost (#10400)
Motivation:

MqttMessageType::valueOf has O(N) cost

Modifications:

MqttMessageType::valueOf uses a const lookup table

Result:

MqttMessageType::valueOf has O(1) cost
2020-08-31 10:32:33 +02:00
Paul Lysak
be2cd68443
MQTT5 support for netty-codec-mqtt (#10483)
Motivation:

 MQTT Specification version 5 was released over a year ago,
 netty-codec-mqtt should be changed to support it.

Modifications:

  Added more message and header types in `io.netty.handler.codec.mqtt`
  package in `netty-coded-mqtt` subproject,
  changed `MqttEncoder` and `MqttDecoder` to handle them properly,
  added attribute `NETTY_CODEC_MQTT_VERSION` to track protocol version

Result:

  `netty-codec-mqtt` supports both MQTT5 and MQTT3 now.
2020-08-31 09:16:40 +02:00
Nick Hill
8e8f01e01d
Use ByteBuf#isAccessible() in more places (#10506)
Motivation

ByteBuf has an isAccessible method which was introduced as part of ref
counting optimizations but there are some places still doing
accessibility checks by accessing the volatile refCnt() directly.

Modifications

- Have PooledNonRetained(Duplicate|Sliced)ByteBuf#isAccessible() use
their refcount delegate's isAccessible() method
- Add static isAccessible(buf) and ensureAccessible(buf) methods to
ByteBufUtil
(since ByteBuf#isAccessible() is package-private)
- Adjust DefaultByteBufHolder and similar classes to use these methods
rather than access refCnt() directly

Result

- More efficient accessibility checks in more places
2020-08-28 09:18:13 +02:00
luffyke
7e823e3842
Replace MQTT deprecated API usage
Motivation:

Mqtt procotol defines packetId instead of messageId, replace deprecated method to match protocol definition

Modification:

Replace messageId() to packetId() in MqttEncoder

Result:

Match mqtt protocol definition and improve readability.
2020-03-30 21:23:23 +02:00
时无两丶
0cde4d9cb4 Uniform null pointer check. (#9840)
Motivation:
Uniform null pointer check.

Modifications:

Use ObjectUtil.checkNonNull(...)

Result:
Less code, same result.
2019-12-09 09:47:35 +01:00
Ameya Lokare
e55e3a59f9 Add constants for fixed-header only MQTT messages (#9749)
Motivation:

Currently, the only way to create fixed-header only messages PINGREQ,
PINGRESP and DISCONNECT is to explicitly instantiate a `MqttFixedHeader` like:
```
MqttFixedHeader disconnectFixedHeader = new MqttFixedHeader(MqttMessageType.DISCONNECT,
    false, MqttQoS.AT_MOST_ONCE, false, 0);
MqttMessage disconnectMessage = new MqttMessage(disconnectFixedHeader);
```

According to the MQTT spec
(http://docs.oasis-open.org/mqtt/mqtt/v3.1.1/os/mqtt-v3.1.1-os.html#_Toc398718077),
the fixed-header flags for these messages are reserved and  must be set to zero, otherwise
the receiver must close the connection. It's easy to mess this up when
you're creating the header explicitly, for e.g by setting the QoS bit to
`AT_LEAST_ONCE`.

As such, provide static constants for PINGREQ, PINGRESP and
DISCONNECT messages that will set the flags correctly for the developer.

Modification:

Add static constants to MqttMessage class to construct PINGREQ, PINGRESP and
DISCONNECT messages that will set the fixed-header flags correctly to 0.

Result:

Easier usage.
2019-11-08 10:17:01 +01:00
jimin
51843d8e8e MqttConnectPayload.toString() should use Arrays.toString() instead of [].toString() (#9292)
Motivation:

The toString() method should use Arrays.toString() to produce a meaningful String representation for arrays.

Modification:

Use Arrays.toString()

Result:

More useful toString() implementation
2019-06-27 21:55:02 +02:00
SplotyCode
ede7251ecb Fixed toString() exception in MqttSubscribePayload and MqttUnsubscribePayload (#9202)
Motivation:
The toString() methods of MqttSubscribePayload and MqttUnsubscribePayload are causing exceptions when no topics are set.

Modification:
The toString() methods will not throw Excpetions anymore.

Result:
Fixes #9197
2019-05-31 06:46:50 +02:00
Chi-Joung So
a9863f8128 Add headers to MqttMessage returned by MqttDecoder in case of DecoderException (#8219)
Motivation:
When the MqttDecoder decodes a message larger than the 'maxBytesInMessage' a DecoderException is thrown and a MqttMessage with just the failure cause is returned. Even if I can't handle the message, I might want to send an ACK so that I won't have to worry about it again.

Modification:
The DecoderException is thrown after the variableHeader is decoded. The fixed and variable headers are then added to the MqttMessage along with the failure cause.

Result:
The invalid MqttMessage will have headers if available.
2018-08-31 15:06:09 +02:00
Dmitriy Dumanskiy
7bbb4ef8a2 Motivation:
Since 3.1.1 mqtt protocol version SUBACK message can now indicate the failure in payload.

Modification:

Do not erase failure payload in for SUBACK message.

Result:

Fixes #7665
2018-02-05 08:54:50 +01:00
Paolo Patierno
901c66fa81 MQTT encode doesn't complain if password is set but username not
Motivation:

The MQTT decoder should raise an exception trying to build a CONNECT packet where password field is set but not the username one (as by MQTT 3.1/3.1.1 spec).

Modification:

Throw exception if password field is set but not the username

Result:

Fixes [#7205].
2017-09-14 09:37:37 -07:00
Michael Andre Pearce
1ba592049c Add null checks before converting to string to avoid NPE.
Motivation:

Fixing an introduced NPE by #6817

Modification:

Add null checks.

Result:

Fixes #7076 .
2017-08-11 07:14:39 +02:00
ppatierno
b8d3d96550 MQTT unknown message type isn't handled as decoding error
Motivation:

MQTT unknown message type isn't handled as decoding error

Modification:

Catching exception during the MQTT decoding of the fixed header
Adding a unit test for unknown MQTT message type

Result:

Fixes #6984.
2017-07-18 15:48:09 +02:00
Subhobrata Dey
66c83f7b74 codec.mqtt: password and willMessage field types should be byte[]
Motivation:

Update the mqtt-codec based on mqtt spec (3.1.3.5).

Modification:

Changes made to the file MqttConnectPayload.java.
Subsequent changes have been made to files MqttDecoder.java, MqttEncoder.java, MqttMessageBuilders.java.
Test cases have been updated.
Result:

Fixes #6750 .
2017-06-13 18:49:13 +02:00
Pavel Drankov
f8788a9f6c Issue №6802. Not specified field in MQTT codec (#6807) 2017-06-05 13:21:49 -07:00
Nikolay Fedorovskikh
0692bf1b6a fix the typos 2017-04-20 04:56:09 +02:00
Nikolay Fedorovskikh
f49bf4b201 Convert fields to the local variable when possible
Motivation:

Some classes have fields which can be local.

Modifications:

Convert fields to the local variable when possible.

Result:

Clean up. More chances for young generation or scalar replacement.
2017-03-08 17:09:17 -08:00
andsel
ad51cda2cd Introduced MqttMessageBuilders to fluently create MQTT messages 2017-02-19 13:39:59 +01:00
Norman Maurer
a7c0ff665c Only use Mockito for mocking.
Motivation:

We used various mocking frameworks. We should only use one...

Modifications:

Make usage of mocking framework consistent by only using Mockito.

Result:

Less dependencies and more consistent mocking usage.
2017-02-07 08:47:22 +01:00
Xiaoyan Lin
3dbbf06e9b Fix typo in the assert description in MqttCodecTest
Motivation:

There is a spelling error in MqttCodecTest, where "bout got" shoud be "but got".

Modifications:

Replace the error spelling with correct one.

Result:

Fix typo in the assert description in MqttCodecTest.
2016-06-14 23:31:53 -07:00
Trustin Lee
3a9f472161 Make retained derived buffers recyclable
Related: #4333 #4421 #5128

Motivation:

slice(), duplicate() and readSlice() currently create a non-recyclable
derived buffer instance. Under heavy load, an application that creates a
lot of derived buffers can put the garbage collector under pressure.

Modifications:

- Add the following methods which creates a non-recyclable derived buffer
  - retainedSlice()
  - retainedDuplicate()
  - readRetainedSlice()
- Add the new recyclable derived buffer implementations, which has its
  own reference count value
- Add ByteBufHolder.retainedDuplicate()
- Add ByteBufHolder.replace(ByteBuf) so that..
  - a user can replace the content of the holder in a consistent way
  - copy/duplicate/retainedDuplicate() can delegate the holder
    construction to replace(ByteBuf)
- Use retainedDuplicate() and retainedSlice() wherever possible
- Miscellaneous:
  - Rename DuplicateByteBufTest to DuplicatedByteBufTest (missing 'D')
  - Make ReplayingDecoderByteBuf.reject() return an exception instead of
    throwing it so that its callers don't need to add dummy return
    statement

Result:

Derived buffers are now recycled when created via retainedSlice() and
retainedDuplicate() and derived from a pooled buffer
2016-05-17 11:16:13 +02:00
Norman Maurer
d081851156 Remove ByteBuf.readBytes(int) calls when possible
Motivation:

We use ByteBuf.readBytes(int) in various places where we could either remove it completely or use readSlice(int).retain().

Modifications:

- Remove ByteBuf.readBytes(int) when possible or replace by readSlice(int).retain().

Result:

Faster code.
2016-04-09 18:40:57 +02:00
Norman Maurer
4a18bcaa59 [#5062] Mark MqttEncoder @Sharable
Motivation:

Commit 2696778 changed MqttEncoder to be a singelton but missed to add @Sharable annotation. This broke the encoder as it can not be added to multiple pipelines.

Modifications:

Add @Sharable annotation

Result:

MqttEncoder can be used in multiple pipelines again.
2016-04-01 14:48:43 +02:00
Norman Maurer
269677820d Cleanup of codec-mqtt
Motivation:

codec-mqtt had some typos and was not restrict enough in terms of making things final and private constructors.

Modifications:

- Fix typos
- Make most pojos final
- Remove redundant else blocks.

Result:

Cleaner and more restrict code.
2016-03-24 11:02:24 +01:00
Xiaoyan Lin
abbdc70d8b Validate MQTT CONNECT reserved flag in variable header
Motivation:

According to the MQTT 3.1.1 Protocol Specification: The Server MUST validate that the reserved flag in the CONNECT Control Packet is set to zero and disconnect the Client if it is not zero. (http://docs.oasis-open.org/mqtt/mqtt/v3.1.1/os/mqtt-v3.1.1-os.html#_Toc385349230)

Resolves #4182

Modifications:

Check the CONNECT reserved flag for MQTT 3.1.1. If it's not 0, throw an exception.

Result:

If the CONNECT reserved flag, a decode failure will be emitted.
2016-03-16 20:23:31 +01:00
James Lee
acf1b0f90b Fix code styles on MQTT codec classes 2015-08-31 08:25:36 +02:00