blob: c6c58bfa3207855f3c07ba3baa75c5455482def4 [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>
Jamie McCraef7d86602023-04-14 09:33:42 +010039#include <zcbor_encode.h>
Almir Okatoe8cbc0d2022-06-13 10:45:39 -030040#elif __ESPRESSIF__
Jamie McCraef7d86602023-04-14 09:33:42 +010041#include "zcbor_encode.h"
Almir Okatoe8cbc0d2022-06-13 10:45:39 -030042#include <bootloader_utility.h>
43#include <esp_rom_sys.h>
Almir Okato7d3622f2022-10-20 12:44:58 -030044#include <esp_crc.h>
Almir Okatoe8cbc0d2022-06-13 10:45:39 -030045#include <endian.h>
46#include <mbedtls/base64.h>
Andrzej Puzdrowski8e96b832017-09-08 16:49:14 +020047#else
Jamie McCraef7d86602023-04-14 09:33:42 +010048#include "zcbor_encode.h"
Christopher Collins92ea77f2016-12-12 15:59:26 -080049#include <bsp/bsp.h>
Christopher Collins92ea77f2016-12-12 15:59:26 -080050#include <hal/hal_system.h>
Almir Okatoe8cbc0d2022-06-13 10:45:39 -030051#include <hal/hal_flash.h>
Christopher Collins92ea77f2016-12-12 15:59:26 -080052#include <os/endian.h>
Christopher Collins92ea77f2016-12-12 15:59:26 -080053#include <os/os_cputime.h>
Andrzej Puzdrowski8e96b832017-09-08 16:49:14 +020054#include <crc/crc16.h>
55#include <base64/base64.h>
Andrzej Puzdrowski386b5922018-04-06 19:26:24 +020056#endif /* __ZEPHYR__ */
57
Andrzej Puzdrowskib788c712018-04-12 12:42:49 +020058#include <flash_map_backend/flash_map_backend.h>
Andrzej Puzdrowski8e96b832017-09-08 16:49:14 +020059#include <os/os.h>
60#include <os/os_malloc.h>
Christopher Collins92ea77f2016-12-12 15:59:26 -080061
62#include <bootutil/image.h>
Andrzej Puzdrowskif48de7a2020-10-19 09:42:02 +020063#include <bootutil/bootutil.h>
Christopher Collins92ea77f2016-12-12 15:59:26 -080064
65#include "boot_serial/boot_serial.h"
66#include "boot_serial_priv.h"
Almir Okatoe8cbc0d2022-06-13 10:45:39 -030067#include "mcuboot_config/mcuboot_config.h"
Christopher Collins92ea77f2016-12-12 15:59:26 -080068
Dominik Ermel3d4e55d2021-07-09 11:14:10 +000069#ifdef MCUBOOT_ERASE_PROGRESSIVELY
Andrzej Puzdrowskic2e30cf2018-07-20 16:19:09 +020070#include "bootutil_priv.h"
71#endif
72
Wouter Cappelle953a7612021-05-03 16:53:05 +020073#ifdef MCUBOOT_ENC_IMAGES
74#include "single_loader.h"
75#endif
76
Øyvind Rønningstadf42a8202019-12-13 03:27:54 +010077#include "serial_recovery_cbor.h"
Dominik Ermel88bd5672022-06-07 15:17:06 +000078#include "serial_recovery_echo.h"
Andrzej Puzdrowski4f9c7302021-07-16 17:34:43 +020079#include "bootutil/boot_hooks.h"
Øyvind Rønningstadf42a8202019-12-13 03:27:54 +010080
Carlos Falgueras Garcíaa4b4b0f2021-06-22 10:00:22 +020081BOOT_LOG_MODULE_DECLARE(mcuboot);
Emanuele Di Santo9f1933d2018-11-20 10:59:59 +010082
Jamie McCraead1fb3d2022-12-01 14:24:37 +000083#ifndef MCUBOOT_SERIAL_MAX_RECEIVE_SIZE
84#define MCUBOOT_SERIAL_MAX_RECEIVE_SIZE 512
85#endif
86
Jamie McCrae827118f2023-03-10 13:24:57 +000087#define BOOT_SERIAL_OUT_MAX (160 * BOOT_IMAGE_NUMBER)
Piotr Dymaczf5e77532022-10-30 17:43:45 +010088#define BOOT_SERIAL_FRAME_MTU 124 /* 127 - pkt start (2 bytes) and stop (1 byte) */
Christopher Collins92ea77f2016-12-12 15:59:26 -080089
Andrzej Puzdrowski8e96b832017-09-08 16:49:14 +020090#ifdef __ZEPHYR__
Carles Cufi0165be82018-03-26 17:43:51 +020091/* base64 lib encodes data to null-terminated string */
Andrzej Puzdrowski8e96b832017-09-08 16:49:14 +020092#define BASE64_ENCODE_SIZE(in_size) ((((((in_size) - 1) / 3) * 4) + 4) + 1)
93
94#define CRC16_INITIAL_CRC 0 /* what to seed crc16 with */
95#define CRC_CITT_POLYMINAL 0x1021
96
97#define ntohs(x) sys_be16_to_cpu(x)
98#define htons(x) sys_cpu_to_be16(x)
Almir Okatoe8cbc0d2022-06-13 10:45:39 -030099#elif __ESPRESSIF__
100#define BASE64_ENCODE_SIZE(in_size) ((((((in_size) - 1) / 3) * 4) + 4) + 1)
101#define CRC16_INITIAL_CRC 0 /* what to seed crc16 with */
102
103#define ntohs(x) be16toh(x)
104#define htons(x) htobe16(x)
105
106#define base64_decode mbedtls_base64_decode
107#define base64_encode mbedtls_base64_encode
Andrzej Puzdrowski8e96b832017-09-08 16:49:14 +0200108#endif
Emanuele Di Santo9f1933d2018-11-20 10:59:59 +0100109
Fabio Utzig6f49c272019-08-23 11:42:58 -0300110#if (BOOT_IMAGE_NUMBER > 1)
111#define IMAGES_ITER(x) for ((x) = 0; (x) < BOOT_IMAGE_NUMBER; ++(x))
112#else
113#define IMAGES_ITER(x)
114#endif
115
Jamie McCraead1fb3d2022-12-01 14:24:37 +0000116static char in_buf[MCUBOOT_SERIAL_MAX_RECEIVE_SIZE + 1];
117static char dec_buf[MCUBOOT_SERIAL_MAX_RECEIVE_SIZE + 1];
Marko Kiiskila8b1ce3a2018-06-14 13:20:46 -0700118const struct boot_uart_funcs *boot_uf;
Christopher Collins92ea77f2016-12-12 15:59:26 -0800119static struct nmgr_hdr *bs_hdr;
Wouter Cappellee3822f82022-01-19 15:39:43 +0100120static bool bs_entry;
Christopher Collins92ea77f2016-12-12 15:59:26 -0800121
122static char bs_obuf[BOOT_SERIAL_OUT_MAX];
123
Christopher Collins92ea77f2016-12-12 15:59:26 -0800124static void boot_serial_output(void);
125
Jamie McCrae827118f2023-03-10 13:24:57 +0000126#ifdef MCUBOOT_SERIAL_IMG_GRP_HASH
127static int boot_serial_get_hash(const struct image_header *hdr,
128 const struct flash_area *fap, uint8_t *hash);
129#endif
130
Øyvind Rønningstada7d34ca2022-02-28 13:47:57 +0100131static zcbor_state_t cbor_state[2];
Christopher Collins92ea77f2016-12-12 15:59:26 -0800132
Dominik Ermel4c0f6c12022-03-04 15:47:37 +0000133void reset_cbor_state(void)
134{
Øyvind Rønningstada7d34ca2022-02-28 13:47:57 +0100135 zcbor_new_encode_state(cbor_state, 2, (uint8_t *)bs_obuf,
136 (size_t)bs_obuf + sizeof(bs_obuf), 0);
Dominik Ermel4c0f6c12022-03-04 15:47:37 +0000137}
138
Dominik Ermel3d51e432021-06-25 17:29:50 +0000139/**
Dominik Ermelbd69c3d2021-07-28 11:27:31 +0000140 * Function that processes MGMT_GROUP_ID_PERUSER mcumgr group and may be
141 * used to process any groups that have not been processed by generic boot
142 * serial implementation.
Dominik Ermel3d51e432021-06-25 17:29:50 +0000143 *
144 * @param[in] hdr -- the decoded header of mcumgr message;
145 * @param[in] buffer -- buffer with first mcumgr message;
146 * @param[in] len -- length of of data in buffer;
147 * @param[out] *cs -- object with encoded response.
148 *
149 * @return 0 on success; non-0 error code otherwise.
150 */
151extern int bs_peruser_system_specific(const struct nmgr_hdr *hdr,
152 const char *buffer,
Øyvind Rønningstada7d34ca2022-02-28 13:47:57 +0100153 int len, zcbor_state_t *cs);
Christopher Collins92ea77f2016-12-12 15:59:26 -0800154
Dominik Ermeld49cfc12022-06-09 08:24:48 +0000155#define zcbor_tstr_put_lit_cast(state, string) \
Jamie McCrae393af792023-04-14 11:31:16 +0100156 zcbor_tstr_encode_ptr(state, (char *)string, sizeof(string) - 1)
Dominik Ermeld49cfc12022-06-09 08:24:48 +0000157
158#ifndef MCUBOOT_USE_SNPRINTF
Christopher Collins92ea77f2016-12-12 15:59:26 -0800159/*
Marko Kiiskilace50ab02018-06-06 11:33:33 +0300160 * Convert version into string without use of snprintf().
Christopher Collins92ea77f2016-12-12 15:59:26 -0800161 */
Marko Kiiskilace50ab02018-06-06 11:33:33 +0300162static int
163u32toa(char *tgt, uint32_t val)
Christopher Collins92ea77f2016-12-12 15:59:26 -0800164{
Marko Kiiskilace50ab02018-06-06 11:33:33 +0300165 char *dst;
166 uint32_t d = 1;
167 uint32_t dgt;
168 int n = 0;
Christopher Collins92ea77f2016-12-12 15:59:26 -0800169
Marko Kiiskilace50ab02018-06-06 11:33:33 +0300170 dst = tgt;
171 while (val / d >= 10) {
172 d *= 10;
Christopher Collins92ea77f2016-12-12 15:59:26 -0800173 }
Marko Kiiskilace50ab02018-06-06 11:33:33 +0300174 while (d) {
175 dgt = val / d;
176 val %= d;
177 d /= 10;
178 if (n || dgt > 0 || d == 0) {
179 *dst++ = dgt + '0';
180 ++n;
Christopher Collins92ea77f2016-12-12 15:59:26 -0800181 }
Christopher Collins92ea77f2016-12-12 15:59:26 -0800182 }
Marko Kiiskilace50ab02018-06-06 11:33:33 +0300183 *dst = '\0';
184
185 return dst - tgt;
186}
187
188/*
189 * dst has to be able to fit "255.255.65535.4294967295" (25 characters).
190 */
191static void
192bs_list_img_ver(char *dst, int maxlen, struct image_version *ver)
193{
194 int off;
195
196 off = u32toa(dst, ver->iv_major);
197 dst[off++] = '.';
198 off += u32toa(dst + off, ver->iv_minor);
199 dst[off++] = '.';
200 off += u32toa(dst + off, ver->iv_revision);
Jamie McCraee5c57dd2023-03-21 14:45:21 +0000201
202 if (ver->iv_build_num != 0) {
203 dst[off++] = '.';
204 off += u32toa(dst + off, ver->iv_build_num);
205 }
Christopher Collins92ea77f2016-12-12 15:59:26 -0800206}
Dominik Ermeld49cfc12022-06-09 08:24:48 +0000207#else
208/*
209 * dst has to be able to fit "255.255.65535.4294967295" (25 characters).
210 */
211static void
212bs_list_img_ver(char *dst, int maxlen, struct image_version *ver)
213{
Jamie McCraee5c57dd2023-03-21 14:45:21 +0000214 int len;
215
216 len = snprintf(dst, maxlen, "%hu.%hu.%hu", (uint16_t)ver->iv_major,
217 (uint16_t)ver->iv_minor, ver->iv_revision);
218
219 if (ver->iv_build_num != 0 && len > 0 && len < maxlen) {
220 snprintf(&dst[len], (maxlen - len), "%u", ver->iv_build_num);
221 }
Dominik Ermeld49cfc12022-06-09 08:24:48 +0000222}
223#endif /* !MCUBOOT_USE_SNPRINTF */
Christopher Collins92ea77f2016-12-12 15:59:26 -0800224
225/*
226 * List images.
227 */
228static void
229bs_list(char *buf, int len)
230{
Christopher Collins92ea77f2016-12-12 15:59:26 -0800231 struct image_header hdr;
232 uint8_t tmpbuf[64];
Øyvind Rønningstad9f4aefd2021-03-08 21:11:25 +0100233 uint32_t slot, area_id;
Christopher Collins92ea77f2016-12-12 15:59:26 -0800234 const struct flash_area *fap;
Fabio Utzig6f49c272019-08-23 11:42:58 -0300235 uint8_t image_index;
Jamie McCrae827118f2023-03-10 13:24:57 +0000236#ifdef MCUBOOT_SERIAL_IMG_GRP_HASH
237 uint8_t hash[32];
238#endif
Christopher Collins92ea77f2016-12-12 15:59:26 -0800239
Øyvind Rønningstada7d34ca2022-02-28 13:47:57 +0100240 zcbor_map_start_encode(cbor_state, 1);
241 zcbor_tstr_put_lit_cast(cbor_state, "images");
242 zcbor_list_start_encode(cbor_state, 5);
Fabio Utzig6f49c272019-08-23 11:42:58 -0300243 image_index = 0;
244 IMAGES_ITER(image_index) {
245 for (slot = 0; slot < 2; slot++) {
246 area_id = flash_area_id_from_multi_image_slot(image_index, slot);
247 if (flash_area_open(area_id, &fap)) {
248 continue;
249 }
Christopher Collins92ea77f2016-12-12 15:59:26 -0800250
Andrzej Puzdrowski4f9c7302021-07-16 17:34:43 +0200251 int rc = BOOT_HOOK_CALL(boot_read_image_header_hook,
252 BOOT_HOOK_REGULAR, image_index, slot, &hdr);
253 if (rc == BOOT_HOOK_REGULAR)
254 {
255 flash_area_read(fap, 0, &hdr, sizeof(hdr));
256 }
Christopher Collins92ea77f2016-12-12 15:59:26 -0800257
Michael Grand5047f032022-11-24 16:49:56 +0100258 FIH_DECLARE(fih_rc, FIH_FAILURE);
Andrzej Puzdrowski4f9c7302021-07-16 17:34:43 +0200259
260 if (hdr.ih_magic == IMAGE_MAGIC)
261 {
262 BOOT_HOOK_CALL_FIH(boot_image_check_hook,
Michael Grand5047f032022-11-24 16:49:56 +0100263 FIH_BOOT_HOOK_REGULAR,
Andrzej Puzdrowski4f9c7302021-07-16 17:34:43 +0200264 fih_rc, image_index, slot);
Michael Grand5047f032022-11-24 16:49:56 +0100265 if (FIH_EQ(fih_rc, FIH_BOOT_HOOK_REGULAR))
Andrzej Puzdrowski4f9c7302021-07-16 17:34:43 +0200266 {
Wouter Cappelle953a7612021-05-03 16:53:05 +0200267#ifdef MCUBOOT_ENC_IMAGES
268 if (slot == 0 && IS_ENCRYPTED(&hdr)) {
269 /* Clear the encrypted flag we didn't supply a key
270 * This flag could be set if there was a decryption in place
271 * performed before. We will try to validate the image without
272 * decryption by clearing the flag in the heder. If
273 * still encrypted the validation will fail.
274 */
275 hdr.ih_flags &= ~(ENCRYPTIONFLAGS);
276 }
277#endif
Andrzej Puzdrowski4f9c7302021-07-16 17:34:43 +0200278 FIH_CALL(bootutil_img_validate, fih_rc, NULL, 0, &hdr, fap, tmpbuf, sizeof(tmpbuf),
279 NULL, 0, NULL);
280 }
281 }
282
Jamie McCrae827118f2023-03-10 13:24:57 +0000283#ifdef MCUBOOT_SERIAL_IMG_GRP_HASH
284 /* Retrieve SHA256 hash of image for identification */
285 rc = boot_serial_get_hash(&hdr, fap, hash);
286#endif
287
Andrzej Puzdrowski4f9c7302021-07-16 17:34:43 +0200288 flash_area_close(fap);
289
Michael Grand5047f032022-11-24 16:49:56 +0100290 if (FIH_NOT_EQ(fih_rc, FIH_SUCCESS)) {
Fabio Utzig6f49c272019-08-23 11:42:58 -0300291 continue;
292 }
Fabio Utzig6f49c272019-08-23 11:42:58 -0300293
Øyvind Rønningstada7d34ca2022-02-28 13:47:57 +0100294 zcbor_map_start_encode(cbor_state, 20);
Fabio Utzig6f49c272019-08-23 11:42:58 -0300295
296#if (BOOT_IMAGE_NUMBER > 1)
Øyvind Rønningstada7d34ca2022-02-28 13:47:57 +0100297 zcbor_tstr_put_lit_cast(cbor_state, "image");
298 zcbor_uint32_put(cbor_state, image_index);
Fabio Utzig6f49c272019-08-23 11:42:58 -0300299#endif
300
Øyvind Rønningstada7d34ca2022-02-28 13:47:57 +0100301 zcbor_tstr_put_lit_cast(cbor_state, "slot");
302 zcbor_uint32_put(cbor_state, slot);
Jamie McCrae827118f2023-03-10 13:24:57 +0000303
304#ifdef MCUBOOT_SERIAL_IMG_GRP_HASH
305 if (rc == 0) {
306 zcbor_tstr_put_lit_cast(cbor_state, "hash");
307 zcbor_bstr_encode_ptr(cbor_state, hash, sizeof(hash));
308 }
309#endif
310
Øyvind Rønningstada7d34ca2022-02-28 13:47:57 +0100311 zcbor_tstr_put_lit_cast(cbor_state, "version");
Fabio Utzig6f49c272019-08-23 11:42:58 -0300312
313 bs_list_img_ver((char *)tmpbuf, sizeof(tmpbuf), &hdr.ih_ver);
Jamie McCrae827118f2023-03-10 13:24:57 +0000314
Jamie McCrae393af792023-04-14 11:31:16 +0100315 zcbor_tstr_encode_ptr(cbor_state, (char *)tmpbuf, strlen((char *)tmpbuf));
Øyvind Rønningstada7d34ca2022-02-28 13:47:57 +0100316 zcbor_map_end_encode(cbor_state, 20);
Christopher Collins92ea77f2016-12-12 15:59:26 -0800317 }
Christopher Collins92ea77f2016-12-12 15:59:26 -0800318 }
Øyvind Rønningstada7d34ca2022-02-28 13:47:57 +0100319 zcbor_list_end_encode(cbor_state, 5);
320 zcbor_map_end_encode(cbor_state, 1);
Christopher Collins92ea77f2016-12-12 15:59:26 -0800321 boot_serial_output();
322}
323
Dominik Ermelbcc17b42022-06-15 15:33:04 +0000324#ifdef MCUBOOT_ERASE_PROGRESSIVELY
325
326/** Erases range of flash, aligned to sector size
327 *
328 * Function will erase all sectors withing [start, end] range; it does not check
329 * the @p start for alignment, and it will use @p end to find boundaries of las
330 * sector to erase. Function returns offset of the first byte past the last
331 * erased sector, so basically offset of next sector to be erased if needed.
332 * The function is intended to be called iteratively with previously returned
333 * offset as @p start.
334 *
335 * @param start starting offset, aligned to sector offset;
336 * @param end ending offset, maybe anywhere within sector;
337 *
338 * @retval On success: offset of the first byte past last erased sector;
339 * On failure: -EINVAL.
340 */
341static off_t erase_range(const struct flash_area *fap, off_t start, off_t end)
342{
343 struct flash_sector sect;
344 size_t size;
345 int rc;
346
347 if (end >= flash_area_get_size(fap)) {
348 return -EINVAL;
349 }
350
351 if (end < start) {
352 return start;
353 }
354
Dominik Ermel24769882023-01-05 13:36:35 +0000355 if (flash_area_get_sector(fap, end, &sect)) {
Dominik Ermelbcc17b42022-06-15 15:33:04 +0000356 return -EINVAL;
357 }
358
359 size = flash_sector_get_off(&sect) + flash_sector_get_size(&sect) - start;
Stephanos Ioannidis09e2bd72022-07-11 22:01:49 +0900360 BOOT_LOG_INF("Erasing range 0x%jx:0x%jx", (intmax_t)start,
361 (intmax_t)(start + size - 1));
Dominik Ermelbcc17b42022-06-15 15:33:04 +0000362
363 rc = flash_area_erase(fap, start, size);
364 if (rc != 0) {
365 BOOT_LOG_ERR("Error %d while erasing range", rc);
366 return -EINVAL;
367 }
368
369 return start + size;
370}
371#endif
372
Christopher Collins92ea77f2016-12-12 15:59:26 -0800373/*
374 * Image upload request.
375 */
376static void
377bs_upload(char *buf, int len)
378{
Dominik Ermel5bd87442022-06-13 15:14:01 +0000379 static size_t img_size; /* Total image size, held for duration of upload */
380 static uint32_t curr_off; /* Expected current offset */
381 const uint8_t *img_chunk = NULL; /* Pointer to buffer with received image chunk */
382 size_t img_chunk_len = 0; /* Length of received image chunk */
383 size_t img_chunk_off = SIZE_MAX; /* Offset of image chunk within image */
384 uint8_t rem_bytes; /* Reminder bytes after aligning chunk write to
385 * to flash alignment */
Fabio Utzig6f49c272019-08-23 11:42:58 -0300386 int img_num;
Dominik Ermel5bd87442022-06-13 15:14:01 +0000387 size_t img_size_tmp = SIZE_MAX; /* Temp variable for image size */
Christopher Collins92ea77f2016-12-12 15:59:26 -0800388 const struct flash_area *fap = NULL;
389 int rc;
Dominik Ermel3d4e55d2021-07-09 11:14:10 +0000390#ifdef MCUBOOT_ERASE_PROGRESSIVELY
Dominik Ermelbcc17b42022-06-15 15:33:04 +0000391 static off_t not_yet_erased = 0; /* Offset of next byte to erase; writes to flash
392 * are done in consecutive manner and erases are done
393 * to allow currently received chunk to be written;
394 * this state variable holds information where last
395 * erase has stopped to let us know whether erase
396 * is needed to be able to write current chunk.
397 */
398 static struct flash_sector status_sector;
Emanuele Di Santo205c8c62018-07-20 11:42:31 +0200399#endif
Christopher Collins92ea77f2016-12-12 15:59:26 -0800400
Fabio Utzig6f49c272019-08-23 11:42:58 -0300401 img_num = 0;
Marko Kiiskilace50ab02018-06-06 11:33:33 +0300402
403 /*
404 * Expected data format.
405 * {
Fabio Utzig6f49c272019-08-23 11:42:58 -0300406 * "image":<image number in a multi-image set (OPTIONAL)>
407 * "data":<image data>
Marko Kiiskilace50ab02018-06-06 11:33:33 +0300408 * "len":<image len>
409 * "off":<current offset of image data>
410 * }
411 */
412
Øyvind Rønningstad212a35b2021-05-07 21:06:48 +0200413 struct Upload upload;
Øyvind Rønningstada7d34ca2022-02-28 13:47:57 +0100414 size_t decoded_len;
415 uint_fast8_t result = cbor_decode_Upload((const uint8_t *)buf, len, &upload, &decoded_len);
Øyvind Rønningstad212a35b2021-05-07 21:06:48 +0200416
Øyvind Rønningstada7d34ca2022-02-28 13:47:57 +0100417 if ((result != ZCBOR_SUCCESS) || (len != decoded_len)) {
Øyvind Rønningstadf42a8202019-12-13 03:27:54 +0100418 goto out_invalid_data;
419 }
Dominik Ermel470e2f32020-01-10 13:28:48 +0000420
Øyvind Rønningstadf42a8202019-12-13 03:27:54 +0100421 for (int i = 0; i < upload._Upload_members_count; i++) {
Øyvind Rønningstada7d34ca2022-02-28 13:47:57 +0100422 struct Member_ *member = &upload._Upload_members[i]._Upload_members;
Øyvind Rønningstadf42a8202019-12-13 03:27:54 +0100423 switch(member->_Member_choice) {
424 case _Member_image:
425 img_num = member->_Member_image;
426 break;
427 case _Member_data:
Dominik Ermel5bd87442022-06-13 15:14:01 +0000428 img_chunk = member->_Member_data.value;
429 img_chunk_len = member->_Member_data.len;
Øyvind Rønningstadf42a8202019-12-13 03:27:54 +0100430 break;
431 case _Member_len:
Dominik Ermel5bd87442022-06-13 15:14:01 +0000432 img_size_tmp = member->_Member_len;
Øyvind Rønningstadf42a8202019-12-13 03:27:54 +0100433 break;
434 case _Member_off:
Dominik Ermel5bd87442022-06-13 15:14:01 +0000435 img_chunk_off = member->_Member_off;
Øyvind Rønningstadf42a8202019-12-13 03:27:54 +0100436 break;
437 case _Member_sha:
438 default:
439 /* Nothing to do. */
440 break;
Marko Kiiskilace50ab02018-06-06 11:33:33 +0300441 }
442 }
Øyvind Rønningstadf42a8202019-12-13 03:27:54 +0100443
Dominik Ermel5bd87442022-06-13 15:14:01 +0000444 if (img_chunk_off == SIZE_MAX || img_chunk == NULL) {
Marko Kiiskilace50ab02018-06-06 11:33:33 +0300445 /*
446 * Offset must be set in every block.
447 */
448 goto out_invalid_data;
Christopher Collins92ea77f2016-12-12 15:59:26 -0800449 }
450
Dominik Ermel48decca2021-07-09 10:23:58 +0000451#if !defined(MCUBOOT_SERIAL_DIRECT_IMAGE_UPLOAD)
Fabio Utzig6f49c272019-08-23 11:42:58 -0300452 rc = flash_area_open(flash_area_id_from_multi_image_slot(img_num, 0), &fap);
Dominik Ermel48decca2021-07-09 10:23:58 +0000453#else
454 rc = flash_area_open(flash_area_id_from_direct_image(img_num), &fap);
455#endif
Christopher Collins92ea77f2016-12-12 15:59:26 -0800456 if (rc) {
457 rc = MGMT_ERR_EINVAL;
458 goto out;
459 }
460
Dominik Ermel5bd87442022-06-13 15:14:01 +0000461 if (img_chunk_off == 0) {
Dominik Ermelbcc17b42022-06-15 15:33:04 +0000462 /* Receiving chunk with 0 offset resets the upload state; this basically
463 * means that upload has started from beginning.
464 */
465 const size_t area_size = flash_area_get_size(fap);
Dominik Ermel5bd87442022-06-13 15:14:01 +0000466
Dominik Ermelbcc17b42022-06-15 15:33:04 +0000467 curr_off = 0;
468#ifdef MCUBOOT_ERASE_PROGRESSIVELY
469 /* Get trailer sector information; this is done early because inability to get
470 * that sector information means that upload will not work anyway.
471 * TODO: This is single occurrence issue, it should get detected during tests
472 * and fixed otherwise you are deploying broken mcuboot.
473 */
Dominik Ermel24769882023-01-05 13:36:35 +0000474 if (flash_area_get_sector(fap, boot_status_off(fap), &status_sector)) {
Dominik Ermelbcc17b42022-06-15 15:33:04 +0000475 rc = MGMT_ERR_EUNKNOWN;
476 BOOT_LOG_ERR("Unable to determine flash sector of the image trailer");
477 goto out;
478 }
479#endif
480
481
Wouter Cappellebb7a39d2021-05-03 16:44:44 +0200482#if defined(MCUBOOT_VALIDATE_PRIMARY_SLOT_ONCE)
483 /* We are using swap state at end of flash area to store validation
484 * result. Make sure the user cannot write it from an image to skip validation.
485 */
Dominik Ermelbcc17b42022-06-15 15:33:04 +0000486 if (img_size_tmp > (area_size - BOOT_MAGIC_SZ)) {
Wouter Cappellebb7a39d2021-05-03 16:44:44 +0200487 goto out_invalid_data;
488 }
Dominik Ermelbcc17b42022-06-15 15:33:04 +0000489#else
490 if (img_size_tmp > area_size) {
491 goto out_invalid_data;
492 }
493
Wouter Cappellebb7a39d2021-05-03 16:44:44 +0200494#endif
Dominik Ermelbcc17b42022-06-15 15:33:04 +0000495
Dominik Ermel3d4e55d2021-07-09 11:14:10 +0000496#ifndef MCUBOOT_ERASE_PROGRESSIVELY
Dominik Ermelbcc17b42022-06-15 15:33:04 +0000497 /* Non-progressive erase erases entire image slot when first chunk of
498 * an image is received.
499 */
500 rc = flash_area_erase(fap, 0, area_size);
Christopher Collins92ea77f2016-12-12 15:59:26 -0800501 if (rc) {
Marko Kiiskilace50ab02018-06-06 11:33:33 +0300502 goto out_invalid_data;
Christopher Collins92ea77f2016-12-12 15:59:26 -0800503 }
Dominik Ermelbcc17b42022-06-15 15:33:04 +0000504#else
505 not_yet_erased = 0;
Emanuele Di Santo205c8c62018-07-20 11:42:31 +0200506#endif
Dominik Ermelbcc17b42022-06-15 15:33:04 +0000507
Dominik Ermel5bd87442022-06-13 15:14:01 +0000508 img_size = img_size_tmp;
Dominik Ermelbcc17b42022-06-15 15:33:04 +0000509 } else if (img_chunk_off != curr_off) {
510 /* If received chunk offset does not match expected one jump, pretend
511 * success and jump to out; out will respond to client with success
512 * and request the expected offset, held by curr_off.
513 */
Christopher Collins92ea77f2016-12-12 15:59:26 -0800514 rc = 0;
515 goto out;
Dominik Ermelbcc17b42022-06-15 15:33:04 +0000516 } else if (curr_off + img_chunk_len > img_size) {
Andrzej Puzdrowskif48de7a2020-10-19 09:42:02 +0200517 rc = MGMT_ERR_EINVAL;
518 goto out;
519 }
520
Dominik Ermelbcc17b42022-06-15 15:33:04 +0000521#ifdef MCUBOOT_ERASE_PROGRESSIVELY
522 /* Progressive erase will erase enough flash, aligned to sector size,
523 * as needed for the current chunk to be written.
524 */
525 not_yet_erased = erase_range(fap, not_yet_erased,
526 curr_off + img_chunk_len - 1);
527
528 if (not_yet_erased < 0) {
529 rc = MGMT_ERR_EINVAL;
530 goto out;
531 }
532#endif
533
534 /* Writes are aligned to flash write alignment, so may drop a few bytes
535 * from the end of the buffer; we will request these bytes again with
536 * new buffer by responding with request for offset after the last aligned
537 * write.
538 */
Dominik Ermel5bd87442022-06-13 15:14:01 +0000539 rem_bytes = img_chunk_len % flash_area_align(fap);
Dominik Ermel7d2f0bf2022-06-21 16:15:34 +0000540 img_chunk_len -= rem_bytes;
Andrzej Puzdrowskif48de7a2020-10-19 09:42:02 +0200541
Dominik Ermel7d2f0bf2022-06-21 16:15:34 +0000542 if (curr_off + img_chunk_len + rem_bytes < img_size) {
Andrzej Puzdrowskif48de7a2020-10-19 09:42:02 +0200543 rem_bytes = 0;
Fabio Utzig30f6b2a2018-03-29 16:18:53 -0300544 }
Emanuele Di Santo205c8c62018-07-20 11:42:31 +0200545
Dominik Ermel5bd87442022-06-13 15:14:01 +0000546 BOOT_LOG_INF("Writing at 0x%x until 0x%x", curr_off, curr_off + img_chunk_len);
Dominik Ermel7d2f0bf2022-06-21 16:15:34 +0000547 /* Write flash aligned chunk, note that img_chunk_len now holds aligned length */
Jamie McCrae9d3fd7f2022-11-30 15:44:44 +0000548#if defined(MCUBOOT_SERIAL_UNALIGNED_BUFFER_SIZE) && MCUBOOT_SERIAL_UNALIGNED_BUFFER_SIZE > 0
549 if (flash_area_align(fap) > 1 &&
550 (((size_t)img_chunk) & (flash_area_align(fap) - 1)) != 0) {
551 /* Buffer address incompatible with write address, use buffer to write */
552 uint8_t write_size = MCUBOOT_SERIAL_UNALIGNED_BUFFER_SIZE;
553 uint8_t wbs_aligned[MCUBOOT_SERIAL_UNALIGNED_BUFFER_SIZE];
554
555 while (img_chunk_len >= flash_area_align(fap)) {
556 if (write_size > img_chunk_len) {
557 write_size = img_chunk_len;
558 }
559
560 memset(wbs_aligned, flash_area_erased_val(fap), sizeof(wbs_aligned));
561 memcpy(wbs_aligned, img_chunk, write_size);
562
563 rc = flash_area_write(fap, curr_off, wbs_aligned, write_size);
564
565 if (rc != 0) {
566 goto out;
567 }
568
569 curr_off += write_size;
570 img_chunk += write_size;
571 img_chunk_len -= write_size;
572 }
573 } else {
574 rc = flash_area_write(fap, curr_off, img_chunk, img_chunk_len);
575 }
576#else
Dominik Ermel7d2f0bf2022-06-21 16:15:34 +0000577 rc = flash_area_write(fap, curr_off, img_chunk, img_chunk_len);
Jamie McCrae9d3fd7f2022-11-30 15:44:44 +0000578#endif
579
Dominik Ermel7d2f0bf2022-06-21 16:15:34 +0000580 if (rc == 0 && rem_bytes) {
581 /* Non-zero rem_bytes means that last chunk needs alignment; the aligned
582 * part, in the img_chunk_len - rem_bytes count bytes, has already been
583 * written by the above write, so we are left with the rem_bytes.
584 */
Andrzej Puzdrowskif48de7a2020-10-19 09:42:02 +0200585 uint8_t wbs_aligned[BOOT_MAX_ALIGN];
Andrzej Puzdrowskif48de7a2020-10-19 09:42:02 +0200586
Dominik Ermel7d2f0bf2022-06-21 16:15:34 +0000587 memset(wbs_aligned, flash_area_erased_val(fap), sizeof(wbs_aligned));
588 memcpy(wbs_aligned, img_chunk + img_chunk_len, rem_bytes);
Andrzej Puzdrowskif48de7a2020-10-19 09:42:02 +0200589
Dominik Ermel7d2f0bf2022-06-21 16:15:34 +0000590 rc = flash_area_write(fap, curr_off + img_chunk_len, wbs_aligned,
591 flash_area_align(fap));
Andrzej Puzdrowskif48de7a2020-10-19 09:42:02 +0200592 }
593
Marko Kiiskilace50ab02018-06-06 11:33:33 +0300594 if (rc == 0) {
Dominik Ermel7d2f0bf2022-06-21 16:15:34 +0000595 curr_off += img_chunk_len + rem_bytes;
Andrzej Puzdrowskic2e30cf2018-07-20 16:19:09 +0200596 if (curr_off == img_size) {
Andrzej Puzdrowski4f9c7302021-07-16 17:34:43 +0200597#ifdef MCUBOOT_ERASE_PROGRESSIVELY
Andrzej Puzdrowskic2e30cf2018-07-20 16:19:09 +0200598 /* Assure that sector for image trailer was erased. */
599 /* Check whether it was erased during previous upload. */
Dominik Ermelbcc17b42022-06-15 15:33:04 +0000600 off_t start = flash_sector_get_off(&status_sector);
601
602 if (erase_range(fap, start, start) < 0) {
603 rc = MGMT_ERR_EUNKNOWN;
604 goto out;
Andrzej Puzdrowskic2e30cf2018-07-20 16:19:09 +0200605 }
Andrzej Puzdrowskic2e30cf2018-07-20 16:19:09 +0200606#endif
Andrzej Puzdrowski4f9c7302021-07-16 17:34:43 +0200607 rc = BOOT_HOOK_CALL(boot_serial_uploaded_hook, 0, img_num, fap,
608 img_size);
609 if (rc) {
610 BOOT_LOG_ERR("Error %d post upload hook", rc);
611 goto out;
612 }
613 }
Marko Kiiskilace50ab02018-06-06 11:33:33 +0300614 } else {
615 out_invalid_data:
Christopher Collins92ea77f2016-12-12 15:59:26 -0800616 rc = MGMT_ERR_EINVAL;
Christopher Collins92ea77f2016-12-12 15:59:26 -0800617 }
Emanuele Di Santo205c8c62018-07-20 11:42:31 +0200618
Christopher Collins92ea77f2016-12-12 15:59:26 -0800619out:
Andrzej Puzdrowski8e96b832017-09-08 16:49:14 +0200620 BOOT_LOG_INF("RX: 0x%x", rc);
Øyvind Rønningstada7d34ca2022-02-28 13:47:57 +0100621 zcbor_map_start_encode(cbor_state, 10);
622 zcbor_tstr_put_lit_cast(cbor_state, "rc");
Jamie McCrae0b6d3432022-12-02 09:24:10 +0000623 zcbor_int32_put(cbor_state, rc);
Christopher Collins92ea77f2016-12-12 15:59:26 -0800624 if (rc == 0) {
Øyvind Rønningstada7d34ca2022-02-28 13:47:57 +0100625 zcbor_tstr_put_lit_cast(cbor_state, "off");
626 zcbor_uint32_put(cbor_state, curr_off);
Christopher Collins92ea77f2016-12-12 15:59:26 -0800627 }
Øyvind Rønningstada7d34ca2022-02-28 13:47:57 +0100628 zcbor_map_end_encode(cbor_state, 10);
Christopher Collins92ea77f2016-12-12 15:59:26 -0800629
630 boot_serial_output();
631 flash_area_close(fap);
Wouter Cappelle953a7612021-05-03 16:53:05 +0200632
633#ifdef MCUBOOT_ENC_IMAGES
634 if (curr_off == img_size) {
635 /* Last sector received, now start a decryption on the image if it is encrypted*/
636 rc = boot_handle_enc_fw();
637 }
638#endif //#ifdef MCUBOOT_ENC_IMAGES
Christopher Collins92ea77f2016-12-12 15:59:26 -0800639}
640
Dominik Ermel4c0f6c12022-03-04 15:47:37 +0000641/*
642 * Send rc code only.
643 */
644static void
645bs_rc_rsp(int rc_code)
646{
Øyvind Rønningstada7d34ca2022-02-28 13:47:57 +0100647 zcbor_map_start_encode(cbor_state, 10);
648 zcbor_tstr_put_lit_cast(cbor_state, "rc");
Jamie McCrae0b6d3432022-12-02 09:24:10 +0000649 zcbor_int32_put(cbor_state, rc_code);
Øyvind Rønningstada7d34ca2022-02-28 13:47:57 +0100650 zcbor_map_end_encode(cbor_state, 10);
Dominik Ermel4c0f6c12022-03-04 15:47:37 +0000651 boot_serial_output();
652}
653
654
Wouter Cappellee3ff1752021-05-03 16:36:22 +0200655#ifdef MCUBOOT_BOOT_MGMT_ECHO
Wouter Cappellee3ff1752021-05-03 16:36:22 +0200656static void
657bs_echo(char *buf, int len)
658{
Dominik Ermel88bd5672022-06-07 15:17:06 +0000659 struct Echo echo = { 0 };
660 size_t decoded_len;
661 uint32_t rc = MGMT_ERR_EINVAL;
662 uint_fast8_t result = cbor_decode_Echo((const uint8_t *)buf, len, &echo, &decoded_len);
Wouter Cappellee3ff1752021-05-03 16:36:22 +0200663
Dominik Ermel88bd5672022-06-07 15:17:06 +0000664 if ((result != ZCBOR_SUCCESS) || (len != decoded_len)) {
665 goto out;
Wouter Cappellee3ff1752021-05-03 16:36:22 +0200666 }
Dominik Ermel88bd5672022-06-07 15:17:06 +0000667
668 if (echo._Echo_d.value == NULL) {
669 goto out;
670 }
671
672 zcbor_map_start_encode(cbor_state, 10);
673 zcbor_tstr_put_term(cbor_state, "r");
674 if (zcbor_tstr_encode(cbor_state, &echo._Echo_d) && zcbor_map_end_encode(cbor_state, 10)) {
675 boot_serial_output();
676 return;
677 } else {
678 rc = MGMT_ERR_ENOMEM;
679 }
680
681out:
682 reset_cbor_state();
683 bs_rc_rsp(rc);
Wouter Cappellee3ff1752021-05-03 16:36:22 +0200684}
685#endif
686
Christopher Collins92ea77f2016-12-12 15:59:26 -0800687/*
Christopher Collins92ea77f2016-12-12 15:59:26 -0800688 * Reset, and (presumably) boot to newly uploaded image. Flush console
689 * before restarting.
690 */
Andrzej Puzdrowski268cdd02018-04-10 12:57:54 +0200691static void
Christopher Collins92ea77f2016-12-12 15:59:26 -0800692bs_reset(char *buf, int len)
693{
Dominik Ermelb26fc482022-12-09 17:10:20 +0000694 int rc = BOOT_HOOK_CALL(boot_reset_request_hook, 0, false);
695 if (rc == BOOT_RESET_REQUEST_HOOK_BUSY) {
696 rc = MGMT_ERR_EBUSY;
697 } else {
698 /* Currently whatever else is returned it is just converted
699 * to 0/no error. Boot serial starts accepting "force" parameter
700 * in command this needs to change.
701 */
702 rc = 0;
703 }
704 bs_rc_rsp(rc);
Christopher Collins92ea77f2016-12-12 15:59:26 -0800705
Dominik Ermelb26fc482022-12-09 17:10:20 +0000706 if (rc == 0) {
Andrzej Puzdrowski8e96b832017-09-08 16:49:14 +0200707#ifdef __ZEPHYR__
Andrzej Puzdrowski0cf0dbd2021-05-14 11:55:57 +0200708#ifdef CONFIG_MULTITHREADING
Dominik Ermelb26fc482022-12-09 17:10:20 +0000709 k_sleep(K_MSEC(250));
Andrzej Puzdrowski0cf0dbd2021-05-14 11:55:57 +0200710#else
Dominik Ermelb26fc482022-12-09 17:10:20 +0000711 k_busy_wait(250000);
Andrzej Puzdrowski0cf0dbd2021-05-14 11:55:57 +0200712#endif
Dominik Ermelb26fc482022-12-09 17:10:20 +0000713 sys_reboot(SYS_REBOOT_COLD);
Almir Okatoe8cbc0d2022-06-13 10:45:39 -0300714#elif __ESPRESSIF__
Dominik Ermelb26fc482022-12-09 17:10:20 +0000715 esp_rom_delay_us(250000);
716 bootloader_reset();
Andrzej Puzdrowski8e96b832017-09-08 16:49:14 +0200717#else
Dominik Ermelb26fc482022-12-09 17:10:20 +0000718 os_cputime_delay_usecs(250000);
719 hal_system_reset();
Andrzej Puzdrowski8e96b832017-09-08 16:49:14 +0200720#endif
Dominik Ermelb26fc482022-12-09 17:10:20 +0000721 }
Christopher Collins92ea77f2016-12-12 15:59:26 -0800722}
723
724/*
725 * Parse incoming line of input from console.
726 * Expect newtmgr protocol with serial transport.
727 */
728void
729boot_serial_input(char *buf, int len)
730{
731 struct nmgr_hdr *hdr;
732
733 hdr = (struct nmgr_hdr *)buf;
734 if (len < sizeof(*hdr) ||
735 (hdr->nh_op != NMGR_OP_READ && hdr->nh_op != NMGR_OP_WRITE) ||
736 (ntohs(hdr->nh_len) < len - sizeof(*hdr))) {
737 return;
738 }
739 bs_hdr = hdr;
740 hdr->nh_group = ntohs(hdr->nh_group);
741
742 buf += sizeof(*hdr);
743 len -= sizeof(*hdr);
Marko Kiiskilace50ab02018-06-06 11:33:33 +0300744
Dominik Ermel4c0f6c12022-03-04 15:47:37 +0000745 reset_cbor_state();
Christopher Collins92ea77f2016-12-12 15:59:26 -0800746
747 /*
748 * Limited support for commands.
749 */
750 if (hdr->nh_group == MGMT_GROUP_ID_IMAGE) {
751 switch (hdr->nh_id) {
Marko Kiiskilace50ab02018-06-06 11:33:33 +0300752 case IMGMGR_NMGR_ID_STATE:
Christopher Collins92ea77f2016-12-12 15:59:26 -0800753 bs_list(buf, len);
754 break;
Marko Kiiskilace50ab02018-06-06 11:33:33 +0300755 case IMGMGR_NMGR_ID_UPLOAD:
Christopher Collins92ea77f2016-12-12 15:59:26 -0800756 bs_upload(buf, len);
757 break;
758 default:
Dominik Ermelc9dc2242021-07-28 17:08:23 +0000759 bs_rc_rsp(MGMT_ERR_ENOTSUP);
Christopher Collins92ea77f2016-12-12 15:59:26 -0800760 break;
761 }
762 } else if (hdr->nh_group == MGMT_GROUP_ID_DEFAULT) {
763 switch (hdr->nh_id) {
Wouter Cappellee3ff1752021-05-03 16:36:22 +0200764 case NMGR_ID_ECHO:
765#ifdef MCUBOOT_BOOT_MGMT_ECHO
766 bs_echo(buf, len);
767#endif
768 break;
Christopher Collins92ea77f2016-12-12 15:59:26 -0800769 case NMGR_ID_CONS_ECHO_CTRL:
Dominik Ermelc9dc2242021-07-28 17:08:23 +0000770 bs_rc_rsp(0);
Christopher Collins92ea77f2016-12-12 15:59:26 -0800771 break;
772 case NMGR_ID_RESET:
773 bs_reset(buf, len);
774 break;
775 default:
Dominik Ermelc9dc2242021-07-28 17:08:23 +0000776 bs_rc_rsp(MGMT_ERR_ENOTSUP);
Christopher Collins92ea77f2016-12-12 15:59:26 -0800777 break;
778 }
Dominik Ermelbd69c3d2021-07-28 11:27:31 +0000779 } else if (MCUBOOT_PERUSER_MGMT_GROUP_ENABLED == 1) {
Øyvind Rønningstada7d34ca2022-02-28 13:47:57 +0100780 if (bs_peruser_system_specific(hdr, buf, len, cbor_state) == 0) {
Dominik Ermel3d51e432021-06-25 17:29:50 +0000781 boot_serial_output();
782 }
Dominik Ermelc9dc2242021-07-28 17:08:23 +0000783 } else {
784 bs_rc_rsp(MGMT_ERR_ENOTSUP);
Christopher Collins92ea77f2016-12-12 15:59:26 -0800785 }
Wouter Cappellee3822f82022-01-19 15:39:43 +0100786#ifdef MCUBOOT_SERIAL_WAIT_FOR_DFU
787 bs_entry = true;
788#endif
Christopher Collins92ea77f2016-12-12 15:59:26 -0800789}
790
791static void
792boot_serial_output(void)
793{
794 char *data;
Piotr Dymaczf5e77532022-10-30 17:43:45 +0100795 int len, out;
Christopher Collins92ea77f2016-12-12 15:59:26 -0800796 uint16_t crc;
797 uint16_t totlen;
Piotr Dymaczf5e77532022-10-30 17:43:45 +0100798 char pkt_cont[2] = { SHELL_NLIP_DATA_START1, SHELL_NLIP_DATA_START2 };
Christopher Collins92ea77f2016-12-12 15:59:26 -0800799 char pkt_start[2] = { SHELL_NLIP_PKT_START1, SHELL_NLIP_PKT_START2 };
Dominik Ermel5ff89582022-03-03 17:09:07 +0000800 char buf[BOOT_SERIAL_OUT_MAX + sizeof(*bs_hdr) + sizeof(crc) + sizeof(totlen)];
801 char encoded_buf[BASE64_ENCODE_SIZE(sizeof(buf))];
Christopher Collins92ea77f2016-12-12 15:59:26 -0800802
803 data = bs_obuf;
Øyvind Rønningstada7d34ca2022-02-28 13:47:57 +0100804 len = (uint32_t)cbor_state->payload_mut - (uint32_t)bs_obuf;
Christopher Collins92ea77f2016-12-12 15:59:26 -0800805
806 bs_hdr->nh_op++;
Marko Kiiskilace50ab02018-06-06 11:33:33 +0300807 bs_hdr->nh_flags = 0;
Christopher Collins92ea77f2016-12-12 15:59:26 -0800808 bs_hdr->nh_len = htons(len);
809 bs_hdr->nh_group = htons(bs_hdr->nh_group);
810
Andrzej Puzdrowski8e96b832017-09-08 16:49:14 +0200811#ifdef __ZEPHYR__
Carles Cufib9192a42022-02-10 11:41:57 +0100812 crc = crc16_itu_t(CRC16_INITIAL_CRC, (uint8_t *)bs_hdr, sizeof(*bs_hdr));
813 crc = crc16_itu_t(crc, data, len);
Almir Okatoe8cbc0d2022-06-13 10:45:39 -0300814#elif __ESPRESSIF__
815 /* For ESP32 it was used the CRC API in rom/crc.h */
Almir Okato7d3622f2022-10-20 12:44:58 -0300816 crc = ~esp_crc16_be(~CRC16_INITIAL_CRC, (uint8_t *)bs_hdr, sizeof(*bs_hdr));
817 crc = ~esp_crc16_be(~crc, (uint8_t *)data, len);
Andrzej Puzdrowski8e96b832017-09-08 16:49:14 +0200818#else
Christopher Collins92ea77f2016-12-12 15:59:26 -0800819 crc = crc16_ccitt(CRC16_INITIAL_CRC, bs_hdr, sizeof(*bs_hdr));
820 crc = crc16_ccitt(crc, data, len);
Andrzej Puzdrowski8e96b832017-09-08 16:49:14 +0200821#endif
Christopher Collins92ea77f2016-12-12 15:59:26 -0800822 crc = htons(crc);
823
Christopher Collins92ea77f2016-12-12 15:59:26 -0800824 totlen = len + sizeof(*bs_hdr) + sizeof(crc);
825 totlen = htons(totlen);
826
827 memcpy(buf, &totlen, sizeof(totlen));
828 totlen = sizeof(totlen);
829 memcpy(&buf[totlen], bs_hdr, sizeof(*bs_hdr));
830 totlen += sizeof(*bs_hdr);
831 memcpy(&buf[totlen], data, len);
832 totlen += len;
833 memcpy(&buf[totlen], &crc, sizeof(crc));
834 totlen += sizeof(crc);
Andrzej Puzdrowski8e96b832017-09-08 16:49:14 +0200835#ifdef __ZEPHYR__
836 size_t enc_len;
Carles Cufi0165be82018-03-26 17:43:51 +0200837 base64_encode(encoded_buf, sizeof(encoded_buf), &enc_len, buf, totlen);
Andrzej Puzdrowski8e96b832017-09-08 16:49:14 +0200838 totlen = enc_len;
Almir Okatoe8cbc0d2022-06-13 10:45:39 -0300839#elif __ESPRESSIF__
840 size_t enc_len;
841 base64_encode((unsigned char *)encoded_buf, sizeof(encoded_buf), &enc_len, (unsigned char *)buf, totlen);
842 totlen = enc_len;
Andrzej Puzdrowski8e96b832017-09-08 16:49:14 +0200843#else
Christopher Collins92ea77f2016-12-12 15:59:26 -0800844 totlen = base64_encode(buf, totlen, encoded_buf, 1);
Andrzej Puzdrowski8e96b832017-09-08 16:49:14 +0200845#endif
Piotr Dymaczf5e77532022-10-30 17:43:45 +0100846
847 out = 0;
848 while (out < totlen) {
849 if (out == 0) {
850 boot_uf->write(pkt_start, sizeof(pkt_start));
851 } else {
852 boot_uf->write(pkt_cont, sizeof(pkt_cont));
853 }
854
855 len = MIN(BOOT_SERIAL_FRAME_MTU, totlen - out);
856 boot_uf->write(&encoded_buf[out], len);
857
858 out += len;
859
860 boot_uf->write("\n", 1);
861 }
862
Andrzej Puzdrowski8e96b832017-09-08 16:49:14 +0200863 BOOT_LOG_INF("TX");
Christopher Collins92ea77f2016-12-12 15:59:26 -0800864}
865
866/*
867 * Returns 1 if full packet has been received.
868 */
869static int
870boot_serial_in_dec(char *in, int inlen, char *out, int *out_off, int maxout)
871{
872 int rc;
873 uint16_t crc;
874 uint16_t len;
Marko Kiiskilae5aeee42018-12-21 15:00:16 +0200875
Andrzej Puzdrowski8e96b832017-09-08 16:49:14 +0200876#ifdef __ZEPHYR__
877 int err;
Andrzej Puzdrowskiec1e4d12018-06-18 14:36:14 +0200878 err = base64_decode( &out[*out_off], maxout - *out_off, &rc, in, inlen - 2);
Andrzej Puzdrowski8e96b832017-09-08 16:49:14 +0200879 if (err) {
880 return -1;
881 }
Almir Okatoe8cbc0d2022-06-13 10:45:39 -0300882#elif __ESPRESSIF__
883 int err;
884 err = base64_decode((unsigned char *)&out[*out_off], maxout - *out_off, (size_t *)&rc, (unsigned char *)in, inlen);
885 if (err) {
886 return -1;
887 }
Andrzej Puzdrowski8e96b832017-09-08 16:49:14 +0200888#else
Christopher Collins92ea77f2016-12-12 15:59:26 -0800889 if (*out_off + base64_decode_len(in) >= maxout) {
890 return -1;
891 }
892 rc = base64_decode(in, &out[*out_off]);
893 if (rc < 0) {
894 return -1;
895 }
Andrzej Puzdrowski8e96b832017-09-08 16:49:14 +0200896#endif
Fabio Utzig6f49c272019-08-23 11:42:58 -0300897
Christopher Collins92ea77f2016-12-12 15:59:26 -0800898 *out_off += rc;
Fabio Utzig6f49c272019-08-23 11:42:58 -0300899 if (*out_off <= sizeof(uint16_t)) {
900 return 0;
Christopher Collins92ea77f2016-12-12 15:59:26 -0800901 }
Fabio Utzig6f49c272019-08-23 11:42:58 -0300902
903 len = ntohs(*(uint16_t *)out);
904 if (len != *out_off - sizeof(uint16_t)) {
905 return 0;
906 }
907
908 if (len > *out_off - sizeof(uint16_t)) {
909 len = *out_off - sizeof(uint16_t);
910 }
911
912 out += sizeof(uint16_t);
913#ifdef __ZEPHYR__
Carles Cufib9192a42022-02-10 11:41:57 +0100914 crc = crc16_itu_t(CRC16_INITIAL_CRC, out, len);
Almir Okatoe8cbc0d2022-06-13 10:45:39 -0300915#elif __ESPRESSIF__
Almir Okato7d3622f2022-10-20 12:44:58 -0300916 crc = ~esp_crc16_be(~CRC16_INITIAL_CRC, (uint8_t *)out, len);
Fabio Utzig6f49c272019-08-23 11:42:58 -0300917#else
918 crc = crc16_ccitt(CRC16_INITIAL_CRC, out, len);
919#endif
920 if (crc || len <= sizeof(crc)) {
921 return 0;
922 }
923 *out_off -= sizeof(crc);
924 out[*out_off] = '\0';
925
926 return 1;
Christopher Collins92ea77f2016-12-12 15:59:26 -0800927}
928
929/*
930 * Task which waits reading console, expecting to get image over
931 * serial port.
932 */
Wouter Cappellee3822f82022-01-19 15:39:43 +0100933static void
934boot_serial_read_console(const struct boot_uart_funcs *f,int timeout_in_ms)
Christopher Collins92ea77f2016-12-12 15:59:26 -0800935{
936 int rc;
937 int off;
David Brown57f0df32020-05-12 08:39:21 -0600938 int dec_off = 0;
Christopher Collins92ea77f2016-12-12 15:59:26 -0800939 int full_line;
Marko Kiiskila149b4572018-06-06 14:18:54 +0300940 int max_input;
Wouter Cappellee3822f82022-01-19 15:39:43 +0100941 int elapsed_in_ms = 0;
Christopher Collins92ea77f2016-12-12 15:59:26 -0800942
Marko Kiiskila149b4572018-06-06 14:18:54 +0300943 boot_uf = f;
Marko Kiiskila149b4572018-06-06 14:18:54 +0300944 max_input = sizeof(in_buf);
Christopher Collins92ea77f2016-12-12 15:59:26 -0800945
946 off = 0;
Wouter Cappellee3822f82022-01-19 15:39:43 +0100947 while (timeout_in_ms > 0 || bs_entry) {
Piotr Dymacz067f30a2022-08-12 18:25:34 +0200948 /*
949 * Don't enter CPU idle state here if timeout based serial recovery is
950 * used as otherwise the boot process hangs forever, waiting for input
951 * from serial console (if single-thread mode is used).
952 */
Piotr Dymacz3942e9b2022-07-18 10:19:25 +0200953#ifndef MCUBOOT_SERIAL_WAIT_FOR_DFU
Andrzej Puzdrowskiaea38eb2021-06-11 12:28:59 +0200954 MCUBOOT_CPU_IDLE();
Piotr Dymacz3942e9b2022-07-18 10:19:25 +0200955#endif
Hein Wessels56d28f02021-11-19 08:42:08 +0100956 MCUBOOT_WATCHDOG_FEED();
Wouter Cappellee3822f82022-01-19 15:39:43 +0100957#ifdef MCUBOOT_SERIAL_WAIT_FOR_DFU
958 uint32_t start = k_uptime_get_32();
959#endif
Andrzej Puzdrowskiec1e4d12018-06-18 14:36:14 +0200960 rc = f->read(in_buf + off, sizeof(in_buf) - off, &full_line);
Christopher Collins92ea77f2016-12-12 15:59:26 -0800961 if (rc <= 0 && !full_line) {
Wouter Cappellee3822f82022-01-19 15:39:43 +0100962 goto check_timeout;
Christopher Collins92ea77f2016-12-12 15:59:26 -0800963 }
964 off += rc;
965 if (!full_line) {
Marko Kiiskilace50ab02018-06-06 11:33:33 +0300966 if (off == max_input) {
967 /*
968 * Full line, no newline yet. Reset the input buffer.
969 */
970 off = 0;
971 }
Wouter Cappellee3822f82022-01-19 15:39:43 +0100972 goto check_timeout;
Christopher Collins92ea77f2016-12-12 15:59:26 -0800973 }
Andrzej Puzdrowskiec1e4d12018-06-18 14:36:14 +0200974 if (in_buf[0] == SHELL_NLIP_PKT_START1 &&
975 in_buf[1] == SHELL_NLIP_PKT_START2) {
Christopher Collins92ea77f2016-12-12 15:59:26 -0800976 dec_off = 0;
Andrzej Puzdrowskiec1e4d12018-06-18 14:36:14 +0200977 rc = boot_serial_in_dec(&in_buf[2], off - 2, dec_buf, &dec_off, max_input);
978 } else if (in_buf[0] == SHELL_NLIP_DATA_START1 &&
979 in_buf[1] == SHELL_NLIP_DATA_START2) {
980 rc = boot_serial_in_dec(&in_buf[2], off - 2, dec_buf, &dec_off, max_input);
Christopher Collins92ea77f2016-12-12 15:59:26 -0800981 }
Andrzej Puzdrowskiec1e4d12018-06-18 14:36:14 +0200982
983 /* serve errors: out of decode memory, or bad encoding */
Christopher Collins92ea77f2016-12-12 15:59:26 -0800984 if (rc == 1) {
Andrzej Puzdrowskiec1e4d12018-06-18 14:36:14 +0200985 boot_serial_input(&dec_buf[2], dec_off - 2);
Christopher Collins92ea77f2016-12-12 15:59:26 -0800986 }
987 off = 0;
Wouter Cappellee3822f82022-01-19 15:39:43 +0100988check_timeout:
989 /* Subtract elapsed time */
990#ifdef MCUBOOT_SERIAL_WAIT_FOR_DFU
991 elapsed_in_ms = (k_uptime_get_32() - start);
992#endif
993 timeout_in_ms -= elapsed_in_ms;
Christopher Collins92ea77f2016-12-12 15:59:26 -0800994 }
995}
Wouter Cappellee3822f82022-01-19 15:39:43 +0100996
997/*
998 * Task which waits reading console, expecting to get image over
999 * serial port.
1000 */
1001void
1002boot_serial_start(const struct boot_uart_funcs *f)
1003{
1004 bs_entry = true;
1005 boot_serial_read_console(f,0);
1006}
1007
1008#ifdef MCUBOOT_SERIAL_WAIT_FOR_DFU
1009/*
1010 * Task which waits reading console for a certain amount of timeout.
1011 * If within this timeout no mcumgr command is received, the function is
1012 * returning, else the serial boot is never exited
1013 */
1014void
1015boot_serial_check_start(const struct boot_uart_funcs *f, int timeout_in_ms)
1016{
1017 bs_entry = false;
1018 boot_serial_read_console(f,timeout_in_ms);
1019}
1020#endif
Jamie McCrae827118f2023-03-10 13:24:57 +00001021
1022#ifdef MCUBOOT_SERIAL_IMG_GRP_HASH
1023/* Function to find the hash of an image, returns 0 on success. */
1024static int boot_serial_get_hash(const struct image_header *hdr,
1025 const struct flash_area *fap, uint8_t *hash)
1026{
1027 struct image_tlv_iter it;
1028 uint32_t offset;
1029 uint16_t len;
1030 uint16_t type;
1031 int rc;
1032
1033 /* Manifest data is concatenated to the end of the image.
1034 * It is encoded in TLV format.
1035 */
1036 rc = bootutil_tlv_iter_begin(&it, hdr, fap, IMAGE_TLV_ANY, false);
1037 if (rc) {
1038 return -1;
1039 }
1040
1041 /* Traverse through the TLV area to find the image hash TLV. */
1042 while (true) {
1043 rc = bootutil_tlv_iter_next(&it, &offset, &len, &type);
1044 if (rc < 0) {
1045 return -1;
1046 } else if (rc > 0) {
1047 break;
1048 }
1049
1050 if (type == IMAGE_TLV_SHA256) {
1051 /* Get the image's hash value from the manifest section. */
1052 if (len != 32) {
1053 return -1;
1054 }
1055
1056 rc = flash_area_read(fap, offset, hash, len);
1057 if (rc) {
1058 return -1;
1059 }
1060
1061 return 0;
1062 }
1063 }
1064
1065 return -1;
1066}
1067#endif