blob: 5f83ed27506bc0eb6dc3c62d2ce2491f05fcfe0a [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"
29
Andrzej Puzdrowski8e96b832017-09-08 16:49:14 +020030#ifdef __ZEPHYR__
Fabio Baltieri888e2612022-07-19 20:54:26 +000031#include <zephyr/sys/reboot.h>
32#include <zephyr/sys/byteorder.h>
33#include <zephyr/sys/__assert.h>
34#include <zephyr/drivers/flash.h>
Gerard Marull-Paretas4eca54f2022-10-06 11:45:11 +020035#include <zephyr/kernel.h>
Fabio Baltieri888e2612022-07-19 20:54:26 +000036#include <zephyr/sys/crc.h>
37#include <zephyr/sys/base64.h>
Almir Okatoe8cbc0d2022-06-13 10:45:39 -030038#include <hal/hal_flash.h>
39#elif __ESPRESSIF__
40#include <bootloader_utility.h>
41#include <esp_rom_sys.h>
Almir Okato7d3622f2022-10-20 12:44:58 -030042#include <esp_crc.h>
Almir Okatoe8cbc0d2022-06-13 10:45:39 -030043#include <endian.h>
44#include <mbedtls/base64.h>
Andrzej Puzdrowski8e96b832017-09-08 16:49:14 +020045#else
Christopher Collins92ea77f2016-12-12 15:59:26 -080046#include <bsp/bsp.h>
Christopher Collins92ea77f2016-12-12 15:59:26 -080047#include <hal/hal_system.h>
Almir Okatoe8cbc0d2022-06-13 10:45:39 -030048#include <hal/hal_flash.h>
Christopher Collins92ea77f2016-12-12 15:59:26 -080049#include <os/endian.h>
Christopher Collins92ea77f2016-12-12 15:59:26 -080050#include <os/os_cputime.h>
Andrzej Puzdrowski8e96b832017-09-08 16:49:14 +020051#include <crc/crc16.h>
52#include <base64/base64.h>
Andrzej Puzdrowski386b5922018-04-06 19:26:24 +020053#endif /* __ZEPHYR__ */
54
Jamie McCraecb07e882023-04-14 09:28:24 +010055#include <zcbor_decode.h>
56#include <zcbor_encode.h>
57#include "zcbor_bulk.h"
58
Andrzej Puzdrowskib788c712018-04-12 12:42:49 +020059#include <flash_map_backend/flash_map_backend.h>
Andrzej Puzdrowski8e96b832017-09-08 16:49:14 +020060#include <os/os.h>
61#include <os/os_malloc.h>
Christopher Collins92ea77f2016-12-12 15:59:26 -080062
63#include <bootutil/image.h>
Andrzej Puzdrowskif48de7a2020-10-19 09:42:02 +020064#include <bootutil/bootutil.h>
Christopher Collins92ea77f2016-12-12 15:59:26 -080065
66#include "boot_serial/boot_serial.h"
67#include "boot_serial_priv.h"
Almir Okatoe8cbc0d2022-06-13 10:45:39 -030068#include "mcuboot_config/mcuboot_config.h"
Christopher Collins92ea77f2016-12-12 15:59:26 -080069
Dominik Ermel3d4e55d2021-07-09 11:14:10 +000070#ifdef MCUBOOT_ERASE_PROGRESSIVELY
Andrzej Puzdrowskic2e30cf2018-07-20 16:19:09 +020071#include "bootutil_priv.h"
72#endif
73
Wouter Cappelle953a7612021-05-03 16:53:05 +020074#ifdef MCUBOOT_ENC_IMAGES
75#include "single_loader.h"
76#endif
77
Andrzej Puzdrowski4f9c7302021-07-16 17:34:43 +020078#include "bootutil/boot_hooks.h"
Øyvind Rønningstadf42a8202019-12-13 03:27:54 +010079
Carlos Falgueras Garcíaa4b4b0f2021-06-22 10:00:22 +020080BOOT_LOG_MODULE_DECLARE(mcuboot);
Emanuele Di Santo9f1933d2018-11-20 10:59:59 +010081
Jamie McCraecb07e882023-04-14 09:28:24 +010082#ifndef ARRAY_SIZE
83#define ARRAY_SIZE ZCBOR_ARRAY_SIZE
84#endif
85
Jamie McCraead1fb3d2022-12-01 14:24:37 +000086#ifndef MCUBOOT_SERIAL_MAX_RECEIVE_SIZE
87#define MCUBOOT_SERIAL_MAX_RECEIVE_SIZE 512
88#endif
89
Jamie McCrae827118f2023-03-10 13:24:57 +000090#define BOOT_SERIAL_OUT_MAX (160 * BOOT_IMAGE_NUMBER)
Piotr Dymaczf5e77532022-10-30 17:43:45 +010091#define BOOT_SERIAL_FRAME_MTU 124 /* 127 - pkt start (2 bytes) and stop (1 byte) */
Christopher Collins92ea77f2016-12-12 15:59:26 -080092
Andrzej Puzdrowski8e96b832017-09-08 16:49:14 +020093#ifdef __ZEPHYR__
Carles Cufi0165be82018-03-26 17:43:51 +020094/* base64 lib encodes data to null-terminated string */
Andrzej Puzdrowski8e96b832017-09-08 16:49:14 +020095#define BASE64_ENCODE_SIZE(in_size) ((((((in_size) - 1) / 3) * 4) + 4) + 1)
96
97#define CRC16_INITIAL_CRC 0 /* what to seed crc16 with */
98#define CRC_CITT_POLYMINAL 0x1021
99
100#define ntohs(x) sys_be16_to_cpu(x)
101#define htons(x) sys_cpu_to_be16(x)
Almir Okatoe8cbc0d2022-06-13 10:45:39 -0300102#elif __ESPRESSIF__
103#define BASE64_ENCODE_SIZE(in_size) ((((((in_size) - 1) / 3) * 4) + 4) + 1)
104#define CRC16_INITIAL_CRC 0 /* what to seed crc16 with */
105
106#define ntohs(x) be16toh(x)
107#define htons(x) htobe16(x)
108
109#define base64_decode mbedtls_base64_decode
110#define base64_encode mbedtls_base64_encode
Andrzej Puzdrowski8e96b832017-09-08 16:49:14 +0200111#endif
Emanuele Di Santo9f1933d2018-11-20 10:59:59 +0100112
Fabio Utzig6f49c272019-08-23 11:42:58 -0300113#if (BOOT_IMAGE_NUMBER > 1)
114#define IMAGES_ITER(x) for ((x) = 0; (x) < BOOT_IMAGE_NUMBER; ++(x))
115#else
116#define IMAGES_ITER(x)
117#endif
118
Jamie McCraead1fb3d2022-12-01 14:24:37 +0000119static char in_buf[MCUBOOT_SERIAL_MAX_RECEIVE_SIZE + 1];
120static char dec_buf[MCUBOOT_SERIAL_MAX_RECEIVE_SIZE + 1];
Marko Kiiskila8b1ce3a2018-06-14 13:20:46 -0700121const struct boot_uart_funcs *boot_uf;
Christopher Collins92ea77f2016-12-12 15:59:26 -0800122static struct nmgr_hdr *bs_hdr;
Wouter Cappellee3822f82022-01-19 15:39:43 +0100123static bool bs_entry;
Christopher Collins92ea77f2016-12-12 15:59:26 -0800124
125static char bs_obuf[BOOT_SERIAL_OUT_MAX];
126
Christopher Collins92ea77f2016-12-12 15:59:26 -0800127static void boot_serial_output(void);
128
Jamie McCrae827118f2023-03-10 13:24:57 +0000129#ifdef MCUBOOT_SERIAL_IMG_GRP_HASH
130static int boot_serial_get_hash(const struct image_header *hdr,
131 const struct flash_area *fap, uint8_t *hash);
132#endif
133
Øyvind Rønningstada7d34ca2022-02-28 13:47:57 +0100134static zcbor_state_t cbor_state[2];
Christopher Collins92ea77f2016-12-12 15:59:26 -0800135
Dominik Ermel4c0f6c12022-03-04 15:47:37 +0000136void reset_cbor_state(void)
137{
Øyvind Rønningstada7d34ca2022-02-28 13:47:57 +0100138 zcbor_new_encode_state(cbor_state, 2, (uint8_t *)bs_obuf,
139 (size_t)bs_obuf + sizeof(bs_obuf), 0);
Dominik Ermel4c0f6c12022-03-04 15:47:37 +0000140}
141
Dominik Ermel3d51e432021-06-25 17:29:50 +0000142/**
Dominik Ermelbd69c3d2021-07-28 11:27:31 +0000143 * Function that processes MGMT_GROUP_ID_PERUSER mcumgr group and may be
144 * used to process any groups that have not been processed by generic boot
145 * serial implementation.
Dominik Ermel3d51e432021-06-25 17:29:50 +0000146 *
147 * @param[in] hdr -- the decoded header of mcumgr message;
148 * @param[in] buffer -- buffer with first mcumgr message;
149 * @param[in] len -- length of of data in buffer;
150 * @param[out] *cs -- object with encoded response.
151 *
152 * @return 0 on success; non-0 error code otherwise.
153 */
154extern int bs_peruser_system_specific(const struct nmgr_hdr *hdr,
155 const char *buffer,
Øyvind Rønningstada7d34ca2022-02-28 13:47:57 +0100156 int len, zcbor_state_t *cs);
Christopher Collins92ea77f2016-12-12 15:59:26 -0800157
Dominik Ermeld49cfc12022-06-09 08:24:48 +0000158#define zcbor_tstr_put_lit_cast(state, string) \
Jamie McCrae393af792023-04-14 11:31:16 +0100159 zcbor_tstr_encode_ptr(state, (char *)string, sizeof(string) - 1)
Dominik Ermeld49cfc12022-06-09 08:24:48 +0000160
161#ifndef MCUBOOT_USE_SNPRINTF
Christopher Collins92ea77f2016-12-12 15:59:26 -0800162/*
Marko Kiiskilace50ab02018-06-06 11:33:33 +0300163 * Convert version into string without use of snprintf().
Christopher Collins92ea77f2016-12-12 15:59:26 -0800164 */
Marko Kiiskilace50ab02018-06-06 11:33:33 +0300165static int
166u32toa(char *tgt, uint32_t val)
Christopher Collins92ea77f2016-12-12 15:59:26 -0800167{
Marko Kiiskilace50ab02018-06-06 11:33:33 +0300168 char *dst;
169 uint32_t d = 1;
170 uint32_t dgt;
171 int n = 0;
Christopher Collins92ea77f2016-12-12 15:59:26 -0800172
Marko Kiiskilace50ab02018-06-06 11:33:33 +0300173 dst = tgt;
174 while (val / d >= 10) {
175 d *= 10;
Christopher Collins92ea77f2016-12-12 15:59:26 -0800176 }
Marko Kiiskilace50ab02018-06-06 11:33:33 +0300177 while (d) {
178 dgt = val / d;
179 val %= d;
180 d /= 10;
181 if (n || dgt > 0 || d == 0) {
182 *dst++ = dgt + '0';
183 ++n;
Christopher Collins92ea77f2016-12-12 15:59:26 -0800184 }
Christopher Collins92ea77f2016-12-12 15:59:26 -0800185 }
Marko Kiiskilace50ab02018-06-06 11:33:33 +0300186 *dst = '\0';
187
188 return dst - tgt;
189}
190
191/*
192 * dst has to be able to fit "255.255.65535.4294967295" (25 characters).
193 */
194static void
195bs_list_img_ver(char *dst, int maxlen, struct image_version *ver)
196{
197 int off;
198
199 off = u32toa(dst, ver->iv_major);
200 dst[off++] = '.';
201 off += u32toa(dst + off, ver->iv_minor);
202 dst[off++] = '.';
203 off += u32toa(dst + off, ver->iv_revision);
Jamie McCraee5c57dd2023-03-21 14:45:21 +0000204
205 if (ver->iv_build_num != 0) {
206 dst[off++] = '.';
207 off += u32toa(dst + off, ver->iv_build_num);
208 }
Christopher Collins92ea77f2016-12-12 15:59:26 -0800209}
Dominik Ermeld49cfc12022-06-09 08:24:48 +0000210#else
211/*
212 * dst has to be able to fit "255.255.65535.4294967295" (25 characters).
213 */
214static void
215bs_list_img_ver(char *dst, int maxlen, struct image_version *ver)
216{
Jamie McCraee5c57dd2023-03-21 14:45:21 +0000217 int len;
218
219 len = snprintf(dst, maxlen, "%hu.%hu.%hu", (uint16_t)ver->iv_major,
220 (uint16_t)ver->iv_minor, ver->iv_revision);
221
222 if (ver->iv_build_num != 0 && len > 0 && len < maxlen) {
223 snprintf(&dst[len], (maxlen - len), "%u", ver->iv_build_num);
224 }
Dominik Ermeld49cfc12022-06-09 08:24:48 +0000225}
226#endif /* !MCUBOOT_USE_SNPRINTF */
Christopher Collins92ea77f2016-12-12 15:59:26 -0800227
228/*
229 * List images.
230 */
231static void
232bs_list(char *buf, int len)
233{
Christopher Collins92ea77f2016-12-12 15:59:26 -0800234 struct image_header hdr;
235 uint8_t tmpbuf[64];
Øyvind Rønningstad9f4aefd2021-03-08 21:11:25 +0100236 uint32_t slot, area_id;
Christopher Collins92ea77f2016-12-12 15:59:26 -0800237 const struct flash_area *fap;
Fabio Utzig6f49c272019-08-23 11:42:58 -0300238 uint8_t image_index;
Jamie McCrae827118f2023-03-10 13:24:57 +0000239#ifdef MCUBOOT_SERIAL_IMG_GRP_HASH
240 uint8_t hash[32];
241#endif
Christopher Collins92ea77f2016-12-12 15:59:26 -0800242
Øyvind Rønningstada7d34ca2022-02-28 13:47:57 +0100243 zcbor_map_start_encode(cbor_state, 1);
244 zcbor_tstr_put_lit_cast(cbor_state, "images");
245 zcbor_list_start_encode(cbor_state, 5);
Fabio Utzig6f49c272019-08-23 11:42:58 -0300246 image_index = 0;
247 IMAGES_ITER(image_index) {
248 for (slot = 0; slot < 2; slot++) {
249 area_id = flash_area_id_from_multi_image_slot(image_index, slot);
250 if (flash_area_open(area_id, &fap)) {
251 continue;
252 }
Christopher Collins92ea77f2016-12-12 15:59:26 -0800253
Andrzej Puzdrowski4f9c7302021-07-16 17:34:43 +0200254 int rc = BOOT_HOOK_CALL(boot_read_image_header_hook,
255 BOOT_HOOK_REGULAR, image_index, slot, &hdr);
256 if (rc == BOOT_HOOK_REGULAR)
257 {
258 flash_area_read(fap, 0, &hdr, sizeof(hdr));
259 }
Christopher Collins92ea77f2016-12-12 15:59:26 -0800260
Michael Grand5047f032022-11-24 16:49:56 +0100261 FIH_DECLARE(fih_rc, FIH_FAILURE);
Andrzej Puzdrowski4f9c7302021-07-16 17:34:43 +0200262
263 if (hdr.ih_magic == IMAGE_MAGIC)
264 {
265 BOOT_HOOK_CALL_FIH(boot_image_check_hook,
Michael Grand5047f032022-11-24 16:49:56 +0100266 FIH_BOOT_HOOK_REGULAR,
Andrzej Puzdrowski4f9c7302021-07-16 17:34:43 +0200267 fih_rc, image_index, slot);
Michael Grand5047f032022-11-24 16:49:56 +0100268 if (FIH_EQ(fih_rc, FIH_BOOT_HOOK_REGULAR))
Andrzej Puzdrowski4f9c7302021-07-16 17:34:43 +0200269 {
Wouter Cappelle953a7612021-05-03 16:53:05 +0200270#ifdef MCUBOOT_ENC_IMAGES
271 if (slot == 0 && IS_ENCRYPTED(&hdr)) {
272 /* Clear the encrypted flag we didn't supply a key
273 * This flag could be set if there was a decryption in place
274 * performed before. We will try to validate the image without
275 * decryption by clearing the flag in the heder. If
276 * still encrypted the validation will fail.
277 */
278 hdr.ih_flags &= ~(ENCRYPTIONFLAGS);
279 }
280#endif
Andrzej Puzdrowski4f9c7302021-07-16 17:34:43 +0200281 FIH_CALL(bootutil_img_validate, fih_rc, NULL, 0, &hdr, fap, tmpbuf, sizeof(tmpbuf),
282 NULL, 0, NULL);
283 }
284 }
285
Jamie McCrae827118f2023-03-10 13:24:57 +0000286#ifdef MCUBOOT_SERIAL_IMG_GRP_HASH
287 /* Retrieve SHA256 hash of image for identification */
288 rc = boot_serial_get_hash(&hdr, fap, hash);
289#endif
290
Andrzej Puzdrowski4f9c7302021-07-16 17:34:43 +0200291 flash_area_close(fap);
292
Michael Grand5047f032022-11-24 16:49:56 +0100293 if (FIH_NOT_EQ(fih_rc, FIH_SUCCESS)) {
Fabio Utzig6f49c272019-08-23 11:42:58 -0300294 continue;
295 }
Fabio Utzig6f49c272019-08-23 11:42:58 -0300296
Øyvind Rønningstada7d34ca2022-02-28 13:47:57 +0100297 zcbor_map_start_encode(cbor_state, 20);
Fabio Utzig6f49c272019-08-23 11:42:58 -0300298
299#if (BOOT_IMAGE_NUMBER > 1)
Øyvind Rønningstada7d34ca2022-02-28 13:47:57 +0100300 zcbor_tstr_put_lit_cast(cbor_state, "image");
301 zcbor_uint32_put(cbor_state, image_index);
Fabio Utzig6f49c272019-08-23 11:42:58 -0300302#endif
303
Øyvind Rønningstada7d34ca2022-02-28 13:47:57 +0100304 zcbor_tstr_put_lit_cast(cbor_state, "slot");
305 zcbor_uint32_put(cbor_state, slot);
Jamie McCrae827118f2023-03-10 13:24:57 +0000306
307#ifdef MCUBOOT_SERIAL_IMG_GRP_HASH
308 if (rc == 0) {
309 zcbor_tstr_put_lit_cast(cbor_state, "hash");
310 zcbor_bstr_encode_ptr(cbor_state, hash, sizeof(hash));
311 }
312#endif
313
Øyvind Rønningstada7d34ca2022-02-28 13:47:57 +0100314 zcbor_tstr_put_lit_cast(cbor_state, "version");
Fabio Utzig6f49c272019-08-23 11:42:58 -0300315
316 bs_list_img_ver((char *)tmpbuf, sizeof(tmpbuf), &hdr.ih_ver);
Jamie McCrae827118f2023-03-10 13:24:57 +0000317
Jamie McCrae393af792023-04-14 11:31:16 +0100318 zcbor_tstr_encode_ptr(cbor_state, (char *)tmpbuf, strlen((char *)tmpbuf));
Øyvind Rønningstada7d34ca2022-02-28 13:47:57 +0100319 zcbor_map_end_encode(cbor_state, 20);
Christopher Collins92ea77f2016-12-12 15:59:26 -0800320 }
Christopher Collins92ea77f2016-12-12 15:59:26 -0800321 }
Øyvind Rønningstada7d34ca2022-02-28 13:47:57 +0100322 zcbor_list_end_encode(cbor_state, 5);
323 zcbor_map_end_encode(cbor_state, 1);
Christopher Collins92ea77f2016-12-12 15:59:26 -0800324 boot_serial_output();
325}
326
Dominik Ermelbcc17b42022-06-15 15:33:04 +0000327#ifdef MCUBOOT_ERASE_PROGRESSIVELY
328
329/** Erases range of flash, aligned to sector size
330 *
331 * Function will erase all sectors withing [start, end] range; it does not check
332 * the @p start for alignment, and it will use @p end to find boundaries of las
333 * sector to erase. Function returns offset of the first byte past the last
334 * erased sector, so basically offset of next sector to be erased if needed.
335 * The function is intended to be called iteratively with previously returned
336 * offset as @p start.
337 *
338 * @param start starting offset, aligned to sector offset;
339 * @param end ending offset, maybe anywhere within sector;
340 *
341 * @retval On success: offset of the first byte past last erased sector;
342 * On failure: -EINVAL.
343 */
344static off_t erase_range(const struct flash_area *fap, off_t start, off_t end)
345{
346 struct flash_sector sect;
347 size_t size;
348 int rc;
349
350 if (end >= flash_area_get_size(fap)) {
351 return -EINVAL;
352 }
353
354 if (end < start) {
355 return start;
356 }
357
Dominik Ermel24769882023-01-05 13:36:35 +0000358 if (flash_area_get_sector(fap, end, &sect)) {
Dominik Ermelbcc17b42022-06-15 15:33:04 +0000359 return -EINVAL;
360 }
361
362 size = flash_sector_get_off(&sect) + flash_sector_get_size(&sect) - start;
Stephanos Ioannidis09e2bd72022-07-11 22:01:49 +0900363 BOOT_LOG_INF("Erasing range 0x%jx:0x%jx", (intmax_t)start,
364 (intmax_t)(start + size - 1));
Dominik Ermelbcc17b42022-06-15 15:33:04 +0000365
366 rc = flash_area_erase(fap, start, size);
367 if (rc != 0) {
368 BOOT_LOG_ERR("Error %d while erasing range", rc);
369 return -EINVAL;
370 }
371
372 return start + size;
373}
374#endif
375
Christopher Collins92ea77f2016-12-12 15:59:26 -0800376/*
377 * Image upload request.
378 */
379static void
380bs_upload(char *buf, int len)
381{
Dominik Ermel5bd87442022-06-13 15:14:01 +0000382 static size_t img_size; /* Total image size, held for duration of upload */
383 static uint32_t curr_off; /* Expected current offset */
384 const uint8_t *img_chunk = NULL; /* Pointer to buffer with received image chunk */
385 size_t img_chunk_len = 0; /* Length of received image chunk */
386 size_t img_chunk_off = SIZE_MAX; /* Offset of image chunk within image */
387 uint8_t rem_bytes; /* Reminder bytes after aligning chunk write to
388 * to flash alignment */
Jamie McCraecb07e882023-04-14 09:28:24 +0100389 uint32_t img_num;
Dominik Ermel5bd87442022-06-13 15:14:01 +0000390 size_t img_size_tmp = SIZE_MAX; /* Temp variable for image size */
Christopher Collins92ea77f2016-12-12 15:59:26 -0800391 const struct flash_area *fap = NULL;
392 int rc;
Jamie McCraecb07e882023-04-14 09:28:24 +0100393 struct zcbor_string img_chunk_data;
394 size_t decoded = 0;
395 bool ok;
Dominik Ermel3d4e55d2021-07-09 11:14:10 +0000396#ifdef MCUBOOT_ERASE_PROGRESSIVELY
Dominik Ermelbcc17b42022-06-15 15:33:04 +0000397 static off_t not_yet_erased = 0; /* Offset of next byte to erase; writes to flash
398 * are done in consecutive manner and erases are done
399 * to allow currently received chunk to be written;
400 * this state variable holds information where last
401 * erase has stopped to let us know whether erase
402 * is needed to be able to write current chunk.
403 */
404 static struct flash_sector status_sector;
Emanuele Di Santo205c8c62018-07-20 11:42:31 +0200405#endif
Christopher Collins92ea77f2016-12-12 15:59:26 -0800406
Jamie McCraecb07e882023-04-14 09:28:24 +0100407 zcbor_state_t zsd[4];
408 zcbor_new_state(zsd, sizeof(zsd) / sizeof(zcbor_state_t), (uint8_t *)buf, len, 1);
409
410 struct zcbor_map_decode_key_val image_upload_decode[] = {
411 ZCBOR_MAP_DECODE_KEY_DECODER("image", zcbor_uint32_decode, &img_num),
412 ZCBOR_MAP_DECODE_KEY_DECODER("data", zcbor_bstr_decode, &img_chunk_data),
413 ZCBOR_MAP_DECODE_KEY_DECODER("len", zcbor_size_decode, &img_size_tmp),
414 ZCBOR_MAP_DECODE_KEY_DECODER("off", zcbor_size_decode, &img_chunk_off),
415 };
416
417 ok = zcbor_map_decode_bulk(zsd, image_upload_decode, ARRAY_SIZE(image_upload_decode),
418 &decoded) == 0;
419
420 if (!ok) {
421 goto out_invalid_data;
422 }
423
424 img_chunk = img_chunk_data.value;
425 img_chunk_len = img_chunk_data.len;
Marko Kiiskilace50ab02018-06-06 11:33:33 +0300426
427 /*
428 * Expected data format.
429 * {
Fabio Utzig6f49c272019-08-23 11:42:58 -0300430 * "image":<image number in a multi-image set (OPTIONAL)>
431 * "data":<image data>
Marko Kiiskilace50ab02018-06-06 11:33:33 +0300432 * "len":<image len>
433 * "off":<current offset of image data>
434 * }
435 */
436
Dominik Ermel5bd87442022-06-13 15:14:01 +0000437 if (img_chunk_off == SIZE_MAX || img_chunk == NULL) {
Marko Kiiskilace50ab02018-06-06 11:33:33 +0300438 /*
439 * Offset must be set in every block.
440 */
441 goto out_invalid_data;
Christopher Collins92ea77f2016-12-12 15:59:26 -0800442 }
443
Dominik Ermel48decca2021-07-09 10:23:58 +0000444#if !defined(MCUBOOT_SERIAL_DIRECT_IMAGE_UPLOAD)
Fabio Utzig6f49c272019-08-23 11:42:58 -0300445 rc = flash_area_open(flash_area_id_from_multi_image_slot(img_num, 0), &fap);
Dominik Ermel48decca2021-07-09 10:23:58 +0000446#else
447 rc = flash_area_open(flash_area_id_from_direct_image(img_num), &fap);
448#endif
Christopher Collins92ea77f2016-12-12 15:59:26 -0800449 if (rc) {
450 rc = MGMT_ERR_EINVAL;
451 goto out;
452 }
453
Dominik Ermel5bd87442022-06-13 15:14:01 +0000454 if (img_chunk_off == 0) {
Dominik Ermelbcc17b42022-06-15 15:33:04 +0000455 /* Receiving chunk with 0 offset resets the upload state; this basically
456 * means that upload has started from beginning.
457 */
458 const size_t area_size = flash_area_get_size(fap);
Dominik Ermel5bd87442022-06-13 15:14:01 +0000459
Dominik Ermelbcc17b42022-06-15 15:33:04 +0000460 curr_off = 0;
461#ifdef MCUBOOT_ERASE_PROGRESSIVELY
462 /* Get trailer sector information; this is done early because inability to get
463 * that sector information means that upload will not work anyway.
464 * TODO: This is single occurrence issue, it should get detected during tests
465 * and fixed otherwise you are deploying broken mcuboot.
466 */
Dominik Ermel24769882023-01-05 13:36:35 +0000467 if (flash_area_get_sector(fap, boot_status_off(fap), &status_sector)) {
Dominik Ermelbcc17b42022-06-15 15:33:04 +0000468 rc = MGMT_ERR_EUNKNOWN;
469 BOOT_LOG_ERR("Unable to determine flash sector of the image trailer");
470 goto out;
471 }
472#endif
473
Wouter Cappellebb7a39d2021-05-03 16:44:44 +0200474#if defined(MCUBOOT_VALIDATE_PRIMARY_SLOT_ONCE)
475 /* We are using swap state at end of flash area to store validation
476 * result. Make sure the user cannot write it from an image to skip validation.
477 */
Dominik Ermelbcc17b42022-06-15 15:33:04 +0000478 if (img_size_tmp > (area_size - BOOT_MAGIC_SZ)) {
Wouter Cappellebb7a39d2021-05-03 16:44:44 +0200479 goto out_invalid_data;
480 }
Dominik Ermelbcc17b42022-06-15 15:33:04 +0000481#else
482 if (img_size_tmp > area_size) {
483 goto out_invalid_data;
484 }
485
Wouter Cappellebb7a39d2021-05-03 16:44:44 +0200486#endif
Dominik Ermelbcc17b42022-06-15 15:33:04 +0000487
Dominik Ermel3d4e55d2021-07-09 11:14:10 +0000488#ifndef MCUBOOT_ERASE_PROGRESSIVELY
Dominik Ermelbcc17b42022-06-15 15:33:04 +0000489 /* Non-progressive erase erases entire image slot when first chunk of
490 * an image is received.
491 */
492 rc = flash_area_erase(fap, 0, area_size);
Christopher Collins92ea77f2016-12-12 15:59:26 -0800493 if (rc) {
Marko Kiiskilace50ab02018-06-06 11:33:33 +0300494 goto out_invalid_data;
Christopher Collins92ea77f2016-12-12 15:59:26 -0800495 }
Dominik Ermelbcc17b42022-06-15 15:33:04 +0000496#else
497 not_yet_erased = 0;
Emanuele Di Santo205c8c62018-07-20 11:42:31 +0200498#endif
Dominik Ermelbcc17b42022-06-15 15:33:04 +0000499
Dominik Ermel5bd87442022-06-13 15:14:01 +0000500 img_size = img_size_tmp;
Dominik Ermelbcc17b42022-06-15 15:33:04 +0000501 } else if (img_chunk_off != curr_off) {
502 /* If received chunk offset does not match expected one jump, pretend
503 * success and jump to out; out will respond to client with success
504 * and request the expected offset, held by curr_off.
505 */
Christopher Collins92ea77f2016-12-12 15:59:26 -0800506 rc = 0;
507 goto out;
Dominik Ermelbcc17b42022-06-15 15:33:04 +0000508 } else if (curr_off + img_chunk_len > img_size) {
Andrzej Puzdrowskif48de7a2020-10-19 09:42:02 +0200509 rc = MGMT_ERR_EINVAL;
510 goto out;
511 }
512
Dominik Ermelbcc17b42022-06-15 15:33:04 +0000513#ifdef MCUBOOT_ERASE_PROGRESSIVELY
514 /* Progressive erase will erase enough flash, aligned to sector size,
515 * as needed for the current chunk to be written.
516 */
517 not_yet_erased = erase_range(fap, not_yet_erased,
518 curr_off + img_chunk_len - 1);
519
520 if (not_yet_erased < 0) {
521 rc = MGMT_ERR_EINVAL;
522 goto out;
523 }
524#endif
525
526 /* Writes are aligned to flash write alignment, so may drop a few bytes
527 * from the end of the buffer; we will request these bytes again with
528 * new buffer by responding with request for offset after the last aligned
529 * write.
530 */
Dominik Ermel5bd87442022-06-13 15:14:01 +0000531 rem_bytes = img_chunk_len % flash_area_align(fap);
Dominik Ermel7d2f0bf2022-06-21 16:15:34 +0000532 img_chunk_len -= rem_bytes;
Andrzej Puzdrowskif48de7a2020-10-19 09:42:02 +0200533
Dominik Ermel7d2f0bf2022-06-21 16:15:34 +0000534 if (curr_off + img_chunk_len + rem_bytes < img_size) {
Andrzej Puzdrowskif48de7a2020-10-19 09:42:02 +0200535 rem_bytes = 0;
Fabio Utzig30f6b2a2018-03-29 16:18:53 -0300536 }
Emanuele Di Santo205c8c62018-07-20 11:42:31 +0200537
Dominik Ermel5bd87442022-06-13 15:14:01 +0000538 BOOT_LOG_INF("Writing at 0x%x until 0x%x", curr_off, curr_off + img_chunk_len);
Dominik Ermel7d2f0bf2022-06-21 16:15:34 +0000539 /* Write flash aligned chunk, note that img_chunk_len now holds aligned length */
Jamie McCrae9d3fd7f2022-11-30 15:44:44 +0000540#if defined(MCUBOOT_SERIAL_UNALIGNED_BUFFER_SIZE) && MCUBOOT_SERIAL_UNALIGNED_BUFFER_SIZE > 0
541 if (flash_area_align(fap) > 1 &&
542 (((size_t)img_chunk) & (flash_area_align(fap) - 1)) != 0) {
543 /* Buffer address incompatible with write address, use buffer to write */
544 uint8_t write_size = MCUBOOT_SERIAL_UNALIGNED_BUFFER_SIZE;
545 uint8_t wbs_aligned[MCUBOOT_SERIAL_UNALIGNED_BUFFER_SIZE];
546
547 while (img_chunk_len >= flash_area_align(fap)) {
548 if (write_size > img_chunk_len) {
549 write_size = img_chunk_len;
550 }
551
552 memset(wbs_aligned, flash_area_erased_val(fap), sizeof(wbs_aligned));
553 memcpy(wbs_aligned, img_chunk, write_size);
554
555 rc = flash_area_write(fap, curr_off, wbs_aligned, write_size);
556
557 if (rc != 0) {
558 goto out;
559 }
560
561 curr_off += write_size;
562 img_chunk += write_size;
563 img_chunk_len -= write_size;
564 }
565 } else {
566 rc = flash_area_write(fap, curr_off, img_chunk, img_chunk_len);
567 }
568#else
Dominik Ermel7d2f0bf2022-06-21 16:15:34 +0000569 rc = flash_area_write(fap, curr_off, img_chunk, img_chunk_len);
Jamie McCrae9d3fd7f2022-11-30 15:44:44 +0000570#endif
571
Dominik Ermel7d2f0bf2022-06-21 16:15:34 +0000572 if (rc == 0 && rem_bytes) {
573 /* Non-zero rem_bytes means that last chunk needs alignment; the aligned
574 * part, in the img_chunk_len - rem_bytes count bytes, has already been
575 * written by the above write, so we are left with the rem_bytes.
576 */
Andrzej Puzdrowskif48de7a2020-10-19 09:42:02 +0200577 uint8_t wbs_aligned[BOOT_MAX_ALIGN];
Andrzej Puzdrowskif48de7a2020-10-19 09:42:02 +0200578
Dominik Ermel7d2f0bf2022-06-21 16:15:34 +0000579 memset(wbs_aligned, flash_area_erased_val(fap), sizeof(wbs_aligned));
580 memcpy(wbs_aligned, img_chunk + img_chunk_len, rem_bytes);
Andrzej Puzdrowskif48de7a2020-10-19 09:42:02 +0200581
Dominik Ermel7d2f0bf2022-06-21 16:15:34 +0000582 rc = flash_area_write(fap, curr_off + img_chunk_len, wbs_aligned,
583 flash_area_align(fap));
Andrzej Puzdrowskif48de7a2020-10-19 09:42:02 +0200584 }
585
Marko Kiiskilace50ab02018-06-06 11:33:33 +0300586 if (rc == 0) {
Dominik Ermel7d2f0bf2022-06-21 16:15:34 +0000587 curr_off += img_chunk_len + rem_bytes;
Andrzej Puzdrowskic2e30cf2018-07-20 16:19:09 +0200588 if (curr_off == img_size) {
Andrzej Puzdrowski4f9c7302021-07-16 17:34:43 +0200589#ifdef MCUBOOT_ERASE_PROGRESSIVELY
Andrzej Puzdrowskic2e30cf2018-07-20 16:19:09 +0200590 /* Assure that sector for image trailer was erased. */
591 /* Check whether it was erased during previous upload. */
Dominik Ermelbcc17b42022-06-15 15:33:04 +0000592 off_t start = flash_sector_get_off(&status_sector);
593
594 if (erase_range(fap, start, start) < 0) {
595 rc = MGMT_ERR_EUNKNOWN;
596 goto out;
Andrzej Puzdrowskic2e30cf2018-07-20 16:19:09 +0200597 }
Andrzej Puzdrowskic2e30cf2018-07-20 16:19:09 +0200598#endif
Andrzej Puzdrowski4f9c7302021-07-16 17:34:43 +0200599 rc = BOOT_HOOK_CALL(boot_serial_uploaded_hook, 0, img_num, fap,
600 img_size);
601 if (rc) {
602 BOOT_LOG_ERR("Error %d post upload hook", rc);
603 goto out;
604 }
605 }
Marko Kiiskilace50ab02018-06-06 11:33:33 +0300606 } else {
607 out_invalid_data:
Christopher Collins92ea77f2016-12-12 15:59:26 -0800608 rc = MGMT_ERR_EINVAL;
Christopher Collins92ea77f2016-12-12 15:59:26 -0800609 }
Emanuele Di Santo205c8c62018-07-20 11:42:31 +0200610
Christopher Collins92ea77f2016-12-12 15:59:26 -0800611out:
Andrzej Puzdrowski8e96b832017-09-08 16:49:14 +0200612 BOOT_LOG_INF("RX: 0x%x", rc);
Øyvind Rønningstada7d34ca2022-02-28 13:47:57 +0100613 zcbor_map_start_encode(cbor_state, 10);
614 zcbor_tstr_put_lit_cast(cbor_state, "rc");
Jamie McCrae0b6d3432022-12-02 09:24:10 +0000615 zcbor_int32_put(cbor_state, rc);
Christopher Collins92ea77f2016-12-12 15:59:26 -0800616 if (rc == 0) {
Øyvind Rønningstada7d34ca2022-02-28 13:47:57 +0100617 zcbor_tstr_put_lit_cast(cbor_state, "off");
618 zcbor_uint32_put(cbor_state, curr_off);
Christopher Collins92ea77f2016-12-12 15:59:26 -0800619 }
Øyvind Rønningstada7d34ca2022-02-28 13:47:57 +0100620 zcbor_map_end_encode(cbor_state, 10);
Christopher Collins92ea77f2016-12-12 15:59:26 -0800621
622 boot_serial_output();
623 flash_area_close(fap);
Wouter Cappelle953a7612021-05-03 16:53:05 +0200624
625#ifdef MCUBOOT_ENC_IMAGES
626 if (curr_off == img_size) {
627 /* Last sector received, now start a decryption on the image if it is encrypted*/
628 rc = boot_handle_enc_fw();
629 }
630#endif //#ifdef MCUBOOT_ENC_IMAGES
Christopher Collins92ea77f2016-12-12 15:59:26 -0800631}
632
Dominik Ermel4c0f6c12022-03-04 15:47:37 +0000633/*
634 * Send rc code only.
635 */
636static void
637bs_rc_rsp(int rc_code)
638{
Øyvind Rønningstada7d34ca2022-02-28 13:47:57 +0100639 zcbor_map_start_encode(cbor_state, 10);
640 zcbor_tstr_put_lit_cast(cbor_state, "rc");
Jamie McCrae0b6d3432022-12-02 09:24:10 +0000641 zcbor_int32_put(cbor_state, rc_code);
Øyvind Rønningstada7d34ca2022-02-28 13:47:57 +0100642 zcbor_map_end_encode(cbor_state, 10);
Dominik Ermel4c0f6c12022-03-04 15:47:37 +0000643 boot_serial_output();
644}
645
646
Wouter Cappellee3ff1752021-05-03 16:36:22 +0200647#ifdef MCUBOOT_BOOT_MGMT_ECHO
Wouter Cappellee3ff1752021-05-03 16:36:22 +0200648static void
649bs_echo(char *buf, int len)
650{
Jamie McCraecb07e882023-04-14 09:28:24 +0100651 struct zcbor_string value = { 0 };
652 struct zcbor_string key;
653 bool ok;
Dominik Ermel88bd5672022-06-07 15:17:06 +0000654 uint32_t rc = MGMT_ERR_EINVAL;
Wouter Cappellee3ff1752021-05-03 16:36:22 +0200655
Jamie McCraecb07e882023-04-14 09:28:24 +0100656 zcbor_state_t zsd[4];
657 zcbor_new_state(zsd, sizeof(zsd) / sizeof(zcbor_state_t), (uint8_t *)buf, len, 1);
658
659 if (!zcbor_map_start_decode(zsd)) {
Dominik Ermel88bd5672022-06-07 15:17:06 +0000660 goto out;
Wouter Cappellee3ff1752021-05-03 16:36:22 +0200661 }
Dominik Ermel88bd5672022-06-07 15:17:06 +0000662
Jamie McCraecb07e882023-04-14 09:28:24 +0100663 do {
664 ok = zcbor_tstr_decode(zsd, &key);
665
666 if (ok) {
667 if (key.len == 1 && *key.value == 'd') {
668 ok = zcbor_tstr_decode(zsd, &value);
669 break;
670 }
671
672 ok = zcbor_any_skip(zsd, NULL);
673 }
674 } while (ok);
675
676 if (!ok || !zcbor_map_end_decode(zsd)) {
Dominik Ermel88bd5672022-06-07 15:17:06 +0000677 goto out;
678 }
679
680 zcbor_map_start_encode(cbor_state, 10);
681 zcbor_tstr_put_term(cbor_state, "r");
Jamie McCraecb07e882023-04-14 09:28:24 +0100682 if (zcbor_tstr_encode(cbor_state, &value) && zcbor_map_end_encode(cbor_state, 10)) {
Dominik Ermel88bd5672022-06-07 15:17:06 +0000683 boot_serial_output();
684 return;
685 } else {
686 rc = MGMT_ERR_ENOMEM;
687 }
688
689out:
690 reset_cbor_state();
691 bs_rc_rsp(rc);
Wouter Cappellee3ff1752021-05-03 16:36:22 +0200692}
693#endif
694
Christopher Collins92ea77f2016-12-12 15:59:26 -0800695/*
Christopher Collins92ea77f2016-12-12 15:59:26 -0800696 * Reset, and (presumably) boot to newly uploaded image. Flush console
697 * before restarting.
698 */
Andrzej Puzdrowski268cdd02018-04-10 12:57:54 +0200699static void
Christopher Collins92ea77f2016-12-12 15:59:26 -0800700bs_reset(char *buf, int len)
701{
Dominik Ermelb26fc482022-12-09 17:10:20 +0000702 int rc = BOOT_HOOK_CALL(boot_reset_request_hook, 0, false);
703 if (rc == BOOT_RESET_REQUEST_HOOK_BUSY) {
704 rc = MGMT_ERR_EBUSY;
705 } else {
706 /* Currently whatever else is returned it is just converted
707 * to 0/no error. Boot serial starts accepting "force" parameter
708 * in command this needs to change.
709 */
710 rc = 0;
711 }
712 bs_rc_rsp(rc);
Christopher Collins92ea77f2016-12-12 15:59:26 -0800713
Dominik Ermelb26fc482022-12-09 17:10:20 +0000714 if (rc == 0) {
Andrzej Puzdrowski8e96b832017-09-08 16:49:14 +0200715#ifdef __ZEPHYR__
Andrzej Puzdrowski0cf0dbd2021-05-14 11:55:57 +0200716#ifdef CONFIG_MULTITHREADING
Dominik Ermelb26fc482022-12-09 17:10:20 +0000717 k_sleep(K_MSEC(250));
Andrzej Puzdrowski0cf0dbd2021-05-14 11:55:57 +0200718#else
Dominik Ermelb26fc482022-12-09 17:10:20 +0000719 k_busy_wait(250000);
Andrzej Puzdrowski0cf0dbd2021-05-14 11:55:57 +0200720#endif
Dominik Ermelb26fc482022-12-09 17:10:20 +0000721 sys_reboot(SYS_REBOOT_COLD);
Almir Okatoe8cbc0d2022-06-13 10:45:39 -0300722#elif __ESPRESSIF__
Dominik Ermelb26fc482022-12-09 17:10:20 +0000723 esp_rom_delay_us(250000);
724 bootloader_reset();
Andrzej Puzdrowski8e96b832017-09-08 16:49:14 +0200725#else
Dominik Ermelb26fc482022-12-09 17:10:20 +0000726 os_cputime_delay_usecs(250000);
727 hal_system_reset();
Andrzej Puzdrowski8e96b832017-09-08 16:49:14 +0200728#endif
Dominik Ermelb26fc482022-12-09 17:10:20 +0000729 }
Christopher Collins92ea77f2016-12-12 15:59:26 -0800730}
731
732/*
733 * Parse incoming line of input from console.
734 * Expect newtmgr protocol with serial transport.
735 */
736void
737boot_serial_input(char *buf, int len)
738{
739 struct nmgr_hdr *hdr;
740
741 hdr = (struct nmgr_hdr *)buf;
742 if (len < sizeof(*hdr) ||
743 (hdr->nh_op != NMGR_OP_READ && hdr->nh_op != NMGR_OP_WRITE) ||
744 (ntohs(hdr->nh_len) < len - sizeof(*hdr))) {
745 return;
746 }
747 bs_hdr = hdr;
748 hdr->nh_group = ntohs(hdr->nh_group);
749
750 buf += sizeof(*hdr);
751 len -= sizeof(*hdr);
Marko Kiiskilace50ab02018-06-06 11:33:33 +0300752
Dominik Ermel4c0f6c12022-03-04 15:47:37 +0000753 reset_cbor_state();
Christopher Collins92ea77f2016-12-12 15:59:26 -0800754
755 /*
756 * Limited support for commands.
757 */
758 if (hdr->nh_group == MGMT_GROUP_ID_IMAGE) {
759 switch (hdr->nh_id) {
Marko Kiiskilace50ab02018-06-06 11:33:33 +0300760 case IMGMGR_NMGR_ID_STATE:
Christopher Collins92ea77f2016-12-12 15:59:26 -0800761 bs_list(buf, len);
762 break;
Marko Kiiskilace50ab02018-06-06 11:33:33 +0300763 case IMGMGR_NMGR_ID_UPLOAD:
Christopher Collins92ea77f2016-12-12 15:59:26 -0800764 bs_upload(buf, len);
765 break;
766 default:
Dominik Ermelc9dc2242021-07-28 17:08:23 +0000767 bs_rc_rsp(MGMT_ERR_ENOTSUP);
Christopher Collins92ea77f2016-12-12 15:59:26 -0800768 break;
769 }
770 } else if (hdr->nh_group == MGMT_GROUP_ID_DEFAULT) {
771 switch (hdr->nh_id) {
Wouter Cappellee3ff1752021-05-03 16:36:22 +0200772 case NMGR_ID_ECHO:
773#ifdef MCUBOOT_BOOT_MGMT_ECHO
774 bs_echo(buf, len);
775#endif
776 break;
Christopher Collins92ea77f2016-12-12 15:59:26 -0800777 case NMGR_ID_CONS_ECHO_CTRL:
Dominik Ermelc9dc2242021-07-28 17:08:23 +0000778 bs_rc_rsp(0);
Christopher Collins92ea77f2016-12-12 15:59:26 -0800779 break;
780 case NMGR_ID_RESET:
781 bs_reset(buf, len);
782 break;
783 default:
Dominik Ermelc9dc2242021-07-28 17:08:23 +0000784 bs_rc_rsp(MGMT_ERR_ENOTSUP);
Christopher Collins92ea77f2016-12-12 15:59:26 -0800785 break;
786 }
Dominik Ermelbd69c3d2021-07-28 11:27:31 +0000787 } else if (MCUBOOT_PERUSER_MGMT_GROUP_ENABLED == 1) {
Øyvind Rønningstada7d34ca2022-02-28 13:47:57 +0100788 if (bs_peruser_system_specific(hdr, buf, len, cbor_state) == 0) {
Dominik Ermel3d51e432021-06-25 17:29:50 +0000789 boot_serial_output();
790 }
Dominik Ermelc9dc2242021-07-28 17:08:23 +0000791 } else {
792 bs_rc_rsp(MGMT_ERR_ENOTSUP);
Christopher Collins92ea77f2016-12-12 15:59:26 -0800793 }
Wouter Cappellee3822f82022-01-19 15:39:43 +0100794#ifdef MCUBOOT_SERIAL_WAIT_FOR_DFU
795 bs_entry = true;
796#endif
Christopher Collins92ea77f2016-12-12 15:59:26 -0800797}
798
799static void
800boot_serial_output(void)
801{
802 char *data;
Piotr Dymaczf5e77532022-10-30 17:43:45 +0100803 int len, out;
Christopher Collins92ea77f2016-12-12 15:59:26 -0800804 uint16_t crc;
805 uint16_t totlen;
Piotr Dymaczf5e77532022-10-30 17:43:45 +0100806 char pkt_cont[2] = { SHELL_NLIP_DATA_START1, SHELL_NLIP_DATA_START2 };
Christopher Collins92ea77f2016-12-12 15:59:26 -0800807 char pkt_start[2] = { SHELL_NLIP_PKT_START1, SHELL_NLIP_PKT_START2 };
Dominik Ermel5ff89582022-03-03 17:09:07 +0000808 char buf[BOOT_SERIAL_OUT_MAX + sizeof(*bs_hdr) + sizeof(crc) + sizeof(totlen)];
809 char encoded_buf[BASE64_ENCODE_SIZE(sizeof(buf))];
Christopher Collins92ea77f2016-12-12 15:59:26 -0800810
811 data = bs_obuf;
Øyvind Rønningstada7d34ca2022-02-28 13:47:57 +0100812 len = (uint32_t)cbor_state->payload_mut - (uint32_t)bs_obuf;
Christopher Collins92ea77f2016-12-12 15:59:26 -0800813
814 bs_hdr->nh_op++;
Marko Kiiskilace50ab02018-06-06 11:33:33 +0300815 bs_hdr->nh_flags = 0;
Christopher Collins92ea77f2016-12-12 15:59:26 -0800816 bs_hdr->nh_len = htons(len);
817 bs_hdr->nh_group = htons(bs_hdr->nh_group);
818
Andrzej Puzdrowski8e96b832017-09-08 16:49:14 +0200819#ifdef __ZEPHYR__
Carles Cufib9192a42022-02-10 11:41:57 +0100820 crc = crc16_itu_t(CRC16_INITIAL_CRC, (uint8_t *)bs_hdr, sizeof(*bs_hdr));
821 crc = crc16_itu_t(crc, data, len);
Almir Okatoe8cbc0d2022-06-13 10:45:39 -0300822#elif __ESPRESSIF__
823 /* For ESP32 it was used the CRC API in rom/crc.h */
Almir Okato7d3622f2022-10-20 12:44:58 -0300824 crc = ~esp_crc16_be(~CRC16_INITIAL_CRC, (uint8_t *)bs_hdr, sizeof(*bs_hdr));
825 crc = ~esp_crc16_be(~crc, (uint8_t *)data, len);
Andrzej Puzdrowski8e96b832017-09-08 16:49:14 +0200826#else
Christopher Collins92ea77f2016-12-12 15:59:26 -0800827 crc = crc16_ccitt(CRC16_INITIAL_CRC, bs_hdr, sizeof(*bs_hdr));
828 crc = crc16_ccitt(crc, data, len);
Andrzej Puzdrowski8e96b832017-09-08 16:49:14 +0200829#endif
Christopher Collins92ea77f2016-12-12 15:59:26 -0800830 crc = htons(crc);
831
Christopher Collins92ea77f2016-12-12 15:59:26 -0800832 totlen = len + sizeof(*bs_hdr) + sizeof(crc);
833 totlen = htons(totlen);
834
835 memcpy(buf, &totlen, sizeof(totlen));
836 totlen = sizeof(totlen);
837 memcpy(&buf[totlen], bs_hdr, sizeof(*bs_hdr));
838 totlen += sizeof(*bs_hdr);
839 memcpy(&buf[totlen], data, len);
840 totlen += len;
841 memcpy(&buf[totlen], &crc, sizeof(crc));
842 totlen += sizeof(crc);
Andrzej Puzdrowski8e96b832017-09-08 16:49:14 +0200843#ifdef __ZEPHYR__
844 size_t enc_len;
Carles Cufi0165be82018-03-26 17:43:51 +0200845 base64_encode(encoded_buf, sizeof(encoded_buf), &enc_len, buf, totlen);
Andrzej Puzdrowski8e96b832017-09-08 16:49:14 +0200846 totlen = enc_len;
Almir Okatoe8cbc0d2022-06-13 10:45:39 -0300847#elif __ESPRESSIF__
848 size_t enc_len;
849 base64_encode((unsigned char *)encoded_buf, sizeof(encoded_buf), &enc_len, (unsigned char *)buf, totlen);
850 totlen = enc_len;
Andrzej Puzdrowski8e96b832017-09-08 16:49:14 +0200851#else
Christopher Collins92ea77f2016-12-12 15:59:26 -0800852 totlen = base64_encode(buf, totlen, encoded_buf, 1);
Andrzej Puzdrowski8e96b832017-09-08 16:49:14 +0200853#endif
Piotr Dymaczf5e77532022-10-30 17:43:45 +0100854
855 out = 0;
856 while (out < totlen) {
857 if (out == 0) {
858 boot_uf->write(pkt_start, sizeof(pkt_start));
859 } else {
860 boot_uf->write(pkt_cont, sizeof(pkt_cont));
861 }
862
863 len = MIN(BOOT_SERIAL_FRAME_MTU, totlen - out);
864 boot_uf->write(&encoded_buf[out], len);
865
866 out += len;
867
868 boot_uf->write("\n", 1);
869 }
870
Andrzej Puzdrowski8e96b832017-09-08 16:49:14 +0200871 BOOT_LOG_INF("TX");
Christopher Collins92ea77f2016-12-12 15:59:26 -0800872}
873
874/*
875 * Returns 1 if full packet has been received.
876 */
877static int
878boot_serial_in_dec(char *in, int inlen, char *out, int *out_off, int maxout)
879{
880 int rc;
881 uint16_t crc;
882 uint16_t len;
Marko Kiiskilae5aeee42018-12-21 15:00:16 +0200883
Andrzej Puzdrowski8e96b832017-09-08 16:49:14 +0200884#ifdef __ZEPHYR__
885 int err;
Andrzej Puzdrowskiec1e4d12018-06-18 14:36:14 +0200886 err = base64_decode( &out[*out_off], maxout - *out_off, &rc, in, inlen - 2);
Andrzej Puzdrowski8e96b832017-09-08 16:49:14 +0200887 if (err) {
888 return -1;
889 }
Almir Okatoe8cbc0d2022-06-13 10:45:39 -0300890#elif __ESPRESSIF__
891 int err;
892 err = base64_decode((unsigned char *)&out[*out_off], maxout - *out_off, (size_t *)&rc, (unsigned char *)in, inlen);
893 if (err) {
894 return -1;
895 }
Andrzej Puzdrowski8e96b832017-09-08 16:49:14 +0200896#else
Christopher Collins92ea77f2016-12-12 15:59:26 -0800897 if (*out_off + base64_decode_len(in) >= maxout) {
898 return -1;
899 }
900 rc = base64_decode(in, &out[*out_off]);
901 if (rc < 0) {
902 return -1;
903 }
Andrzej Puzdrowski8e96b832017-09-08 16:49:14 +0200904#endif
Fabio Utzig6f49c272019-08-23 11:42:58 -0300905
Christopher Collins92ea77f2016-12-12 15:59:26 -0800906 *out_off += rc;
Fabio Utzig6f49c272019-08-23 11:42:58 -0300907 if (*out_off <= sizeof(uint16_t)) {
908 return 0;
Christopher Collins92ea77f2016-12-12 15:59:26 -0800909 }
Fabio Utzig6f49c272019-08-23 11:42:58 -0300910
911 len = ntohs(*(uint16_t *)out);
912 if (len != *out_off - sizeof(uint16_t)) {
913 return 0;
914 }
915
916 if (len > *out_off - sizeof(uint16_t)) {
917 len = *out_off - sizeof(uint16_t);
918 }
919
920 out += sizeof(uint16_t);
921#ifdef __ZEPHYR__
Carles Cufib9192a42022-02-10 11:41:57 +0100922 crc = crc16_itu_t(CRC16_INITIAL_CRC, out, len);
Almir Okatoe8cbc0d2022-06-13 10:45:39 -0300923#elif __ESPRESSIF__
Almir Okato7d3622f2022-10-20 12:44:58 -0300924 crc = ~esp_crc16_be(~CRC16_INITIAL_CRC, (uint8_t *)out, len);
Fabio Utzig6f49c272019-08-23 11:42:58 -0300925#else
926 crc = crc16_ccitt(CRC16_INITIAL_CRC, out, len);
927#endif
928 if (crc || len <= sizeof(crc)) {
929 return 0;
930 }
931 *out_off -= sizeof(crc);
932 out[*out_off] = '\0';
933
934 return 1;
Christopher Collins92ea77f2016-12-12 15:59:26 -0800935}
936
937/*
938 * Task which waits reading console, expecting to get image over
939 * serial port.
940 */
Wouter Cappellee3822f82022-01-19 15:39:43 +0100941static void
942boot_serial_read_console(const struct boot_uart_funcs *f,int timeout_in_ms)
Christopher Collins92ea77f2016-12-12 15:59:26 -0800943{
944 int rc;
945 int off;
David Brown57f0df32020-05-12 08:39:21 -0600946 int dec_off = 0;
Christopher Collins92ea77f2016-12-12 15:59:26 -0800947 int full_line;
Marko Kiiskila149b4572018-06-06 14:18:54 +0300948 int max_input;
Wouter Cappellee3822f82022-01-19 15:39:43 +0100949 int elapsed_in_ms = 0;
Christopher Collins92ea77f2016-12-12 15:59:26 -0800950
Marko Kiiskila149b4572018-06-06 14:18:54 +0300951 boot_uf = f;
Marko Kiiskila149b4572018-06-06 14:18:54 +0300952 max_input = sizeof(in_buf);
Christopher Collins92ea77f2016-12-12 15:59:26 -0800953
954 off = 0;
Wouter Cappellee3822f82022-01-19 15:39:43 +0100955 while (timeout_in_ms > 0 || bs_entry) {
Piotr Dymacz067f30a2022-08-12 18:25:34 +0200956 /*
957 * Don't enter CPU idle state here if timeout based serial recovery is
958 * used as otherwise the boot process hangs forever, waiting for input
959 * from serial console (if single-thread mode is used).
960 */
Piotr Dymacz3942e9b2022-07-18 10:19:25 +0200961#ifndef MCUBOOT_SERIAL_WAIT_FOR_DFU
Andrzej Puzdrowskiaea38eb2021-06-11 12:28:59 +0200962 MCUBOOT_CPU_IDLE();
Piotr Dymacz3942e9b2022-07-18 10:19:25 +0200963#endif
Hein Wessels56d28f02021-11-19 08:42:08 +0100964 MCUBOOT_WATCHDOG_FEED();
Wouter Cappellee3822f82022-01-19 15:39:43 +0100965#ifdef MCUBOOT_SERIAL_WAIT_FOR_DFU
966 uint32_t start = k_uptime_get_32();
967#endif
Andrzej Puzdrowskiec1e4d12018-06-18 14:36:14 +0200968 rc = f->read(in_buf + off, sizeof(in_buf) - off, &full_line);
Christopher Collins92ea77f2016-12-12 15:59:26 -0800969 if (rc <= 0 && !full_line) {
Wouter Cappellee3822f82022-01-19 15:39:43 +0100970 goto check_timeout;
Christopher Collins92ea77f2016-12-12 15:59:26 -0800971 }
972 off += rc;
973 if (!full_line) {
Marko Kiiskilace50ab02018-06-06 11:33:33 +0300974 if (off == max_input) {
975 /*
976 * Full line, no newline yet. Reset the input buffer.
977 */
978 off = 0;
979 }
Wouter Cappellee3822f82022-01-19 15:39:43 +0100980 goto check_timeout;
Christopher Collins92ea77f2016-12-12 15:59:26 -0800981 }
Andrzej Puzdrowskiec1e4d12018-06-18 14:36:14 +0200982 if (in_buf[0] == SHELL_NLIP_PKT_START1 &&
983 in_buf[1] == SHELL_NLIP_PKT_START2) {
Christopher Collins92ea77f2016-12-12 15:59:26 -0800984 dec_off = 0;
Andrzej Puzdrowskiec1e4d12018-06-18 14:36:14 +0200985 rc = boot_serial_in_dec(&in_buf[2], off - 2, dec_buf, &dec_off, max_input);
986 } else if (in_buf[0] == SHELL_NLIP_DATA_START1 &&
987 in_buf[1] == SHELL_NLIP_DATA_START2) {
988 rc = boot_serial_in_dec(&in_buf[2], off - 2, dec_buf, &dec_off, max_input);
Christopher Collins92ea77f2016-12-12 15:59:26 -0800989 }
Andrzej Puzdrowskiec1e4d12018-06-18 14:36:14 +0200990
991 /* serve errors: out of decode memory, or bad encoding */
Christopher Collins92ea77f2016-12-12 15:59:26 -0800992 if (rc == 1) {
Andrzej Puzdrowskiec1e4d12018-06-18 14:36:14 +0200993 boot_serial_input(&dec_buf[2], dec_off - 2);
Christopher Collins92ea77f2016-12-12 15:59:26 -0800994 }
995 off = 0;
Wouter Cappellee3822f82022-01-19 15:39:43 +0100996check_timeout:
997 /* Subtract elapsed time */
998#ifdef MCUBOOT_SERIAL_WAIT_FOR_DFU
999 elapsed_in_ms = (k_uptime_get_32() - start);
1000#endif
1001 timeout_in_ms -= elapsed_in_ms;
Christopher Collins92ea77f2016-12-12 15:59:26 -08001002 }
1003}
Wouter Cappellee3822f82022-01-19 15:39:43 +01001004
1005/*
1006 * Task which waits reading console, expecting to get image over
1007 * serial port.
1008 */
1009void
1010boot_serial_start(const struct boot_uart_funcs *f)
1011{
1012 bs_entry = true;
1013 boot_serial_read_console(f,0);
1014}
1015
1016#ifdef MCUBOOT_SERIAL_WAIT_FOR_DFU
1017/*
1018 * Task which waits reading console for a certain amount of timeout.
1019 * If within this timeout no mcumgr command is received, the function is
1020 * returning, else the serial boot is never exited
1021 */
1022void
1023boot_serial_check_start(const struct boot_uart_funcs *f, int timeout_in_ms)
1024{
1025 bs_entry = false;
1026 boot_serial_read_console(f,timeout_in_ms);
1027}
1028#endif
Jamie McCrae827118f2023-03-10 13:24:57 +00001029
1030#ifdef MCUBOOT_SERIAL_IMG_GRP_HASH
1031/* Function to find the hash of an image, returns 0 on success. */
1032static int boot_serial_get_hash(const struct image_header *hdr,
1033 const struct flash_area *fap, uint8_t *hash)
1034{
1035 struct image_tlv_iter it;
1036 uint32_t offset;
1037 uint16_t len;
1038 uint16_t type;
1039 int rc;
1040
1041 /* Manifest data is concatenated to the end of the image.
1042 * It is encoded in TLV format.
1043 */
1044 rc = bootutil_tlv_iter_begin(&it, hdr, fap, IMAGE_TLV_ANY, false);
1045 if (rc) {
1046 return -1;
1047 }
1048
1049 /* Traverse through the TLV area to find the image hash TLV. */
1050 while (true) {
1051 rc = bootutil_tlv_iter_next(&it, &offset, &len, &type);
1052 if (rc < 0) {
1053 return -1;
1054 } else if (rc > 0) {
1055 break;
1056 }
1057
1058 if (type == IMAGE_TLV_SHA256) {
1059 /* Get the image's hash value from the manifest section. */
1060 if (len != 32) {
1061 return -1;
1062 }
1063
1064 rc = flash_area_read(fap, offset, hash, len);
1065 if (rc) {
1066 return -1;
1067 }
1068
1069 return 0;
1070 }
1071 }
1072
1073 return -1;
1074}
1075#endif