-
Notifications
You must be signed in to change notification settings - Fork 72
/
ota.c
3752 lines (3147 loc) · 130 KB
/
ota.c
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
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* AWS IoT Over-the-air Update v3.3.0
* Copyright (C) 2021 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of
* this software and associated documentation files (the "Software"), to deal in
* the Software without restriction, including without limitation the rights to
* use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
* the Software, and to permit persons to whom the Software is furnished to do so,
* subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
* FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
* COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
* IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
/**
* @file ota.c
* @brief Implementation of the AWS IoT Over-The-Air Updates Client Library.
*/
/* Standard library includes. */
#include <stddef.h>
#include <string.h>
#include <stdlib.h>
#include <stdio.h>
#include <errno.h>
#include <assert.h>
/* OTA agent includes. */
#include "ota.h"
/* OTA_DO_NOT_USE_CUSTOM_CONFIG allows building the OTA library
* without a custom config. If a custom config is provided, the
* OTA_DO_NOT_USE_CUSTOM_CONFIG macro should not be defined. */
#ifndef OTA_DO_NOT_USE_CUSTOM_CONFIG
#include "ota_config.h"
#endif
/* Include config defaults header to get default values of configs not defined
* in ota_config.h file. */
#include "ota_config_defaults.h"
/* OTA Base64 includes */
#include "ota_base64_private.h"
/* OTA pal includes. */
#include "ota_platform_interface.h"
/* Internal header file for shared OTA definitions. */
#include "ota_private.h"
/* OTA interface includes. */
#include "ota_interface_private.h"
/* OTA OS interface. */
#include "ota_os_interface.h"
/* Core JSON include */
#include "core_json.h"
/* Include firmware version struct definition. */
#include "ota_appversion32.h"
/**
* @brief Offset helper.
*/
#define U16_OFFSET( type, member ) ( ( uint16_t ) offsetof( type, member ) )
/**
* @brief OTA event handler definition.
*/
typedef OtaErr_t ( * OtaEventHandler_t )( const OtaEventData_t * pEventMsg );
/**
* @ingroup ota_datatypes_structs
* @brief OTA Agent state table entry.
* */
typedef struct OtaStateTableEntry
{
OtaState_t currentState; /**< Current state of the agent. */
OtaEvent_t eventId; /**< Event corresponding to the action. */
OtaEventHandler_t handler; /**< Handler to invoke the next action. */
OtaState_t nextState; /**< New state to be triggered*/
} OtaStateTableEntry_t;
/**
* @brief OTA control interface.
*/
static OtaControlInterface_t otaControlInterface;
/**
* @brief OTA data interface.
*/
static OtaDataInterface_t otaDataInterface;
/* OTA agent private function prototypes. */
/**
* @brief Ingest a data block.
*
* A block of file data was received by the application via some configured communication protocol.
* If it looks like it is in range, write it to persistent storage. If it's the last block we're
* expecting, close the file and perform the final signature check on it. If the close and signature
* check are OK, let the caller know so it can be used by the system. Firmware updates generally
* reboot the system and perform a self test phase. If the close or signature check fails, abort
* the file transfer and return the result and any available details to the caller.
*
* @param[in] pFileContext Information of file to be streamed.
* @param[in] pEventData The event data containing the job document.
* @param[in] pCloseResult Result of closing file in PAL.
* @return IngestResult_t IngestResultAccepted_Continue if successful, other error for failure.
*/
static IngestResult_t ingestDataBlock( OtaFileContext_t * pFileContext,
const OtaEventData_t * pEventData,
OtaPalStatus_t * pCloseResult );
/**
* @brief Validate the incoming data block and store it in the file context.
*
* @param[in] pFileContext Information of file to be streamed.
* @param[in] uBlockIndex Incoming block index.
* @param[in] uBlockSize Incoming block size.
* @param[out] pCloseResult Result of closing file in PAL.
* @param[in] pPayload Data from the block.
* @return IngestResult_t IngestResultAccepted_Continue if successful, other error for failure.
*/
static IngestResult_t processDataBlock( OtaFileContext_t * pFileContext,
uint32_t uBlockIndex,
uint32_t uBlockSize,
OtaPalStatus_t * pCloseResult,
uint8_t * pPayload );
/**
* @brief Free the resources allocated for data ingestion and close the file handle.
*
* @param[in] pFileContext Information of file to be streamed.
* @param[out] pCloseResult Result of closing file in PAL.
* @return IngestResult_t IngestResultAccepted_Continue if successful, other error for failure.
*/
static IngestResult_t ingestDataBlockCleanup( OtaFileContext_t * pFileContext,
OtaPalStatus_t * pCloseResult );
/**
* @brief Get the File Context From Job Document.
*
* We received an OTA update job message from the job service so process
* the message and update the file context.
*
* @param[in] pRawMsg Raw job document.
* @param[in] messageLength length of document.
* @return OtaFileContext_t* Information of file to be streamed.
*/
static OtaFileContext_t * getFileContextFromJob( const char * pRawMsg,
uint32_t messageLength );
/**
* @brief Validate JSON document and the DocModel.
*
* @param[in] pJson JSON job document.
* @param[in] messageLength Length of the job document.
* @return DocParseErr_t DocParseErrNone if successful, JSON document parser errors.
*/
static DocParseErr_t validateJSON( const char * pJson,
uint32_t messageLength );
/**
* @brief Store the parameter from the json to the offset specified by the document model.
*
* @param[in] docParam Structure to store the details of keys and where to store them.
* @param[in] pContextBase Start of file context.
* @param[in] pValueInJson Pointer to the value of the key in JSON buffer.
* @param[in] valueLength Length of the value.
* @return DocParseErr_t DocParseErrNone if successful, JSON document parser errors.
*/
static DocParseErr_t extractParameter( JsonDocParam_t docParam,
void * pContextBase,
const char * pValueInJson,
size_t valueLength );
/**
* @brief Extract the desired fields from the JSON document based on the specified document model.
*
* @param[in] pJson JSON job document.
* @param[in] messageLength Length of the job document.
* @param[in] pDocModel Details of expected parameters in the job doc.
* @return DocParseErr_t DocParseErr_t DocParseErrNone if successful, JSON document parser errors.
*/
static DocParseErr_t parseJSONbyModel( const char * pJson,
uint32_t messageLength,
JsonDocModel_t * pDocModel );
/**
* @brief Decode the base64 encoded file signature key from the job document and store it in file context.
*
* @param[in] pValueInJson Pointer to the value of the key in JSON buffer.
* @param[in] valueLength Length of the value.
* @param[out] pParamAdd Pointer to the location where the value is stored.
* @return DocParseErr_t DocParseErrNone if successful, JSON document parser errors.
*/
static DocParseErr_t decodeAndStoreKey( const char * pValueInJson,
size_t valueLength,
void * pParamAdd );
/**
* @brief Extract the value from json and store it into the allocated memory.
*
* @param[in] pKey Name of the Key to extract.
* @param[in] pValueInJson Pointer to the value of the key in JSON buffer.
* @param[in] valueLength Length of the value.
* @param[out] pParamAdd Pointer to the location where the value is stored.
* @param[in] pParamSizeAdd Size required to store the param.
* @return DocParseErr_t DocParseErrNone if successful, JSON document parser errors.
*/
static DocParseErr_t extractAndStoreArray( const char * pKey,
const char * pValueInJson,
size_t valueLength,
void * pParamAdd,
uint32_t * pParamSizeAdd );
/**
* @brief Check if all the required parameters for job document are extracted from the JSON.
*
* @param[in] pModelParam Structure to store the details of keys and where to store them.
* @param[in] pDocModel Details of expected parameters in the job doc.
* @return DocParseErr_t DocParseErrNone if successful, JSON document parser errors.
*/
static DocParseErr_t verifyRequiredParamsExtracted( const JsonDocParam_t * pModelParam,
const JsonDocModel_t * pDocModel );
/**
* @brief Validate the version of the update received.
*
* @param[in] pFileContext Information of file to be streamed.
* @return OtaErr_t OtaErrNone if successful, other error codes if failure.
*/
static OtaErr_t validateUpdateVersion( const OtaFileContext_t * pFileContext );
/**
* @brief Check if the JSON can be parsed through the app callback if initial parsing fails.
*
* @param[in] pJson JSON job document.
* @param[in] messageLength Length of the job document.
* @return OtaJobParseErr_t OtaJobParseErrNone if successful, other error codes if failure.
*/
static OtaJobParseErr_t handleCustomJob( const char * pJson,
uint32_t messageLength );
/**
* @brief Check if the incoming job document is not conflicting with current job status.
*
* @param[in] pFileContext Information of file to be streamed.
* @param[out] pFinalFile File that stores all extracted params.
* @param[out] pUpdateJob Represents if the job is accepted.
* @return OtaJobParseErr_t OtaErrNone if successful, other error codes if failure.
*/
static OtaJobParseErr_t verifyActiveJobStatus( OtaFileContext_t * pFileContext,
OtaFileContext_t ** pFinalFile,
bool * pUpdateJob );
/**
* @brief Check if all the file context params are valid and initialize resources for the job transfer.
*
* @param[in] pFileContext Information of file to be streamed.
* @param[out] pFinalFile File that stores all extracted params.
* @param[out] pUpdateJob Represents if the job is accepted.
* @return OtaJobParseErr_t OtaJobParseErrNone if successful, other error codes if failure.
*/
static OtaJobParseErr_t validateAndStartJob( OtaFileContext_t * pFileContext,
OtaFileContext_t ** pFinalFile,
bool * pUpdateJob );
/**
* @brief Parse the OTA job document, validate and return the populated OTA context if valid.
*
* @param[in] pJsonExpectedParams Structure to store the details of keys and where to store them.
* @param[in] numJobParams Number of parameters to be extracted.
* @param[in] pJson JSON job document.
* @param[in] messageLength Length of the job document.
* @param[in] pUpdateJob Represents if the job is accepted.
* @return OtaFileContext_t* File context to store file information.
*/
static OtaFileContext_t * parseJobDoc( const JsonDocParam_t * pJsonExpectedParams,
uint16_t numJobParams,
const char * pJson,
uint32_t messageLength,
bool * pUpdateJob );
/**
* @brief Validate block index and block size of the data block.
*
* @param[in] pFileContext Information of file to be streamed.
* @param[in] blockIndex Block index of incoming data block.
* @param[in] blockSize Block size of incoming data block.
* @return true if successful, false otherwise.
*/
static bool validateDataBlock( const OtaFileContext_t * pFileContext,
uint32_t blockIndex,
uint32_t blockSize );
/**
* @brief Decode and ingest the incoming data block.
*
* @param[in] pFileContext Information of file to be streamed.
* @param[in] pRawMsg Raw job document.
* @param[in] messageSize Length of document.
* @param[in] pPayload Data stored in the document.
* @param[out] pBlockSize Block size of incoming data block.
* @param[out] pBlockIndex Block index of incoming data block.
* @return IngestResult_t IngestResultAccepted_Continue if successful, other error for failure.
*/
static IngestResult_t decodeAndStoreDataBlock( OtaFileContext_t * pFileContext,
const uint8_t * pRawMsg,
uint32_t messageSize,
uint8_t ** pPayload,
uint32_t * pBlockSize,
uint32_t * pBlockIndex );
/**
* @brief Close an open OTA file context and free it.
*
* @param[in] pFileContext Information of file to be streamed.
* @return true if successful, false otherwise.
*/
static bool otaClose( OtaFileContext_t * const pFileContext );
/**
* @brief OTA Timer callback.
*
* @param[in] otaTimerId Reference to the timer to use.
*/
static void otaTimerCallback( OtaTimerId_t otaTimerId );
/**
* @brief Internal function to set the image state including an optional reason code.
*
* @param[in] stateToSet State to set.
* @param[in] reasonToSet Reason to set.
* @return OtaErr_t OtaErrNone if successful, other codes on failure.
*/
static OtaErr_t setImageStateWithReason( OtaImageState_t stateToSet,
uint32_t reasonToSet );
/**
* @brief Internal function to update the job status to the jobs service from current image state.
*
* @param[in] state State to set.
* @param[in] subReason Reason for status.
* @return OtaErr_t OtaErrNone if successful, other codes on failure.
*/
static OtaErr_t updateJobStatusFromImageState( OtaImageState_t state,
int32_t subReason );
/**
* @brief A helper function to cleanup resources during OTA agent shutdown.
*/
static void agentShutdownCleanup( void );
/**
* @brief A helper function to cleanup resources when data ingestion is complete.
*/
static void dataHandlerCleanup( void );
/**
* @brief Prepare the document model for use by sanity checking the initialization parameters and detecting all required parameters.
*
* @param[inout] pDocModel Details of expected parameters in the job doc.
* @param[in] pBodyDef Structure to store the details of keys and where to store them.
* @param[in] contextBaseAddr Start of file context.
* @param[in] contextSize Size of file context.
* @param[in] numJobParams Number of parameters to be extracted.
* @return DocParseErr_t DocParseErrNone if successful, JSON document parser errors.
*/
static DocParseErr_t initDocModel( JsonDocModel_t * pDocModel,
const JsonDocParam_t * pBodyDef,
void * contextBaseAddr,
uint32_t contextSize,
uint16_t numJobParams );
/**
* @brief Initialize buffers for storing the file attributes.
*
* @param[out] pOtaBuffer OTA Application buffers.
*/
static void initializeAppBuffers( OtaAppBuffer_t * pOtaBuffer );
/**
* @brief Initialize jobId and protocol buffers.
*/
static void initializeLocalBuffers( void );
/**
* @brief Search the state transition table for the entry based on current state and incoming event.
*
* @param[in] pEventMsg Incoming event information.
* @return uint32_t Index of the transition.
*/
static uint32_t searchTransition( const OtaEventMsg_t * pEventMsg );
/**
* @brief Initiate download if not in self-test else reboot
*
* @return OtaErr_t OtaErrNone if successful.
*/
static OtaErr_t processValidFileContext( void );
/**
* @brief Validate update version when receiving job doc in self test state.
*
* @param[in] pFileContext Stores file information.
*/
static void handleSelfTestJobDoc( OtaFileContext_t * pFileContext );
/**
* @brief Handle invalid file context.
*
* @return OtaErr_t OtaErrNone if job parsing is handled.
*/
static OtaErr_t processNullFileContext( void );
/**
* @brief Check if the platform is in self-test
*
* @return true if in self-test, else false.
*/
static bool platformInSelftest( void );
/**
* @brief Function to handle events that were unexpected in the current state.
*
* @param[in] pEventMsg Stores information of the event.
*/
static void handleUnexpectedEvents( const OtaEventMsg_t * pEventMsg );
/**
* @brief Free or clear multiple buffers used in the file context.
*
* @param[in] pFileContext Information of file to be streamed.
*/
static void freeFileContextMem( OtaFileContext_t * const pFileContext );
/**
* @brief Handle job parsing error.
*
* @param[in] pFileContext Pointer to the file context.
*
* @param[in] err Parsing error of type OtaJobParseErr_t.
*/
static void handleJobParsingError( const OtaFileContext_t * pFileContext,
OtaJobParseErr_t err );
/**
* @brief Receive and process the next available event from the event queue.
*
* Each event is processed based on the behavior defined in the OTA transition
* table. The state of the OTA state machine will be updated and the
* corresponding event handler will be called.
*/
static void receiveAndProcessOtaEvent( void );
/* OTA state event handler functions. */
static OtaErr_t startHandler( const OtaEventData_t * pEventData ); /*!< Start timers and initiate request for job document. */
static OtaErr_t requestJobHandler( const OtaEventData_t * pEventData ); /*!< Initiate a request for a job. */
static OtaErr_t processJobHandler( const OtaEventData_t * pEventData ); /*!< Update file context from job document. */
static OtaErr_t inSelfTestHandler( const OtaEventData_t * pEventData ); /*!< Handle self test. */
static OtaErr_t initFileHandler( const OtaEventData_t * pEventData ); /*!< Initialize and handle file transfer. */
static OtaErr_t processDataHandler( const OtaEventData_t * pEventData ); /*!< Process incoming data blocks. */
static OtaErr_t requestDataHandler( const OtaEventData_t * pEventData ); /*!< Request for data blocks. */
static OtaErr_t shutdownHandler( const OtaEventData_t * pEventData ); /*!< Shutdown OTA and cleanup. */
static OtaErr_t closeFileHandler( const OtaEventData_t * pEventData ); /*!< Close file opened for download. */
static OtaErr_t userAbortHandler( const OtaEventData_t * pEventData ); /*!< Handle user interrupt to abort task. */
static OtaErr_t suspendHandler( const OtaEventData_t * pEventData ); /*!< Handle suspend event for OTA agent. */
static OtaErr_t resumeHandler( const OtaEventData_t * pEventData ); /*!< Resume from a suspended state. */
static OtaErr_t jobNotificationHandler( const OtaEventData_t * pEventData ); /*!< Upon receiving a new job document cancel current job if present and initiate new download. */
static void executeHandler( uint32_t index,
const OtaEventMsg_t * const pEventMsg ); /*!< Execute the handler for selected index from the transition table. */
/**
* @brief This is THE OTA agent context and initialization state.
*/
static OtaAgentContext_t otaAgent =
{
OtaAgentStateStopped, /* state */
{ 0 }, /* pThingName */
{ 0 }, /* fileContext */
0, /* fileIndex */
0, /* serverFileID */
{ 0 }, /* pActiveJobName */
NULL, /* pClientTokenFromJob */
0, /* timestampFromJob */
OtaImageStateUnknown, /* imageState */
1, /* numOfBlocksToReceive */
{ 0 }, /* statistics */
0, /* requestMomentum */
NULL, /* pOtaInterface */
NULL, /* OtaAppCallback */
1 /* unsubscribe flag */
};
/**
* @brief Transition table for the OTA state machine.
*/
static OtaStateTableEntry_t otaTransitionTable[] =
{
/*STATE , EVENT , ACTION , NEXT STATE */
{ OtaAgentStateReady, OtaAgentEventStart, startHandler, OtaAgentStateRequestingJob },
{ OtaAgentStateRequestingJob, OtaAgentEventRequestJobDocument, requestJobHandler, OtaAgentStateWaitingForJob },
{ OtaAgentStateRequestingJob, OtaAgentEventRequestTimer, requestJobHandler, OtaAgentStateWaitingForJob },
{ OtaAgentStateWaitingForJob, OtaAgentEventReceivedJobDocument, processJobHandler, OtaAgentStateCreatingFile },
{ OtaAgentStateCreatingFile, OtaAgentEventStartSelfTest, inSelfTestHandler, OtaAgentStateWaitingForJob },
{ OtaAgentStateCreatingFile, OtaAgentEventCreateFile, initFileHandler, OtaAgentStateRequestingFileBlock },
{ OtaAgentStateCreatingFile, OtaAgentEventRequestTimer, initFileHandler, OtaAgentStateRequestingFileBlock },
{ OtaAgentStateRequestingFileBlock, OtaAgentEventRequestFileBlock, requestDataHandler, OtaAgentStateWaitingForFileBlock },
{ OtaAgentStateRequestingFileBlock, OtaAgentEventRequestTimer, requestDataHandler, OtaAgentStateWaitingForFileBlock },
{ OtaAgentStateWaitingForFileBlock, OtaAgentEventReceivedFileBlock, processDataHandler, OtaAgentStateWaitingForFileBlock },
{ OtaAgentStateWaitingForFileBlock, OtaAgentEventRequestTimer, requestDataHandler, OtaAgentStateWaitingForFileBlock },
{ OtaAgentStateWaitingForFileBlock, OtaAgentEventRequestFileBlock, requestDataHandler, OtaAgentStateWaitingForFileBlock },
{ OtaAgentStateWaitingForFileBlock, OtaAgentEventRequestJobDocument, requestJobHandler, OtaAgentStateWaitingForJob },
{ OtaAgentStateWaitingForFileBlock, OtaAgentEventReceivedJobDocument, jobNotificationHandler, OtaAgentStateRequestingJob },
{ OtaAgentStateWaitingForFileBlock, OtaAgentEventCloseFile, closeFileHandler, OtaAgentStateWaitingForJob },
{ OtaAgentStateSuspended, OtaAgentEventResume, resumeHandler, OtaAgentStateRequestingJob },
{ OtaAgentStateAll, OtaAgentEventSuspend, suspendHandler, OtaAgentStateSuspended },
{ OtaAgentStateAll, OtaAgentEventUserAbort, userAbortHandler, OtaAgentStateWaitingForJob },
{ OtaAgentStateAll, OtaAgentEventShutdown, shutdownHandler, OtaAgentStateStopped },
};
/* MISRA rule 2.2 warns about unused variables. These 2 variables are used in log messages, which is
* disabled when running static analysis. So it's a false positive. */
/* coverity[misra_c_2012_rule_2_2_violation] */
/*!< String set to represent the States of the OTA agent. */
static const char * pOtaAgentStateStrings[ OtaAgentStateAll + 1 ] =
{
"Init",
"Ready",
"RequestingJob",
"WaitingForJob",
"CreatingFile",
"RequestingFileBlock",
"WaitingForFileBlock",
"ClosingFile",
"Suspended",
"ShuttingDown",
"Stopped",
"All"
};
/* coverity[misra_c_2012_rule_2_2_violation] */
/*!< String set to represent the Events for the OTA agent. */
static const char * pOtaEventStrings[ OtaAgentEventMax ] =
{
"Start",
"StartSelfTest",
"RequestJobDocument",
"ReceivedJobDocument",
"CreateFile",
"RequestFileBlock",
"ReceivedFileBlock",
"RequestTimer",
"CloseFile",
"Suspend",
"Resume",
"UserAbort",
"Shutdown"
};
/**
* @brief This is the OTA job document model describing the parameters, their types, destination and how to extract.
*/
static const JsonDocParam_t otaJobDocModelParamStructure[ OTA_NUM_JOB_PARAMS ] =
{
{ OTA_JSON_CLIENT_TOKEN_KEY, OTA_JOB_PARAM_OPTIONAL, OTA_DONT_STORE_PARAM, OTA_DONT_STORE_PARAM, ModelParamTypeStringInDoc },
{ OTA_JSON_TIMESTAMP_KEY, OTA_JOB_PARAM_OPTIONAL, OTA_DONT_STORE_PARAM, OTA_DONT_STORE_PARAM, ModelParamTypeUInt32 },
{ OTA_JSON_EXECUTION_KEY, OTA_JOB_PARAM_REQUIRED, OTA_DONT_STORE_PARAM, OTA_DONT_STORE_PARAM, ModelParamTypeObject },
{ OTA_JSON_JOB_ID_KEY, OTA_JOB_PARAM_REQUIRED, U16_OFFSET( OtaFileContext_t, pJobName ), U16_OFFSET( OtaFileContext_t, jobNameMaxSize ), ModelParamTypeStringCopy},
{ OTA_JSON_STATUS_DETAILS_KEY, OTA_JOB_PARAM_OPTIONAL, OTA_DONT_STORE_PARAM, OTA_DONT_STORE_PARAM, ModelParamTypeObject },
{ OTA_JSON_SELF_TEST_KEY, OTA_JOB_PARAM_OPTIONAL, U16_OFFSET( OtaFileContext_t, isInSelfTest ), OTA_DONT_STORE_PARAM, ModelParamTypeIdent},
{ OTA_JSON_UPDATED_BY_KEY, OTA_JOB_PARAM_OPTIONAL, U16_OFFSET( OtaFileContext_t, updaterVersion ), OTA_DONT_STORE_PARAM, ModelParamTypeUInt32},
{ OTA_JSON_JOB_DOC_KEY, OTA_JOB_PARAM_REQUIRED, OTA_DONT_STORE_PARAM, OTA_DONT_STORE_PARAM, ModelParamTypeObject },
{ OTA_JSON_OTA_UNIT_KEY, OTA_JOB_PARAM_REQUIRED, OTA_DONT_STORE_PARAM, OTA_DONT_STORE_PARAM, ModelParamTypeObject },
{ OTA_JSON_STREAM_NAME_KEY, OTA_JOB_PARAM_OPTIONAL, U16_OFFSET( OtaFileContext_t, pStreamName ), U16_OFFSET( OtaFileContext_t, streamNameMaxSize ), ModelParamTypeStringCopy},
{ OTA_JSON_PROTOCOLS_KEY, OTA_JOB_PARAM_REQUIRED, U16_OFFSET( OtaFileContext_t, pProtocols ), U16_OFFSET( OtaFileContext_t, protocolMaxSize ), ModelParamTypeArrayCopy},
{ OTA_JSON_FILE_GROUP_KEY, OTA_JOB_PARAM_REQUIRED, OTA_STORE_NESTED_JSON, OTA_STORE_NESTED_JSON, ModelParamTypeArray },
{ OTA_JSON_FILE_PATH_KEY, OTA_JOB_PARAM_OPTIONAL, U16_OFFSET( OtaFileContext_t, pFilePath ), U16_OFFSET( OtaFileContext_t, filePathMaxSize ), ModelParamTypeStringCopy},
{ OTA_JSON_FILE_SIZE_KEY, OTA_JOB_PARAM_REQUIRED, U16_OFFSET( OtaFileContext_t, fileSize ), OTA_DONT_STORE_PARAM, ModelParamTypeUInt32},
{ OTA_JSON_FILE_ID_KEY, OTA_JOB_PARAM_REQUIRED, U16_OFFSET( OtaFileContext_t, serverFileID ), OTA_DONT_STORE_PARAM, ModelParamTypeUInt32},
{ OTA_JSON_FILE_CERT_NAME_KEY, OTA_JOB_PARAM_OPTIONAL, U16_OFFSET( OtaFileContext_t, pCertFilepath ), U16_OFFSET( OtaFileContext_t, certFilePathMaxSize ), ModelParamTypeStringCopy},
{ OTA_JSON_UPDATE_DATA_URL_KEY, OTA_JOB_PARAM_OPTIONAL, U16_OFFSET( OtaFileContext_t, pUpdateUrlPath ), U16_OFFSET( OtaFileContext_t, updateUrlMaxSize ), ModelParamTypeStringCopy},
{ OTA_JSON_AUTH_SCHEME_KEY, OTA_JOB_PARAM_OPTIONAL, U16_OFFSET( OtaFileContext_t, pAuthScheme ), U16_OFFSET( OtaFileContext_t, authSchemeMaxSize ), ModelParamTypeStringCopy},
{ OTA_JsonFileSignatureKey, OTA_JOB_PARAM_OPTIONAL, U16_OFFSET( OtaFileContext_t, pSignature ), OTA_DONT_STORE_PARAM, ModelParamTypeSigBase64},
{ OTA_JSON_FILE_ATTRIBUTE_KEY, OTA_JOB_PARAM_OPTIONAL, U16_OFFSET( OtaFileContext_t, fileAttributes ), OTA_DONT_STORE_PARAM, ModelParamTypeUInt32},
{ OTA_JSON_FILETYPE_KEY, OTA_JOB_PARAM_OPTIONAL, U16_OFFSET( OtaFileContext_t, fileType ), OTA_DONT_STORE_PARAM, ModelParamTypeUInt32}
};
static uint8_t pJobNameBuffer[ OTA_JOB_ID_MAX_SIZE ]; /*!< Buffer to store job name. */
static uint8_t pProtocolBuffer[ OTA_PROTOCOL_BUFFER_SIZE ]; /*!< Buffer to store data protocol. */
static Sig256_t sig256Buffer; /*!< Buffer to store key file signature. */
static void otaTimerCallback( OtaTimerId_t otaTimerId )
{
assert( ( otaTimerId == OtaRequestTimer ) || ( otaTimerId == OtaSelfTestTimer ) );
if( otaTimerId == OtaRequestTimer )
{
OtaEventMsg_t xEventMsg = { 0 };
LogDebug( ( "Self-test expired within %ums",
otaconfigFILE_REQUEST_WAIT_MS ) );
xEventMsg.eventId = OtaAgentEventRequestTimer;
/* Send request timer event. */
if( OTA_SignalEvent( &xEventMsg ) == false )
{
LogError( ( "Failed to signal the OTA Agent to start request timer" ) );
}
}
else /* ( otaTimerId == OtaSelfTestTimer ) */
{
LogError( ( "Self test failed to complete within %ums",
otaconfigSELF_TEST_RESPONSE_WAIT_MS ) );
( void ) otaAgent.pOtaInterface->pal.reset( &otaAgent.fileContext );
}
}
static bool platformInSelftest( void )
{
bool selfTest = false;
/*
* Get the platform state from the OTA pal layer.
*/
if( otaAgent.pOtaInterface->pal.getPlatformImageState( &( otaAgent.fileContext ) ) == OtaPalImageStatePendingCommit )
{
selfTest = true;
}
return selfTest;
}
static OtaErr_t updateJobStatusFromImageState( OtaImageState_t state,
int32_t subReason )
{
OtaErr_t err = OtaErrNone;
OtaJobReason_t reason = JobReasonReceiving;
if( state == OtaImageStateTesting )
{
/* We discovered we're ready for test mode, put job status in self_test active. */
err = otaControlInterface.updateJobStatus( &otaAgent,
JobStatusInProgress,
JobReasonSelfTestActive,
0 );
}
else
{
if( state == OtaImageStateAccepted )
{
/* Now that we have accepted the firmware update, we can complete the job. */
err = otaControlInterface.updateJobStatus( &otaAgent,
JobStatusSucceeded,
JobReasonAccepted,
appFirmwareVersion.u.signedVersion32 );
}
else
{
/*
* The firmware update was either rejected or aborted, complete the job as FAILED (Job service
* will not allow us to set REJECTED after the job has been started already).
*/
reason = ( state == OtaImageStateRejected ) ? JobReasonRejected : JobReasonAborted;
err = otaControlInterface.updateJobStatus( &otaAgent,
JobStatusFailed,
reason,
subReason );
}
/*
* We don't need the job name memory anymore since we're done with this job.
*/
( void ) memset( otaAgent.pActiveJobName, 0, OTA_JOB_ID_MAX_SIZE );
}
return err;
}
static OtaErr_t setImageStateWithReason( OtaImageState_t stateToSet,
uint32_t reasonToSet )
{
OtaErr_t err = OtaErrNone;
OtaImageState_t state = stateToSet;
uint32_t reason = reasonToSet;
OtaPalStatus_t palStatus;
/* Call the platform specific code to set the image state. */
palStatus = otaAgent.pOtaInterface->pal.setPlatformImageState( &( otaAgent.fileContext ), state );
/*
* If the platform image state couldn't be set correctly, force fail the update by setting the
* image state to "Rejected" unless it's already in "Aborted".
*/
if( ( OTA_PAL_MAIN_ERR( palStatus ) != OtaPalSuccess ) && ( state != OtaImageStateAborted ) )
{
/* Intentionally override state since we failed within this function. */
state = OtaImageStateRejected;
/*
* Capture the failure reason if not already set (and we're not already Aborted as checked above). Otherwise Keep
* the original reject reason code since it is possible for the PAL to fail to update the image state in some
* cases (e.g. a reset already caused the bundle rollback and we failed to rollback again).
*/
if( reason == 0U )
{
/* Intentionally override reason since we failed within this function. */
reason = palStatus;
}
}
/* Now update the image state and job status on service side. */
otaAgent.imageState = state;
if( strlen( ( const char * ) otaAgent.pActiveJobName ) > 0u )
{
err = updateJobStatusFromImageState( state, ( int32_t ) reason );
}
else
{
err = OtaErrNoActiveJob;
}
if( err != OtaErrNone )
{
LogWarn( ( "Failed to set image state with reason: "
"OtaErr_t=%s"
", OtaPalStatus_t=%s"
", state=%d"
", reason=%d",
OTA_Err_strerror( err ),
OTA_PalStatus_strerror( OTA_PAL_MAIN_ERR( palStatus ) ),
stateToSet,
reasonToSet ) );
}
return err;
}
static OtaErr_t startHandler( const OtaEventData_t * pEventData )
{
OtaErr_t retVal = OtaErrNone;
OtaEventMsg_t eventMsg = { 0 };
( void ) pEventData;
/* Start self-test timer, if platform is in self-test. */
if( platformInSelftest() == true )
{
( void ) otaAgent.pOtaInterface->os.timer.start( OtaSelfTestTimer,
"OtaSelfTestTimer",
otaconfigSELF_TEST_RESPONSE_WAIT_MS,
otaTimerCallback );
}
/* Send event to OTA task to get job document. */
eventMsg.eventId = OtaAgentEventRequestJobDocument;
if( OTA_SignalEvent( &eventMsg ) == false )
{
retVal = OtaErrSignalEventFailed;
}
return retVal;
}
static OtaErr_t inSelfTestHandler( const OtaEventData_t * pEventData )
{
OtaErr_t err = OtaErrNone;
( void ) pEventData;
LogInfo( ( "Beginning self-test." ) );
/* Check the platform's OTA update image state. It should also be in self test. */
if( platformInSelftest() == true )
{
/* Callback for application specific self-test. */
otaAgent.OtaAppCallback( OtaJobEventStartTest, NULL );
/* Clear self-test flag. */
otaAgent.fileContext.isInSelfTest = false;
/* Stop the self test timer as it is no longer required. */
( void ) otaAgent.pOtaInterface->os.timer.stop( OtaSelfTestTimer );
}
else
{
/* The job is in self test but the platform image state is not so it could be
* an attack on the platform image state. Reject the update (this should also
* cause the image to be erased), aborting the job and reset the device. */
LogWarn( ( "Rejecting new image and rebooting:"
"The job is in the self-test state while the platform is not." ) );
err = setImageStateWithReason( OtaImageStateRejected, ( uint32_t ) OtaErrImageStateMismatch );
( void ) otaAgent.pOtaInterface->pal.reset( &( otaAgent.fileContext ) );
}
if( err != OtaErrNone )
{
LogError( ( "Failed to start self-test: "
"OtaErr_t=%s",
OTA_Err_strerror( err ) ) );
}
return err;
}
static OtaErr_t requestJobHandler( const OtaEventData_t * pEventData )
{
OtaErr_t retVal = OtaErrUninitialized;
OtaOsStatus_t osErr = OtaOsSuccess;
OtaEventMsg_t eventMsg = { 0 };
( void ) pEventData;
/*
* Check if any pending jobs are available from job service.
*/
retVal = otaControlInterface.requestJob( &otaAgent );
if( retVal != OtaErrNone )
{
if( otaAgent.requestMomentum < otaconfigMAX_NUM_REQUEST_MOMENTUM )
{
/* Start the request timer. */
osErr = otaAgent.pOtaInterface->os.timer.start( OtaRequestTimer,
"OtaRequestTimer",
otaconfigFILE_REQUEST_WAIT_MS,
otaTimerCallback );
if( osErr != OtaOsSuccess )
{
LogError( ( "Failed to start request timer: "
"OtaOsStatus_t=%s",
OTA_OsStatus_strerror( osErr ) ) );
retVal = OtaErrRequestJobFailed;
}
else
{
otaAgent.requestMomentum++;
}
}
else
{
/* Stop the request timer. */
( void ) otaAgent.pOtaInterface->os.timer.stop( OtaRequestTimer );
/* Send shutdown event to the OTA Agent task. */
eventMsg.eventId = OtaAgentEventShutdown;
if( OTA_SignalEvent( &eventMsg ) == false )
{
retVal = OtaErrSignalEventFailed;
}
else
{
/* Too many requests have been sent without a response or too many failures
* when trying to publish the request message. Abort. */
retVal = OtaErrMomentumAbort;
}
}
}
else
{
/* Stop the request timer. */
( void ) otaAgent.pOtaInterface->os.timer.stop( OtaRequestTimer );
/* Reset the request momentum. */
otaAgent.requestMomentum = 0;
}
return retVal;
}
static OtaErr_t processNullFileContext( void )
{
OtaErr_t retVal = OtaErrNone;
OtaEventMsg_t eventMsg = { 0 };
/* If the OTA job is in the self_test state, alert the application layer. */
if( OTA_GetImageState() == OtaImageStateTesting )
{
/* Send event to OTA task to start self-test. */
eventMsg.eventId = OtaAgentEventStartSelfTest;
if( OTA_SignalEvent( &eventMsg ) == false )
{
retVal = OtaErrSignalEventFailed;
}
}
else
{
/*
* If the job context returned NULL and the image state is not in the self_test state,
* then an error occurred parsing the OTA job message. */
retVal = OtaErrJobParserError;
}
return retVal;
}
static OtaErr_t processValidFileContext( void )
{
OtaErr_t retVal = OtaErrNone;
OtaEventMsg_t eventMsg = { 0 };
/* If the platform is not in the self_test state, initiate file download. */
if( platformInSelftest() == false )
{
/* Init data interface routines */
retVal = setDataInterface( &otaDataInterface, otaAgent.fileContext.pProtocols );
if( retVal == OtaErrNone )
{
LogInfo( ( "Setting OTA data interface." ) );
/* Received a valid context so send event to request file blocks. */
eventMsg.eventId = OtaAgentEventCreateFile;
/*Send the event to OTA Agent task. */
if( OTA_SignalEvent( &eventMsg ) == false )
{
retVal = OtaErrSignalEventFailed;
}
}
else
{
/*
* Failed to set the data interface so abort the OTA.If there is a valid job id,
* then a job status update will be sent.
*/
LogError( ( "Failed to set OTA data interface: OtaErr_t=%s, aborting current update.", OTA_Err_strerror( retVal ) ) );
retVal = setImageStateWithReason( OtaImageStateAborted, ( uint32_t ) retVal );
if( retVal != OtaErrNone )
{
LogError( ( "Failed to abort OTA update: OtaErr_t=%s", OTA_Err_strerror( retVal ) ) );
}
}
}
else
{
/*
* Received a job that is not in self-test but platform is, so reboot the device to allow
* roll back to previous image.
*/
LogWarn( ( "Rejecting new image and rebooting:"
"The platform is in the self-test state while the job is not." ) );
( void ) otaAgent.pOtaInterface->pal.reset( &( otaAgent.fileContext ) );
}
return retVal;
}
static OtaErr_t processJobHandler( const OtaEventData_t * pEventData )
{
OtaErr_t retVal = OtaErrNone;
OtaFileContext_t * pOtaFileContext = NULL;
/*
* Parse the job document and update file information in the file context.
*/
pOtaFileContext = getFileContextFromJob( ( const char * ) pEventData->data,
pEventData->dataLength );
/*
* A null context here could either mean we didn't receive a valid job or it could
* signify that we're in the self test phase (where the OTA file transfer is already
* completed and we have reset the device and are now running the new firmware). We
* will check the state to determine which case we're in.
*/
if( pOtaFileContext == NULL )
{
retVal = processNullFileContext();
}
else
{