1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
declare(strict_types=1); |
4
|
|
|
|
5
|
|
|
namespace unreal4u\MQTT\Protocol; |
6
|
|
|
|
7
|
|
|
use InvalidArgumentException; |
8
|
|
|
use OutOfBoundsException; |
9
|
|
|
use OutOfRangeException; |
10
|
|
|
use unreal4u\MQTT\Application\EmptyReadableResponse; |
11
|
|
|
use unreal4u\MQTT\DataTypes\Message; |
12
|
|
|
use unreal4u\MQTT\DataTypes\PacketIdentifier; |
13
|
|
|
use unreal4u\MQTT\DataTypes\QoSLevel; |
14
|
|
|
use unreal4u\MQTT\DataTypes\TopicName; |
15
|
|
|
use unreal4u\MQTT\Exceptions\Connect\NoConnectionParametersDefined; |
16
|
|
|
use unreal4u\MQTT\Exceptions\InvalidQoSLevel; |
17
|
|
|
use unreal4u\MQTT\Exceptions\InvalidRequest; |
18
|
|
|
use unreal4u\MQTT\Exceptions\InvalidResponseType; |
19
|
|
|
use unreal4u\MQTT\Exceptions\MessageTooBig; |
20
|
|
|
use unreal4u\MQTT\Exceptions\MissingTopicName; |
21
|
|
|
use unreal4u\MQTT\Exceptions\NotConnected; |
22
|
|
|
use unreal4u\MQTT\Internals\ClientInterface; |
23
|
|
|
use unreal4u\MQTT\Internals\PacketIdentifierFunctionality; |
24
|
|
|
use unreal4u\MQTT\Internals\ProtocolBase; |
25
|
|
|
use unreal4u\MQTT\Internals\ReadableContent; |
26
|
|
|
use unreal4u\MQTT\Internals\ReadableContentInterface; |
27
|
|
|
use unreal4u\MQTT\Internals\WritableContent; |
28
|
|
|
use unreal4u\MQTT\Internals\WritableContentInterface; |
29
|
|
|
use unreal4u\MQTT\Utilities; |
30
|
|
|
|
31
|
|
|
use function decbin; |
32
|
|
|
use function ord; |
33
|
|
|
use function sprintf; |
34
|
|
|
use function strlen; |
35
|
|
|
use function substr; |
36
|
|
|
|
37
|
|
|
/** |
38
|
|
|
* A PUBLISH Control Packet is sent from a Client to a Server or vice-versa to transport an Application Message. |
39
|
|
|
* |
40
|
|
|
* @see http://docs.oasis-open.org/mqtt/mqtt/v3.1.1/os/mqtt-v3.1.1-os.html#_Toc398718037 |
41
|
|
|
* |
42
|
|
|
* QoS lvl1: |
43
|
|
|
* First packet: PUBLISH |
44
|
|
|
* Second packet: PUBACK |
45
|
|
|
* |
46
|
|
|
* QoS lvl2: |
47
|
|
|
* First packet: PUBLISH |
48
|
|
|
* Second packet: PUBREC |
49
|
|
|
* Third packet: PUBREL |
50
|
|
|
* Fourth packet: PUBCOMP |
51
|
|
|
* |
52
|
|
|
* @see https://go.gliffy.com/go/publish/12498076 |
53
|
|
|
*/ |
54
|
|
|
final class Publish extends ProtocolBase implements ReadableContentInterface, WritableContentInterface |
55
|
|
|
{ |
56
|
|
|
use ReadableContent; |
57
|
|
|
use /** @noinspection TraitsPropertiesConflictsInspection */ |
58
|
|
|
WritableContent; |
59
|
|
|
use PacketIdentifierFunctionality; |
60
|
|
|
|
61
|
|
|
private const CONTROL_PACKET_VALUE = 3; |
62
|
|
|
/** |
63
|
|
|
* Flag to check whether a message is a redelivery (DUP flag) |
64
|
|
|
* @see http://docs.oasis-open.org/mqtt/mqtt/v3.1.1/os/mqtt-v3.1.1-os.html#_Toc398718038 |
65
|
|
|
* @var bool |
66
|
|
|
*/ |
67
|
|
|
public $isRedelivery = false; |
68
|
|
|
/** |
69
|
|
|
* Contains the message to be sent |
70
|
|
|
* @var Message |
71
|
|
|
*/ |
72
|
|
|
private $message; |
73
|
|
|
|
74
|
|
|
/** |
75
|
|
|
* @return string |
76
|
|
|
* @throws InvalidQoSLevel |
77
|
|
|
* @throws MissingTopicName |
78
|
|
|
* @throws OutOfRangeException |
79
|
|
|
* @throws InvalidArgumentException |
80
|
|
|
*/ |
81
|
5 |
|
public function createVariableHeader(): string |
82
|
|
|
{ |
83
|
5 |
|
if ($this->message === null) { |
84
|
1 |
|
throw new InvalidArgumentException('You must at least provide a message object with a topic name'); |
85
|
|
|
} |
86
|
|
|
|
87
|
4 |
|
$variableHeaderContents = $this->createUTF8String($this->message->getTopicName()); |
88
|
|
|
// Reset the special flags should the same object be reused with another message |
89
|
4 |
|
$this->specialFlags = 0; |
90
|
|
|
|
91
|
4 |
|
$variableHeaderContents .= $this->createVariableHeaderFlags(); |
92
|
|
|
|
93
|
4 |
|
return $variableHeaderContents; |
94
|
|
|
} |
95
|
|
|
|
96
|
|
|
/** |
97
|
|
|
* Sets some common flags and returns the variable header string should there be one |
98
|
|
|
* |
99
|
|
|
* @return string |
100
|
|
|
* @throws OutOfRangeException |
101
|
|
|
* @throws InvalidQoSLevel |
102
|
|
|
*/ |
103
|
4 |
|
private function createVariableHeaderFlags(): string |
104
|
|
|
{ |
105
|
4 |
|
if ($this->isRedelivery) { |
106
|
|
|
// DUP flag: if the message is a re-delivery, mark it as such |
107
|
|
|
$this->specialFlags |= 8; |
108
|
|
|
$this->logger->debug('Activating redelivery bit'); |
109
|
|
|
} |
110
|
|
|
|
111
|
4 |
|
if ($this->message->isRetained()) { |
112
|
|
|
// RETAIN flag: should the server retain the message? |
113
|
1 |
|
$this->specialFlags |= 1; |
114
|
1 |
|
$this->logger->debug('Activating retain flag'); |
115
|
|
|
} |
116
|
|
|
|
117
|
|
|
// Check QoS level and perform the corresponding actions |
118
|
4 |
|
if ($this->message->getQoSLevel() !== 0) { |
119
|
|
|
// 0 for QoS lvl2 for QoS lvl1 and 4 for QoS lvl2 |
120
|
3 |
|
$this->specialFlags |= ($this->message->getQoSLevel() * 2); |
121
|
3 |
|
$this->logger->debug(sprintf('Activating QoS level %d bit', $this->message->getQoSLevel()), [ |
122
|
3 |
|
'PI' => $this->packetIdentifier->getPacketIdentifierValue(), |
123
|
|
|
]); |
124
|
3 |
|
return $this->getPacketIdentifierBinaryRepresentation(); |
125
|
|
|
} |
126
|
|
|
|
127
|
1 |
|
return ''; |
128
|
|
|
} |
129
|
|
|
|
130
|
|
|
/** |
131
|
|
|
* @return string |
132
|
|
|
* @throws MissingTopicName |
133
|
|
|
* @throws MessageTooBig |
134
|
|
|
* @throws InvalidArgumentException |
135
|
|
|
*/ |
136
|
2 |
|
public function createPayload(): string |
137
|
|
|
{ |
138
|
2 |
|
if ($this->message === null) { |
139
|
1 |
|
throw new InvalidArgumentException('A message must be set before publishing'); |
140
|
|
|
} |
141
|
1 |
|
return $this->message->getPayload(); |
142
|
|
|
} |
143
|
|
|
|
144
|
|
|
/** |
145
|
|
|
* QoS level 0 does not have to wait for a answer, so return false. Any other QoS level returns true |
146
|
|
|
* @return bool |
147
|
|
|
* @throws InvalidQoSLevel |
148
|
|
|
*/ |
149
|
2 |
|
public function shouldExpectAnswer(): bool |
150
|
|
|
{ |
151
|
2 |
|
$shouldExpectAnswer = !($this->message->getQoSLevel() === 0); |
152
|
2 |
|
$this->logger->debug('Checking whether we should expect an answer or not', [ |
153
|
2 |
|
'shouldExpectAnswer' => $shouldExpectAnswer, |
154
|
|
|
]); |
155
|
2 |
|
return $shouldExpectAnswer; |
156
|
|
|
} |
157
|
|
|
|
158
|
|
|
/** |
159
|
|
|
* @param string $brokerBitStream |
160
|
|
|
* @param ClientInterface $client |
161
|
|
|
* @return ReadableContentInterface |
162
|
|
|
* @throws InvalidResponseType |
163
|
|
|
*/ |
164
|
3 |
|
public function expectAnswer(string $brokerBitStream, ClientInterface $client): ReadableContentInterface |
165
|
|
|
{ |
166
|
3 |
|
switch ($this->message->getQoSLevel()) { |
167
|
3 |
|
case 1: |
168
|
1 |
|
$pubAck = new PubAck($this->logger); |
169
|
1 |
|
$pubAck->instantiateObject($brokerBitStream, $client); |
170
|
1 |
|
return $pubAck; |
171
|
2 |
|
case 2: |
172
|
1 |
|
$pubRec = new PubRec($this->logger); |
173
|
1 |
|
$pubRec->instantiateObject($brokerBitStream, $client); |
174
|
1 |
|
return $pubRec; |
175
|
1 |
|
case 0: |
176
|
|
|
default: |
177
|
1 |
|
return new EmptyReadableResponse($this->logger); |
178
|
|
|
} |
179
|
|
|
} |
180
|
|
|
|
181
|
|
|
/** |
182
|
|
|
* Gets the set message |
183
|
|
|
* |
184
|
|
|
* @return Message |
185
|
|
|
*/ |
186
|
15 |
|
public function getMessage(): Message |
187
|
|
|
{ |
188
|
15 |
|
return $this->message; |
189
|
|
|
} |
190
|
|
|
|
191
|
|
|
/** |
192
|
|
|
* Sets the to be sent message |
193
|
|
|
* |
194
|
|
|
* @param Message $message |
195
|
|
|
* @return WritableContentInterface |
196
|
|
|
*/ |
197
|
19 |
|
public function setMessage(Message $message): WritableContentInterface |
198
|
|
|
{ |
199
|
19 |
|
$this->message = $message; |
200
|
19 |
|
return $this; |
201
|
|
|
} |
202
|
|
|
|
203
|
|
|
/** |
204
|
|
|
* Will perform sanity checks and fill in the Readable object with data |
205
|
|
|
* @param string $rawMQTTHeaders |
206
|
|
|
* @param ClientInterface $client |
207
|
|
|
* @return ReadableContentInterface |
208
|
|
|
* @throws MessageTooBig |
209
|
|
|
* @throws OutOfBoundsException |
210
|
|
|
* @throws InvalidQoSLevel |
211
|
|
|
* @throws InvalidArgumentException |
212
|
|
|
* @throws OutOfRangeException |
213
|
|
|
*/ |
214
|
7 |
|
public function fillObject(string $rawMQTTHeaders, ClientInterface $client): ReadableContentInterface |
215
|
|
|
{ |
216
|
|
|
// Retrieve full message first |
217
|
7 |
|
$fullMessage = $this->completePossibleIncompleteMessage($rawMQTTHeaders, $client); |
218
|
|
|
// Handy to maintain for debugging purposes |
219
|
|
|
#$this->logger->debug('Bin data', [\unreal4u\MQTT\DebugTools::convertToBinaryRepresentation($rawMQTTHeaders)]); |
220
|
|
|
|
221
|
|
|
// Handy to have: the first byte |
222
|
7 |
|
$firstByte = ord($fullMessage[0]); |
223
|
|
|
// TopicName size is always on the second position after the size of the remaining length field (1 to 4 bytes) |
224
|
7 |
|
$topicSize = ord($fullMessage[$this->sizeOfRemainingLengthField + 2]); |
225
|
|
|
// With the first byte, we can determine the QoS level of the incoming message |
226
|
7 |
|
$qosLevel = $this->determineIncomingQoSLevel($firstByte); |
227
|
|
|
|
228
|
7 |
|
$messageStartPosition = $this->sizeOfRemainingLengthField + 3; |
229
|
|
|
// If we have a QoS level present, we must retrieve the packet identifier as well |
230
|
7 |
|
if ($qosLevel->getQoSLevel() > 0) { |
231
|
3 |
|
$this->logger->debug('QoS level above 0, shifting message start position and getting packet identifier'); |
232
|
|
|
// [2 (fixed header) + 2 (topic size) + $topicSize] marks the beginning of the 2 packet identifier bytes |
233
|
3 |
|
$this->setPacketIdentifier(new PacketIdentifier(Utilities::convertBinaryStringToNumber( |
234
|
3 |
|
$fullMessage[$this->sizeOfRemainingLengthField + 3 + $topicSize] . |
235
|
3 |
|
$fullMessage[$this->sizeOfRemainingLengthField + 4 + $topicSize] |
236
|
|
|
))); |
237
|
3 |
|
$this->logger->debug('Determined packet identifier', ['PI' => $this->getPacketIdentifier()]); |
238
|
3 |
|
$messageStartPosition += 2; |
239
|
|
|
} |
240
|
|
|
|
241
|
|
|
// At this point $rawMQTTHeaders will be always 1 byte long, initialize a Message object with dummy data for now |
242
|
7 |
|
$this->message = new Message( |
243
|
|
|
// Save to assume a constant here: first 2 bytes will always be fixed header, next 2 bytes are topic size |
244
|
7 |
|
substr($fullMessage, $messageStartPosition + $topicSize), |
245
|
7 |
|
new TopicName(substr($fullMessage, $this->sizeOfRemainingLengthField + 3, $topicSize)) |
246
|
|
|
); |
247
|
7 |
|
$this->analyzeFirstByte($firstByte, $qosLevel); |
248
|
|
|
|
249
|
7 |
|
$this->logger->debug('Determined headers', [ |
250
|
7 |
|
'topicSize' => $topicSize, |
251
|
7 |
|
'QoSLevel' => $this->message->getQoSLevel(), |
252
|
7 |
|
'isDuplicate' => $this->isRedelivery, |
253
|
7 |
|
'isRetained' => $this->message->isRetained(), |
254
|
|
|
#'packetIdentifier' => $this->packetIdentifier->getPacketIdentifierValue(), // This is not always set! |
255
|
|
|
]); |
256
|
|
|
|
257
|
7 |
|
return $this; |
258
|
|
|
} |
259
|
|
|
|
260
|
|
|
/** |
261
|
|
|
* Gets the full message in case this object needs to |
262
|
|
|
* |
263
|
|
|
* @param string $rawMQTTHeaders |
264
|
|
|
* @param ClientInterface $client |
265
|
|
|
* @return string |
266
|
|
|
* @throws OutOfBoundsException |
267
|
|
|
* @throws InvalidArgumentException |
268
|
|
|
* @throws MessageTooBig |
269
|
|
|
* @throws InvalidQoSLevel |
270
|
|
|
*/ |
271
|
11 |
|
private function completePossibleIncompleteMessage(string $rawMQTTHeaders, ClientInterface $client): string |
272
|
|
|
{ |
273
|
|
|
// Read at least one extra byte from the stream if we know that the message is too short |
274
|
11 |
|
if (strlen($rawMQTTHeaders) < 2) { |
275
|
3 |
|
$rawMQTTHeaders .= $client->readBrokerData(1); |
276
|
|
|
} |
277
|
|
|
|
278
|
11 |
|
$restOfBytes = $this->performRemainingLengthFieldOperations($rawMQTTHeaders, $client); |
279
|
|
|
|
280
|
|
|
/* |
281
|
|
|
* A complete message consists of: |
282
|
|
|
* - The very first byte |
283
|
|
|
* - The size of the remaining length field (from 1 to 4 bytes) |
284
|
|
|
* - The $restOfBytes |
285
|
|
|
* |
286
|
|
|
* So we have to compare what we already have vs the above calculation |
287
|
|
|
* |
288
|
|
|
* More information: |
289
|
|
|
* http://docs.oasis-open.org/mqtt/mqtt/v3.1.1/errata01/os/mqtt-v3.1.1-errata01-os-complete.html#_Toc442180832 |
290
|
|
|
*/ |
291
|
11 |
|
if (strlen($rawMQTTHeaders) < ($restOfBytes + $this->sizeOfRemainingLengthField + 1)) { |
292
|
|
|
// Read only the portion of data we have left from the socket |
293
|
6 |
|
$readableDataLeft = ($restOfBytes + $this->sizeOfRemainingLengthField + 1) - strlen($rawMQTTHeaders); |
294
|
6 |
|
$rawMQTTHeaders .= $client->readBrokerData($readableDataLeft); |
295
|
|
|
} |
296
|
|
|
|
297
|
11 |
|
return $rawMQTTHeaders; |
298
|
|
|
} |
299
|
|
|
|
300
|
|
|
/** |
301
|
|
|
* Finds out the QoS level in a fixed header for the Publish object |
302
|
|
|
* |
303
|
|
|
* @param int $bitString |
304
|
|
|
* @return QoSLevel |
305
|
|
|
* @throws InvalidQoSLevel |
306
|
|
|
*/ |
307
|
11 |
|
private function determineIncomingQoSLevel(int $bitString): QoSLevel |
308
|
|
|
{ |
309
|
|
|
// QoS lvl are in bit positions 1-2. Shifting is strictly speaking not needed, but increases human comprehension |
310
|
11 |
|
$shiftedBits = $bitString >> 1; |
311
|
11 |
|
$incomingQoSLevel = 0; |
312
|
11 |
|
if (($shiftedBits & 1) === 1) { |
313
|
4 |
|
$incomingQoSLevel = 1; |
314
|
|
|
} |
315
|
11 |
|
if (($shiftedBits & 2) === 2) { |
316
|
2 |
|
$incomingQoSLevel = 2; |
317
|
|
|
} |
318
|
|
|
|
319
|
11 |
|
$this->logger->debug('Setting QoS level', ['bitString' => $bitString, 'incomingQoSLevel' => $incomingQoSLevel]); |
320
|
11 |
|
return new QoSLevel($incomingQoSLevel); |
321
|
|
|
} |
322
|
|
|
|
323
|
|
|
/** |
324
|
|
|
* Sets several bits and pieces from the first byte of the fixed header for the Publish packet |
325
|
|
|
* |
326
|
|
|
* @param int $firstByte |
327
|
|
|
* @param QoSLevel $qoSLevel |
328
|
|
|
* @return Publish |
329
|
|
|
* @throws InvalidQoSLevel |
330
|
|
|
*/ |
331
|
14 |
|
private function analyzeFirstByte(int $firstByte, QoSLevel $qoSLevel): Publish |
332
|
|
|
{ |
333
|
14 |
|
$this->logger->debug('Analyzing first byte', [sprintf('%08d', decbin($firstByte))]); |
334
|
|
|
// Retained bit is bit 0 of first byte |
335
|
14 |
|
$this->message->setRetainFlag(false); |
336
|
14 |
|
if (($firstByte & 1) === 1) { |
337
|
4 |
|
$this->logger->debug('Setting retain flag to true'); |
338
|
4 |
|
$this->message->setRetainFlag(true); |
339
|
|
|
} |
340
|
|
|
// QoS level is already been taken care of, assign it to the message at this point |
341
|
14 |
|
$this->message->setQoSLevel($qoSLevel); |
342
|
|
|
|
343
|
|
|
// Duplicate message must be checked only on QoS > 0, else set it to false |
344
|
14 |
|
$this->isRedelivery = false; |
345
|
14 |
|
if (($firstByte & 8) === 8 && $this->message->getQoSLevel() !== 0) { |
346
|
|
|
// Is a duplicate is always bit 3 of first byte |
347
|
2 |
|
$this->isRedelivery = true; |
348
|
2 |
|
$this->logger->debug('Setting redelivery bit'); |
349
|
|
|
} |
350
|
|
|
|
351
|
14 |
|
return $this; |
352
|
|
|
} |
353
|
|
|
|
354
|
|
|
/** |
355
|
|
|
* @inheritdoc |
356
|
|
|
* @throws InvalidRequest |
357
|
|
|
* @throws InvalidQoSLevel |
358
|
|
|
* @throws NotConnected |
359
|
|
|
* @throws NoConnectionParametersDefined |
360
|
|
|
*/ |
361
|
5 |
|
public function performSpecialActions(ClientInterface $client, WritableContentInterface $originalRequest): bool |
362
|
|
|
{ |
363
|
5 |
|
$qosLevel = $this->message->getQoSLevel(); |
364
|
5 |
|
if ($qosLevel === 0) { |
365
|
3 |
|
$this->logger->debug('No response needed', ['qosLevel', $qosLevel]); |
366
|
2 |
|
} elseif ($qosLevel === 1) { |
367
|
1 |
|
$this->logger->debug('Responding with PubAck', ['qosLevel' => $qosLevel]); |
368
|
1 |
|
$client->processObject($this->composePubAckAnswer()); |
369
|
1 |
|
} elseif ($qosLevel === 2) { |
370
|
1 |
|
$this->logger->debug('Responding with PubRec', ['qosLevel' => $qosLevel]); |
371
|
1 |
|
$client->processObject($this->composePubRecAnswer()); |
372
|
|
|
} |
373
|
|
|
|
374
|
5 |
|
return true; |
375
|
|
|
} |
376
|
|
|
|
377
|
|
|
/** |
378
|
|
|
* Composes a PubAck answer with the same packetIdentifier as what we received |
379
|
|
|
* |
380
|
|
|
* @return PubAck |
381
|
|
|
* @throws InvalidRequest |
382
|
|
|
*/ |
383
|
2 |
|
private function composePubAckAnswer(): PubAck |
384
|
|
|
{ |
385
|
2 |
|
$this->checkForValidPacketIdentifier(); |
386
|
2 |
|
$pubAck = new PubAck($this->logger); |
387
|
2 |
|
$pubAck->setPacketIdentifier($this->packetIdentifier); |
388
|
2 |
|
return $pubAck; |
389
|
|
|
} |
390
|
|
|
|
391
|
|
|
/** |
392
|
|
|
* Will check whether the current object has a packet identifier set. If not, we are in serious problems! |
393
|
|
|
* |
394
|
|
|
* @return Publish |
395
|
|
|
* @throws InvalidRequest |
396
|
|
|
*/ |
397
|
5 |
|
private function checkForValidPacketIdentifier(): self |
398
|
|
|
{ |
399
|
5 |
|
if ($this->packetIdentifier === null) { |
400
|
1 |
|
$this->logger->critical('No valid packet identifier found at a stage where there MUST be one set'); |
401
|
1 |
|
throw new InvalidRequest('You are trying to send a request without a valid packet identifier'); |
402
|
|
|
} |
403
|
|
|
|
404
|
4 |
|
return $this; |
405
|
|
|
} |
406
|
|
|
|
407
|
|
|
/** |
408
|
|
|
* Composes a PubRec answer with the same packetIdentifier as what we received |
409
|
|
|
* |
410
|
|
|
* @return PubRec |
411
|
|
|
* @throws InvalidRequest |
412
|
|
|
*/ |
413
|
2 |
|
private function composePubRecAnswer(): PubRec |
414
|
|
|
{ |
415
|
2 |
|
$this->checkForValidPacketIdentifier(); |
416
|
2 |
|
$pubRec = new PubRec($this->logger); |
417
|
2 |
|
$pubRec->setPacketIdentifier($this->packetIdentifier); |
418
|
2 |
|
return $pubRec; |
419
|
|
|
} |
420
|
|
|
|
421
|
|
|
/** |
422
|
|
|
* PUBLISH packet is the exception to the rule: it is not started on base of a packet that gets sent by us |
423
|
|
|
*/ |
424
|
1 |
|
public function getOriginControlPacket(): int |
425
|
|
|
{ |
426
|
1 |
|
return 0; |
427
|
|
|
} |
428
|
|
|
} |
429
|
|
|
|