1 /*
2  * SPDX-FileCopyrightText: 2015-2021 Espressif Systems (Shanghai) CO LTD
3  *
4  * SPDX-License-Identifier: Apache-2.0
5  */
6 
7 #ifndef _OTA_OPS_H
8 #define _OTA_OPS_H
9 
10 #include <stdint.h>
11 #include <stdbool.h>
12 #include <stddef.h>
13 #include "esp_err.h"
14 #include "esp_partition.h"
15 #include "esp_image_format.h"
16 #include "esp_flash_partitions.h"
17 #include "soc/soc_caps.h"
18 
19 #ifdef __cplusplus
20 extern "C"
21 {
22 #endif
23 
24 #define OTA_SIZE_UNKNOWN 0xffffffff /*!< Used for esp_ota_begin() if new image size is unknown */
25 #define OTA_WITH_SEQUENTIAL_WRITES 0xfffffffe /*!< Used for esp_ota_begin() if new image size is unknown and erase can be done in incremental manner (assuming write operation is in continuous sequence) */
26 
27 #define ESP_ERR_OTA_BASE                         0x1500                     /*!< Base error code for ota_ops api */
28 #define ESP_ERR_OTA_PARTITION_CONFLICT           (ESP_ERR_OTA_BASE + 0x01)  /*!< Error if request was to write or erase the current running partition */
29 #define ESP_ERR_OTA_SELECT_INFO_INVALID          (ESP_ERR_OTA_BASE + 0x02)  /*!< Error if OTA data partition contains invalid content */
30 #define ESP_ERR_OTA_VALIDATE_FAILED              (ESP_ERR_OTA_BASE + 0x03)  /*!< Error if OTA app image is invalid */
31 #define ESP_ERR_OTA_SMALL_SEC_VER                (ESP_ERR_OTA_BASE + 0x04)  /*!< Error if the firmware has a secure version less than the running firmware. */
32 #define ESP_ERR_OTA_ROLLBACK_FAILED              (ESP_ERR_OTA_BASE + 0x05)  /*!< Error if flash does not have valid firmware in passive partition and hence rollback is not possible */
33 #define ESP_ERR_OTA_ROLLBACK_INVALID_STATE       (ESP_ERR_OTA_BASE + 0x06)  /*!< Error if current active firmware is still marked in pending validation state (ESP_OTA_IMG_PENDING_VERIFY), essentially first boot of firmware image post upgrade and hence firmware upgrade is not possible */
34 
35 
36 /**
37  * @brief Opaque handle for an application OTA update
38  *
39  * esp_ota_begin() returns a handle which is then used for subsequent
40  * calls to esp_ota_write() and esp_ota_end().
41  */
42 typedef uint32_t esp_ota_handle_t;
43 
44 /**
45  * @brief   Return esp_app_desc structure. This structure includes app version.
46  *
47  * Return description for running app.
48  * @return Pointer to esp_app_desc structure.
49  */
50 const esp_app_desc_t *esp_ota_get_app_description(void);
51 
52 /**
53  * @brief   Fill the provided buffer with SHA256 of the ELF file, formatted as hexadecimal, null-terminated.
54  * If the buffer size is not sufficient to fit the entire SHA256 in hex plus a null terminator,
55  * the largest possible number of bytes will be written followed by a null.
56  * @param dst   Destination buffer
57  * @param size  Size of the buffer
58  * @return      Number of bytes written to dst (including null terminator)
59  */
60 int esp_ota_get_app_elf_sha256(char* dst, size_t size);
61 
62 /**
63  * @brief   Commence an OTA update writing to the specified partition.
64 
65  * The specified partition is erased to the specified image size.
66  *
67  * If image size is not yet known, pass OTA_SIZE_UNKNOWN which will
68  * cause the entire partition to be erased.
69  *
70  * On success, this function allocates memory that remains in use
71  * until esp_ota_end() is called with the returned handle.
72  *
73  * Note: If the rollback option is enabled and the running application has the ESP_OTA_IMG_PENDING_VERIFY state then
74  * it will lead to the ESP_ERR_OTA_ROLLBACK_INVALID_STATE error. Confirm the running app before to run download a new app,
75  * use esp_ota_mark_app_valid_cancel_rollback() function for it (this should be done as early as possible when you first download a new application).
76  *
77  * @param partition Pointer to info for partition which will receive the OTA update. Required.
78  * @param image_size Size of new OTA app image. Partition will be erased in order to receive this size of image. If 0 or OTA_SIZE_UNKNOWN, the entire partition is erased.
79  * @param out_handle On success, returns a handle which should be used for subsequent esp_ota_write() and esp_ota_end() calls.
80 
81  * @return
82  *    - ESP_OK: OTA operation commenced successfully.
83  *    - ESP_ERR_INVALID_ARG: partition or out_handle arguments were NULL, or partition doesn't point to an OTA app partition.
84  *    - ESP_ERR_NO_MEM: Cannot allocate memory for OTA operation.
85  *    - ESP_ERR_OTA_PARTITION_CONFLICT: Partition holds the currently running firmware, cannot update in place.
86  *    - ESP_ERR_NOT_FOUND: Partition argument not found in partition table.
87  *    - ESP_ERR_OTA_SELECT_INFO_INVALID: The OTA data partition contains invalid data.
88  *    - ESP_ERR_INVALID_SIZE: Partition doesn't fit in configured flash size.
89  *    - ESP_ERR_FLASH_OP_TIMEOUT or ESP_ERR_FLASH_OP_FAIL: Flash write failed.
90  *    - ESP_ERR_OTA_ROLLBACK_INVALID_STATE: If the running app has not confirmed state. Before performing an update, the application must be valid.
91  */
92 esp_err_t esp_ota_begin(const esp_partition_t* partition, size_t image_size, esp_ota_handle_t* out_handle);
93 
94 /**
95  * @brief   Write OTA update data to partition
96  *
97  * This function can be called multiple times as
98  * data is received during the OTA operation. Data is written
99  * sequentially to the partition.
100  *
101  * @param handle  Handle obtained from esp_ota_begin
102  * @param data    Data buffer to write
103  * @param size    Size of data buffer in bytes.
104  *
105  * @return
106  *    - ESP_OK: Data was written to flash successfully.
107  *    - ESP_ERR_INVALID_ARG: handle is invalid.
108  *    - ESP_ERR_OTA_VALIDATE_FAILED: First byte of image contains invalid app image magic byte.
109  *    - ESP_ERR_FLASH_OP_TIMEOUT or ESP_ERR_FLASH_OP_FAIL: Flash write failed.
110  *    - ESP_ERR_OTA_SELECT_INFO_INVALID: OTA data partition has invalid contents
111  */
112 esp_err_t esp_ota_write(esp_ota_handle_t handle, const void* data, size_t size);
113 
114 /**
115  * @brief   Write OTA update data to partition
116  *
117  * This function can write data in non contiguous manner.
118  * If flash encryption is enabled, data should be 16 byte aligned.
119  *
120  * @param handle  Handle obtained from esp_ota_begin
121  * @param data    Data buffer to write
122  * @param size    Size of data buffer in bytes
123  * @param offset  Offset in flash partition
124  *
125  * @note While performing OTA, if the packets arrive out of order, esp_ota_write_with_offset() can be used to write data in non contiguous manner.
126  *       Use of esp_ota_write_with_offset() in combination with esp_ota_write() is not recommended.
127  *
128  * @return
129  *    - ESP_OK: Data was written to flash successfully.
130  *    - ESP_ERR_INVALID_ARG: handle is invalid.
131  *    - ESP_ERR_OTA_VALIDATE_FAILED: First byte of image contains invalid app image magic byte.
132  *    - ESP_ERR_FLASH_OP_TIMEOUT or ESP_ERR_FLASH_OP_FAIL: Flash write failed.
133  *    - ESP_ERR_OTA_SELECT_INFO_INVALID: OTA data partition has invalid contents
134  */
135 esp_err_t esp_ota_write_with_offset(esp_ota_handle_t handle, const void *data, size_t size, uint32_t offset);
136 
137 /**
138  * @brief Finish OTA update and validate newly written app image.
139  *
140  * @param handle  Handle obtained from esp_ota_begin().
141  *
142  * @note After calling esp_ota_end(), the handle is no longer valid and any memory associated with it is freed (regardless of result).
143  *
144  * @return
145  *    - ESP_OK: Newly written OTA app image is valid.
146  *    - ESP_ERR_NOT_FOUND: OTA handle was not found.
147  *    - ESP_ERR_INVALID_ARG: Handle was never written to.
148  *    - ESP_ERR_OTA_VALIDATE_FAILED: OTA image is invalid (either not a valid app image, or - if secure boot is enabled - signature failed to verify.)
149  *    - ESP_ERR_INVALID_STATE: If flash encryption is enabled, this result indicates an internal error writing the final encrypted bytes to flash.
150  */
151 esp_err_t esp_ota_end(esp_ota_handle_t handle);
152 
153 /**
154  * @brief Abort OTA update, free the handle and memory associated with it.
155  *
156  * @param handle obtained from esp_ota_begin().
157  *
158  * @return
159  *    - ESP_OK: Handle and its associated memory is freed successfully.
160  *    - ESP_ERR_NOT_FOUND: OTA handle was not found.
161  */
162 esp_err_t esp_ota_abort(esp_ota_handle_t handle);
163 
164 
165 /**
166  * @brief Configure OTA data for a new boot partition
167  *
168  * @note If this function returns ESP_OK, calling esp_restart() will boot the newly configured app partition.
169  *
170  * @param partition Pointer to info for partition containing app image to boot.
171  *
172  * @return
173  *    - ESP_OK: OTA data updated, next reboot will use specified partition.
174  *    - ESP_ERR_INVALID_ARG: partition argument was NULL or didn't point to a valid OTA partition of type "app".
175  *    - ESP_ERR_OTA_VALIDATE_FAILED: Partition contained invalid app image. Also returned if secure boot is enabled and signature validation failed.
176  *    - ESP_ERR_NOT_FOUND: OTA data partition not found.
177  *    - ESP_ERR_FLASH_OP_TIMEOUT or ESP_ERR_FLASH_OP_FAIL: Flash erase or write failed.
178  */
179 esp_err_t esp_ota_set_boot_partition(const esp_partition_t* partition);
180 
181 /**
182  * @brief Get partition info of currently configured boot app
183  *
184  * If esp_ota_set_boot_partition() has been called, the partition which was set by that function will be returned.
185  *
186  * If esp_ota_set_boot_partition() has not been called, the result is usually the same as esp_ota_get_running_partition().
187  * The two results are not equal if the configured boot partition does not contain a valid app (meaning that the running partition
188  * will be an app that the bootloader chose via fallback).
189  *
190  * If the OTA data partition is not present or not valid then the result is the first app partition found in the
191  * partition table. In priority order, this means: the factory app, the first OTA app slot, or the test app partition.
192  *
193  * Note that there is no guarantee the returned partition is a valid app. Use esp_image_verify(ESP_IMAGE_VERIFY, ...) to verify if the
194  * returned partition contains a bootable image.
195  *
196  * @return Pointer to info for partition structure, or NULL if partition table is invalid or a flash read operation failed. Any returned pointer is valid for the lifetime of the application.
197  */
198 const esp_partition_t* esp_ota_get_boot_partition(void);
199 
200 
201 /**
202  * @brief Get partition info of currently running app
203  *
204  * This function is different to esp_ota_get_boot_partition() in that
205  * it ignores any change of selected boot partition caused by
206  * esp_ota_set_boot_partition(). Only the app whose code is currently
207  * running will have its partition information returned.
208  *
209  * The partition returned by this function may also differ from esp_ota_get_boot_partition() if the configured boot
210  * partition is somehow invalid, and the bootloader fell back to a different app partition at boot.
211  *
212  * @return Pointer to info for partition structure, or NULL if no partition is found or flash read operation failed. Returned pointer is valid for the lifetime of the application.
213  */
214 const esp_partition_t* esp_ota_get_running_partition(void);
215 
216 
217 /**
218  * @brief Return the next OTA app partition which should be written with a new firmware.
219  *
220  * Call this function to find an OTA app partition which can be passed to esp_ota_begin().
221  *
222  * Finds next partition round-robin, starting from the current running partition.
223  *
224  * @param start_from If set, treat this partition info as describing the current running partition. Can be NULL, in which case esp_ota_get_running_partition() is used to find the currently running partition. The result of this function is never the same as this argument.
225  *
226  * @return Pointer to info for partition which should be updated next. NULL result indicates invalid OTA data partition, or that no eligible OTA app slot partition was found.
227  *
228  */
229 const esp_partition_t* esp_ota_get_next_update_partition(const esp_partition_t *start_from);
230 
231 /**
232  * @brief Returns esp_app_desc structure for app partition. This structure includes app version.
233  *
234  * Returns a description for the requested app partition.
235  * @param[in] partition     Pointer to app partition. (only app partition)
236  * @param[out] app_desc     Structure of info about app.
237  * @return
238  *  - ESP_OK                Successful.
239  *  - ESP_ERR_NOT_FOUND     app_desc structure is not found. Magic word is incorrect.
240  *  - ESP_ERR_NOT_SUPPORTED Partition is not application.
241  *  - ESP_ERR_INVALID_ARG   Arguments is NULL or if partition's offset exceeds partition size.
242  *  - ESP_ERR_INVALID_SIZE  Read would go out of bounds of the partition.
243  *  - or one of error codes from lower-level flash driver.
244  */
245 esp_err_t esp_ota_get_partition_description(const esp_partition_t *partition, esp_app_desc_t *app_desc);
246 
247 /**
248  * @brief Returns number of ota partitions provided in partition table.
249  *
250  * @return
251  *  - Number of OTA partitions
252  */
253 uint8_t esp_ota_get_app_partition_count(void);
254 
255 /**
256  * @brief This function is called to indicate that the running app is working well.
257  *
258  * @return
259  *  - ESP_OK: if successful.
260  */
261 esp_err_t esp_ota_mark_app_valid_cancel_rollback(void);
262 
263 /**
264  * @brief This function is called to roll back to the previously workable app with reboot.
265  *
266  * If rollback is successful then device will reset else API will return with error code.
267  * Checks applications on a flash drive that can be booted in case of rollback.
268  * If the flash does not have at least one app (except the running app) then rollback is not possible.
269  * @return
270  *  - ESP_FAIL: if not successful.
271  *  - ESP_ERR_OTA_ROLLBACK_FAILED: The rollback is not possible due to flash does not have any apps.
272  */
273 esp_err_t esp_ota_mark_app_invalid_rollback_and_reboot(void);
274 
275 /**
276  * @brief Returns last partition with invalid state (ESP_OTA_IMG_INVALID or ESP_OTA_IMG_ABORTED).
277  *
278  * @return partition.
279  */
280 const esp_partition_t* esp_ota_get_last_invalid_partition(void);
281 
282 /**
283  * @brief Returns state for given partition.
284  *
285  * @param[in] partition  Pointer to partition.
286  * @param[out] ota_state state of partition (if this partition has a record in otadata).
287  * @return
288  *        - ESP_OK:                 Successful.
289  *        - ESP_ERR_INVALID_ARG:    partition or ota_state arguments were NULL.
290  *        - ESP_ERR_NOT_SUPPORTED:  partition is not ota.
291  *        - ESP_ERR_NOT_FOUND:      Partition table does not have otadata or state was not found for given partition.
292  */
293 esp_err_t esp_ota_get_state_partition(const esp_partition_t *partition, esp_ota_img_states_t *ota_state);
294 
295 /**
296  * @brief Erase previous boot app partition and corresponding otadata select for this partition.
297  *
298  * When current app is marked to as valid then you can erase previous app partition.
299  * @return
300  *        - ESP_OK:   Successful, otherwise ESP_ERR.
301  */
302 esp_err_t esp_ota_erase_last_boot_app_partition(void);
303 
304 /**
305  * @brief Checks applications on the slots which can be booted in case of rollback.
306  *
307  * These applications should be valid (marked in otadata as not UNDEFINED, INVALID or ABORTED and crc is good) and be able booted,
308  * and secure_version of app >= secure_version of efuse (if anti-rollback is enabled).
309  *
310  * @return
311  *        - True: Returns true if the slots have at least one app (except the running app).
312  *        - False: The rollback is not possible.
313  */
314 bool esp_ota_check_rollback_is_possible(void);
315 
316 #if SOC_EFUSE_SECURE_BOOT_KEY_DIGESTS > 1 && (CONFIG_SECURE_BOOT_V2_ENABLED || __DOXYGEN__)
317 
318 /**
319  * Secure Boot V2 public key indexes.
320  */
321 typedef enum {
322     SECURE_BOOT_PUBLIC_KEY_INDEX_0,     /*!< Points to the 0th index of the Secure Boot v2 public key */
323     SECURE_BOOT_PUBLIC_KEY_INDEX_1,     /*!< Points to the 1st index of the Secure Boot v2 public key */
324     SECURE_BOOT_PUBLIC_KEY_INDEX_2      /*!< Points to the 2nd index of the Secure Boot v2 public key */
325 } esp_ota_secure_boot_public_key_index_t;
326 
327 /**
328  * @brief Revokes the old signature digest. To be called in the application after the rollback logic.
329  *
330  * Relevant for Secure boot v2 on ESP32-S2 where upto 3 key digests can be stored (Key #N-1, Key #N, Key #N+1).
331  * When key #N-1 used to sign an app is invalidated, an OTA update is to be sent with an app signed with key #N-1 & Key #N.
332  * After successfully booting the OTA app should call this function to revoke Key #N-1.
333  *
334  * @param index - The index of the signature block to be revoked
335  *
336  * @return
337  *        - ESP_OK: If revocation is successful.
338  *        - ESP_ERR_INVALID_ARG: If the index of the public key to be revoked is incorrect.
339  *        - ESP_FAIL: If secure boot v2 has not been enabled.
340  */
341 esp_err_t esp_ota_revoke_secure_boot_public_key(esp_ota_secure_boot_public_key_index_t index);
342 #endif /* SOC_EFUSE_SECURE_BOOT_KEY_DIGESTS > 1 */
343 
344 #ifdef __cplusplus
345 }
346 #endif
347 
348 #endif /* OTA_OPS_H */
349