blob: a05c816f00e30d0d837ab96162d2103d7446bc6c [file] [log] [blame]
Christopher Collins92ea77f2016-12-12 15:59:26 -08001/*
2 * Licensed to the Apache Software Foundation (ASF) under one
3 * or more contributor license agreements. See the NOTICE file
4 * distributed with this work for additional information
5 * regarding copyright ownership. The ASF licenses this file
6 * to you under the Apache License, Version 2.0 (the
7 * "License"); you may not use this file except in compliance
8 * with the License. You may obtain a copy of the License at
9 *
10 * http://www.apache.org/licenses/LICENSE-2.0
11 *
12 * Unless required by applicable law or agreed to in writing,
13 * software distributed under the License is distributed on an
14 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
15 * KIND, either express or implied. See the License for the
16 * specific language governing permissions and limitations
17 * under the License.
18 */
19#include <assert.h>
20#include <stddef.h>
21#include <inttypes.h>
22#include <ctype.h>
23#include <stdio.h>
Almir Okato90be6e62022-09-23 14:52:25 -030024#include <errno.h>
Christopher Collins92ea77f2016-12-12 15:59:26 -080025
26#include "sysflash/sysflash.h"
27
Fabio Utzig1a2e41a2017-11-17 12:13:09 -020028#include "bootutil/bootutil_log.h"
Øyvind Rønningstada7d34ca2022-02-28 13:47:57 +010029#include "zcbor_encode.h"
Fabio Utzig1a2e41a2017-11-17 12:13:09 -020030
Andrzej Puzdrowski8e96b832017-09-08 16:49:14 +020031#ifdef __ZEPHYR__
Fabio Baltieri888e2612022-07-19 20:54:26 +000032#include <zephyr/sys/reboot.h>
33#include <zephyr/sys/byteorder.h>
34#include <zephyr/sys/__assert.h>
35#include <zephyr/drivers/flash.h>
Gerard Marull-Paretas4eca54f2022-10-06 11:45:11 +020036#include <zephyr/kernel.h>
Fabio Baltieri888e2612022-07-19 20:54:26 +000037#include <zephyr/sys/crc.h>
38#include <zephyr/sys/base64.h>
Almir Okatoe8cbc0d2022-06-13 10:45:39 -030039#include <hal/hal_flash.h>
40#elif __ESPRESSIF__
41#include <bootloader_utility.h>
42#include <esp_rom_sys.h>
Almir Okato7d3622f2022-10-20 12:44:58 -030043#include <esp_crc.h>
Almir Okatoe8cbc0d2022-06-13 10:45:39 -030044#include <endian.h>
45#include <mbedtls/base64.h>
Andrzej Puzdrowski8e96b832017-09-08 16:49:14 +020046#else
Christopher Collins92ea77f2016-12-12 15:59:26 -080047#include <bsp/bsp.h>
Christopher Collins92ea77f2016-12-12 15:59:26 -080048#include <hal/hal_system.h>
Almir Okatoe8cbc0d2022-06-13 10:45:39 -030049#include <hal/hal_flash.h>
Christopher Collins92ea77f2016-12-12 15:59:26 -080050#include <os/endian.h>
Christopher Collins92ea77f2016-12-12 15:59:26 -080051#include <os/os_cputime.h>
Andrzej Puzdrowski8e96b832017-09-08 16:49:14 +020052#include <crc/crc16.h>
53#include <base64/base64.h>
Andrzej Puzdrowski386b5922018-04-06 19:26:24 +020054#endif /* __ZEPHYR__ */
55
Andrzej Puzdrowskib788c712018-04-12 12:42:49 +020056#include <flash_map_backend/flash_map_backend.h>
Andrzej Puzdrowski8e96b832017-09-08 16:49:14 +020057#include <os/os.h>
58#include <os/os_malloc.h>
Christopher Collins92ea77f2016-12-12 15:59:26 -080059
60#include <bootutil/image.h>
Andrzej Puzdrowskif48de7a2020-10-19 09:42:02 +020061#include <bootutil/bootutil.h>
Christopher Collins92ea77f2016-12-12 15:59:26 -080062
63#include "boot_serial/boot_serial.h"
64#include "boot_serial_priv.h"
Almir Okatoe8cbc0d2022-06-13 10:45:39 -030065#include "mcuboot_config/mcuboot_config.h"
Christopher Collins92ea77f2016-12-12 15:59:26 -080066
Dominik Ermel3d4e55d2021-07-09 11:14:10 +000067#ifdef MCUBOOT_ERASE_PROGRESSIVELY
Andrzej Puzdrowskic2e30cf2018-07-20 16:19:09 +020068#include "bootutil_priv.h"
69#endif
70
Wouter Cappelle953a7612021-05-03 16:53:05 +020071#ifdef MCUBOOT_ENC_IMAGES
72#include "single_loader.h"
73#endif
74
Øyvind Rønningstadf42a8202019-12-13 03:27:54 +010075#include "serial_recovery_cbor.h"
Dominik Ermel88bd5672022-06-07 15:17:06 +000076#include "serial_recovery_echo.h"
Andrzej Puzdrowski4f9c7302021-07-16 17:34:43 +020077#include "bootutil/boot_hooks.h"
Øyvind Rønningstadf42a8202019-12-13 03:27:54 +010078
Carlos Falgueras Garcíaa4b4b0f2021-06-22 10:00:22 +020079BOOT_LOG_MODULE_DECLARE(mcuboot);
Emanuele Di Santo9f1933d2018-11-20 10:59:59 +010080
Jamie McCraead1fb3d2022-12-01 14:24:37 +000081#ifndef MCUBOOT_SERIAL_MAX_RECEIVE_SIZE
82#define MCUBOOT_SERIAL_MAX_RECEIVE_SIZE 512
83#endif
84
Jamie McCrae827118f2023-03-10 13:24:57 +000085#define BOOT_SERIAL_OUT_MAX (160 * BOOT_IMAGE_NUMBER)
Piotr Dymaczf5e77532022-10-30 17:43:45 +010086#define BOOT_SERIAL_FRAME_MTU 124 /* 127 - pkt start (2 bytes) and stop (1 byte) */
Christopher Collins92ea77f2016-12-12 15:59:26 -080087
Andrzej Puzdrowski8e96b832017-09-08 16:49:14 +020088#ifdef __ZEPHYR__
Carles Cufi0165be82018-03-26 17:43:51 +020089/* base64 lib encodes data to null-terminated string */
Andrzej Puzdrowski8e96b832017-09-08 16:49:14 +020090#define BASE64_ENCODE_SIZE(in_size) ((((((in_size) - 1) / 3) * 4) + 4) + 1)
91
92#define CRC16_INITIAL_CRC 0 /* what to seed crc16 with */
93#define CRC_CITT_POLYMINAL 0x1021
94
95#define ntohs(x) sys_be16_to_cpu(x)
96#define htons(x) sys_cpu_to_be16(x)
Almir Okatoe8cbc0d2022-06-13 10:45:39 -030097#elif __ESPRESSIF__
98#define BASE64_ENCODE_SIZE(in_size) ((((((in_size) - 1) / 3) * 4) + 4) + 1)
99#define CRC16_INITIAL_CRC 0 /* what to seed crc16 with */
100
101#define ntohs(x) be16toh(x)
102#define htons(x) htobe16(x)
103
104#define base64_decode mbedtls_base64_decode
105#define base64_encode mbedtls_base64_encode
Andrzej Puzdrowski8e96b832017-09-08 16:49:14 +0200106#endif
Emanuele Di Santo9f1933d2018-11-20 10:59:59 +0100107
Fabio Utzig6f49c272019-08-23 11:42:58 -0300108#if (BOOT_IMAGE_NUMBER > 1)
109#define IMAGES_ITER(x) for ((x) = 0; (x) < BOOT_IMAGE_NUMBER; ++(x))
110#else
111#define IMAGES_ITER(x)
112#endif
113
Jamie McCraead1fb3d2022-12-01 14:24:37 +0000114static char in_buf[MCUBOOT_SERIAL_MAX_RECEIVE_SIZE + 1];
115static char dec_buf[MCUBOOT_SERIAL_MAX_RECEIVE_SIZE + 1];
Marko Kiiskila8b1ce3a2018-06-14 13:20:46 -0700116const struct boot_uart_funcs *boot_uf;
Christopher Collins92ea77f2016-12-12 15:59:26 -0800117static struct nmgr_hdr *bs_hdr;
Wouter Cappellee3822f82022-01-19 15:39:43 +0100118static bool bs_entry;
Christopher Collins92ea77f2016-12-12 15:59:26 -0800119
120static char bs_obuf[BOOT_SERIAL_OUT_MAX];
121
Christopher Collins92ea77f2016-12-12 15:59:26 -0800122static void boot_serial_output(void);
123
Jamie McCrae827118f2023-03-10 13:24:57 +0000124#ifdef MCUBOOT_SERIAL_IMG_GRP_HASH
125static int boot_serial_get_hash(const struct image_header *hdr,
126 const struct flash_area *fap, uint8_t *hash);
127#endif
128
Øyvind Rønningstada7d34ca2022-02-28 13:47:57 +0100129static zcbor_state_t cbor_state[2];
Christopher Collins92ea77f2016-12-12 15:59:26 -0800130
Dominik Ermel4c0f6c12022-03-04 15:47:37 +0000131void reset_cbor_state(void)
132{
Øyvind Rønningstada7d34ca2022-02-28 13:47:57 +0100133 zcbor_new_encode_state(cbor_state, 2, (uint8_t *)bs_obuf,
134 (size_t)bs_obuf + sizeof(bs_obuf), 0);
Dominik Ermel4c0f6c12022-03-04 15:47:37 +0000135}
136
Dominik Ermel3d51e432021-06-25 17:29:50 +0000137/**
Dominik Ermelbd69c3d2021-07-28 11:27:31 +0000138 * Function that processes MGMT_GROUP_ID_PERUSER mcumgr group and may be
139 * used to process any groups that have not been processed by generic boot
140 * serial implementation.
Dominik Ermel3d51e432021-06-25 17:29:50 +0000141 *
142 * @param[in] hdr -- the decoded header of mcumgr message;
143 * @param[in] buffer -- buffer with first mcumgr message;
144 * @param[in] len -- length of of data in buffer;
145 * @param[out] *cs -- object with encoded response.
146 *
147 * @return 0 on success; non-0 error code otherwise.
148 */
149extern int bs_peruser_system_specific(const struct nmgr_hdr *hdr,
150 const char *buffer,
Øyvind Rønningstada7d34ca2022-02-28 13:47:57 +0100151 int len, zcbor_state_t *cs);
Christopher Collins92ea77f2016-12-12 15:59:26 -0800152
Dominik Ermeld49cfc12022-06-09 08:24:48 +0000153#define zcbor_tstr_put_lit_cast(state, string) \
154 zcbor_tstr_encode_ptr(state, (uint8_t *)string, sizeof(string) - 1)
155
156#ifndef MCUBOOT_USE_SNPRINTF
Christopher Collins92ea77f2016-12-12 15:59:26 -0800157/*
Marko Kiiskilace50ab02018-06-06 11:33:33 +0300158 * Convert version into string without use of snprintf().
Christopher Collins92ea77f2016-12-12 15:59:26 -0800159 */
Marko Kiiskilace50ab02018-06-06 11:33:33 +0300160static int
161u32toa(char *tgt, uint32_t val)
Christopher Collins92ea77f2016-12-12 15:59:26 -0800162{
Marko Kiiskilace50ab02018-06-06 11:33:33 +0300163 char *dst;
164 uint32_t d = 1;
165 uint32_t dgt;
166 int n = 0;
Christopher Collins92ea77f2016-12-12 15:59:26 -0800167
Marko Kiiskilace50ab02018-06-06 11:33:33 +0300168 dst = tgt;
169 while (val / d >= 10) {
170 d *= 10;
Christopher Collins92ea77f2016-12-12 15:59:26 -0800171 }
Marko Kiiskilace50ab02018-06-06 11:33:33 +0300172 while (d) {
173 dgt = val / d;
174 val %= d;
175 d /= 10;
176 if (n || dgt > 0 || d == 0) {
177 *dst++ = dgt + '0';
178 ++n;
Christopher Collins92ea77f2016-12-12 15:59:26 -0800179 }
Christopher Collins92ea77f2016-12-12 15:59:26 -0800180 }
Marko Kiiskilace50ab02018-06-06 11:33:33 +0300181 *dst = '\0';
182
183 return dst - tgt;
184}
185
186/*
187 * dst has to be able to fit "255.255.65535.4294967295" (25 characters).
188 */
189static void
190bs_list_img_ver(char *dst, int maxlen, struct image_version *ver)
191{
192 int off;
193
194 off = u32toa(dst, ver->iv_major);
195 dst[off++] = '.';
196 off += u32toa(dst + off, ver->iv_minor);
197 dst[off++] = '.';
198 off += u32toa(dst + off, ver->iv_revision);
Jamie McCraee5c57dd2023-03-21 14:45:21 +0000199
200 if (ver->iv_build_num != 0) {
201 dst[off++] = '.';
202 off += u32toa(dst + off, ver->iv_build_num);
203 }
Christopher Collins92ea77f2016-12-12 15:59:26 -0800204}
Dominik Ermeld49cfc12022-06-09 08:24:48 +0000205#else
206/*
207 * dst has to be able to fit "255.255.65535.4294967295" (25 characters).
208 */
209static void
210bs_list_img_ver(char *dst, int maxlen, struct image_version *ver)
211{
Jamie McCraee5c57dd2023-03-21 14:45:21 +0000212 int len;
213
214 len = snprintf(dst, maxlen, "%hu.%hu.%hu", (uint16_t)ver->iv_major,
215 (uint16_t)ver->iv_minor, ver->iv_revision);
216
217 if (ver->iv_build_num != 0 && len > 0 && len < maxlen) {
218 snprintf(&dst[len], (maxlen - len), "%u", ver->iv_build_num);
219 }
Dominik Ermeld49cfc12022-06-09 08:24:48 +0000220}
221#endif /* !MCUBOOT_USE_SNPRINTF */
Christopher Collins92ea77f2016-12-12 15:59:26 -0800222
223/*
224 * List images.
225 */
226static void
227bs_list(char *buf, int len)
228{
Christopher Collins92ea77f2016-12-12 15:59:26 -0800229 struct image_header hdr;
230 uint8_t tmpbuf[64];
Øyvind Rønningstad9f4aefd2021-03-08 21:11:25 +0100231 uint32_t slot, area_id;
Christopher Collins92ea77f2016-12-12 15:59:26 -0800232 const struct flash_area *fap;
Fabio Utzig6f49c272019-08-23 11:42:58 -0300233 uint8_t image_index;
Jamie McCrae827118f2023-03-10 13:24:57 +0000234#ifdef MCUBOOT_SERIAL_IMG_GRP_HASH
235 uint8_t hash[32];
236#endif
Christopher Collins92ea77f2016-12-12 15:59:26 -0800237
Øyvind Rønningstada7d34ca2022-02-28 13:47:57 +0100238 zcbor_map_start_encode(cbor_state, 1);
239 zcbor_tstr_put_lit_cast(cbor_state, "images");
240 zcbor_list_start_encode(cbor_state, 5);
Fabio Utzig6f49c272019-08-23 11:42:58 -0300241 image_index = 0;
242 IMAGES_ITER(image_index) {
243 for (slot = 0; slot < 2; slot++) {
244 area_id = flash_area_id_from_multi_image_slot(image_index, slot);
245 if (flash_area_open(area_id, &fap)) {
246 continue;
247 }
Christopher Collins92ea77f2016-12-12 15:59:26 -0800248
Andrzej Puzdrowski4f9c7302021-07-16 17:34:43 +0200249 int rc = BOOT_HOOK_CALL(boot_read_image_header_hook,
250 BOOT_HOOK_REGULAR, image_index, slot, &hdr);
251 if (rc == BOOT_HOOK_REGULAR)
252 {
253 flash_area_read(fap, 0, &hdr, sizeof(hdr));
254 }
Christopher Collins92ea77f2016-12-12 15:59:26 -0800255
Michael Grand5047f032022-11-24 16:49:56 +0100256 FIH_DECLARE(fih_rc, FIH_FAILURE);
Andrzej Puzdrowski4f9c7302021-07-16 17:34:43 +0200257
258 if (hdr.ih_magic == IMAGE_MAGIC)
259 {
260 BOOT_HOOK_CALL_FIH(boot_image_check_hook,
Michael Grand5047f032022-11-24 16:49:56 +0100261 FIH_BOOT_HOOK_REGULAR,
Andrzej Puzdrowski4f9c7302021-07-16 17:34:43 +0200262 fih_rc, image_index, slot);
Michael Grand5047f032022-11-24 16:49:56 +0100263 if (FIH_EQ(fih_rc, FIH_BOOT_HOOK_REGULAR))
Andrzej Puzdrowski4f9c7302021-07-16 17:34:43 +0200264 {
Wouter Cappelle953a7612021-05-03 16:53:05 +0200265#ifdef MCUBOOT_ENC_IMAGES
266 if (slot == 0 && IS_ENCRYPTED(&hdr)) {
267 /* Clear the encrypted flag we didn't supply a key
268 * This flag could be set if there was a decryption in place
269 * performed before. We will try to validate the image without
270 * decryption by clearing the flag in the heder. If
271 * still encrypted the validation will fail.
272 */
273 hdr.ih_flags &= ~(ENCRYPTIONFLAGS);
274 }
275#endif
Andrzej Puzdrowski4f9c7302021-07-16 17:34:43 +0200276 FIH_CALL(bootutil_img_validate, fih_rc, NULL, 0, &hdr, fap, tmpbuf, sizeof(tmpbuf),
277 NULL, 0, NULL);
278 }
279 }
280
Jamie McCrae827118f2023-03-10 13:24:57 +0000281#ifdef MCUBOOT_SERIAL_IMG_GRP_HASH
282 /* Retrieve SHA256 hash of image for identification */
283 rc = boot_serial_get_hash(&hdr, fap, hash);
284#endif
285
Andrzej Puzdrowski4f9c7302021-07-16 17:34:43 +0200286 flash_area_close(fap);
287
Michael Grand5047f032022-11-24 16:49:56 +0100288 if (FIH_NOT_EQ(fih_rc, FIH_SUCCESS)) {
Fabio Utzig6f49c272019-08-23 11:42:58 -0300289 continue;
290 }
Fabio Utzig6f49c272019-08-23 11:42:58 -0300291
Øyvind Rønningstada7d34ca2022-02-28 13:47:57 +0100292 zcbor_map_start_encode(cbor_state, 20);
Fabio Utzig6f49c272019-08-23 11:42:58 -0300293
294#if (BOOT_IMAGE_NUMBER > 1)
Øyvind Rønningstada7d34ca2022-02-28 13:47:57 +0100295 zcbor_tstr_put_lit_cast(cbor_state, "image");
296 zcbor_uint32_put(cbor_state, image_index);
Fabio Utzig6f49c272019-08-23 11:42:58 -0300297#endif
298
Øyvind Rønningstada7d34ca2022-02-28 13:47:57 +0100299 zcbor_tstr_put_lit_cast(cbor_state, "slot");
300 zcbor_uint32_put(cbor_state, slot);
Jamie McCrae827118f2023-03-10 13:24:57 +0000301
302#ifdef MCUBOOT_SERIAL_IMG_GRP_HASH
303 if (rc == 0) {
304 zcbor_tstr_put_lit_cast(cbor_state, "hash");
305 zcbor_bstr_encode_ptr(cbor_state, hash, sizeof(hash));
306 }
307#endif
308
Øyvind Rønningstada7d34ca2022-02-28 13:47:57 +0100309 zcbor_tstr_put_lit_cast(cbor_state, "version");
Fabio Utzig6f49c272019-08-23 11:42:58 -0300310
311 bs_list_img_ver((char *)tmpbuf, sizeof(tmpbuf), &hdr.ih_ver);
Jamie McCrae827118f2023-03-10 13:24:57 +0000312
Øyvind Rønningstada7d34ca2022-02-28 13:47:57 +0100313 zcbor_tstr_encode_ptr(cbor_state, tmpbuf, strlen((char *)tmpbuf));
314 zcbor_map_end_encode(cbor_state, 20);
Christopher Collins92ea77f2016-12-12 15:59:26 -0800315 }
Christopher Collins92ea77f2016-12-12 15:59:26 -0800316 }
Øyvind Rønningstada7d34ca2022-02-28 13:47:57 +0100317 zcbor_list_end_encode(cbor_state, 5);
318 zcbor_map_end_encode(cbor_state, 1);
Christopher Collins92ea77f2016-12-12 15:59:26 -0800319 boot_serial_output();
320}
321
Dominik Ermelbcc17b42022-06-15 15:33:04 +0000322#ifdef MCUBOOT_ERASE_PROGRESSIVELY
323
324/** Erases range of flash, aligned to sector size
325 *
326 * Function will erase all sectors withing [start, end] range; it does not check
327 * the @p start for alignment, and it will use @p end to find boundaries of las
328 * sector to erase. Function returns offset of the first byte past the last
329 * erased sector, so basically offset of next sector to be erased if needed.
330 * The function is intended to be called iteratively with previously returned
331 * offset as @p start.
332 *
333 * @param start starting offset, aligned to sector offset;
334 * @param end ending offset, maybe anywhere within sector;
335 *
336 * @retval On success: offset of the first byte past last erased sector;
337 * On failure: -EINVAL.
338 */
339static off_t erase_range(const struct flash_area *fap, off_t start, off_t end)
340{
341 struct flash_sector sect;
342 size_t size;
343 int rc;
344
345 if (end >= flash_area_get_size(fap)) {
346 return -EINVAL;
347 }
348
349 if (end < start) {
350 return start;
351 }
352
Dominik Ermel24769882023-01-05 13:36:35 +0000353 if (flash_area_get_sector(fap, end, &sect)) {
Dominik Ermelbcc17b42022-06-15 15:33:04 +0000354 return -EINVAL;
355 }
356
357 size = flash_sector_get_off(&sect) + flash_sector_get_size(&sect) - start;
Stephanos Ioannidis09e2bd72022-07-11 22:01:49 +0900358 BOOT_LOG_INF("Erasing range 0x%jx:0x%jx", (intmax_t)start,
359 (intmax_t)(start + size - 1));
Dominik Ermelbcc17b42022-06-15 15:33:04 +0000360
361 rc = flash_area_erase(fap, start, size);
362 if (rc != 0) {
363 BOOT_LOG_ERR("Error %d while erasing range", rc);
364 return -EINVAL;
365 }
366
367 return start + size;
368}
369#endif
370
Christopher Collins92ea77f2016-12-12 15:59:26 -0800371/*
372 * Image upload request.
373 */
374static void
375bs_upload(char *buf, int len)
376{
Dominik Ermel5bd87442022-06-13 15:14:01 +0000377 static size_t img_size; /* Total image size, held for duration of upload */
378 static uint32_t curr_off; /* Expected current offset */
379 const uint8_t *img_chunk = NULL; /* Pointer to buffer with received image chunk */
380 size_t img_chunk_len = 0; /* Length of received image chunk */
381 size_t img_chunk_off = SIZE_MAX; /* Offset of image chunk within image */
382 uint8_t rem_bytes; /* Reminder bytes after aligning chunk write to
383 * to flash alignment */
Fabio Utzig6f49c272019-08-23 11:42:58 -0300384 int img_num;
Dominik Ermel5bd87442022-06-13 15:14:01 +0000385 size_t img_size_tmp = SIZE_MAX; /* Temp variable for image size */
Christopher Collins92ea77f2016-12-12 15:59:26 -0800386 const struct flash_area *fap = NULL;
387 int rc;
Dominik Ermel3d4e55d2021-07-09 11:14:10 +0000388#ifdef MCUBOOT_ERASE_PROGRESSIVELY
Dominik Ermelbcc17b42022-06-15 15:33:04 +0000389 static off_t not_yet_erased = 0; /* Offset of next byte to erase; writes to flash
390 * are done in consecutive manner and erases are done
391 * to allow currently received chunk to be written;
392 * this state variable holds information where last
393 * erase has stopped to let us know whether erase
394 * is needed to be able to write current chunk.
395 */
396 static struct flash_sector status_sector;
Emanuele Di Santo205c8c62018-07-20 11:42:31 +0200397#endif
Christopher Collins92ea77f2016-12-12 15:59:26 -0800398
Fabio Utzig6f49c272019-08-23 11:42:58 -0300399 img_num = 0;
Marko Kiiskilace50ab02018-06-06 11:33:33 +0300400
401 /*
402 * Expected data format.
403 * {
Fabio Utzig6f49c272019-08-23 11:42:58 -0300404 * "image":<image number in a multi-image set (OPTIONAL)>
405 * "data":<image data>
Marko Kiiskilace50ab02018-06-06 11:33:33 +0300406 * "len":<image len>
407 * "off":<current offset of image data>
408 * }
409 */
410
Øyvind Rønningstad212a35b2021-05-07 21:06:48 +0200411 struct Upload upload;
Øyvind Rønningstada7d34ca2022-02-28 13:47:57 +0100412 size_t decoded_len;
413 uint_fast8_t result = cbor_decode_Upload((const uint8_t *)buf, len, &upload, &decoded_len);
Øyvind Rønningstad212a35b2021-05-07 21:06:48 +0200414
Øyvind Rønningstada7d34ca2022-02-28 13:47:57 +0100415 if ((result != ZCBOR_SUCCESS) || (len != decoded_len)) {
Øyvind Rønningstadf42a8202019-12-13 03:27:54 +0100416 goto out_invalid_data;
417 }
Dominik Ermel470e2f32020-01-10 13:28:48 +0000418
Øyvind Rønningstadf42a8202019-12-13 03:27:54 +0100419 for (int i = 0; i < upload._Upload_members_count; i++) {
Øyvind Rønningstada7d34ca2022-02-28 13:47:57 +0100420 struct Member_ *member = &upload._Upload_members[i]._Upload_members;
Øyvind Rønningstadf42a8202019-12-13 03:27:54 +0100421 switch(member->_Member_choice) {
422 case _Member_image:
423 img_num = member->_Member_image;
424 break;
425 case _Member_data:
Dominik Ermel5bd87442022-06-13 15:14:01 +0000426 img_chunk = member->_Member_data.value;
427 img_chunk_len = member->_Member_data.len;
Øyvind Rønningstadf42a8202019-12-13 03:27:54 +0100428 break;
429 case _Member_len:
Dominik Ermel5bd87442022-06-13 15:14:01 +0000430 img_size_tmp = member->_Member_len;
Øyvind Rønningstadf42a8202019-12-13 03:27:54 +0100431 break;
432 case _Member_off:
Dominik Ermel5bd87442022-06-13 15:14:01 +0000433 img_chunk_off = member->_Member_off;
Øyvind Rønningstadf42a8202019-12-13 03:27:54 +0100434 break;
435 case _Member_sha:
436 default:
437 /* Nothing to do. */
438 break;
Marko Kiiskilace50ab02018-06-06 11:33:33 +0300439 }
440 }
Øyvind Rønningstadf42a8202019-12-13 03:27:54 +0100441
Dominik Ermel5bd87442022-06-13 15:14:01 +0000442 if (img_chunk_off == SIZE_MAX || img_chunk == NULL) {
Marko Kiiskilace50ab02018-06-06 11:33:33 +0300443 /*
444 * Offset must be set in every block.
445 */
446 goto out_invalid_data;
Christopher Collins92ea77f2016-12-12 15:59:26 -0800447 }
448
Dominik Ermel48decca2021-07-09 10:23:58 +0000449#if !defined(MCUBOOT_SERIAL_DIRECT_IMAGE_UPLOAD)
Fabio Utzig6f49c272019-08-23 11:42:58 -0300450 rc = flash_area_open(flash_area_id_from_multi_image_slot(img_num, 0), &fap);
Dominik Ermel48decca2021-07-09 10:23:58 +0000451#else
452 rc = flash_area_open(flash_area_id_from_direct_image(img_num), &fap);
453#endif
Christopher Collins92ea77f2016-12-12 15:59:26 -0800454 if (rc) {
455 rc = MGMT_ERR_EINVAL;
456 goto out;
457 }
458
Dominik Ermel5bd87442022-06-13 15:14:01 +0000459 if (img_chunk_off == 0) {
Dominik Ermelbcc17b42022-06-15 15:33:04 +0000460 /* Receiving chunk with 0 offset resets the upload state; this basically
461 * means that upload has started from beginning.
462 */
463 const size_t area_size = flash_area_get_size(fap);
Dominik Ermel5bd87442022-06-13 15:14:01 +0000464
Dominik Ermelbcc17b42022-06-15 15:33:04 +0000465 curr_off = 0;
466#ifdef MCUBOOT_ERASE_PROGRESSIVELY
467 /* Get trailer sector information; this is done early because inability to get
468 * that sector information means that upload will not work anyway.
469 * TODO: This is single occurrence issue, it should get detected during tests
470 * and fixed otherwise you are deploying broken mcuboot.
471 */
Dominik Ermel24769882023-01-05 13:36:35 +0000472 if (flash_area_get_sector(fap, boot_status_off(fap), &status_sector)) {
Dominik Ermelbcc17b42022-06-15 15:33:04 +0000473 rc = MGMT_ERR_EUNKNOWN;
474 BOOT_LOG_ERR("Unable to determine flash sector of the image trailer");
475 goto out;
476 }
477#endif
478
479
Wouter Cappellebb7a39d2021-05-03 16:44:44 +0200480#if defined(MCUBOOT_VALIDATE_PRIMARY_SLOT_ONCE)
481 /* We are using swap state at end of flash area to store validation
482 * result. Make sure the user cannot write it from an image to skip validation.
483 */
Dominik Ermelbcc17b42022-06-15 15:33:04 +0000484 if (img_size_tmp > (area_size - BOOT_MAGIC_SZ)) {
Wouter Cappellebb7a39d2021-05-03 16:44:44 +0200485 goto out_invalid_data;
486 }
Dominik Ermelbcc17b42022-06-15 15:33:04 +0000487#else
488 if (img_size_tmp > area_size) {
489 goto out_invalid_data;
490 }
491
Wouter Cappellebb7a39d2021-05-03 16:44:44 +0200492#endif
Dominik Ermelbcc17b42022-06-15 15:33:04 +0000493
Dominik Ermel3d4e55d2021-07-09 11:14:10 +0000494#ifndef MCUBOOT_ERASE_PROGRESSIVELY
Dominik Ermelbcc17b42022-06-15 15:33:04 +0000495 /* Non-progressive erase erases entire image slot when first chunk of
496 * an image is received.
497 */
498 rc = flash_area_erase(fap, 0, area_size);
Christopher Collins92ea77f2016-12-12 15:59:26 -0800499 if (rc) {
Marko Kiiskilace50ab02018-06-06 11:33:33 +0300500 goto out_invalid_data;
Christopher Collins92ea77f2016-12-12 15:59:26 -0800501 }
Dominik Ermelbcc17b42022-06-15 15:33:04 +0000502#else
503 not_yet_erased = 0;
Emanuele Di Santo205c8c62018-07-20 11:42:31 +0200504#endif
Dominik Ermelbcc17b42022-06-15 15:33:04 +0000505
Dominik Ermel5bd87442022-06-13 15:14:01 +0000506 img_size = img_size_tmp;
Dominik Ermelbcc17b42022-06-15 15:33:04 +0000507 } else if (img_chunk_off != curr_off) {
508 /* If received chunk offset does not match expected one jump, pretend
509 * success and jump to out; out will respond to client with success
510 * and request the expected offset, held by curr_off.
511 */
Christopher Collins92ea77f2016-12-12 15:59:26 -0800512 rc = 0;
513 goto out;
Dominik Ermelbcc17b42022-06-15 15:33:04 +0000514 } else if (curr_off + img_chunk_len > img_size) {
Andrzej Puzdrowskif48de7a2020-10-19 09:42:02 +0200515 rc = MGMT_ERR_EINVAL;
516 goto out;
517 }
518
Dominik Ermelbcc17b42022-06-15 15:33:04 +0000519#ifdef MCUBOOT_ERASE_PROGRESSIVELY
520 /* Progressive erase will erase enough flash, aligned to sector size,
521 * as needed for the current chunk to be written.
522 */
523 not_yet_erased = erase_range(fap, not_yet_erased,
524 curr_off + img_chunk_len - 1);
525
526 if (not_yet_erased < 0) {
527 rc = MGMT_ERR_EINVAL;
528 goto out;
529 }
530#endif
531
532 /* Writes are aligned to flash write alignment, so may drop a few bytes
533 * from the end of the buffer; we will request these bytes again with
534 * new buffer by responding with request for offset after the last aligned
535 * write.
536 */
Dominik Ermel5bd87442022-06-13 15:14:01 +0000537 rem_bytes = img_chunk_len % flash_area_align(fap);
Dominik Ermel7d2f0bf2022-06-21 16:15:34 +0000538 img_chunk_len -= rem_bytes;
Andrzej Puzdrowskif48de7a2020-10-19 09:42:02 +0200539
Dominik Ermel7d2f0bf2022-06-21 16:15:34 +0000540 if (curr_off + img_chunk_len + rem_bytes < img_size) {
Andrzej Puzdrowskif48de7a2020-10-19 09:42:02 +0200541 rem_bytes = 0;
Fabio Utzig30f6b2a2018-03-29 16:18:53 -0300542 }
Emanuele Di Santo205c8c62018-07-20 11:42:31 +0200543
Dominik Ermel5bd87442022-06-13 15:14:01 +0000544 BOOT_LOG_INF("Writing at 0x%x until 0x%x", curr_off, curr_off + img_chunk_len);
Dominik Ermel7d2f0bf2022-06-21 16:15:34 +0000545 /* Write flash aligned chunk, note that img_chunk_len now holds aligned length */
Jamie McCrae9d3fd7f2022-11-30 15:44:44 +0000546#if defined(MCUBOOT_SERIAL_UNALIGNED_BUFFER_SIZE) && MCUBOOT_SERIAL_UNALIGNED_BUFFER_SIZE > 0
547 if (flash_area_align(fap) > 1 &&
548 (((size_t)img_chunk) & (flash_area_align(fap) - 1)) != 0) {
549 /* Buffer address incompatible with write address, use buffer to write */
550 uint8_t write_size = MCUBOOT_SERIAL_UNALIGNED_BUFFER_SIZE;
551 uint8_t wbs_aligned[MCUBOOT_SERIAL_UNALIGNED_BUFFER_SIZE];
552
553 while (img_chunk_len >= flash_area_align(fap)) {
554 if (write_size > img_chunk_len) {
555 write_size = img_chunk_len;
556 }
557
558 memset(wbs_aligned, flash_area_erased_val(fap), sizeof(wbs_aligned));
559 memcpy(wbs_aligned, img_chunk, write_size);
560
561 rc = flash_area_write(fap, curr_off, wbs_aligned, write_size);
562
563 if (rc != 0) {
564 goto out;
565 }
566
567 curr_off += write_size;
568 img_chunk += write_size;
569 img_chunk_len -= write_size;
570 }
571 } else {
572 rc = flash_area_write(fap, curr_off, img_chunk, img_chunk_len);
573 }
574#else
Dominik Ermel7d2f0bf2022-06-21 16:15:34 +0000575 rc = flash_area_write(fap, curr_off, img_chunk, img_chunk_len);
Jamie McCrae9d3fd7f2022-11-30 15:44:44 +0000576#endif
577
Dominik Ermel7d2f0bf2022-06-21 16:15:34 +0000578 if (rc == 0 && rem_bytes) {
579 /* Non-zero rem_bytes means that last chunk needs alignment; the aligned
580 * part, in the img_chunk_len - rem_bytes count bytes, has already been
581 * written by the above write, so we are left with the rem_bytes.
582 */
Andrzej Puzdrowskif48de7a2020-10-19 09:42:02 +0200583 uint8_t wbs_aligned[BOOT_MAX_ALIGN];
Andrzej Puzdrowskif48de7a2020-10-19 09:42:02 +0200584
Dominik Ermel7d2f0bf2022-06-21 16:15:34 +0000585 memset(wbs_aligned, flash_area_erased_val(fap), sizeof(wbs_aligned));
586 memcpy(wbs_aligned, img_chunk + img_chunk_len, rem_bytes);
Andrzej Puzdrowskif48de7a2020-10-19 09:42:02 +0200587
Dominik Ermel7d2f0bf2022-06-21 16:15:34 +0000588 rc = flash_area_write(fap, curr_off + img_chunk_len, wbs_aligned,
589 flash_area_align(fap));
Andrzej Puzdrowskif48de7a2020-10-19 09:42:02 +0200590 }
591
Marko Kiiskilace50ab02018-06-06 11:33:33 +0300592 if (rc == 0) {
Dominik Ermel7d2f0bf2022-06-21 16:15:34 +0000593 curr_off += img_chunk_len + rem_bytes;
Andrzej Puzdrowskic2e30cf2018-07-20 16:19:09 +0200594 if (curr_off == img_size) {
Andrzej Puzdrowski4f9c7302021-07-16 17:34:43 +0200595#ifdef MCUBOOT_ERASE_PROGRESSIVELY
Andrzej Puzdrowskic2e30cf2018-07-20 16:19:09 +0200596 /* Assure that sector for image trailer was erased. */
597 /* Check whether it was erased during previous upload. */
Dominik Ermelbcc17b42022-06-15 15:33:04 +0000598 off_t start = flash_sector_get_off(&status_sector);
599
600 if (erase_range(fap, start, start) < 0) {
601 rc = MGMT_ERR_EUNKNOWN;
602 goto out;
Andrzej Puzdrowskic2e30cf2018-07-20 16:19:09 +0200603 }
Andrzej Puzdrowskic2e30cf2018-07-20 16:19:09 +0200604#endif
Andrzej Puzdrowski4f9c7302021-07-16 17:34:43 +0200605 rc = BOOT_HOOK_CALL(boot_serial_uploaded_hook, 0, img_num, fap,
606 img_size);
607 if (rc) {
608 BOOT_LOG_ERR("Error %d post upload hook", rc);
609 goto out;
610 }
611 }
Marko Kiiskilace50ab02018-06-06 11:33:33 +0300612 } else {
613 out_invalid_data:
Christopher Collins92ea77f2016-12-12 15:59:26 -0800614 rc = MGMT_ERR_EINVAL;
Christopher Collins92ea77f2016-12-12 15:59:26 -0800615 }
Emanuele Di Santo205c8c62018-07-20 11:42:31 +0200616
Christopher Collins92ea77f2016-12-12 15:59:26 -0800617out:
Andrzej Puzdrowski8e96b832017-09-08 16:49:14 +0200618 BOOT_LOG_INF("RX: 0x%x", rc);
Øyvind Rønningstada7d34ca2022-02-28 13:47:57 +0100619 zcbor_map_start_encode(cbor_state, 10);
620 zcbor_tstr_put_lit_cast(cbor_state, "rc");
Jamie McCrae0b6d3432022-12-02 09:24:10 +0000621 zcbor_int32_put(cbor_state, rc);
Christopher Collins92ea77f2016-12-12 15:59:26 -0800622 if (rc == 0) {
Øyvind Rønningstada7d34ca2022-02-28 13:47:57 +0100623 zcbor_tstr_put_lit_cast(cbor_state, "off");
624 zcbor_uint32_put(cbor_state, curr_off);
Christopher Collins92ea77f2016-12-12 15:59:26 -0800625 }
Øyvind Rønningstada7d34ca2022-02-28 13:47:57 +0100626 zcbor_map_end_encode(cbor_state, 10);
Christopher Collins92ea77f2016-12-12 15:59:26 -0800627
628 boot_serial_output();
629 flash_area_close(fap);
Wouter Cappelle953a7612021-05-03 16:53:05 +0200630
631#ifdef MCUBOOT_ENC_IMAGES
632 if (curr_off == img_size) {
633 /* Last sector received, now start a decryption on the image if it is encrypted*/
634 rc = boot_handle_enc_fw();
635 }
636#endif //#ifdef MCUBOOT_ENC_IMAGES
Christopher Collins92ea77f2016-12-12 15:59:26 -0800637}
638
Dominik Ermel4c0f6c12022-03-04 15:47:37 +0000639/*
640 * Send rc code only.
641 */
642static void
643bs_rc_rsp(int rc_code)
644{
Øyvind Rønningstada7d34ca2022-02-28 13:47:57 +0100645 zcbor_map_start_encode(cbor_state, 10);
646 zcbor_tstr_put_lit_cast(cbor_state, "rc");
Jamie McCrae0b6d3432022-12-02 09:24:10 +0000647 zcbor_int32_put(cbor_state, rc_code);
Øyvind Rønningstada7d34ca2022-02-28 13:47:57 +0100648 zcbor_map_end_encode(cbor_state, 10);
Dominik Ermel4c0f6c12022-03-04 15:47:37 +0000649 boot_serial_output();
650}
651
652
Wouter Cappellee3ff1752021-05-03 16:36:22 +0200653#ifdef MCUBOOT_BOOT_MGMT_ECHO
Wouter Cappellee3ff1752021-05-03 16:36:22 +0200654static void
655bs_echo(char *buf, int len)
656{
Dominik Ermel88bd5672022-06-07 15:17:06 +0000657 struct Echo echo = { 0 };
658 size_t decoded_len;
659 uint32_t rc = MGMT_ERR_EINVAL;
660 uint_fast8_t result = cbor_decode_Echo((const uint8_t *)buf, len, &echo, &decoded_len);
Wouter Cappellee3ff1752021-05-03 16:36:22 +0200661
Dominik Ermel88bd5672022-06-07 15:17:06 +0000662 if ((result != ZCBOR_SUCCESS) || (len != decoded_len)) {
663 goto out;
Wouter Cappellee3ff1752021-05-03 16:36:22 +0200664 }
Dominik Ermel88bd5672022-06-07 15:17:06 +0000665
666 if (echo._Echo_d.value == NULL) {
667 goto out;
668 }
669
670 zcbor_map_start_encode(cbor_state, 10);
671 zcbor_tstr_put_term(cbor_state, "r");
672 if (zcbor_tstr_encode(cbor_state, &echo._Echo_d) && zcbor_map_end_encode(cbor_state, 10)) {
673 boot_serial_output();
674 return;
675 } else {
676 rc = MGMT_ERR_ENOMEM;
677 }
678
679out:
680 reset_cbor_state();
681 bs_rc_rsp(rc);
Wouter Cappellee3ff1752021-05-03 16:36:22 +0200682}
683#endif
684
Christopher Collins92ea77f2016-12-12 15:59:26 -0800685/*
Christopher Collins92ea77f2016-12-12 15:59:26 -0800686 * Reset, and (presumably) boot to newly uploaded image. Flush console
687 * before restarting.
688 */
Andrzej Puzdrowski268cdd02018-04-10 12:57:54 +0200689static void
Christopher Collins92ea77f2016-12-12 15:59:26 -0800690bs_reset(char *buf, int len)
691{
Dominik Ermelb26fc482022-12-09 17:10:20 +0000692 int rc = BOOT_HOOK_CALL(boot_reset_request_hook, 0, false);
693 if (rc == BOOT_RESET_REQUEST_HOOK_BUSY) {
694 rc = MGMT_ERR_EBUSY;
695 } else {
696 /* Currently whatever else is returned it is just converted
697 * to 0/no error. Boot serial starts accepting "force" parameter
698 * in command this needs to change.
699 */
700 rc = 0;
701 }
702 bs_rc_rsp(rc);
Christopher Collins92ea77f2016-12-12 15:59:26 -0800703
Dominik Ermelb26fc482022-12-09 17:10:20 +0000704 if (rc == 0) {
Andrzej Puzdrowski8e96b832017-09-08 16:49:14 +0200705#ifdef __ZEPHYR__
Andrzej Puzdrowski0cf0dbd2021-05-14 11:55:57 +0200706#ifdef CONFIG_MULTITHREADING
Dominik Ermelb26fc482022-12-09 17:10:20 +0000707 k_sleep(K_MSEC(250));
Andrzej Puzdrowski0cf0dbd2021-05-14 11:55:57 +0200708#else
Dominik Ermelb26fc482022-12-09 17:10:20 +0000709 k_busy_wait(250000);
Andrzej Puzdrowski0cf0dbd2021-05-14 11:55:57 +0200710#endif
Dominik Ermelb26fc482022-12-09 17:10:20 +0000711 sys_reboot(SYS_REBOOT_COLD);
Almir Okatoe8cbc0d2022-06-13 10:45:39 -0300712#elif __ESPRESSIF__
Dominik Ermelb26fc482022-12-09 17:10:20 +0000713 esp_rom_delay_us(250000);
714 bootloader_reset();
Andrzej Puzdrowski8e96b832017-09-08 16:49:14 +0200715#else
Dominik Ermelb26fc482022-12-09 17:10:20 +0000716 os_cputime_delay_usecs(250000);
717 hal_system_reset();
Andrzej Puzdrowski8e96b832017-09-08 16:49:14 +0200718#endif
Dominik Ermelb26fc482022-12-09 17:10:20 +0000719 }
Christopher Collins92ea77f2016-12-12 15:59:26 -0800720}
721
722/*
723 * Parse incoming line of input from console.
724 * Expect newtmgr protocol with serial transport.
725 */
726void
727boot_serial_input(char *buf, int len)
728{
729 struct nmgr_hdr *hdr;
730
731 hdr = (struct nmgr_hdr *)buf;
732 if (len < sizeof(*hdr) ||
733 (hdr->nh_op != NMGR_OP_READ && hdr->nh_op != NMGR_OP_WRITE) ||
734 (ntohs(hdr->nh_len) < len - sizeof(*hdr))) {
735 return;
736 }
737 bs_hdr = hdr;
738 hdr->nh_group = ntohs(hdr->nh_group);
739
740 buf += sizeof(*hdr);
741 len -= sizeof(*hdr);
Marko Kiiskilace50ab02018-06-06 11:33:33 +0300742
Dominik Ermel4c0f6c12022-03-04 15:47:37 +0000743 reset_cbor_state();
Christopher Collins92ea77f2016-12-12 15:59:26 -0800744
745 /*
746 * Limited support for commands.
747 */
748 if (hdr->nh_group == MGMT_GROUP_ID_IMAGE) {
749 switch (hdr->nh_id) {
Marko Kiiskilace50ab02018-06-06 11:33:33 +0300750 case IMGMGR_NMGR_ID_STATE:
Christopher Collins92ea77f2016-12-12 15:59:26 -0800751 bs_list(buf, len);
752 break;
Marko Kiiskilace50ab02018-06-06 11:33:33 +0300753 case IMGMGR_NMGR_ID_UPLOAD:
Christopher Collins92ea77f2016-12-12 15:59:26 -0800754 bs_upload(buf, len);
755 break;
756 default:
Dominik Ermelc9dc2242021-07-28 17:08:23 +0000757 bs_rc_rsp(MGMT_ERR_ENOTSUP);
Christopher Collins92ea77f2016-12-12 15:59:26 -0800758 break;
759 }
760 } else if (hdr->nh_group == MGMT_GROUP_ID_DEFAULT) {
761 switch (hdr->nh_id) {
Wouter Cappellee3ff1752021-05-03 16:36:22 +0200762 case NMGR_ID_ECHO:
763#ifdef MCUBOOT_BOOT_MGMT_ECHO
764 bs_echo(buf, len);
765#endif
766 break;
Christopher Collins92ea77f2016-12-12 15:59:26 -0800767 case NMGR_ID_CONS_ECHO_CTRL:
Dominik Ermelc9dc2242021-07-28 17:08:23 +0000768 bs_rc_rsp(0);
Christopher Collins92ea77f2016-12-12 15:59:26 -0800769 break;
770 case NMGR_ID_RESET:
771 bs_reset(buf, len);
772 break;
773 default:
Dominik Ermelc9dc2242021-07-28 17:08:23 +0000774 bs_rc_rsp(MGMT_ERR_ENOTSUP);
Christopher Collins92ea77f2016-12-12 15:59:26 -0800775 break;
776 }
Dominik Ermelbd69c3d2021-07-28 11:27:31 +0000777 } else if (MCUBOOT_PERUSER_MGMT_GROUP_ENABLED == 1) {
Øyvind Rønningstada7d34ca2022-02-28 13:47:57 +0100778 if (bs_peruser_system_specific(hdr, buf, len, cbor_state) == 0) {
Dominik Ermel3d51e432021-06-25 17:29:50 +0000779 boot_serial_output();
780 }
Dominik Ermelc9dc2242021-07-28 17:08:23 +0000781 } else {
782 bs_rc_rsp(MGMT_ERR_ENOTSUP);
Christopher Collins92ea77f2016-12-12 15:59:26 -0800783 }
Wouter Cappellee3822f82022-01-19 15:39:43 +0100784#ifdef MCUBOOT_SERIAL_WAIT_FOR_DFU
785 bs_entry = true;
786#endif
Christopher Collins92ea77f2016-12-12 15:59:26 -0800787}
788
789static void
790boot_serial_output(void)
791{
792 char *data;
Piotr Dymaczf5e77532022-10-30 17:43:45 +0100793 int len, out;
Christopher Collins92ea77f2016-12-12 15:59:26 -0800794 uint16_t crc;
795 uint16_t totlen;
Piotr Dymaczf5e77532022-10-30 17:43:45 +0100796 char pkt_cont[2] = { SHELL_NLIP_DATA_START1, SHELL_NLIP_DATA_START2 };
Christopher Collins92ea77f2016-12-12 15:59:26 -0800797 char pkt_start[2] = { SHELL_NLIP_PKT_START1, SHELL_NLIP_PKT_START2 };
Dominik Ermel5ff89582022-03-03 17:09:07 +0000798 char buf[BOOT_SERIAL_OUT_MAX + sizeof(*bs_hdr) + sizeof(crc) + sizeof(totlen)];
799 char encoded_buf[BASE64_ENCODE_SIZE(sizeof(buf))];
Christopher Collins92ea77f2016-12-12 15:59:26 -0800800
801 data = bs_obuf;
Øyvind Rønningstada7d34ca2022-02-28 13:47:57 +0100802 len = (uint32_t)cbor_state->payload_mut - (uint32_t)bs_obuf;
Christopher Collins92ea77f2016-12-12 15:59:26 -0800803
804 bs_hdr->nh_op++;
Marko Kiiskilace50ab02018-06-06 11:33:33 +0300805 bs_hdr->nh_flags = 0;
Christopher Collins92ea77f2016-12-12 15:59:26 -0800806 bs_hdr->nh_len = htons(len);
807 bs_hdr->nh_group = htons(bs_hdr->nh_group);
808
Andrzej Puzdrowski8e96b832017-09-08 16:49:14 +0200809#ifdef __ZEPHYR__
Carles Cufib9192a42022-02-10 11:41:57 +0100810 crc = crc16_itu_t(CRC16_INITIAL_CRC, (uint8_t *)bs_hdr, sizeof(*bs_hdr));
811 crc = crc16_itu_t(crc, data, len);
Almir Okatoe8cbc0d2022-06-13 10:45:39 -0300812#elif __ESPRESSIF__
813 /* For ESP32 it was used the CRC API in rom/crc.h */
Almir Okato7d3622f2022-10-20 12:44:58 -0300814 crc = ~esp_crc16_be(~CRC16_INITIAL_CRC, (uint8_t *)bs_hdr, sizeof(*bs_hdr));
815 crc = ~esp_crc16_be(~crc, (uint8_t *)data, len);
Andrzej Puzdrowski8e96b832017-09-08 16:49:14 +0200816#else
Christopher Collins92ea77f2016-12-12 15:59:26 -0800817 crc = crc16_ccitt(CRC16_INITIAL_CRC, bs_hdr, sizeof(*bs_hdr));
818 crc = crc16_ccitt(crc, data, len);
Andrzej Puzdrowski8e96b832017-09-08 16:49:14 +0200819#endif
Christopher Collins92ea77f2016-12-12 15:59:26 -0800820 crc = htons(crc);
821
Christopher Collins92ea77f2016-12-12 15:59:26 -0800822 totlen = len + sizeof(*bs_hdr) + sizeof(crc);
823 totlen = htons(totlen);
824
825 memcpy(buf, &totlen, sizeof(totlen));
826 totlen = sizeof(totlen);
827 memcpy(&buf[totlen], bs_hdr, sizeof(*bs_hdr));
828 totlen += sizeof(*bs_hdr);
829 memcpy(&buf[totlen], data, len);
830 totlen += len;
831 memcpy(&buf[totlen], &crc, sizeof(crc));
832 totlen += sizeof(crc);
Andrzej Puzdrowski8e96b832017-09-08 16:49:14 +0200833#ifdef __ZEPHYR__
834 size_t enc_len;
Carles Cufi0165be82018-03-26 17:43:51 +0200835 base64_encode(encoded_buf, sizeof(encoded_buf), &enc_len, buf, totlen);
Andrzej Puzdrowski8e96b832017-09-08 16:49:14 +0200836 totlen = enc_len;
Almir Okatoe8cbc0d2022-06-13 10:45:39 -0300837#elif __ESPRESSIF__
838 size_t enc_len;
839 base64_encode((unsigned char *)encoded_buf, sizeof(encoded_buf), &enc_len, (unsigned char *)buf, totlen);
840 totlen = enc_len;
Andrzej Puzdrowski8e96b832017-09-08 16:49:14 +0200841#else
Christopher Collins92ea77f2016-12-12 15:59:26 -0800842 totlen = base64_encode(buf, totlen, encoded_buf, 1);
Andrzej Puzdrowski8e96b832017-09-08 16:49:14 +0200843#endif
Piotr Dymaczf5e77532022-10-30 17:43:45 +0100844
845 out = 0;
846 while (out < totlen) {
847 if (out == 0) {
848 boot_uf->write(pkt_start, sizeof(pkt_start));
849 } else {
850 boot_uf->write(pkt_cont, sizeof(pkt_cont));
851 }
852
853 len = MIN(BOOT_SERIAL_FRAME_MTU, totlen - out);
854 boot_uf->write(&encoded_buf[out], len);
855
856 out += len;
857
858 boot_uf->write("\n", 1);
859 }
860
Andrzej Puzdrowski8e96b832017-09-08 16:49:14 +0200861 BOOT_LOG_INF("TX");
Christopher Collins92ea77f2016-12-12 15:59:26 -0800862}
863
864/*
865 * Returns 1 if full packet has been received.
866 */
867static int
868boot_serial_in_dec(char *in, int inlen, char *out, int *out_off, int maxout)
869{
870 int rc;
871 uint16_t crc;
872 uint16_t len;
Marko Kiiskilae5aeee42018-12-21 15:00:16 +0200873
Andrzej Puzdrowski8e96b832017-09-08 16:49:14 +0200874#ifdef __ZEPHYR__
875 int err;
Andrzej Puzdrowskiec1e4d12018-06-18 14:36:14 +0200876 err = base64_decode( &out[*out_off], maxout - *out_off, &rc, in, inlen - 2);
Andrzej Puzdrowski8e96b832017-09-08 16:49:14 +0200877 if (err) {
878 return -1;
879 }
Almir Okatoe8cbc0d2022-06-13 10:45:39 -0300880#elif __ESPRESSIF__
881 int err;
882 err = base64_decode((unsigned char *)&out[*out_off], maxout - *out_off, (size_t *)&rc, (unsigned char *)in, inlen);
883 if (err) {
884 return -1;
885 }
Andrzej Puzdrowski8e96b832017-09-08 16:49:14 +0200886#else
Christopher Collins92ea77f2016-12-12 15:59:26 -0800887 if (*out_off + base64_decode_len(in) >= maxout) {
888 return -1;
889 }
890 rc = base64_decode(in, &out[*out_off]);
891 if (rc < 0) {
892 return -1;
893 }
Andrzej Puzdrowski8e96b832017-09-08 16:49:14 +0200894#endif
Fabio Utzig6f49c272019-08-23 11:42:58 -0300895
Christopher Collins92ea77f2016-12-12 15:59:26 -0800896 *out_off += rc;
Fabio Utzig6f49c272019-08-23 11:42:58 -0300897 if (*out_off <= sizeof(uint16_t)) {
898 return 0;
Christopher Collins92ea77f2016-12-12 15:59:26 -0800899 }
Fabio Utzig6f49c272019-08-23 11:42:58 -0300900
901 len = ntohs(*(uint16_t *)out);
902 if (len != *out_off - sizeof(uint16_t)) {
903 return 0;
904 }
905
906 if (len > *out_off - sizeof(uint16_t)) {
907 len = *out_off - sizeof(uint16_t);
908 }
909
910 out += sizeof(uint16_t);
911#ifdef __ZEPHYR__
Carles Cufib9192a42022-02-10 11:41:57 +0100912 crc = crc16_itu_t(CRC16_INITIAL_CRC, out, len);
Almir Okatoe8cbc0d2022-06-13 10:45:39 -0300913#elif __ESPRESSIF__
Almir Okato7d3622f2022-10-20 12:44:58 -0300914 crc = ~esp_crc16_be(~CRC16_INITIAL_CRC, (uint8_t *)out, len);
Fabio Utzig6f49c272019-08-23 11:42:58 -0300915#else
916 crc = crc16_ccitt(CRC16_INITIAL_CRC, out, len);
917#endif
918 if (crc || len <= sizeof(crc)) {
919 return 0;
920 }
921 *out_off -= sizeof(crc);
922 out[*out_off] = '\0';
923
924 return 1;
Christopher Collins92ea77f2016-12-12 15:59:26 -0800925}
926
927/*
928 * Task which waits reading console, expecting to get image over
929 * serial port.
930 */
Wouter Cappellee3822f82022-01-19 15:39:43 +0100931static void
932boot_serial_read_console(const struct boot_uart_funcs *f,int timeout_in_ms)
Christopher Collins92ea77f2016-12-12 15:59:26 -0800933{
934 int rc;
935 int off;
David Brown57f0df32020-05-12 08:39:21 -0600936 int dec_off = 0;
Christopher Collins92ea77f2016-12-12 15:59:26 -0800937 int full_line;
Marko Kiiskila149b4572018-06-06 14:18:54 +0300938 int max_input;
Wouter Cappellee3822f82022-01-19 15:39:43 +0100939 int elapsed_in_ms = 0;
Christopher Collins92ea77f2016-12-12 15:59:26 -0800940
Marko Kiiskila149b4572018-06-06 14:18:54 +0300941 boot_uf = f;
Marko Kiiskila149b4572018-06-06 14:18:54 +0300942 max_input = sizeof(in_buf);
Christopher Collins92ea77f2016-12-12 15:59:26 -0800943
944 off = 0;
Wouter Cappellee3822f82022-01-19 15:39:43 +0100945 while (timeout_in_ms > 0 || bs_entry) {
Piotr Dymacz067f30a2022-08-12 18:25:34 +0200946 /*
947 * Don't enter CPU idle state here if timeout based serial recovery is
948 * used as otherwise the boot process hangs forever, waiting for input
949 * from serial console (if single-thread mode is used).
950 */
Piotr Dymacz3942e9b2022-07-18 10:19:25 +0200951#ifndef MCUBOOT_SERIAL_WAIT_FOR_DFU
Andrzej Puzdrowskiaea38eb2021-06-11 12:28:59 +0200952 MCUBOOT_CPU_IDLE();
Piotr Dymacz3942e9b2022-07-18 10:19:25 +0200953#endif
Hein Wessels56d28f02021-11-19 08:42:08 +0100954 MCUBOOT_WATCHDOG_FEED();
Wouter Cappellee3822f82022-01-19 15:39:43 +0100955#ifdef MCUBOOT_SERIAL_WAIT_FOR_DFU
956 uint32_t start = k_uptime_get_32();
957#endif
Andrzej Puzdrowskiec1e4d12018-06-18 14:36:14 +0200958 rc = f->read(in_buf + off, sizeof(in_buf) - off, &full_line);
Christopher Collins92ea77f2016-12-12 15:59:26 -0800959 if (rc <= 0 && !full_line) {
Wouter Cappellee3822f82022-01-19 15:39:43 +0100960 goto check_timeout;
Christopher Collins92ea77f2016-12-12 15:59:26 -0800961 }
962 off += rc;
963 if (!full_line) {
Marko Kiiskilace50ab02018-06-06 11:33:33 +0300964 if (off == max_input) {
965 /*
966 * Full line, no newline yet. Reset the input buffer.
967 */
968 off = 0;
969 }
Wouter Cappellee3822f82022-01-19 15:39:43 +0100970 goto check_timeout;
Christopher Collins92ea77f2016-12-12 15:59:26 -0800971 }
Andrzej Puzdrowskiec1e4d12018-06-18 14:36:14 +0200972 if (in_buf[0] == SHELL_NLIP_PKT_START1 &&
973 in_buf[1] == SHELL_NLIP_PKT_START2) {
Christopher Collins92ea77f2016-12-12 15:59:26 -0800974 dec_off = 0;
Andrzej Puzdrowskiec1e4d12018-06-18 14:36:14 +0200975 rc = boot_serial_in_dec(&in_buf[2], off - 2, dec_buf, &dec_off, max_input);
976 } else if (in_buf[0] == SHELL_NLIP_DATA_START1 &&
977 in_buf[1] == SHELL_NLIP_DATA_START2) {
978 rc = boot_serial_in_dec(&in_buf[2], off - 2, dec_buf, &dec_off, max_input);
Christopher Collins92ea77f2016-12-12 15:59:26 -0800979 }
Andrzej Puzdrowskiec1e4d12018-06-18 14:36:14 +0200980
981 /* serve errors: out of decode memory, or bad encoding */
Christopher Collins92ea77f2016-12-12 15:59:26 -0800982 if (rc == 1) {
Andrzej Puzdrowskiec1e4d12018-06-18 14:36:14 +0200983 boot_serial_input(&dec_buf[2], dec_off - 2);
Christopher Collins92ea77f2016-12-12 15:59:26 -0800984 }
985 off = 0;
Wouter Cappellee3822f82022-01-19 15:39:43 +0100986check_timeout:
987 /* Subtract elapsed time */
988#ifdef MCUBOOT_SERIAL_WAIT_FOR_DFU
989 elapsed_in_ms = (k_uptime_get_32() - start);
990#endif
991 timeout_in_ms -= elapsed_in_ms;
Christopher Collins92ea77f2016-12-12 15:59:26 -0800992 }
993}
Wouter Cappellee3822f82022-01-19 15:39:43 +0100994
995/*
996 * Task which waits reading console, expecting to get image over
997 * serial port.
998 */
999void
1000boot_serial_start(const struct boot_uart_funcs *f)
1001{
1002 bs_entry = true;
1003 boot_serial_read_console(f,0);
1004}
1005
1006#ifdef MCUBOOT_SERIAL_WAIT_FOR_DFU
1007/*
1008 * Task which waits reading console for a certain amount of timeout.
1009 * If within this timeout no mcumgr command is received, the function is
1010 * returning, else the serial boot is never exited
1011 */
1012void
1013boot_serial_check_start(const struct boot_uart_funcs *f, int timeout_in_ms)
1014{
1015 bs_entry = false;
1016 boot_serial_read_console(f,timeout_in_ms);
1017}
1018#endif
Jamie McCrae827118f2023-03-10 13:24:57 +00001019
1020#ifdef MCUBOOT_SERIAL_IMG_GRP_HASH
1021/* Function to find the hash of an image, returns 0 on success. */
1022static int boot_serial_get_hash(const struct image_header *hdr,
1023 const struct flash_area *fap, uint8_t *hash)
1024{
1025 struct image_tlv_iter it;
1026 uint32_t offset;
1027 uint16_t len;
1028 uint16_t type;
1029 int rc;
1030
1031 /* Manifest data is concatenated to the end of the image.
1032 * It is encoded in TLV format.
1033 */
1034 rc = bootutil_tlv_iter_begin(&it, hdr, fap, IMAGE_TLV_ANY, false);
1035 if (rc) {
1036 return -1;
1037 }
1038
1039 /* Traverse through the TLV area to find the image hash TLV. */
1040 while (true) {
1041 rc = bootutil_tlv_iter_next(&it, &offset, &len, &type);
1042 if (rc < 0) {
1043 return -1;
1044 } else if (rc > 0) {
1045 break;
1046 }
1047
1048 if (type == IMAGE_TLV_SHA256) {
1049 /* Get the image's hash value from the manifest section. */
1050 if (len != 32) {
1051 return -1;
1052 }
1053
1054 rc = flash_area_read(fap, offset, hash, len);
1055 if (rc) {
1056 return -1;
1057 }
1058
1059 return 0;
1060 }
1061 }
1062
1063 return -1;
1064}
1065#endif