Line data Source code
1 : /*
2 : *
3 : * Copyright (c) 2025 Project CHIP Authors
4 : *
5 : * Licensed under the Apache License, Version 2.0 (the "License");
6 : * you may not use this file except in compliance with the License.
7 : * You may obtain a copy of the License at
8 : *
9 : * http://www.apache.org/licenses/LICENSE-2.0
10 : *
11 : * Unless required by applicable law or agreed to in writing, software
12 : * distributed under the License is distributed on an "AS IS" BASIS,
13 : * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 : * See the License for the specific language governing permissions and
15 : * limitations under the License.
16 : */
17 :
18 : /**
19 : * @file
20 : * This file implements a WiFiPAF endpoint abstraction for CHIP over WiFiPAF (CHIPoPAF)
21 : * Public Action Frame Transport Protocol (PAFTP).
22 : *
23 : */
24 :
25 : #include "WiFiPAFEndPoint.h"
26 :
27 : #include <cstdint>
28 : #include <cstring>
29 : #include <utility>
30 :
31 : #include <lib/support/BitFlags.h>
32 : #include <lib/support/BufferReader.h>
33 : #include <lib/support/CodeUtils.h>
34 : #include <lib/support/logging/CHIPLogging.h>
35 : #include <system/SystemClock.h>
36 : #include <system/SystemLayer.h>
37 : #include <system/SystemPacketBuffer.h>
38 :
39 : #include "WiFiPAFConfig.h"
40 : #include "WiFiPAFError.h"
41 : #include "WiFiPAFLayer.h"
42 : #include "WiFiPAFTP.h"
43 :
44 : // Define below to enable extremely verbose, WiFiPAF end point-specific debug logging.
45 : #undef CHIP_WIFIPAF_END_POINT_DEBUG_LOGGING_ENABLED
46 : #define CHIP_WIFIPAF_END_POINT_DEBUG_LOGGING_LEVEL 0
47 :
48 : #ifdef CHIP_WIFIPAF_END_POINT_DEBUG_LOGGING_ENABLED
49 : #define ChipLogDebugWiFiPAFEndPoint_L0(MOD, MSG, ...) ChipLogDetail(MOD, MSG, ##__VA_ARGS__)
50 : #if (CHIP_WIFIPAF_END_POINT_DEBUG_LOGGING_LEVEL == 0)
51 : #define ChipLogDebugWiFiPAFEndPoint(MOD, MSG, ...)
52 : #else
53 : #define ChipLogDebugWiFiPAFEndPoint(MOD, MSG, ...) ChipLogDetail(MOD, MSG, ##__VA_ARGS__)
54 : #endif // CHIP_WIFIPAF_END_POINT_DEBUG_LOGGING_LEVEL
55 : #define ChipLogDebugBufferWiFiPAFEndPoint(MOD, BUF) \
56 : ChipLogByteSpan(MOD, ByteSpan((BUF)->Start(), ((BUF)->DataLength() < 8 ? (BUF)->DataLength() : 8u)))
57 : #else
58 : #define ChipLogDebugWiFiPAFEndPoint(MOD, MSG, ...)
59 : #define ChipLogDebugBufferWiFiPAFEndPoint(MOD, BUF)
60 : #endif
61 :
62 : /**
63 : * @def WIFIPAF_CONFIG_IMMEDIATE_ACK_WINDOW_THRESHOLD
64 : *
65 : * @brief
66 : * If an end point's receive window drops equal to or below this value, it will send an immediate acknowledgement
67 : * packet to re-open its window instead of waiting for the send-ack timer to expire.
68 : *
69 : */
70 : #define WIFIPAF_CONFIG_IMMEDIATE_ACK_WINDOW_THRESHOLD 1
71 :
72 : #define WIFIPAF_ACK_SEND_TIMEOUT_MS 2500
73 : #define WIFIPAF_WAIT_RES_TIMEOUT_MS 1000
74 : // Drop the connection if network resources remain unavailable for the period.
75 : // Known condition: If the remote side is awaiting an ACK packet, the wait time must not exceed PAFTP_ACK_TIMEOUT_MS.
76 : #define WIFIPAF_MAX_RESOURCE_BLOCK_COUNT (PAFTP_ACK_TIMEOUT_MS / WIFIPAF_WAIT_RES_TIMEOUT_MS)
77 :
78 : /**
79 : * @def WIFIPAF_WINDOW_NO_ACK_SEND_THRESHOLD
80 : *
81 : * @brief
82 : * Data fragments may only be sent without piggybacked acks if receiver's window size is above this threshold.
83 : *
84 : */
85 : #define WIFIPAF_WINDOW_NO_ACK_SEND_THRESHOLD 1
86 :
87 : namespace chip {
88 : namespace WiFiPAF {
89 :
90 1 : CHIP_ERROR WiFiPAFEndPoint::StartConnect()
91 : {
92 1 : CHIP_ERROR err = CHIP_NO_ERROR;
93 : PAFTransportCapabilitiesRequestMessage req;
94 1 : PacketBufferHandle buf;
95 1 : constexpr uint8_t numVersions =
96 : CHIP_PAF_TRANSPORT_PROTOCOL_MAX_SUPPORTED_VERSION - CHIP_PAF_TRANSPORT_PROTOCOL_MIN_SUPPORTED_VERSION + 1;
97 : static_assert(numVersions <= NUM_PAFTP_SUPPORTED_PROTOCOL_VERSIONS, "Incompatibly protocol versions");
98 :
99 : // Ensure we're in the correct state.
100 1 : VerifyOrExit(mState == kState_Ready, err = CHIP_ERROR_INCORRECT_STATE);
101 1 : mState = kState_Connecting;
102 :
103 : // Build PAF transport protocol capabilities request.
104 1 : buf = System::PacketBufferHandle::New(System::PacketBuffer::kMaxSize);
105 1 : VerifyOrExit(!buf.IsNull(), err = CHIP_ERROR_NO_MEMORY);
106 :
107 : // Zero-initialize PAF transport capabilities request.
108 1 : memset(&req, 0, sizeof(req));
109 1 : req.mMtu = CHIP_PAF_DEFAULT_MTU;
110 1 : req.mWindowSize = PAF_MAX_RECEIVE_WINDOW_SIZE;
111 :
112 : // Populate request with highest supported protocol versions
113 2 : for (uint8_t i = 0; i < numVersions; i++)
114 : {
115 1 : req.SetSupportedProtocolVersion(i, static_cast<uint8_t>(CHIP_PAF_TRANSPORT_PROTOCOL_MAX_SUPPORTED_VERSION - i));
116 : }
117 :
118 1 : err = req.Encode(buf);
119 1 : SuccessOrExit(err);
120 :
121 : // Start connect timer. Canceled when end point freed or connection established.
122 1 : err = StartConnectTimer();
123 1 : SuccessOrExit(err);
124 :
125 : // Send PAF transport capabilities request to peripheral.
126 : // Add reference to message fragment. CHIP retains partial ownership of message fragment's packet buffer,
127 : // since this is the same buffer as that of the whole message, just with a fragmenter-modified payload offset
128 : // and data length, by a Retain() on the handle when calling this function.
129 1 : err = SendWrite(buf.Retain());
130 1 : SuccessOrExit(err);
131 : // Free request buffer on write confirmation. Stash a reference to it in mSendQueue, which we don't use anyway
132 : // until the connection has been set up.
133 1 : QueueTx(std::move(buf), kType_Data);
134 :
135 1 : exit:
136 : // If we failed to initiate the connection, close the end point.
137 1 : if (err != CHIP_NO_ERROR)
138 : {
139 0 : StopConnectTimer();
140 0 : DoClose(kWiFiPAFCloseFlag_AbortTransmission, err);
141 : }
142 :
143 1 : return err;
144 1 : }
145 :
146 2 : CHIP_ERROR WiFiPAFEndPoint::HandleConnectComplete()
147 : {
148 2 : CHIP_ERROR err = CHIP_NO_ERROR;
149 :
150 2 : mState = kState_Connected;
151 : // Cancel the connect timer.
152 2 : StopConnectTimer();
153 :
154 : // We've successfully completed the PAF transport protocol handshake, so let the application know we're open for business.
155 2 : if (mWiFiPafLayer != nullptr)
156 : {
157 : // Indicate connect complete to next-higher layer.
158 2 : mWiFiPafLayer->OnEndPointConnectComplete(this, CHIP_NO_ERROR);
159 : }
160 : else
161 : {
162 : // If no connect complete callback has been set up, close the end point.
163 0 : err = WIFIPAF_ERROR_NO_CONNECT_COMPLETE_CALLBACK;
164 : }
165 2 : return err;
166 : }
167 :
168 14 : bool WiFiPAFEndPoint::IsConnected(uint8_t state) const
169 : {
170 14 : return (state == kState_Connected || state == kState_Closing);
171 : }
172 :
173 2 : void WiFiPAFEndPoint::DoClose(uint8_t flags, CHIP_ERROR err)
174 : {
175 2 : uint8_t oldState = mState;
176 :
177 : // If end point is not closed or closing, OR end point was closing gracefully, but tx abort has been specified...
178 2 : if ((mState != kState_Closed && mState != kState_Closing) ||
179 0 : (mState == kState_Closing && (flags & kWiFiPAFCloseFlag_AbortTransmission)))
180 : {
181 : // Cancel Connect and ReceiveConnect timers if they are running.
182 : // Check role first to avoid needless iteration over timer pool.
183 2 : if (mRole == kWiFiPafRole_Subscriber)
184 : {
185 1 : StopConnectTimer();
186 : }
187 :
188 : // Free the packets in re-order queue if ones exist
189 14 : for (uint8_t qidx = 0; qidx < PAFTP_REORDER_QUEUE_SIZE; qidx++)
190 : {
191 12 : if (ReorderQueue[qidx] != nullptr)
192 : {
193 0 : ReorderQueue[qidx] = nullptr;
194 0 : ItemsInReorderQueue--;
195 : }
196 : }
197 :
198 : // If transmit buffer is empty or a transmission abort was specified...
199 2 : if (mPafTP.TxState() == WiFiPAFTP::kState_Idle || (flags & kWiFiPAFCloseFlag_AbortTransmission))
200 : {
201 2 : FinalizeClose(oldState, flags, err);
202 : }
203 : else
204 : {
205 : // Wait for send queue and fragmenter's tx buffer to become empty, to ensure all pending messages have been
206 : // sent. Only free end point and tell platform it can throw away the underlying connection once all
207 : // pending messages have been sent and acknowledged by the remote CHIPoPAF stack, or once the remote stack
208 : // closes the CHIPoPAF connection.
209 : //
210 : // In so doing, WiFiPAFEndPoint attempts to emulate the level of reliability afforded by TCPEndPoint and TCP
211 : // sockets in general with a typical default SO_LINGER option. That said, there is no hard guarantee that
212 : // pending messages will be sent once (Do)Close() is called, so developers should use application-level
213 : // messages to confirm the receipt of all data sent prior to a Close() call.
214 0 : mState = kState_Closing;
215 :
216 0 : if ((flags & kWiFiPAFCloseFlag_SuppressCallback) == 0)
217 : {
218 0 : DoCloseCallback(oldState, flags, err);
219 : }
220 : }
221 : }
222 2 : }
223 :
224 2 : void WiFiPAFEndPoint::FinalizeClose(uint8_t oldState, uint8_t flags, CHIP_ERROR err)
225 : {
226 2 : mState = kState_Closed;
227 :
228 : // Ensure transmit queue is empty and set to NULL.
229 2 : mSendQueue = nullptr;
230 : // Clear the session information
231 2 : ChipLogProgress(WiFiPAF, "Shutdown PAF session (%u, %u)", mSessionInfo.id, mSessionInfo.role);
232 2 : mWiFiPafLayer->mWiFiPAFTransport->WiFiPAFCloseSession(mSessionInfo);
233 2 : memset(&mSessionInfo, 0, sizeof(mSessionInfo));
234 : // Fire application's close callback if we haven't already, and it's not suppressed.
235 2 : if (oldState != kState_Closing && (flags & kWiFiPAFCloseFlag_SuppressCallback) == 0)
236 : {
237 2 : DoCloseCallback(oldState, flags, err);
238 : }
239 :
240 : // If underlying WiFiPAF connection has closed, connection object is invalid, so just free the end point and return.
241 2 : if (err == WIFIPAF_ERROR_REMOTE_DEVICE_DISCONNECTED || err == WIFIPAF_ERROR_APP_CLOSED_CONNECTION)
242 : {
243 2 : Free();
244 : }
245 : else // Otherwise, try to signal close to remote device before end point releases WiFiPAF connection and frees itself.
246 : {
247 0 : if (mRole == kWiFiPafRole_Subscriber)
248 : {
249 : // Cancel send and receive-ack timers, if running.
250 0 : StopAckReceivedTimer();
251 0 : StopSendAckTimer();
252 0 : StopWaitResourceTimer();
253 0 : mConnStateFlags.Set(ConnectionStateFlag::kOperationInFlight);
254 : }
255 : else
256 : {
257 0 : Free();
258 : }
259 : }
260 2 : ClearAll();
261 2 : }
262 :
263 2 : void WiFiPAFEndPoint::DoCloseCallback(uint8_t state, uint8_t flags, CHIP_ERROR err)
264 : {
265 : // Callback fires once per end point lifetime.
266 2 : mOnPafSubscribeComplete = nullptr;
267 2 : mOnPafSubscribeError = nullptr;
268 2 : OnConnectionClosed = nullptr;
269 2 : }
270 :
271 2 : void WiFiPAFEndPoint::Free()
272 : {
273 : // Clear fragmentation and reassembly engine's Tx and Rx buffers. Counters will be reset by next engine init.
274 2 : FreePAFtpEngine();
275 :
276 : // Clear pending ack buffer, if any.
277 2 : mAckToSend = nullptr;
278 :
279 : // Cancel all timers.
280 2 : StopConnectTimer();
281 2 : StopAckReceivedTimer();
282 2 : StopSendAckTimer();
283 2 : StopWaitResourceTimer();
284 :
285 : // Clear callbacks.
286 2 : mOnPafSubscribeComplete = nullptr;
287 2 : mOnPafSubscribeError = nullptr;
288 2 : OnMessageReceived = nullptr;
289 2 : OnConnectionClosed = nullptr;
290 2 : }
291 :
292 2 : void WiFiPAFEndPoint::FreePAFtpEngine()
293 : {
294 : // Free transmit disassembly buffer
295 2 : mPafTP.ClearTxPacket();
296 :
297 : // Free receive reassembly buffer
298 2 : mPafTP.ClearRxPacket();
299 2 : }
300 :
301 2 : CHIP_ERROR WiFiPAFEndPoint::Init(WiFiPAFLayer * WiFiPafLayer, WiFiPAFSession & SessionInfo)
302 : {
303 : // Fail if already initialized.
304 2 : VerifyOrReturnError(mWiFiPafLayer == nullptr, CHIP_ERROR_INCORRECT_STATE);
305 :
306 : // Validate args.
307 2 : VerifyOrReturnError(WiFiPafLayer != nullptr, CHIP_ERROR_INVALID_ARGUMENT);
308 :
309 : // If end point plays subscriber role, expect ack as last step of PAFTP handshake.
310 : // If being publisher, subscriber's handshake indication 'ack's write sent by publisher to kick off the PAFTP handshake.
311 2 : bool expectInitialAck = (SessionInfo.role == kWiFiPafRole_Publisher);
312 :
313 2 : CHIP_ERROR err = mPafTP.Init(this, expectInitialAck);
314 2 : if (err != CHIP_NO_ERROR)
315 : {
316 0 : ChipLogError(WiFiPAF, "WiFiPAFTP init failed");
317 0 : return err;
318 : }
319 :
320 2 : mWiFiPafLayer = WiFiPafLayer;
321 :
322 : // WiFiPAF EndPoint data members:
323 2 : memcpy(&mSessionInfo, &SessionInfo, sizeof(mSessionInfo));
324 2 : mRole = SessionInfo.role;
325 2 : mTimerStateFlags.ClearAll();
326 2 : mLocalReceiveWindowSize = 0;
327 2 : mRemoteReceiveWindowSize = 0;
328 2 : mReceiveWindowMaxSize = 0;
329 2 : mSendQueue = nullptr;
330 2 : mAckToSend = nullptr;
331 :
332 : ChipLogDebugWiFiPAFEndPoint(WiFiPAF, "initialized local rx window, size = %u", mLocalReceiveWindowSize);
333 :
334 : // End point is ready.
335 2 : mState = kState_Ready;
336 :
337 2 : return CHIP_NO_ERROR;
338 : }
339 :
340 9 : CHIP_ERROR WiFiPAFEndPoint::SendCharacteristic(PacketBufferHandle && buf)
341 : {
342 9 : CHIP_ERROR err = CHIP_NO_ERROR;
343 :
344 9 : SuccessOrExit(err = SendWrite(std::move(buf)));
345 : // Write succeeded, so shrink remote receive window counter by 1.
346 9 : mRemoteReceiveWindowSize = static_cast<SequenceNumber_t>(mRemoteReceiveWindowSize - 1);
347 : ChipLogDebugWiFiPAFEndPoint(WiFiPAF, "decremented remote rx window, new size = %u", mRemoteReceiveWindowSize);
348 9 : exit:
349 9 : return err;
350 : }
351 :
352 : /*
353 : * Routine to queue the Tx packet with a packet type
354 : * kType_Data(0) - data packet
355 : * kType_Control(1) - control packet
356 : */
357 9 : void WiFiPAFEndPoint::QueueTx(PacketBufferHandle && data, PacketType_t type)
358 : {
359 9 : if (mSendQueue.IsNull())
360 : {
361 7 : mSendQueue = std::move(data);
362 : ChipLogDebugWiFiPAFEndPoint(WiFiPAF, "%s: Set data as new mSendQueue %p, type %d", __FUNCTION__, mSendQueue->Start(), type);
363 : }
364 : else
365 : {
366 2 : mSendQueue->AddToEnd(std::move(data));
367 : ChipLogDebugWiFiPAFEndPoint(WiFiPAF, "%s: Append data to mSendQueue %p, type %d", __FUNCTION__, mSendQueue->Start(), type);
368 : }
369 9 : }
370 :
371 7 : CHIP_ERROR WiFiPAFEndPoint::Send(PacketBufferHandle && data)
372 : {
373 7 : CHIP_ERROR err = CHIP_NO_ERROR;
374 :
375 7 : VerifyOrExit(!data.IsNull(), err = CHIP_ERROR_INVALID_ARGUMENT);
376 7 : VerifyOrExit(IsConnected(mState), err = CHIP_ERROR_INCORRECT_STATE);
377 :
378 : // Ensure outgoing message fits in a single contiguous packet buffer, as currently required by the
379 : // message fragmentation and reassembly engine.
380 7 : if (data->HasChainedBuffer())
381 : {
382 1 : data->CompactHead();
383 :
384 1 : if (data->HasChainedBuffer())
385 : {
386 0 : err = CHIP_ERROR_OUTBOUND_MESSAGE_TOO_BIG;
387 0 : ExitNow();
388 : }
389 : }
390 :
391 : // Add new message to send queue.
392 7 : QueueTx(std::move(data), kType_Data);
393 :
394 : // Send first fragment of new message, if we can.
395 7 : err = DriveSending();
396 7 : SuccessOrExit(err);
397 7 : exit:
398 7 : if (err != CHIP_NO_ERROR)
399 : {
400 0 : DoClose(kWiFiPAFCloseFlag_AbortTransmission, err);
401 : }
402 :
403 7 : return err;
404 : }
405 :
406 8 : bool WiFiPAFEndPoint::PrepareNextFragment(PacketBufferHandle && data, bool & sentAck)
407 : {
408 : // If we have a pending fragment acknowledgement to send, piggyback it on the fragment we're about to transmit.
409 8 : if (mTimerStateFlags.Has(TimerStateFlag::kSendAckTimerRunning))
410 : {
411 : // Reset local receive window counter.
412 2 : mLocalReceiveWindowSize = mReceiveWindowMaxSize;
413 : ChipLogDebugWiFiPAFEndPoint(WiFiPAF, "reset local rx window on piggyback ack tx, size = %u", mLocalReceiveWindowSize);
414 :
415 : // Tell caller AND fragmenter we have an ack to piggyback.
416 2 : sentAck = true;
417 : }
418 : else
419 : {
420 : // No ack to piggyback.
421 6 : sentAck = false;
422 : }
423 :
424 8 : return mPafTP.HandleCharacteristicSend(std::move(data), sentAck);
425 : }
426 :
427 7 : CHIP_ERROR WiFiPAFEndPoint::SendNextMessage()
428 : {
429 : // Get the first queued packet to send
430 7 : PacketBufferHandle data = mSendQueue.PopHead();
431 :
432 : // Hand whole message payload to the fragmenter.
433 : bool sentAck;
434 7 : VerifyOrReturnError(PrepareNextFragment(std::move(data), sentAck), WIFIPAF_ERROR_CHIPPAF_PROTOCOL_ABORT);
435 :
436 7 : ReturnErrorOnFailure(SendCharacteristic(mPafTP.BorrowTxPacket()));
437 :
438 7 : if (sentAck)
439 : {
440 : // If sent piggybacked ack, stop send-ack timer.
441 2 : StopSendAckTimer();
442 : }
443 :
444 : // Start ack received timer, if it's not already running.
445 7 : return StartAckReceivedTimer();
446 7 : }
447 :
448 1 : CHIP_ERROR WiFiPAFEndPoint::ContinueMessageSend()
449 : {
450 : bool sentAck;
451 :
452 1 : if (!PrepareNextFragment(nullptr, sentAck))
453 : {
454 : // Log PAFTP error
455 0 : ChipLogError(WiFiPAF, "paftp fragmenter error on send!");
456 0 : mPafTP.LogState();
457 :
458 0 : return WIFIPAF_ERROR_CHIPPAF_PROTOCOL_ABORT;
459 : }
460 :
461 1 : ReturnErrorOnFailure(SendCharacteristic(mPafTP.BorrowTxPacket()));
462 :
463 1 : if (sentAck)
464 : {
465 : // If sent piggybacked ack, stop send-ack timer.
466 0 : StopSendAckTimer();
467 : }
468 :
469 : // Start ack received timer, if it's not already running.
470 1 : return StartAckReceivedTimer();
471 : }
472 :
473 2 : CHIP_ERROR WiFiPAFEndPoint::HandleHandshakeConfirmationReceived()
474 : {
475 : // Free capabilities request/response payload.
476 2 : mSendQueue.FreeHead();
477 :
478 2 : return CHIP_NO_ERROR;
479 : }
480 :
481 7 : CHIP_ERROR WiFiPAFEndPoint::HandleFragmentConfirmationReceived(bool result)
482 : {
483 7 : CHIP_ERROR err = CHIP_NO_ERROR;
484 : // Ensure we're in correct state to receive confirmation of non-handshake GATT send.
485 7 : VerifyOrExit(IsConnected(mState), err = CHIP_ERROR_INCORRECT_STATE);
486 :
487 7 : if (mConnStateFlags.Has(ConnectionStateFlag::kStandAloneAckInFlight))
488 : {
489 : // If confirmation was received for stand-alone ack, free its tx buffer.
490 0 : mAckToSend = nullptr;
491 0 : mConnStateFlags.Clear(ConnectionStateFlag::kStandAloneAckInFlight);
492 : }
493 :
494 7 : if (result != true)
495 : {
496 : // Something wrong in writing packets
497 0 : ChipLogError(WiFiPAF, "Failed to send PAF packet");
498 0 : err = CHIP_ERROR_SENDING_BLOCKED;
499 0 : StopAckReceivedTimer();
500 0 : SuccessOrExit(err);
501 : }
502 :
503 : // If local receive window size has shrunk to or below immediate ack threshold, AND a message fragment is not
504 : // pending on which to piggyback an ack, send immediate stand-alone ack.
505 : //
506 : // This check covers the case where the local receive window has shrunk between transmission and confirmation of
507 : // the stand-alone ack, and also the case where a window size < the immediate ack threshold was detected in
508 : // Receive(), but the stand-alone ack was deferred due to a pending outbound message fragment.
509 7 : if (mLocalReceiveWindowSize <= WIFIPAF_CONFIG_IMMEDIATE_ACK_WINDOW_THRESHOLD && mSendQueue.IsNull() &&
510 0 : mPafTP.TxState() != WiFiPAFTP::kState_InProgress)
511 : {
512 0 : err = DriveStandAloneAck(); // Encode stand-alone ack and drive sending.
513 0 : SuccessOrExit(err);
514 : }
515 : else
516 : {
517 7 : err = DriveSending();
518 7 : SuccessOrExit(err);
519 : }
520 :
521 7 : exit:
522 7 : if (err != CHIP_NO_ERROR)
523 : {
524 0 : DoClose(kWiFiPAFCloseFlag_AbortTransmission, err);
525 : }
526 :
527 7 : return err;
528 : }
529 :
530 9 : CHIP_ERROR WiFiPAFEndPoint::HandleSendConfirmationReceived(bool result)
531 : {
532 : // Mark outstanding operation as finished.
533 9 : mConnStateFlags.Clear(ConnectionStateFlag::kOperationInFlight);
534 :
535 : // If confirmation was for outbound portion of PAFTP connect handshake...
536 9 : if (!mConnStateFlags.Has(ConnectionStateFlag::kCapabilitiesConfReceived))
537 : {
538 2 : mConnStateFlags.Set(ConnectionStateFlag::kCapabilitiesConfReceived);
539 2 : return HandleHandshakeConfirmationReceived();
540 : }
541 :
542 7 : return HandleFragmentConfirmationReceived(result);
543 : }
544 :
545 1 : CHIP_ERROR WiFiPAFEndPoint::DriveStandAloneAck()
546 : {
547 : // Stop send-ack timer if running.
548 1 : StopSendAckTimer();
549 :
550 : // If stand-alone ack not already pending, allocate new payload buffer here.
551 1 : if (mAckToSend.IsNull())
552 : {
553 1 : mAckToSend = System::PacketBufferHandle::New(kTransferProtocolStandaloneAckHeaderSize);
554 1 : VerifyOrReturnError(!mAckToSend.IsNull(), CHIP_ERROR_NO_MEMORY);
555 : }
556 :
557 : // Attempt to send stand-alone ack.
558 1 : return DriveSending();
559 : }
560 :
561 1 : CHIP_ERROR WiFiPAFEndPoint::DoSendStandAloneAck()
562 : {
563 : ChipLogDebugWiFiPAFEndPoint(WiFiPAF, "sending stand-alone ack");
564 :
565 : // Encode and transmit stand-alone ack.
566 1 : mPafTP.EncodeStandAloneAck(mAckToSend);
567 1 : ReturnErrorOnFailure(SendCharacteristic(mAckToSend.Retain()));
568 :
569 : // Reset local receive window counter.
570 1 : mLocalReceiveWindowSize = mReceiveWindowMaxSize;
571 : ChipLogDebugWiFiPAFEndPoint(WiFiPAF, "reset local rx window on stand-alone ack tx, size = %u", mLocalReceiveWindowSize);
572 :
573 1 : mConnStateFlags.Set(ConnectionStateFlag::kStandAloneAckInFlight);
574 :
575 : // Start ack received timer, if it's not already running.
576 1 : return StartAckReceivedTimer();
577 : }
578 :
579 19 : CHIP_ERROR WiFiPAFEndPoint::DriveSending()
580 : {
581 : // If receiver's window is almost closed and we don't have an ack to send, OR we do have an ack to send but
582 : // receiver's window is completely empty, OR another operation is in flight, awaiting confirmation...
583 39 : if ((mRemoteReceiveWindowSize <= WIFIPAF_WINDOW_NO_ACK_SEND_THRESHOLD &&
584 1 : !mTimerStateFlags.Has(TimerStateFlag::kSendAckTimerRunning) && mAckToSend.IsNull()) ||
585 20 : (mRemoteReceiveWindowSize == 0) || (mConnStateFlags.Has(ConnectionStateFlag::kOperationInFlight)))
586 : {
587 4 : if (mRemoteReceiveWindowSize <= WIFIPAF_WINDOW_NO_ACK_SEND_THRESHOLD &&
588 3 : !mTimerStateFlags.Has(TimerStateFlag::kSendAckTimerRunning) && mAckToSend.IsNull())
589 : {
590 : ChipLogDebugWiFiPAFEndPoint(WiFiPAF, "NO SEND: receive window almost closed, and no ack to send");
591 : }
592 :
593 3 : if (mRemoteReceiveWindowSize == 0)
594 : {
595 : ChipLogDebugWiFiPAFEndPoint(WiFiPAF, "NO SEND: remote receive window closed");
596 : }
597 :
598 3 : if (mConnStateFlags.Has(ConnectionStateFlag::kOperationInFlight))
599 : {
600 : ChipLogDebugWiFiPAFEndPoint(WiFiPAF, "NO SEND: Operation in flight");
601 : }
602 : // Can't send anything.
603 3 : return CHIP_NO_ERROR;
604 : }
605 :
606 16 : if (!mWiFiPafLayer->mWiFiPAFTransport->WiFiPAFResourceAvailable())
607 : {
608 : // Resource is currently unavailable, send packets later
609 1 : StartWaitResourceTimer();
610 1 : return CHIP_NO_ERROR;
611 : }
612 15 : mResourceWaitCount = 0;
613 :
614 : // Otherwise, let's see what we can send.
615 15 : if ((!mAckToSend.IsNull()) && !mConnStateFlags.Has(ConnectionStateFlag::kStandAloneAckInFlight))
616 : {
617 : // If immediate, stand-alone ack is pending, send it.
618 0 : ChipLogProgress(WiFiPAF, "Send the pending stand-alone ack");
619 0 : ReturnErrorOnFailure(DoSendStandAloneAck());
620 : }
621 15 : else if (mPafTP.TxState() == WiFiPAFTP::kState_Idle) // Else send next message fragment, if any.
622 : {
623 : // Fragmenter's idle, let's see what's in the send queue...
624 9 : if (!mSendQueue.IsNull())
625 : {
626 : // Transmit first fragment of next whole message in send queue.
627 6 : ReturnErrorOnFailure(SendNextMessage());
628 : }
629 : else
630 : {
631 : // Nothing to send!
632 : ChipLogDebugWiFiPAFEndPoint(WiFiPAF, "=> No pending packets, nothing to send!");
633 : }
634 : }
635 6 : else if (mPafTP.TxState() == WiFiPAFTP::kState_InProgress)
636 : {
637 : // Send next fragment of message currently held by fragmenter.
638 : ChipLogDebugWiFiPAFEndPoint(WiFiPAF, "Send the next fragment");
639 1 : ReturnErrorOnFailure(ContinueMessageSend());
640 : }
641 5 : else if (mPafTP.TxState() == WiFiPAFTP::kState_Complete)
642 : {
643 : // Clear fragmenter's pointer to sent message buffer and reset its Tx state.
644 : // Buffer will be freed at scope exit.
645 5 : PacketBufferHandle sentBuf = mPafTP.TakeTxPacket();
646 :
647 5 : if (!mSendQueue.IsNull())
648 : {
649 : ChipLogDebugWiFiPAFEndPoint(WiFiPAF, "Send the next pkt");
650 : // Transmit first fragment of next whole message in send queue.
651 1 : ReturnErrorOnFailure(SendNextMessage());
652 : }
653 4 : else if (mState == kState_Closing && !mPafTP.ExpectingAck()) // and mSendQueue is NULL, per above...
654 : {
655 : ChipLogDebugWiFiPAFEndPoint(WiFiPAF, "Closing and no expect ack!");
656 : // If end point closing, got last ack, and got out-of-order confirmation for last send, finalize close.
657 0 : FinalizeClose(mState, kWiFiPAFCloseFlag_SuppressCallback, CHIP_NO_ERROR);
658 : }
659 : else
660 : {
661 : // Nothing to send!
662 : ChipLogDebugWiFiPAFEndPoint(WiFiPAF, "No more packets to send");
663 : }
664 5 : }
665 : else
666 : {
667 0 : ChipLogError(WiFiPAF, "Unknown TxState: %u", mPafTP.TxState());
668 : }
669 15 : return CHIP_NO_ERROR;
670 : }
671 :
672 1 : CHIP_ERROR WiFiPAFEndPoint::HandleCapabilitiesRequestReceived(PacketBufferHandle && data)
673 : {
674 : PAFTransportCapabilitiesRequestMessage req;
675 : PAFTransportCapabilitiesResponseMessage resp;
676 : uint16_t mtu;
677 :
678 1 : VerifyOrReturnError(!data.IsNull(), CHIP_ERROR_INVALID_ARGUMENT);
679 :
680 1 : mState = kState_Connecting;
681 :
682 : // Decode PAFTP capabilities request.
683 1 : ReturnErrorOnFailure(PAFTransportCapabilitiesRequestMessage::Decode(data, req));
684 :
685 1 : PacketBufferHandle responseBuf = System::PacketBufferHandle::New(kCapabilitiesResponseLength);
686 1 : VerifyOrReturnError(!responseBuf.IsNull(), CHIP_ERROR_NO_MEMORY);
687 :
688 1 : if (req.mMtu > 0) // If MTU was observed and provided by central...
689 : {
690 1 : mtu = req.mMtu; // Accept central's observation of the MTU.
691 : }
692 : else
693 : {
694 0 : mtu = CHIP_PAF_DEFAULT_MTU;
695 : }
696 :
697 : // Select fragment size for connection based on MTU.
698 1 : resp.mFragmentSize = std::min(static_cast<uint16_t>(mtu), WiFiPAFTP::sMaxFragmentSize);
699 :
700 : // Select local and remote max receive window size based on local resources available for both incoming writes
701 1 : mRemoteReceiveWindowSize = mLocalReceiveWindowSize = mReceiveWindowMaxSize =
702 1 : std::min(req.mWindowSize, static_cast<uint8_t>(PAF_MAX_RECEIVE_WINDOW_SIZE));
703 1 : resp.mWindowSize = mReceiveWindowMaxSize;
704 1 : ChipLogProgress(WiFiPAF, "local and remote recv window sizes = %u", resp.mWindowSize);
705 :
706 : // Select PAF transport protocol version from those supported by central, or none if no supported version found.
707 1 : resp.mSelectedProtocolVersion = WiFiPAFLayer::GetHighestSupportedProtocolVersion(req);
708 1 : ChipLogProgress(WiFiPAF, "selected PAFTP version %d", resp.mSelectedProtocolVersion);
709 :
710 1 : if (resp.mSelectedProtocolVersion == kWiFiPAFTransportProtocolVersion_None)
711 : {
712 : // If WiFiPAF transport protocol versions incompatible, prepare to close connection after capabilities response
713 : // has been sent.
714 0 : ChipLogError(WiFiPAF, "incompatible PAFTP versions; peripheral expected between %d and %d",
715 : CHIP_PAF_TRANSPORT_PROTOCOL_MIN_SUPPORTED_VERSION, CHIP_PAF_TRANSPORT_PROTOCOL_MAX_SUPPORTED_VERSION);
716 0 : mState = kState_Aborting;
717 : }
718 : else
719 : {
720 : // Set Rx and Tx fragment sizes to the same value
721 1 : mPafTP.SetRxFragmentSize(resp.mFragmentSize);
722 1 : mPafTP.SetTxFragmentSize(resp.mFragmentSize);
723 : }
724 :
725 1 : ChipLogProgress(WiFiPAF, "using PAFTP fragment sizes rx %d / tx %d.", mPafTP.GetRxFragmentSize(), mPafTP.GetTxFragmentSize());
726 1 : ReturnErrorOnFailure(resp.Encode(responseBuf));
727 :
728 : CHIP_ERROR err;
729 1 : err = SendWrite(responseBuf.Retain());
730 1 : SuccessOrExit(err);
731 :
732 : // Stash capabilities response payload
733 1 : QueueTx(std::move(responseBuf), kType_Data);
734 :
735 : // Response has been sent
736 1 : return HandleConnectComplete();
737 0 : exit:
738 0 : return err;
739 1 : }
740 :
741 1 : CHIP_ERROR WiFiPAFEndPoint::HandleCapabilitiesResponseReceived(PacketBufferHandle && data)
742 : {
743 : PAFTransportCapabilitiesResponseMessage resp;
744 :
745 1 : VerifyOrReturnError(!data.IsNull(), CHIP_ERROR_INVALID_ARGUMENT);
746 :
747 : // Decode PAFTP capabilities response.
748 1 : ReturnErrorOnFailure(PAFTransportCapabilitiesResponseMessage::Decode(data, resp));
749 :
750 1 : VerifyOrReturnError(resp.mFragmentSize > 0, WIFIPAF_ERROR_INVALID_FRAGMENT_SIZE);
751 :
752 1 : ChipLogProgress(WiFiPAF, "Publisher chose PAFTP version %d; subscriber expected between %d and %d",
753 : resp.mSelectedProtocolVersion, CHIP_PAF_TRANSPORT_PROTOCOL_MIN_SUPPORTED_VERSION,
754 : CHIP_PAF_TRANSPORT_PROTOCOL_MAX_SUPPORTED_VERSION);
755 :
756 1 : if ((resp.mSelectedProtocolVersion < CHIP_PAF_TRANSPORT_PROTOCOL_MIN_SUPPORTED_VERSION) ||
757 1 : (resp.mSelectedProtocolVersion > CHIP_PAF_TRANSPORT_PROTOCOL_MAX_SUPPORTED_VERSION))
758 : {
759 0 : return WIFIPAF_ERROR_INCOMPATIBLE_PROTOCOL_VERSIONS;
760 : }
761 :
762 : // Set fragment size as minimum of (reported ATT MTU, BTP characteristic size)
763 1 : resp.mFragmentSize = std::min(resp.mFragmentSize, WiFiPAFTP::sMaxFragmentSize);
764 :
765 1 : mPafTP.SetRxFragmentSize(resp.mFragmentSize);
766 1 : mPafTP.SetTxFragmentSize(resp.mFragmentSize);
767 :
768 1 : ChipLogProgress(WiFiPAF, "using PAFTP fragment sizes rx %d / tx %d.", mPafTP.GetRxFragmentSize(), mPafTP.GetTxFragmentSize());
769 :
770 : // Select local and remote max receive window size based on local resources available for both incoming indications
771 1 : mRemoteReceiveWindowSize = mLocalReceiveWindowSize = mReceiveWindowMaxSize = resp.mWindowSize;
772 :
773 1 : ChipLogProgress(WiFiPAF, "local and remote recv window size = %u", resp.mWindowSize);
774 :
775 : // Shrink local receive window counter by 1, since connect handshake indication requires acknowledgement.
776 1 : mLocalReceiveWindowSize = static_cast<SequenceNumber_t>(mLocalReceiveWindowSize - 1);
777 : ChipLogDebugWiFiPAFEndPoint(WiFiPAF, "decremented local rx window, new size = %u", mLocalReceiveWindowSize);
778 :
779 : // Send ack for connection handshake indication when timer expires. Sequence numbers always start at 0,
780 : // and the reassembler's "last received seq num" is initialized to 0 and updated when new fragments are
781 : // received from the peripheral, so we don't need to explicitly mark the ack num to send here.
782 1 : ReturnErrorOnFailure(StartSendAckTimer());
783 :
784 : // We've sent a capabilities request write and received a compatible response, so the connect
785 : // operation has completed successfully.
786 1 : return HandleConnectComplete();
787 : }
788 :
789 : // Returns number of open slots in remote receive window given the input values.
790 4 : SequenceNumber_t WiFiPAFEndPoint::AdjustRemoteReceiveWindow(SequenceNumber_t lastReceivedAck, SequenceNumber_t maxRemoteWindowSize,
791 : SequenceNumber_t newestUnackedSentSeqNum)
792 : {
793 : // Assumption: SequenceNumber_t is uint8_t.
794 : // Assumption: Maximum possible sequence number value is UINT8_MAX.
795 : // Assumption: Sequence numbers incremented past maximum value wrap to 0.
796 : // Assumption: newest unacked sent sequence number never exceeds current (and by extension, new and un-wrapped)
797 : // window boundary, so it never wraps relative to last received ack, if new window boundary would not
798 : // also wrap.
799 :
800 : // Define new window boundary (inclusive) as uint16_t, so its value can temporarily exceed UINT8_MAX.
801 4 : uint16_t newRemoteWindowBoundary = static_cast<uint16_t>(lastReceivedAck + maxRemoteWindowSize);
802 :
803 4 : if (newRemoteWindowBoundary > UINT8_MAX && newestUnackedSentSeqNum < lastReceivedAck)
804 : {
805 : // New window boundary WOULD wrap, and latest unacked seq num already HAS wrapped, so add offset to difference.
806 0 : return static_cast<uint8_t>(newRemoteWindowBoundary - (newestUnackedSentSeqNum + UINT8_MAX));
807 : }
808 :
809 : // Neither values would or have wrapped, OR new boundary WOULD wrap but latest unacked seq num does not, so no
810 : // offset required.
811 4 : return static_cast<uint8_t>(newRemoteWindowBoundary - newestUnackedSentSeqNum);
812 : }
813 :
814 7 : CHIP_ERROR WiFiPAFEndPoint::GetPktSn(Encoding::LittleEndian::Reader & reader, uint8_t * pHead, SequenceNumber_t & seqNum)
815 : {
816 : CHIP_ERROR err;
817 7 : BitFlags<WiFiPAFTP::HeaderFlags> rx_flags;
818 7 : size_t SnOffset = 0;
819 : SequenceNumber_t * pSn;
820 7 : err = reader.Read8(rx_flags.RawStorage()).StatusCode();
821 7 : if (rx_flags.Has(WiFiPAFTP::HeaderFlags::kHankshake))
822 : {
823 : // Handkshake message => No ack/sn
824 2 : return CHIP_ERROR_INTERNAL;
825 : }
826 : // Always has header flag
827 5 : SnOffset += kTransferProtocolHeaderFlagsSize;
828 5 : if (rx_flags.Has(WiFiPAFTP::HeaderFlags::kManagementOpcode)) // Has Mgmt_Op
829 : {
830 0 : SnOffset += kTransferProtocolMgmtOpSize;
831 : }
832 5 : if (rx_flags.Has(WiFiPAFTP::HeaderFlags::kFragmentAck)) // Has ack
833 : {
834 5 : SnOffset += kTransferProtocolAckSize;
835 : }
836 5 : pSn = pHead + SnOffset;
837 5 : seqNum = *pSn;
838 :
839 5 : return CHIP_NO_ERROR;
840 : }
841 :
842 17 : CHIP_ERROR WiFiPAFEndPoint::DebugPktAckSn(const PktDirect_t PktDirect, Encoding::LittleEndian::Reader & reader, uint8_t * pHead)
843 : {
844 : #ifdef CHIP_WIFIPAF_END_POINT_DEBUG_LOGGING_ENABLED
845 : BitFlags<WiFiPAFTP::HeaderFlags> rx_flags;
846 : CHIP_ERROR err;
847 : uint8_t * pAct = nullptr;
848 : char AckBuff[4];
849 : uint8_t * pSn;
850 : size_t SnOffset = 0;
851 :
852 : err = reader.Read8(rx_flags.RawStorage()).StatusCode();
853 : SuccessOrExit(err);
854 : if (rx_flags.Has(WiFiPAFTP::HeaderFlags::kHankshake))
855 : {
856 : // Handkshake message => No ack/sn
857 : return CHIP_NO_ERROR;
858 : }
859 : // Always has header flag
860 : SnOffset += kTransferProtocolHeaderFlagsSize;
861 : if (rx_flags.Has(WiFiPAFTP::HeaderFlags::kManagementOpcode)) // Has Mgmt_Op
862 : {
863 : SnOffset += kTransferProtocolMgmtOpSize;
864 : }
865 : if (rx_flags.Has(WiFiPAFTP::HeaderFlags::kFragmentAck)) // Has ack
866 : {
867 : pAct = pHead + kTransferProtocolHeaderFlagsSize;
868 : SnOffset += kTransferProtocolAckSize;
869 : }
870 : pSn = pHead + SnOffset;
871 : if (pAct == nullptr)
872 : {
873 : strcpy(AckBuff, " ");
874 : }
875 : else
876 : {
877 : snprintf(AckBuff, sizeof(AckBuff), "%02hhu", *pAct);
878 : }
879 : if (PktDirect == PktDirect_t::kTx)
880 : {
881 : ChipLogDebugWiFiPAFEndPoint_L0(WiFiPAF, "==>[tx] [Sn, Ack] = [ %02u, -- %s]", *pSn, AckBuff);
882 : }
883 : else if (PktDirect == PktDirect_t::kRx)
884 : {
885 : ChipLogDebugWiFiPAFEndPoint_L0(WiFiPAF, "<==[rx] [Ack, Sn] = [-- %s, %02u]", AckBuff, *pSn);
886 : }
887 : exit:
888 : return err;
889 : #else
890 17 : return CHIP_NO_ERROR;
891 : #endif
892 : }
893 :
894 7 : CHIP_ERROR WiFiPAFEndPoint::Receive(PacketBufferHandle && data)
895 : {
896 7 : SequenceNumber_t ExpRxNextSeqNum = mPafTP.GetRxNextSeqNum();
897 : SequenceNumber_t seqNum;
898 7 : Encoding::LittleEndian::Reader reader(data->Start(), data->DataLength());
899 7 : CHIP_ERROR err = CHIP_NO_ERROR;
900 :
901 7 : err = GetPktSn(reader, data->Start(), seqNum);
902 7 : if (err != CHIP_NO_ERROR)
903 : {
904 : // Failed to get SeqNum. => Pass down to PAFTP engine directly
905 2 : return RxPacketProcess(std::move(data));
906 : }
907 : /*
908 : If reorder-queue is not empty => Need to queue the packet whose SeqNum is the next one at
909 : offset 0 to fill the hole.
910 : */
911 5 : if ((ExpRxNextSeqNum == seqNum) && (ItemsInReorderQueue == 0))
912 2 : return RxPacketProcess(std::move(data));
913 :
914 3 : ChipLogError(WiFiPAF, "Reorder the packet: [%u, %u]", ExpRxNextSeqNum, seqNum);
915 : // Start reordering packets
916 3 : SequenceNumber_t offset = OffsetSeqNum(seqNum, ExpRxNextSeqNum);
917 3 : if (offset >= PAFTP_REORDER_QUEUE_SIZE)
918 : {
919 : // Offset is too big
920 : // => It may be the unexpected packet or duplicate packet => drop it
921 1 : ChipLogError(WiFiPAF, "Offset (%u) is too big => drop the packet", offset);
922 : ChipLogDebugBufferWiFiPAFEndPoint(WiFiPAF, data);
923 1 : return CHIP_NO_ERROR;
924 : }
925 :
926 : // Save the packet to the reorder-queue
927 2 : if (ReorderQueue[offset] == nullptr)
928 : {
929 2 : ReorderQueue[offset] = std::move(data).UnsafeRelease();
930 2 : ItemsInReorderQueue++;
931 : }
932 :
933 : // Consume the packets in the reorder queue if no hole exists
934 2 : if (ReorderQueue[0] == nullptr)
935 : {
936 : // The hole still exists => Can't continue
937 1 : ChipLogError(WiFiPAF, "The hole still exists. Packets in reorder-queue: %u", ItemsInReorderQueue);
938 1 : return CHIP_NO_ERROR;
939 : }
940 : uint8_t qidx;
941 3 : for (qidx = 0; qidx < PAFTP_REORDER_QUEUE_SIZE; qidx++)
942 : {
943 : // The head slots should have been filled. => Do rx processing
944 3 : if (ReorderQueue[qidx] == nullptr)
945 : {
946 : // Stop consuming packets until the hole or no packets
947 1 : break;
948 : }
949 : // Consume the saved packets
950 2 : ChipLogProgress(WiFiPAF, "Rx processing from the re-order queue [%u]", qidx);
951 2 : err = RxPacketProcess(System::PacketBufferHandle::Adopt(ReorderQueue[qidx]));
952 2 : ReorderQueue[qidx] = nullptr;
953 2 : ItemsInReorderQueue--;
954 : }
955 : // Has reached the 1st hole in the queue => move the rest items forward
956 : // Note: It's to continue => No need to reinit "i"
957 5 : for (uint8_t newId = 0; qidx < PAFTP_REORDER_QUEUE_SIZE; qidx++, newId++)
958 : {
959 4 : if (ReorderQueue[qidx] != nullptr)
960 : {
961 0 : ReorderQueue[newId] = ReorderQueue[qidx];
962 0 : ReorderQueue[qidx] = nullptr;
963 : }
964 : }
965 1 : return err;
966 : }
967 :
968 6 : CHIP_ERROR WiFiPAFEndPoint::RxPacketProcess(PacketBufferHandle && data)
969 : {
970 : ChipLogDebugBufferWiFiPAFEndPoint(WiFiPAF, data);
971 :
972 6 : CHIP_ERROR err = CHIP_NO_ERROR;
973 6 : SequenceNumber_t receivedAck = 0;
974 6 : uint8_t closeFlags = kWiFiPAFCloseFlag_AbortTransmission;
975 6 : bool didReceiveAck = false;
976 6 : BitFlags<WiFiPAFTP::HeaderFlags> rx_flags;
977 6 : Encoding::LittleEndian::Reader reader(data->Start(), data->DataLength());
978 6 : DebugPktAckSn(PktDirect_t::kRx, reader, data->Start());
979 :
980 : { // This is a special handling on the first CHIPoPAF data packet, the CapabilitiesRequest.
981 : // If we're receiving the first inbound packet of a PAF transport connection handshake...
982 6 : if (!mConnStateFlags.Has(ConnectionStateFlag::kCapabilitiesMsgReceived))
983 : {
984 2 : if (mRole == kWiFiPafRole_Subscriber) // If we're a central receiving a capabilities response indication...
985 : {
986 : // Ensure end point's in the right state before continuing.
987 1 : VerifyOrExit(mState == kState_Connecting, err = CHIP_ERROR_INCORRECT_STATE);
988 1 : mConnStateFlags.Set(ConnectionStateFlag::kCapabilitiesMsgReceived);
989 1 : err = HandleCapabilitiesResponseReceived(std::move(data));
990 1 : SuccessOrExit(err);
991 : }
992 : else // Or, a peripheral receiving a capabilities request write...
993 : {
994 : // Ensure end point's in the right state before continuing.
995 1 : VerifyOrExit(mState == kState_Ready, err = CHIP_ERROR_INCORRECT_STATE);
996 1 : mConnStateFlags.Set(ConnectionStateFlag::kCapabilitiesMsgReceived);
997 1 : err = HandleCapabilitiesRequestReceived(std::move(data));
998 1 : if (err != CHIP_NO_ERROR)
999 : {
1000 : // If an error occurred decoding and handling the capabilities request, release the BLE connection.
1001 : // Central's connect attempt will time out if peripheral's application decides to keep the BLE
1002 : // connection open, or fail immediately if the application closes the connection.
1003 0 : closeFlags = closeFlags | kWiFiPAFCloseFlag_SuppressCallback;
1004 0 : ExitNow();
1005 : }
1006 : }
1007 : // If received data was handshake packet, don't feed it to message reassembler.
1008 2 : ExitNow();
1009 : }
1010 : } // End handling the CapabilitiesRequest
1011 :
1012 4 : err = reader.Read8(rx_flags.RawStorage()).StatusCode();
1013 4 : SuccessOrExit(err);
1014 4 : if (rx_flags.Has(WiFiPAFTP::HeaderFlags::kHankshake))
1015 : {
1016 : ChipLogDebugWiFiPAFEndPoint(WiFiPAF, "Unexpected handshake packet => drop");
1017 0 : ExitNow();
1018 : }
1019 :
1020 : ChipLogDebugWiFiPAFEndPoint(WiFiPAF, "PAFTP about to rx characteristic, state before:");
1021 4 : mPafTP.LogStateDebug();
1022 :
1023 : // Pass received packet into PAFTP protocol engine.
1024 4 : err = mPafTP.HandleCharacteristicReceived(std::move(data), receivedAck, didReceiveAck);
1025 :
1026 : ChipLogDebugWiFiPAFEndPoint(WiFiPAF, "PAFTP rx'd characteristic, state after:");
1027 4 : mPafTP.LogStateDebug();
1028 4 : SuccessOrExit(err);
1029 :
1030 : // Protocol engine accepted the fragment, so shrink local receive window counter by 1.
1031 4 : mLocalReceiveWindowSize = static_cast<SequenceNumber_t>(mLocalReceiveWindowSize - 1);
1032 : ChipLogDebugWiFiPAFEndPoint(WiFiPAF, "decremented local rx window, new size = %u", mLocalReceiveWindowSize);
1033 :
1034 : // Respond to received ack, if any.
1035 4 : if (didReceiveAck)
1036 : {
1037 : ChipLogDebugWiFiPAFEndPoint(WiFiPAF, "got paftp ack = %u", receivedAck);
1038 :
1039 : // If ack was rx'd for newest unacked sent fragment, stop ack received timer.
1040 4 : if (!mPafTP.ExpectingAck())
1041 : {
1042 : ChipLogDebugWiFiPAFEndPoint(WiFiPAF, "got ack for last outstanding fragment");
1043 1 : StopAckReceivedTimer();
1044 :
1045 1 : if (mState == kState_Closing && mSendQueue.IsNull() && mPafTP.TxState() == WiFiPAFTP::kState_Idle)
1046 : {
1047 : // If end point closing, got confirmation for last send, and waiting for last ack, finalize close.
1048 0 : FinalizeClose(mState, kWiFiPAFCloseFlag_SuppressCallback, CHIP_NO_ERROR);
1049 0 : ExitNow();
1050 : }
1051 : }
1052 : else // Else there are still sent fragments for which acks are expected, so restart ack received timer.
1053 : {
1054 : ChipLogDebugWiFiPAFEndPoint(WiFiPAF, "still expecting ack(s), restarting timer...");
1055 3 : err = RestartAckReceivedTimer();
1056 3 : SuccessOrExit(err);
1057 : }
1058 :
1059 : ChipLogDebugWiFiPAFEndPoint(
1060 : WiFiPAF, "about to adjust remote rx window; got ack num = %u, newest unacked sent seq num = %u, \
1061 : old window size = %u, max window size = %u",
1062 : receivedAck, mPafTP.GetNewestUnackedSentSequenceNumber(), mRemoteReceiveWindowSize, mReceiveWindowMaxSize);
1063 :
1064 : // Open remote device's receive window according to sequence number it just acknowledged.
1065 4 : mRemoteReceiveWindowSize =
1066 4 : AdjustRemoteReceiveWindow(receivedAck, mReceiveWindowMaxSize, mPafTP.GetNewestUnackedSentSequenceNumber());
1067 :
1068 : ChipLogDebugWiFiPAFEndPoint(WiFiPAF, "adjusted remote rx window, new size = %u", mRemoteReceiveWindowSize);
1069 :
1070 : // Restart message transmission if it was previously paused due to window exhaustion.
1071 4 : err = DriveSending();
1072 4 : SuccessOrExit(err);
1073 : }
1074 :
1075 : // The previous DriveSending() might have generated a piggyback acknowledgement if there was
1076 : // previously un-acked data. Otherwise, prepare to send acknowledgement for newly received fragment.
1077 : //
1078 : // If local receive window is below immediate ack threshold, AND there is no previous stand-alone ack in
1079 : // flight, AND there is no pending outbound message fragment on which the ack can and will be piggybacked,
1080 : // send immediate stand-alone ack to reopen window for sender.
1081 : //
1082 : // The "operation in flight" check below covers "pending outbound message fragment" by extension, as when
1083 : // a message has been passed to the end point via Send(), its next outbound fragment must either be in flight
1084 : // itself, or awaiting the completion of another in-flight operation.
1085 : //
1086 : // If any operation is in flight that is NOT a stand-alone ack, the window size will be checked against
1087 : // this threshold again when the operation is confirmed.
1088 4 : if (mPafTP.HasUnackedData())
1089 : {
1090 4 : if (mLocalReceiveWindowSize <= WIFIPAF_CONFIG_IMMEDIATE_ACK_WINDOW_THRESHOLD &&
1091 0 : !mConnStateFlags.Has(ConnectionStateFlag::kOperationInFlight))
1092 : {
1093 : ChipLogDebugWiFiPAFEndPoint(WiFiPAF, "sending immediate ack");
1094 0 : err = DriveStandAloneAck();
1095 0 : SuccessOrExit(err);
1096 : }
1097 : else
1098 : {
1099 : ChipLogDebugWiFiPAFEndPoint(WiFiPAF, "starting send-ack timer");
1100 :
1101 : // Send ack when timer expires.
1102 4 : err = StartSendAckTimer();
1103 4 : SuccessOrExit(err);
1104 : }
1105 : }
1106 :
1107 : // If we've reassembled a whole message...
1108 4 : if (mPafTP.RxState() == WiFiPAFTP::kState_Complete)
1109 : {
1110 : // Take ownership of message buffer
1111 2 : System::PacketBufferHandle full_packet = mPafTP.TakeRxPacket();
1112 :
1113 : ChipLogDebugWiFiPAFEndPoint(WiFiPAF, "reassembled whole msg, len = %u", static_cast<unsigned>(full_packet->DataLength()));
1114 :
1115 : // If we have a message received callback, and end point is not closing...
1116 2 : if (mWiFiPafLayer != nullptr && mState != kState_Closing)
1117 : {
1118 : // Pass received message up the stack.
1119 2 : err = mWiFiPafLayer->OnWiFiPAFMsgRxComplete(mSessionInfo, std::move(full_packet));
1120 : }
1121 2 : }
1122 :
1123 2 : exit:
1124 6 : if (err != CHIP_NO_ERROR)
1125 : {
1126 0 : DoClose(closeFlags, err);
1127 : }
1128 :
1129 6 : return err;
1130 : }
1131 :
1132 11 : CHIP_ERROR WiFiPAFEndPoint::SendWrite(PacketBufferHandle && buf)
1133 : {
1134 11 : mConnStateFlags.Set(ConnectionStateFlag::kOperationInFlight);
1135 :
1136 : ChipLogDebugBufferWiFiPAFEndPoint(WiFiPAF, buf);
1137 11 : Encoding::LittleEndian::Reader reader(buf->Start(), buf->DataLength());
1138 11 : DebugPktAckSn(PktDirect_t::kTx, reader, buf->Start());
1139 11 : mWiFiPafLayer->mWiFiPAFTransport->WiFiPAFMessageSend(mSessionInfo, std::move(buf));
1140 :
1141 11 : return CHIP_NO_ERROR;
1142 : }
1143 :
1144 1 : CHIP_ERROR WiFiPAFEndPoint::StartConnectTimer()
1145 : {
1146 1 : const CHIP_ERROR timerErr = mWiFiPafLayer->mSystemLayer->StartTimer(System::Clock::Milliseconds32(PAFTP_CONN_RSP_TIMEOUT_MS),
1147 : HandleConnectTimeout, this);
1148 1 : ReturnErrorOnFailure(timerErr);
1149 1 : mTimerStateFlags.Set(TimerStateFlag::kConnectTimerRunning);
1150 :
1151 1 : return CHIP_NO_ERROR;
1152 : }
1153 :
1154 12 : CHIP_ERROR WiFiPAFEndPoint::StartAckReceivedTimer()
1155 : {
1156 12 : if (!mTimerStateFlags.Has(TimerStateFlag::kAckReceivedTimerRunning))
1157 : {
1158 6 : const CHIP_ERROR timerErr = mWiFiPafLayer->mSystemLayer->StartTimer(System::Clock::Milliseconds32(PAFTP_ACK_TIMEOUT_MS),
1159 : HandleAckReceivedTimeout, this);
1160 6 : ReturnErrorOnFailure(timerErr);
1161 :
1162 6 : mTimerStateFlags.Set(TimerStateFlag::kAckReceivedTimerRunning);
1163 : }
1164 :
1165 12 : return CHIP_NO_ERROR;
1166 : }
1167 :
1168 3 : CHIP_ERROR WiFiPAFEndPoint::RestartAckReceivedTimer()
1169 : {
1170 3 : VerifyOrReturnError(mTimerStateFlags.Has(TimerStateFlag::kAckReceivedTimerRunning), CHIP_ERROR_INCORRECT_STATE);
1171 :
1172 3 : StopAckReceivedTimer();
1173 :
1174 3 : return StartAckReceivedTimer();
1175 : }
1176 :
1177 5 : CHIP_ERROR WiFiPAFEndPoint::StartSendAckTimer()
1178 : {
1179 5 : if (!mTimerStateFlags.Has(TimerStateFlag::kSendAckTimerRunning))
1180 : {
1181 : ChipLogDebugWiFiPAFEndPoint(WiFiPAF, "starting new SendAckTimer");
1182 3 : const CHIP_ERROR timerErr = mWiFiPafLayer->mSystemLayer->StartTimer(
1183 3 : System::Clock::Milliseconds32(WIFIPAF_ACK_SEND_TIMEOUT_MS), HandleSendAckTimeout, this);
1184 3 : ReturnErrorOnFailure(timerErr);
1185 :
1186 3 : mTimerStateFlags.Set(TimerStateFlag::kSendAckTimerRunning);
1187 : }
1188 :
1189 5 : return CHIP_NO_ERROR;
1190 : }
1191 :
1192 1 : CHIP_ERROR WiFiPAFEndPoint::StartWaitResourceTimer()
1193 : {
1194 1 : mResourceWaitCount++;
1195 1 : if (mResourceWaitCount >= WIFIPAF_MAX_RESOURCE_BLOCK_COUNT)
1196 : {
1197 0 : ChipLogError(WiFiPAF, "Network resource has been unavailable for a long time");
1198 0 : mResourceWaitCount = 0;
1199 0 : DoClose(kWiFiPAFCloseFlag_AbortTransmission, CHIP_ERROR_NOT_CONNECTED);
1200 0 : return CHIP_NO_ERROR;
1201 : }
1202 1 : if (!mTimerStateFlags.Has(TimerStateFlag::kWaitResTimerRunning))
1203 : {
1204 : ChipLogDebugWiFiPAFEndPoint(WiFiPAF, "starting new SendAckTimer");
1205 1 : const CHIP_ERROR timerErr = mWiFiPafLayer->mSystemLayer->StartTimer(
1206 1 : System::Clock::Milliseconds32(WIFIPAF_WAIT_RES_TIMEOUT_MS), HandleWaitResourceTimeout, this);
1207 1 : ReturnErrorOnFailure(timerErr);
1208 1 : mTimerStateFlags.Set(TimerStateFlag::kWaitResTimerRunning);
1209 : }
1210 1 : return CHIP_NO_ERROR;
1211 : }
1212 :
1213 5 : void WiFiPAFEndPoint::StopConnectTimer()
1214 : {
1215 : // Cancel any existing connect timer.
1216 5 : mWiFiPafLayer->mSystemLayer->CancelTimer(HandleConnectTimeout, this);
1217 5 : mTimerStateFlags.Clear(TimerStateFlag::kConnectTimerRunning);
1218 5 : }
1219 :
1220 6 : void WiFiPAFEndPoint::StopAckReceivedTimer()
1221 : {
1222 : // Cancel any existing ack-received timer.
1223 6 : mWiFiPafLayer->mSystemLayer->CancelTimer(HandleAckReceivedTimeout, this);
1224 6 : mTimerStateFlags.Clear(TimerStateFlag::kAckReceivedTimerRunning);
1225 6 : }
1226 :
1227 5 : void WiFiPAFEndPoint::StopSendAckTimer()
1228 : {
1229 : // Cancel any existing send-ack timer.
1230 5 : mWiFiPafLayer->mSystemLayer->CancelTimer(HandleSendAckTimeout, this);
1231 5 : mTimerStateFlags.Clear(TimerStateFlag::kSendAckTimerRunning);
1232 5 : }
1233 :
1234 2 : void WiFiPAFEndPoint::StopWaitResourceTimer()
1235 : {
1236 : // Cancel any existing wait-resource timer.
1237 2 : mWiFiPafLayer->mSystemLayer->CancelTimer(HandleWaitResourceTimeout, this);
1238 2 : mTimerStateFlags.Clear(TimerStateFlag::kWaitResTimerRunning);
1239 2 : }
1240 :
1241 0 : void WiFiPAFEndPoint::HandleConnectTimeout(chip::System::Layer * systemLayer, void * appState)
1242 : {
1243 0 : WiFiPAFEndPoint * ep = static_cast<WiFiPAFEndPoint *>(appState);
1244 :
1245 : // Check for event-based timer race condition.
1246 0 : if (ep->mTimerStateFlags.Has(TimerStateFlag::kConnectTimerRunning))
1247 : {
1248 0 : ChipLogError(WiFiPAF, "connect handshake timed out, closing ep %p", ep);
1249 0 : ep->mTimerStateFlags.Clear(TimerStateFlag::kConnectTimerRunning);
1250 0 : ep->DoClose(kWiFiPAFCloseFlag_AbortTransmission, WIFIPAF_ERROR_CONNECT_TIMED_OUT);
1251 : }
1252 0 : }
1253 :
1254 0 : void WiFiPAFEndPoint::HandleAckReceivedTimeout(chip::System::Layer * systemLayer, void * appState)
1255 : {
1256 0 : WiFiPAFEndPoint * ep = static_cast<WiFiPAFEndPoint *>(appState);
1257 :
1258 : // Check for event-based timer race condition.
1259 0 : if (ep->mTimerStateFlags.Has(TimerStateFlag::kAckReceivedTimerRunning))
1260 : {
1261 0 : ChipLogError(WiFiPAF, "ack recv timeout, closing ep %p", ep);
1262 0 : ep->mPafTP.LogStateDebug();
1263 0 : ep->mTimerStateFlags.Clear(TimerStateFlag::kAckReceivedTimerRunning);
1264 0 : ep->DoClose(kWiFiPAFCloseFlag_AbortTransmission, WIFIPAF_ERROR_FRAGMENT_ACK_TIMED_OUT);
1265 : }
1266 0 : }
1267 :
1268 0 : void WiFiPAFEndPoint::HandleSendAckTimeout(chip::System::Layer * systemLayer, void * appState)
1269 : {
1270 0 : WiFiPAFEndPoint * ep = static_cast<WiFiPAFEndPoint *>(appState);
1271 :
1272 : // Check for event-based timer race condition.
1273 0 : if (ep->mTimerStateFlags.Has(TimerStateFlag::kSendAckTimerRunning))
1274 : {
1275 0 : ep->mTimerStateFlags.Clear(TimerStateFlag::kSendAckTimerRunning);
1276 :
1277 : // If previous stand-alone ack isn't still in flight...
1278 0 : if (!ep->mConnStateFlags.Has(ConnectionStateFlag::kStandAloneAckInFlight))
1279 : {
1280 0 : CHIP_ERROR sendErr = ep->DriveStandAloneAck();
1281 :
1282 0 : if (sendErr != CHIP_NO_ERROR)
1283 : {
1284 0 : ep->DoClose(kWiFiPAFCloseFlag_AbortTransmission, sendErr);
1285 : }
1286 : }
1287 : }
1288 0 : }
1289 :
1290 0 : void WiFiPAFEndPoint::HandleWaitResourceTimeout(chip::System::Layer * systemLayer, void * appState)
1291 : {
1292 0 : WiFiPAFEndPoint * ep = static_cast<WiFiPAFEndPoint *>(appState);
1293 :
1294 : // Check for event-based timer race condition.
1295 0 : if (ep->mTimerStateFlags.Has(TimerStateFlag::kWaitResTimerRunning))
1296 : {
1297 0 : ep->mTimerStateFlags.Clear(TimerStateFlag::kWaitResTimerRunning);
1298 0 : CHIP_ERROR sendErr = ep->DriveSending();
1299 0 : if (sendErr != CHIP_NO_ERROR)
1300 : {
1301 0 : ep->DoClose(kWiFiPAFCloseFlag_AbortTransmission, sendErr);
1302 : }
1303 : }
1304 0 : }
1305 :
1306 2 : void WiFiPAFEndPoint::ClearAll()
1307 : {
1308 2 : memset(reinterpret_cast<uint8_t *>(this), 0, sizeof(WiFiPAFEndPoint));
1309 2 : return;
1310 : }
1311 :
1312 : } /* namespace WiFiPAF */
1313 : } /* namespace chip */
|