-
Notifications
You must be signed in to change notification settings - Fork 2.4k
Expand file tree
/
Copy pathBdxOTASender.cpp
More file actions
397 lines (328 loc) · 14.9 KB
/
BdxOTASender.cpp
File metadata and controls
397 lines (328 loc) · 14.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
/*
* Copyright (c) 2023 Project CHIP Authors
* All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
#include "BdxOTASender.h"
#include <lib/support/CHIPJNIError.h>
#include <lib/support/JniReferences.h>
#include <lib/support/JniTypeWrappers.h>
#include <platform/LockTracker.h>
#include <protocols/interaction_model/Constants.h>
using namespace chip;
using namespace chip::app;
using namespace chip::bdx;
using Protocols::InteractionModel::Status;
// TODO Expose a method onto the delegate to make that configurable.
constexpr uint32_t kMaxBdxBlockSize = 1024;
// Since the BDX timeout is 5 minutes and we are starting this after query image is available and before the BDX init comes,
// we just double the timeout to give enough time for the BDX init to come in a reasonable amount of time.
constexpr System::Clock::Timeout kBdxInitReceivedTimeout = System::Clock::Seconds16(10 * 60);
constexpr System::Clock::Timeout kBdxTimeout = System::Clock::Seconds16(5 * 60); // OTA Spec mandates >= 5 minutes
constexpr System::Clock::Timeout kBdxPollIntervalMs = System::Clock::Milliseconds32(50);
constexpr bdx::TransferRole kBdxRole = bdx::TransferRole::kSender;
CHIP_ERROR BdxOTASender::PrepareForTransfer(FabricIndex fabricIndex, NodeId nodeId)
{
assertChipStackLockedByCurrentThread();
VerifyOrReturnError(mExchangeMgr != nullptr, CHIP_ERROR_INCORRECT_STATE);
VerifyOrReturnError(mSystemLayer != nullptr, CHIP_ERROR_INCORRECT_STATE);
ReturnErrorOnFailure(ConfigureState(fabricIndex, nodeId));
BitFlags<bdx::TransferControlFlags> flags(bdx::TransferControlFlags::kReceiverDrive);
return Responder::PrepareForTransfer(mSystemLayer, kBdxRole, flags, kMaxBdxBlockSize, kBdxTimeout, kBdxPollIntervalMs);
}
CHIP_ERROR BdxOTASender::Init(System::Layer * systemLayer, Messaging::ExchangeManager * exchangeMgr)
{
assertChipStackLockedByCurrentThread();
VerifyOrReturnError(mSystemLayer == nullptr, CHIP_ERROR_INCORRECT_STATE);
VerifyOrReturnError(mExchangeMgr == nullptr, CHIP_ERROR_INCORRECT_STATE);
VerifyOrReturnError(systemLayer != nullptr, CHIP_ERROR_INCORRECT_STATE);
VerifyOrReturnError(exchangeMgr != nullptr, CHIP_ERROR_INCORRECT_STATE);
TEMPORARY_RETURN_IGNORED exchangeMgr->RegisterUnsolicitedMessageHandlerForProtocol(Protocols::BDX::Id, this);
mSystemLayer = systemLayer;
mExchangeMgr = exchangeMgr;
return CHIP_NO_ERROR;
}
CHIP_ERROR BdxOTASender::Shutdown()
{
assertChipStackLockedByCurrentThread();
VerifyOrReturnError(mExchangeMgr != nullptr, CHIP_ERROR_INCORRECT_STATE);
TEMPORARY_RETURN_IGNORED mExchangeMgr->UnregisterUnsolicitedMessageHandlerForProtocol(Protocols::BDX::Id);
ResetState();
mExchangeMgr = nullptr;
return CHIP_NO_ERROR;
}
void BdxOTASender::ResetState()
{
assertChipStackLockedByCurrentThread();
if (mNodeId != kUndefinedNodeId && mFabricIndex != kUndefinedFabricIndex)
{
ChipLogProgress(Controller,
"Resetting state for OTA Provider; no longer providing an update for node id 0x" ChipLogFormatX64
", fabric index %u",
ChipLogValueX64(mNodeId), mFabricIndex);
}
else
{
ChipLogProgress(Controller, "Resetting state for OTA Provider");
}
if (mSystemLayer)
{
mSystemLayer->CancelTimer(HandleBdxInitReceivedTimeoutExpired, this);
}
// TODO: Check if this can be removed. It seems like we can close the exchange context and reset transfer regardless.
if (!mInitialized)
{
return;
}
Responder::ResetTransfer();
++mTransferGeneration;
mFabricIndex = kUndefinedFabricIndex;
mNodeId = kUndefinedNodeId;
if (mExchangeCtx != nullptr)
{
mExchangeCtx->Close();
mExchangeCtx = nullptr;
}
mInitialized = false;
}
CHIP_ERROR BdxOTASender::OnMessageToSend(TransferSession::OutputEvent & event)
{
assertChipStackLockedByCurrentThread();
VerifyOrReturnError(mExchangeCtx != nullptr, CHIP_ERROR_INCORRECT_STATE);
VerifyOrReturnError(mOtaDelegate != nullptr, CHIP_ERROR_INCORRECT_STATE);
Messaging::SendFlags sendFlags;
// All messages sent from the Sender expect a response, except for a StatusReport which would indicate an error and
// the end of the transfer.
if (!event.msgTypeData.HasMessageType(Protocols::SecureChannel::MsgType::StatusReport))
{
sendFlags.Set(Messaging::SendMessageFlags::kExpectResponse);
}
auto & msgTypeData = event.msgTypeData;
// If there's an error sending the message, close the exchange and call ResetState.
// TODO: If we can remove the !mInitialized check in ResetState(), just calling ResetState() will suffice here.
CHIP_ERROR err =
mExchangeCtx->SendMessage(msgTypeData.ProtocolId, msgTypeData.MessageType, std::move(event.MsgData), sendFlags);
if (err != CHIP_NO_ERROR)
{
mExchangeCtx->Close();
mExchangeCtx = nullptr;
ResetState();
}
else if (event.msgTypeData.HasMessageType(Protocols::SecureChannel::MsgType::StatusReport))
{
// If the send was successful for a status report, since we are not expecting a response the exchange context is
// already closed. We need to null out the reference to avoid having a dangling pointer.
mExchangeCtx = nullptr;
ResetState();
}
return err;
}
CHIP_ERROR BdxOTASender::OnTransferSessionBegin(TransferSession::OutputEvent & event)
{
assertChipStackLockedByCurrentThread();
// Once we receive the BDX init, cancel the BDX Init timeout and start the BDX session
if (mSystemLayer)
{
mSystemLayer->CancelTimer(HandleBdxInitReceivedTimeoutExpired, this);
}
VerifyOrReturnError(mFabricIndex != kUndefinedFabricIndex, CHIP_ERROR_INCORRECT_STATE);
VerifyOrReturnError(mNodeId != kUndefinedNodeId, CHIP_ERROR_INCORRECT_STATE);
uint16_t fdl = 0;
const uint8_t * fd = mTransfer.GetFileDesignator(fdl);
VerifyOrReturnError(fdl <= bdx::kMaxFileDesignatorLen, CHIP_ERROR_INVALID_ARGUMENT);
CharSpan fileDesignatorSpan(Uint8::to_const_char(fd), fdl);
JNIEnv * env = JniReferences::GetInstance().GetEnvForCurrentThread();
JniLocalReferenceScope scope(env);
UtfString fileDesignator(env, fileDesignatorSpan);
uint64_t offset = mTransfer.GetStartOffset();
jmethodID handleBDXTransferSessionBeginMethod;
CHIP_ERROR err = JniReferences::GetInstance().FindMethod(env, mOtaDelegate, "handleBDXTransferSessionBegin",
"(JLjava/lang/String;J)V", &handleBDXTransferSessionBeginMethod);
VerifyOrReturnError(err == CHIP_NO_ERROR, err, ChipLogError(Controller, "Could not find handleBDXTransferSessionBegin method"));
env->CallVoidMethod(mOtaDelegate, handleBDXTransferSessionBeginMethod, static_cast<jlong>(mNodeId), fileDesignator.jniValue(),
static_cast<jlong>(offset));
if (env->ExceptionCheck())
{
ChipLogError(Support, "Exception in call java method");
env->ExceptionDescribe();
env->ExceptionClear();
return CHIP_JNI_ERROR_EXCEPTION_THROWN;
}
TransferSession::TransferAcceptData acceptData;
acceptData.ControlMode = bdx::TransferControlFlags::kReceiverDrive;
acceptData.MaxBlockSize = mTransfer.GetTransferBlockSize();
acceptData.StartOffset = mTransfer.GetStartOffset();
acceptData.Length = mTransfer.GetTransferLength();
LogErrorOnFailure(mTransfer.AcceptTransfer(acceptData));
return CHIP_NO_ERROR;
}
CHIP_ERROR BdxOTASender::OnTransferSessionEnd(TransferSession::OutputEvent & event)
{
assertChipStackLockedByCurrentThread();
VerifyOrReturnError(mFabricIndex != kUndefinedFabricIndex, CHIP_ERROR_INCORRECT_STATE);
VerifyOrReturnError(mNodeId != kUndefinedNodeId, CHIP_ERROR_INCORRECT_STATE);
VerifyOrReturnError(mOtaDelegate != nullptr, CHIP_ERROR_INCORRECT_STATE);
CHIP_ERROR error = CHIP_NO_ERROR;
if (event.EventType == TransferSession::OutputEventType::kTransferTimeout)
{
error = CHIP_ERROR_TIMEOUT;
}
else if (event.EventType != TransferSession::OutputEventType::kAckEOFReceived)
{
error = CHIP_ERROR_INTERNAL;
}
JNIEnv * env = JniReferences::GetInstance().GetEnvForCurrentThread();
jmethodID handleBDXTransferSessionEndMethod;
CHIP_ERROR err = JniReferences::GetInstance().FindMethod(env, mOtaDelegate, "handleBDXTransferSessionEnd", "(JJ)V",
&handleBDXTransferSessionEndMethod);
VerifyOrReturnError(err == CHIP_NO_ERROR, err, ChipLogError(Controller, "Could not find handleBDXTransferSessionEnd method"));
env->CallVoidMethod(mOtaDelegate, handleBDXTransferSessionEndMethod, static_cast<jlong>(error.AsInteger()),
static_cast<jlong>(mNodeId));
if (env->ExceptionCheck())
{
ChipLogError(Support, "Exception in call java method");
env->ExceptionDescribe();
env->ExceptionClear();
return CHIP_JNI_ERROR_EXCEPTION_THROWN;
}
ResetState();
return CHIP_NO_ERROR;
}
CHIP_ERROR BdxOTASender::OnBlockQuery(TransferSession::OutputEvent & event)
{
assertChipStackLockedByCurrentThread();
VerifyOrReturnError(mFabricIndex != kUndefinedFabricIndex, CHIP_ERROR_INCORRECT_STATE);
VerifyOrReturnError(mNodeId != kUndefinedNodeId, CHIP_ERROR_INCORRECT_STATE);
uint16_t blockSize = mTransfer.GetTransferBlockSize();
uint32_t blockIndex = mTransfer.GetNextBlockNum();
uint64_t bytesToSkip = 0;
if (event.EventType == TransferSession::OutputEventType::kQueryWithSkipReceived)
{
bytesToSkip = event.bytesToSkip.BytesToSkip;
}
// uint64_t transferGeneration = mTransferGeneration;
JNIEnv * env = JniReferences::GetInstance().GetEnvForCurrentThread();
JniLocalReferenceScope scope(env);
jmethodID handleBDXQueryMethod;
CHIP_ERROR err = JniReferences::GetInstance().FindMethod(
env, mOtaDelegate, "handleBDXQuery", "(JIJJ)Lchip/devicecontroller/OTAProviderDelegate$BDXData;", &handleBDXQueryMethod);
VerifyOrReturnError(err == CHIP_NO_ERROR, err, ChipLogError(Controller, "Could not find handleBDXQuery method"));
jobject bdxData =
env->CallObjectMethod(mOtaDelegate, handleBDXQueryMethod, static_cast<jlong>(mNodeId), static_cast<jint>(blockSize),
static_cast<jlong>(blockIndex), static_cast<jlong>(bytesToSkip));
if (env->ExceptionCheck())
{
ChipLogError(Support, "Exception in call java method");
env->ExceptionDescribe();
env->ExceptionClear();
return CHIP_JNI_ERROR_EXCEPTION_THROWN;
}
if (bdxData == nullptr)
{
LogErrorOnFailure(mTransfer.AbortTransfer(bdx::StatusCode::kUnknown));
return CHIP_ERROR_INVALID_ARGUMENT;
}
jmethodID getDataMethod;
err = JniReferences::GetInstance().FindMethod(env, bdxData, "getData", "()[B", &getDataMethod);
if (env->ExceptionCheck())
{
ChipLogError(Support, "Exception in call java method");
env->ExceptionDescribe();
env->ExceptionClear();
return CHIP_JNI_ERROR_EXCEPTION_THROWN;
}
jmethodID isEOFMethod;
err = JniReferences::GetInstance().FindMethod(env, bdxData, "isEOF", "()Z", &isEOFMethod);
if (env->ExceptionCheck())
{
ChipLogError(Support, "Exception in call java method");
env->ExceptionDescribe();
env->ExceptionClear();
return CHIP_JNI_ERROR_EXCEPTION_THROWN;
}
jbyteArray jData = (jbyteArray) env->CallObjectMethod(bdxData, getDataMethod);
jboolean jIsEOF = env->CallBooleanMethod(bdxData, isEOFMethod);
JniByteArray data(env, jData);
TransferSession::BlockData blockData;
blockData.Data = static_cast<const uint8_t *>(data.byteSpan().data());
blockData.Length = static_cast<size_t>(data.byteSpan().size());
blockData.IsEof = jIsEOF == JNI_TRUE;
err = mTransfer.PrepareBlock(blockData);
if (CHIP_NO_ERROR != err)
{
LogErrorOnFailure(err);
LogErrorOnFailure(mTransfer.AbortTransfer(bdx::StatusCode::kUnknown));
}
return CHIP_NO_ERROR;
}
void BdxOTASender::HandleTransferSessionOutput(TransferSession::OutputEvent & event)
{
VerifyOrReturn(mOtaDelegate != nullptr);
CHIP_ERROR err = CHIP_NO_ERROR;
switch (event.EventType)
{
case TransferSession::OutputEventType::kInitReceived:
err = OnTransferSessionBegin(event);
if (err != CHIP_NO_ERROR)
{
LogErrorOnFailure(mTransfer.AbortTransfer(GetBdxStatusCodeFromChipError(err)));
}
break;
case TransferSession::OutputEventType::kStatusReceived:
ChipLogError(BDX, "Got StatusReport %x", static_cast<uint16_t>(event.statusData.statusCode));
FALLTHROUGH;
case TransferSession::OutputEventType::kAckEOFReceived:
case TransferSession::OutputEventType::kInternalError:
case TransferSession::OutputEventType::kTransferTimeout:
err = OnTransferSessionEnd(event);
break;
case TransferSession::OutputEventType::kQueryWithSkipReceived:
case TransferSession::OutputEventType::kQueryReceived:
err = OnBlockQuery(event);
break;
case TransferSession::OutputEventType::kMsgToSend:
err = OnMessageToSend(event);
break;
case TransferSession::OutputEventType::kNone:
case TransferSession::OutputEventType::kAckReceived:
// Nothing to do.
break;
case TransferSession::OutputEventType::kAcceptReceived:
case TransferSession::OutputEventType::kBlockReceived:
default:
// Should never happens.
chipDie();
break;
}
LogErrorOnFailure(err);
}
CHIP_ERROR BdxOTASender::ConfigureState(chip::FabricIndex fabricIndex, chip::NodeId nodeId)
{
assertChipStackLockedByCurrentThread();
if (mInitialized)
{
// Prevent a new node connection since another is active.
VerifyOrReturnError(mFabricIndex == fabricIndex && mNodeId == nodeId, CHIP_ERROR_BUSY);
// Reset stale connection from the same Node if exists.
ResetState();
}
// Start a timer to track whether we receive a BDX init after a successful query image in a reasonable amount of time
CHIP_ERROR err = mSystemLayer->StartTimer(kBdxInitReceivedTimeout, HandleBdxInitReceivedTimeoutExpired, this);
LogErrorOnFailure(err);
mFabricIndex = fabricIndex;
mNodeId = nodeId;
mInitialized = true;
return CHIP_NO_ERROR;
}