blob: 6070a3b853a938806ccda9f6c2c804b2262a2b0b [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>
24
25#include "sysflash/sysflash.h"
26
Fabio Utzig1a2e41a2017-11-17 12:13:09 -020027#include "bootutil/bootutil_log.h"
Øyvind Rønningstada7d34ca2022-02-28 13:47:57 +010028#include "zcbor_encode.h"
Fabio Utzig1a2e41a2017-11-17 12:13:09 -020029
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>
35#include <zephyr/sys/crc.h>
36#include <zephyr/sys/base64.h>
Almir Okatoe8cbc0d2022-06-13 10:45:39 -030037#include <hal/hal_flash.h>
38#elif __ESPRESSIF__
39#include <bootloader_utility.h>
40#include <esp_rom_sys.h>
41#include <rom/crc.h>
42#include <endian.h>
43#include <mbedtls/base64.h>
Andrzej Puzdrowski8e96b832017-09-08 16:49:14 +020044#else
Christopher Collins92ea77f2016-12-12 15:59:26 -080045#include <bsp/bsp.h>
Christopher Collins92ea77f2016-12-12 15:59:26 -080046#include <hal/hal_system.h>
Almir Okatoe8cbc0d2022-06-13 10:45:39 -030047#include <hal/hal_flash.h>
Christopher Collins92ea77f2016-12-12 15:59:26 -080048#include <os/endian.h>
Christopher Collins92ea77f2016-12-12 15:59:26 -080049#include <os/os_cputime.h>
Andrzej Puzdrowski8e96b832017-09-08 16:49:14 +020050#include <crc/crc16.h>
51#include <base64/base64.h>
Andrzej Puzdrowski386b5922018-04-06 19:26:24 +020052#endif /* __ZEPHYR__ */
53
Andrzej Puzdrowskib788c712018-04-12 12:42:49 +020054#include <flash_map_backend/flash_map_backend.h>
Andrzej Puzdrowski8e96b832017-09-08 16:49:14 +020055#include <os/os.h>
56#include <os/os_malloc.h>
Christopher Collins92ea77f2016-12-12 15:59:26 -080057
58#include <bootutil/image.h>
Andrzej Puzdrowskif48de7a2020-10-19 09:42:02 +020059#include <bootutil/bootutil.h>
Christopher Collins92ea77f2016-12-12 15:59:26 -080060
61#include "boot_serial/boot_serial.h"
62#include "boot_serial_priv.h"
Almir Okatoe8cbc0d2022-06-13 10:45:39 -030063#include "mcuboot_config/mcuboot_config.h"
Christopher Collins92ea77f2016-12-12 15:59:26 -080064
Dominik Ermel3d4e55d2021-07-09 11:14:10 +000065#ifdef MCUBOOT_ERASE_PROGRESSIVELY
Andrzej Puzdrowskic2e30cf2018-07-20 16:19:09 +020066#include "bootutil_priv.h"
67#endif
68
Wouter Cappelle953a7612021-05-03 16:53:05 +020069#ifdef MCUBOOT_ENC_IMAGES
70#include "single_loader.h"
71#endif
72
Øyvind Rønningstadf42a8202019-12-13 03:27:54 +010073#include "serial_recovery_cbor.h"
Dominik Ermel88bd5672022-06-07 15:17:06 +000074#include "serial_recovery_echo.h"
Andrzej Puzdrowski4f9c7302021-07-16 17:34:43 +020075#include "bootutil/boot_hooks.h"
Øyvind Rønningstadf42a8202019-12-13 03:27:54 +010076
Carlos Falgueras Garcíaa4b4b0f2021-06-22 10:00:22 +020077BOOT_LOG_MODULE_DECLARE(mcuboot);
Emanuele Di Santo9f1933d2018-11-20 10:59:59 +010078
Marko Kiiskila149b4572018-06-06 14:18:54 +030079#define BOOT_SERIAL_INPUT_MAX 512
Andrzej Puzdrowskic9ac5cc2021-11-19 11:58:05 +010080#define BOOT_SERIAL_OUT_MAX (128 * BOOT_IMAGE_NUMBER)
Christopher Collins92ea77f2016-12-12 15:59:26 -080081
Andrzej Puzdrowski8e96b832017-09-08 16:49:14 +020082#ifdef __ZEPHYR__
Carles Cufi0165be82018-03-26 17:43:51 +020083/* base64 lib encodes data to null-terminated string */
Andrzej Puzdrowski8e96b832017-09-08 16:49:14 +020084#define BASE64_ENCODE_SIZE(in_size) ((((((in_size) - 1) / 3) * 4) + 4) + 1)
85
86#define CRC16_INITIAL_CRC 0 /* what to seed crc16 with */
87#define CRC_CITT_POLYMINAL 0x1021
88
89#define ntohs(x) sys_be16_to_cpu(x)
90#define htons(x) sys_cpu_to_be16(x)
Almir Okatoe8cbc0d2022-06-13 10:45:39 -030091#elif __ESPRESSIF__
92#define BASE64_ENCODE_SIZE(in_size) ((((((in_size) - 1) / 3) * 4) + 4) + 1)
93#define CRC16_INITIAL_CRC 0 /* what to seed crc16 with */
94
95#define ntohs(x) be16toh(x)
96#define htons(x) htobe16(x)
97
98#define base64_decode mbedtls_base64_decode
99#define base64_encode mbedtls_base64_encode
Andrzej Puzdrowski8e96b832017-09-08 16:49:14 +0200100#endif
Emanuele Di Santo9f1933d2018-11-20 10:59:59 +0100101
Fabio Utzig6f49c272019-08-23 11:42:58 -0300102#if (BOOT_IMAGE_NUMBER > 1)
103#define IMAGES_ITER(x) for ((x) = 0; (x) < BOOT_IMAGE_NUMBER; ++(x))
104#else
105#define IMAGES_ITER(x)
106#endif
107
Marko Kiiskila149b4572018-06-06 14:18:54 +0300108static char in_buf[BOOT_SERIAL_INPUT_MAX + 1];
109static char dec_buf[BOOT_SERIAL_INPUT_MAX + 1];
Marko Kiiskila8b1ce3a2018-06-14 13:20:46 -0700110const struct boot_uart_funcs *boot_uf;
Christopher Collins92ea77f2016-12-12 15:59:26 -0800111static struct nmgr_hdr *bs_hdr;
Wouter Cappellee3822f82022-01-19 15:39:43 +0100112static bool bs_entry;
Christopher Collins92ea77f2016-12-12 15:59:26 -0800113
114static char bs_obuf[BOOT_SERIAL_OUT_MAX];
115
Christopher Collins92ea77f2016-12-12 15:59:26 -0800116static void boot_serial_output(void);
117
Øyvind Rønningstada7d34ca2022-02-28 13:47:57 +0100118static zcbor_state_t cbor_state[2];
Christopher Collins92ea77f2016-12-12 15:59:26 -0800119
Dominik Ermel4c0f6c12022-03-04 15:47:37 +0000120void reset_cbor_state(void)
121{
Øyvind Rønningstada7d34ca2022-02-28 13:47:57 +0100122 zcbor_new_encode_state(cbor_state, 2, (uint8_t *)bs_obuf,
123 (size_t)bs_obuf + sizeof(bs_obuf), 0);
Dominik Ermel4c0f6c12022-03-04 15:47:37 +0000124}
125
Dominik Ermel3d51e432021-06-25 17:29:50 +0000126/**
Dominik Ermelbd69c3d2021-07-28 11:27:31 +0000127 * Function that processes MGMT_GROUP_ID_PERUSER mcumgr group and may be
128 * used to process any groups that have not been processed by generic boot
129 * serial implementation.
Dominik Ermel3d51e432021-06-25 17:29:50 +0000130 *
131 * @param[in] hdr -- the decoded header of mcumgr message;
132 * @param[in] buffer -- buffer with first mcumgr message;
133 * @param[in] len -- length of of data in buffer;
134 * @param[out] *cs -- object with encoded response.
135 *
136 * @return 0 on success; non-0 error code otherwise.
137 */
138extern int bs_peruser_system_specific(const struct nmgr_hdr *hdr,
139 const char *buffer,
Øyvind Rønningstada7d34ca2022-02-28 13:47:57 +0100140 int len, zcbor_state_t *cs);
Christopher Collins92ea77f2016-12-12 15:59:26 -0800141
Dominik Ermeld49cfc12022-06-09 08:24:48 +0000142#define zcbor_tstr_put_lit_cast(state, string) \
143 zcbor_tstr_encode_ptr(state, (uint8_t *)string, sizeof(string) - 1)
144
145#ifndef MCUBOOT_USE_SNPRINTF
Christopher Collins92ea77f2016-12-12 15:59:26 -0800146/*
Marko Kiiskilace50ab02018-06-06 11:33:33 +0300147 * Convert version into string without use of snprintf().
Christopher Collins92ea77f2016-12-12 15:59:26 -0800148 */
Marko Kiiskilace50ab02018-06-06 11:33:33 +0300149static int
150u32toa(char *tgt, uint32_t val)
Christopher Collins92ea77f2016-12-12 15:59:26 -0800151{
Marko Kiiskilace50ab02018-06-06 11:33:33 +0300152 char *dst;
153 uint32_t d = 1;
154 uint32_t dgt;
155 int n = 0;
Christopher Collins92ea77f2016-12-12 15:59:26 -0800156
Marko Kiiskilace50ab02018-06-06 11:33:33 +0300157 dst = tgt;
158 while (val / d >= 10) {
159 d *= 10;
Christopher Collins92ea77f2016-12-12 15:59:26 -0800160 }
Marko Kiiskilace50ab02018-06-06 11:33:33 +0300161 while (d) {
162 dgt = val / d;
163 val %= d;
164 d /= 10;
165 if (n || dgt > 0 || d == 0) {
166 *dst++ = dgt + '0';
167 ++n;
Christopher Collins92ea77f2016-12-12 15:59:26 -0800168 }
Christopher Collins92ea77f2016-12-12 15:59:26 -0800169 }
Marko Kiiskilace50ab02018-06-06 11:33:33 +0300170 *dst = '\0';
171
172 return dst - tgt;
173}
174
175/*
176 * dst has to be able to fit "255.255.65535.4294967295" (25 characters).
177 */
178static void
179bs_list_img_ver(char *dst, int maxlen, struct image_version *ver)
180{
181 int off;
182
183 off = u32toa(dst, ver->iv_major);
184 dst[off++] = '.';
185 off += u32toa(dst + off, ver->iv_minor);
186 dst[off++] = '.';
187 off += u32toa(dst + off, ver->iv_revision);
188 dst[off++] = '.';
189 off += u32toa(dst + off, ver->iv_build_num);
Christopher Collins92ea77f2016-12-12 15:59:26 -0800190}
Dominik Ermeld49cfc12022-06-09 08:24:48 +0000191#else
192/*
193 * dst has to be able to fit "255.255.65535.4294967295" (25 characters).
194 */
195static void
196bs_list_img_ver(char *dst, int maxlen, struct image_version *ver)
197{
198 snprintf(dst, maxlen, "%hu.%hu.%hu.%u", (uint16_t)ver->iv_major,
199 (uint16_t)ver->iv_minor, ver->iv_revision, ver->iv_build_num);
200}
201#endif /* !MCUBOOT_USE_SNPRINTF */
Christopher Collins92ea77f2016-12-12 15:59:26 -0800202
203/*
204 * List images.
205 */
206static void
207bs_list(char *buf, int len)
208{
Christopher Collins92ea77f2016-12-12 15:59:26 -0800209 struct image_header hdr;
210 uint8_t tmpbuf[64];
Øyvind Rønningstad9f4aefd2021-03-08 21:11:25 +0100211 uint32_t slot, area_id;
Christopher Collins92ea77f2016-12-12 15:59:26 -0800212 const struct flash_area *fap;
Fabio Utzig6f49c272019-08-23 11:42:58 -0300213 uint8_t image_index;
Christopher Collins92ea77f2016-12-12 15:59:26 -0800214
Øyvind Rønningstada7d34ca2022-02-28 13:47:57 +0100215 zcbor_map_start_encode(cbor_state, 1);
216 zcbor_tstr_put_lit_cast(cbor_state, "images");
217 zcbor_list_start_encode(cbor_state, 5);
Fabio Utzig6f49c272019-08-23 11:42:58 -0300218 image_index = 0;
219 IMAGES_ITER(image_index) {
220 for (slot = 0; slot < 2; slot++) {
221 area_id = flash_area_id_from_multi_image_slot(image_index, slot);
222 if (flash_area_open(area_id, &fap)) {
223 continue;
224 }
Christopher Collins92ea77f2016-12-12 15:59:26 -0800225
Andrzej Puzdrowski4f9c7302021-07-16 17:34:43 +0200226 int rc = BOOT_HOOK_CALL(boot_read_image_header_hook,
227 BOOT_HOOK_REGULAR, image_index, slot, &hdr);
228 if (rc == BOOT_HOOK_REGULAR)
229 {
230 flash_area_read(fap, 0, &hdr, sizeof(hdr));
231 }
Christopher Collins92ea77f2016-12-12 15:59:26 -0800232
Andrzej Puzdrowski4f9c7302021-07-16 17:34:43 +0200233 fih_int fih_rc = FIH_FAILURE;
234
235 if (hdr.ih_magic == IMAGE_MAGIC)
236 {
237 BOOT_HOOK_CALL_FIH(boot_image_check_hook,
238 fih_int_encode(BOOT_HOOK_REGULAR),
239 fih_rc, image_index, slot);
240 if (fih_eq(fih_rc, BOOT_HOOK_REGULAR))
241 {
Wouter Cappelle953a7612021-05-03 16:53:05 +0200242#ifdef MCUBOOT_ENC_IMAGES
243 if (slot == 0 && IS_ENCRYPTED(&hdr)) {
244 /* Clear the encrypted flag we didn't supply a key
245 * This flag could be set if there was a decryption in place
246 * performed before. We will try to validate the image without
247 * decryption by clearing the flag in the heder. If
248 * still encrypted the validation will fail.
249 */
250 hdr.ih_flags &= ~(ENCRYPTIONFLAGS);
251 }
252#endif
Andrzej Puzdrowski4f9c7302021-07-16 17:34:43 +0200253 FIH_CALL(bootutil_img_validate, fih_rc, NULL, 0, &hdr, fap, tmpbuf, sizeof(tmpbuf),
254 NULL, 0, NULL);
255 }
256 }
257
258 flash_area_close(fap);
259
260 if (fih_not_eq(fih_rc, FIH_SUCCESS)) {
Fabio Utzig6f49c272019-08-23 11:42:58 -0300261 continue;
262 }
Fabio Utzig6f49c272019-08-23 11:42:58 -0300263
Øyvind Rønningstada7d34ca2022-02-28 13:47:57 +0100264 zcbor_map_start_encode(cbor_state, 20);
Fabio Utzig6f49c272019-08-23 11:42:58 -0300265
266#if (BOOT_IMAGE_NUMBER > 1)
Øyvind Rønningstada7d34ca2022-02-28 13:47:57 +0100267 zcbor_tstr_put_lit_cast(cbor_state, "image");
268 zcbor_uint32_put(cbor_state, image_index);
Fabio Utzig6f49c272019-08-23 11:42:58 -0300269#endif
270
Øyvind Rønningstada7d34ca2022-02-28 13:47:57 +0100271 zcbor_tstr_put_lit_cast(cbor_state, "slot");
272 zcbor_uint32_put(cbor_state, slot);
273 zcbor_tstr_put_lit_cast(cbor_state, "version");
Fabio Utzig6f49c272019-08-23 11:42:58 -0300274
275 bs_list_img_ver((char *)tmpbuf, sizeof(tmpbuf), &hdr.ih_ver);
Øyvind Rønningstada7d34ca2022-02-28 13:47:57 +0100276 zcbor_tstr_encode_ptr(cbor_state, tmpbuf, strlen((char *)tmpbuf));
277 zcbor_map_end_encode(cbor_state, 20);
Christopher Collins92ea77f2016-12-12 15:59:26 -0800278 }
Christopher Collins92ea77f2016-12-12 15:59:26 -0800279 }
Øyvind Rønningstada7d34ca2022-02-28 13:47:57 +0100280 zcbor_list_end_encode(cbor_state, 5);
281 zcbor_map_end_encode(cbor_state, 1);
Christopher Collins92ea77f2016-12-12 15:59:26 -0800282 boot_serial_output();
283}
284
Dominik Ermelbcc17b42022-06-15 15:33:04 +0000285#ifdef MCUBOOT_ERASE_PROGRESSIVELY
286
287/** Erases range of flash, aligned to sector size
288 *
289 * Function will erase all sectors withing [start, end] range; it does not check
290 * the @p start for alignment, and it will use @p end to find boundaries of las
291 * sector to erase. Function returns offset of the first byte past the last
292 * erased sector, so basically offset of next sector to be erased if needed.
293 * The function is intended to be called iteratively with previously returned
294 * offset as @p start.
295 *
296 * @param start starting offset, aligned to sector offset;
297 * @param end ending offset, maybe anywhere within sector;
298 *
299 * @retval On success: offset of the first byte past last erased sector;
300 * On failure: -EINVAL.
301 */
302static off_t erase_range(const struct flash_area *fap, off_t start, off_t end)
303{
304 struct flash_sector sect;
305 size_t size;
306 int rc;
307
308 if (end >= flash_area_get_size(fap)) {
309 return -EINVAL;
310 }
311
312 if (end < start) {
313 return start;
314 }
315
316 if (flash_area_sector_from_off(end, &sect)) {
317 return -EINVAL;
318 }
319
320 size = flash_sector_get_off(&sect) + flash_sector_get_size(&sect) - start;
Stephanos Ioannidis09e2bd72022-07-11 22:01:49 +0900321 BOOT_LOG_INF("Erasing range 0x%jx:0x%jx", (intmax_t)start,
322 (intmax_t)(start + size - 1));
Dominik Ermelbcc17b42022-06-15 15:33:04 +0000323
324 rc = flash_area_erase(fap, start, size);
325 if (rc != 0) {
326 BOOT_LOG_ERR("Error %d while erasing range", rc);
327 return -EINVAL;
328 }
329
330 return start + size;
331}
332#endif
333
Christopher Collins92ea77f2016-12-12 15:59:26 -0800334/*
335 * Image upload request.
336 */
337static void
338bs_upload(char *buf, int len)
339{
Dominik Ermel5bd87442022-06-13 15:14:01 +0000340 static size_t img_size; /* Total image size, held for duration of upload */
341 static uint32_t curr_off; /* Expected current offset */
342 const uint8_t *img_chunk = NULL; /* Pointer to buffer with received image chunk */
343 size_t img_chunk_len = 0; /* Length of received image chunk */
344 size_t img_chunk_off = SIZE_MAX; /* Offset of image chunk within image */
345 uint8_t rem_bytes; /* Reminder bytes after aligning chunk write to
346 * to flash alignment */
Fabio Utzig6f49c272019-08-23 11:42:58 -0300347 int img_num;
Dominik Ermel5bd87442022-06-13 15:14:01 +0000348 size_t img_size_tmp = SIZE_MAX; /* Temp variable for image size */
Christopher Collins92ea77f2016-12-12 15:59:26 -0800349 const struct flash_area *fap = NULL;
350 int rc;
Dominik Ermel3d4e55d2021-07-09 11:14:10 +0000351#ifdef MCUBOOT_ERASE_PROGRESSIVELY
Dominik Ermelbcc17b42022-06-15 15:33:04 +0000352 static off_t not_yet_erased = 0; /* Offset of next byte to erase; writes to flash
353 * are done in consecutive manner and erases are done
354 * to allow currently received chunk to be written;
355 * this state variable holds information where last
356 * erase has stopped to let us know whether erase
357 * is needed to be able to write current chunk.
358 */
359 static struct flash_sector status_sector;
Emanuele Di Santo205c8c62018-07-20 11:42:31 +0200360#endif
Christopher Collins92ea77f2016-12-12 15:59:26 -0800361
Fabio Utzig6f49c272019-08-23 11:42:58 -0300362 img_num = 0;
Marko Kiiskilace50ab02018-06-06 11:33:33 +0300363
364 /*
365 * Expected data format.
366 * {
Fabio Utzig6f49c272019-08-23 11:42:58 -0300367 * "image":<image number in a multi-image set (OPTIONAL)>
368 * "data":<image data>
Marko Kiiskilace50ab02018-06-06 11:33:33 +0300369 * "len":<image len>
370 * "off":<current offset of image data>
371 * }
372 */
373
Øyvind Rønningstad212a35b2021-05-07 21:06:48 +0200374 struct Upload upload;
Øyvind Rønningstada7d34ca2022-02-28 13:47:57 +0100375 size_t decoded_len;
376 uint_fast8_t result = cbor_decode_Upload((const uint8_t *)buf, len, &upload, &decoded_len);
Øyvind Rønningstad212a35b2021-05-07 21:06:48 +0200377
Øyvind Rønningstada7d34ca2022-02-28 13:47:57 +0100378 if ((result != ZCBOR_SUCCESS) || (len != decoded_len)) {
Øyvind Rønningstadf42a8202019-12-13 03:27:54 +0100379 goto out_invalid_data;
380 }
Dominik Ermel470e2f32020-01-10 13:28:48 +0000381
Øyvind Rønningstadf42a8202019-12-13 03:27:54 +0100382 for (int i = 0; i < upload._Upload_members_count; i++) {
Øyvind Rønningstada7d34ca2022-02-28 13:47:57 +0100383 struct Member_ *member = &upload._Upload_members[i]._Upload_members;
Øyvind Rønningstadf42a8202019-12-13 03:27:54 +0100384 switch(member->_Member_choice) {
385 case _Member_image:
386 img_num = member->_Member_image;
387 break;
388 case _Member_data:
Dominik Ermel5bd87442022-06-13 15:14:01 +0000389 img_chunk = member->_Member_data.value;
390 img_chunk_len = member->_Member_data.len;
Øyvind Rønningstadf42a8202019-12-13 03:27:54 +0100391 break;
392 case _Member_len:
Dominik Ermel5bd87442022-06-13 15:14:01 +0000393 img_size_tmp = member->_Member_len;
Øyvind Rønningstadf42a8202019-12-13 03:27:54 +0100394 break;
395 case _Member_off:
Dominik Ermel5bd87442022-06-13 15:14:01 +0000396 img_chunk_off = member->_Member_off;
Øyvind Rønningstadf42a8202019-12-13 03:27:54 +0100397 break;
398 case _Member_sha:
399 default:
400 /* Nothing to do. */
401 break;
Marko Kiiskilace50ab02018-06-06 11:33:33 +0300402 }
403 }
Øyvind Rønningstadf42a8202019-12-13 03:27:54 +0100404
Dominik Ermel5bd87442022-06-13 15:14:01 +0000405 if (img_chunk_off == SIZE_MAX || img_chunk == NULL) {
Marko Kiiskilace50ab02018-06-06 11:33:33 +0300406 /*
407 * Offset must be set in every block.
408 */
409 goto out_invalid_data;
Christopher Collins92ea77f2016-12-12 15:59:26 -0800410 }
411
Dominik Ermel48decca2021-07-09 10:23:58 +0000412#if !defined(MCUBOOT_SERIAL_DIRECT_IMAGE_UPLOAD)
Fabio Utzig6f49c272019-08-23 11:42:58 -0300413 rc = flash_area_open(flash_area_id_from_multi_image_slot(img_num, 0), &fap);
Dominik Ermel48decca2021-07-09 10:23:58 +0000414#else
415 rc = flash_area_open(flash_area_id_from_direct_image(img_num), &fap);
416#endif
Christopher Collins92ea77f2016-12-12 15:59:26 -0800417 if (rc) {
418 rc = MGMT_ERR_EINVAL;
419 goto out;
420 }
421
Dominik Ermel5bd87442022-06-13 15:14:01 +0000422 if (img_chunk_off == 0) {
Dominik Ermelbcc17b42022-06-15 15:33:04 +0000423 /* Receiving chunk with 0 offset resets the upload state; this basically
424 * means that upload has started from beginning.
425 */
426 const size_t area_size = flash_area_get_size(fap);
Dominik Ermel5bd87442022-06-13 15:14:01 +0000427
Dominik Ermelbcc17b42022-06-15 15:33:04 +0000428 curr_off = 0;
429#ifdef MCUBOOT_ERASE_PROGRESSIVELY
430 /* Get trailer sector information; this is done early because inability to get
431 * that sector information means that upload will not work anyway.
432 * TODO: This is single occurrence issue, it should get detected during tests
433 * and fixed otherwise you are deploying broken mcuboot.
434 */
435 if (flash_area_sector_from_off(boot_status_off(fap), &status_sector)) {
436 rc = MGMT_ERR_EUNKNOWN;
437 BOOT_LOG_ERR("Unable to determine flash sector of the image trailer");
438 goto out;
439 }
440#endif
441
442
Wouter Cappellebb7a39d2021-05-03 16:44:44 +0200443#if defined(MCUBOOT_VALIDATE_PRIMARY_SLOT_ONCE)
444 /* We are using swap state at end of flash area to store validation
445 * result. Make sure the user cannot write it from an image to skip validation.
446 */
Dominik Ermelbcc17b42022-06-15 15:33:04 +0000447 if (img_size_tmp > (area_size - BOOT_MAGIC_SZ)) {
Wouter Cappellebb7a39d2021-05-03 16:44:44 +0200448 goto out_invalid_data;
449 }
Dominik Ermelbcc17b42022-06-15 15:33:04 +0000450#else
451 if (img_size_tmp > area_size) {
452 goto out_invalid_data;
453 }
454
Wouter Cappellebb7a39d2021-05-03 16:44:44 +0200455#endif
Dominik Ermelbcc17b42022-06-15 15:33:04 +0000456
Dominik Ermel3d4e55d2021-07-09 11:14:10 +0000457#ifndef MCUBOOT_ERASE_PROGRESSIVELY
Dominik Ermelbcc17b42022-06-15 15:33:04 +0000458 /* Non-progressive erase erases entire image slot when first chunk of
459 * an image is received.
460 */
461 rc = flash_area_erase(fap, 0, area_size);
Christopher Collins92ea77f2016-12-12 15:59:26 -0800462 if (rc) {
Marko Kiiskilace50ab02018-06-06 11:33:33 +0300463 goto out_invalid_data;
Christopher Collins92ea77f2016-12-12 15:59:26 -0800464 }
Dominik Ermelbcc17b42022-06-15 15:33:04 +0000465#else
466 not_yet_erased = 0;
Emanuele Di Santo205c8c62018-07-20 11:42:31 +0200467#endif
Dominik Ermelbcc17b42022-06-15 15:33:04 +0000468
Dominik Ermel5bd87442022-06-13 15:14:01 +0000469 img_size = img_size_tmp;
Dominik Ermelbcc17b42022-06-15 15:33:04 +0000470 } else if (img_chunk_off != curr_off) {
471 /* If received chunk offset does not match expected one jump, pretend
472 * success and jump to out; out will respond to client with success
473 * and request the expected offset, held by curr_off.
474 */
Christopher Collins92ea77f2016-12-12 15:59:26 -0800475 rc = 0;
476 goto out;
Dominik Ermelbcc17b42022-06-15 15:33:04 +0000477 } else if (curr_off + img_chunk_len > img_size) {
Andrzej Puzdrowskif48de7a2020-10-19 09:42:02 +0200478 rc = MGMT_ERR_EINVAL;
479 goto out;
480 }
481
Dominik Ermelbcc17b42022-06-15 15:33:04 +0000482#ifdef MCUBOOT_ERASE_PROGRESSIVELY
483 /* Progressive erase will erase enough flash, aligned to sector size,
484 * as needed for the current chunk to be written.
485 */
486 not_yet_erased = erase_range(fap, not_yet_erased,
487 curr_off + img_chunk_len - 1);
488
489 if (not_yet_erased < 0) {
490 rc = MGMT_ERR_EINVAL;
491 goto out;
492 }
493#endif
494
495 /* Writes are aligned to flash write alignment, so may drop a few bytes
496 * from the end of the buffer; we will request these bytes again with
497 * new buffer by responding with request for offset after the last aligned
498 * write.
499 */
Dominik Ermel5bd87442022-06-13 15:14:01 +0000500 rem_bytes = img_chunk_len % flash_area_align(fap);
Dominik Ermel7d2f0bf2022-06-21 16:15:34 +0000501 img_chunk_len -= rem_bytes;
Andrzej Puzdrowskif48de7a2020-10-19 09:42:02 +0200502
Dominik Ermel7d2f0bf2022-06-21 16:15:34 +0000503 if (curr_off + img_chunk_len + rem_bytes < img_size) {
Andrzej Puzdrowskif48de7a2020-10-19 09:42:02 +0200504 rem_bytes = 0;
Fabio Utzig30f6b2a2018-03-29 16:18:53 -0300505 }
Emanuele Di Santo205c8c62018-07-20 11:42:31 +0200506
Dominik Ermel5bd87442022-06-13 15:14:01 +0000507 BOOT_LOG_INF("Writing at 0x%x until 0x%x", curr_off, curr_off + img_chunk_len);
Dominik Ermel7d2f0bf2022-06-21 16:15:34 +0000508 /* Write flash aligned chunk, note that img_chunk_len now holds aligned length */
509 rc = flash_area_write(fap, curr_off, img_chunk, img_chunk_len);
510 if (rc == 0 && rem_bytes) {
511 /* Non-zero rem_bytes means that last chunk needs alignment; the aligned
512 * part, in the img_chunk_len - rem_bytes count bytes, has already been
513 * written by the above write, so we are left with the rem_bytes.
514 */
Andrzej Puzdrowskif48de7a2020-10-19 09:42:02 +0200515 uint8_t wbs_aligned[BOOT_MAX_ALIGN];
Andrzej Puzdrowskif48de7a2020-10-19 09:42:02 +0200516
Dominik Ermel7d2f0bf2022-06-21 16:15:34 +0000517 memset(wbs_aligned, flash_area_erased_val(fap), sizeof(wbs_aligned));
518 memcpy(wbs_aligned, img_chunk + img_chunk_len, rem_bytes);
Andrzej Puzdrowskif48de7a2020-10-19 09:42:02 +0200519
Dominik Ermel7d2f0bf2022-06-21 16:15:34 +0000520 rc = flash_area_write(fap, curr_off + img_chunk_len, wbs_aligned,
521 flash_area_align(fap));
Andrzej Puzdrowskif48de7a2020-10-19 09:42:02 +0200522 }
523
Marko Kiiskilace50ab02018-06-06 11:33:33 +0300524 if (rc == 0) {
Dominik Ermel7d2f0bf2022-06-21 16:15:34 +0000525 curr_off += img_chunk_len + rem_bytes;
Andrzej Puzdrowskic2e30cf2018-07-20 16:19:09 +0200526 if (curr_off == img_size) {
Andrzej Puzdrowski4f9c7302021-07-16 17:34:43 +0200527#ifdef MCUBOOT_ERASE_PROGRESSIVELY
Andrzej Puzdrowskic2e30cf2018-07-20 16:19:09 +0200528 /* Assure that sector for image trailer was erased. */
529 /* Check whether it was erased during previous upload. */
Dominik Ermelbcc17b42022-06-15 15:33:04 +0000530 off_t start = flash_sector_get_off(&status_sector);
531
532 if (erase_range(fap, start, start) < 0) {
533 rc = MGMT_ERR_EUNKNOWN;
534 goto out;
Andrzej Puzdrowskic2e30cf2018-07-20 16:19:09 +0200535 }
Andrzej Puzdrowskic2e30cf2018-07-20 16:19:09 +0200536#endif
Andrzej Puzdrowski4f9c7302021-07-16 17:34:43 +0200537 rc = BOOT_HOOK_CALL(boot_serial_uploaded_hook, 0, img_num, fap,
538 img_size);
539 if (rc) {
540 BOOT_LOG_ERR("Error %d post upload hook", rc);
541 goto out;
542 }
543 }
Marko Kiiskilace50ab02018-06-06 11:33:33 +0300544 } else {
545 out_invalid_data:
Christopher Collins92ea77f2016-12-12 15:59:26 -0800546 rc = MGMT_ERR_EINVAL;
Christopher Collins92ea77f2016-12-12 15:59:26 -0800547 }
Emanuele Di Santo205c8c62018-07-20 11:42:31 +0200548
Christopher Collins92ea77f2016-12-12 15:59:26 -0800549out:
Andrzej Puzdrowski8e96b832017-09-08 16:49:14 +0200550 BOOT_LOG_INF("RX: 0x%x", rc);
Øyvind Rønningstada7d34ca2022-02-28 13:47:57 +0100551 zcbor_map_start_encode(cbor_state, 10);
552 zcbor_tstr_put_lit_cast(cbor_state, "rc");
553 zcbor_uint32_put(cbor_state, rc);
Christopher Collins92ea77f2016-12-12 15:59:26 -0800554 if (rc == 0) {
Øyvind Rønningstada7d34ca2022-02-28 13:47:57 +0100555 zcbor_tstr_put_lit_cast(cbor_state, "off");
556 zcbor_uint32_put(cbor_state, curr_off);
Christopher Collins92ea77f2016-12-12 15:59:26 -0800557 }
Øyvind Rønningstada7d34ca2022-02-28 13:47:57 +0100558 zcbor_map_end_encode(cbor_state, 10);
Christopher Collins92ea77f2016-12-12 15:59:26 -0800559
560 boot_serial_output();
561 flash_area_close(fap);
Wouter Cappelle953a7612021-05-03 16:53:05 +0200562
563#ifdef MCUBOOT_ENC_IMAGES
564 if (curr_off == img_size) {
565 /* Last sector received, now start a decryption on the image if it is encrypted*/
566 rc = boot_handle_enc_fw();
567 }
568#endif //#ifdef MCUBOOT_ENC_IMAGES
Christopher Collins92ea77f2016-12-12 15:59:26 -0800569}
570
Dominik Ermel4c0f6c12022-03-04 15:47:37 +0000571/*
572 * Send rc code only.
573 */
574static void
575bs_rc_rsp(int rc_code)
576{
Øyvind Rønningstada7d34ca2022-02-28 13:47:57 +0100577 zcbor_map_start_encode(cbor_state, 10);
578 zcbor_tstr_put_lit_cast(cbor_state, "rc");
579 zcbor_uint32_put(cbor_state, rc_code);
580 zcbor_map_end_encode(cbor_state, 10);
Dominik Ermel4c0f6c12022-03-04 15:47:37 +0000581 boot_serial_output();
582}
583
584
Wouter Cappellee3ff1752021-05-03 16:36:22 +0200585#ifdef MCUBOOT_BOOT_MGMT_ECHO
Wouter Cappellee3ff1752021-05-03 16:36:22 +0200586static void
587bs_echo(char *buf, int len)
588{
Dominik Ermel88bd5672022-06-07 15:17:06 +0000589 struct Echo echo = { 0 };
590 size_t decoded_len;
591 uint32_t rc = MGMT_ERR_EINVAL;
592 uint_fast8_t result = cbor_decode_Echo((const uint8_t *)buf, len, &echo, &decoded_len);
Wouter Cappellee3ff1752021-05-03 16:36:22 +0200593
Dominik Ermel88bd5672022-06-07 15:17:06 +0000594 if ((result != ZCBOR_SUCCESS) || (len != decoded_len)) {
595 goto out;
Wouter Cappellee3ff1752021-05-03 16:36:22 +0200596 }
Dominik Ermel88bd5672022-06-07 15:17:06 +0000597
598 if (echo._Echo_d.value == NULL) {
599 goto out;
600 }
601
602 zcbor_map_start_encode(cbor_state, 10);
603 zcbor_tstr_put_term(cbor_state, "r");
604 if (zcbor_tstr_encode(cbor_state, &echo._Echo_d) && zcbor_map_end_encode(cbor_state, 10)) {
605 boot_serial_output();
606 return;
607 } else {
608 rc = MGMT_ERR_ENOMEM;
609 }
610
611out:
612 reset_cbor_state();
613 bs_rc_rsp(rc);
Wouter Cappellee3ff1752021-05-03 16:36:22 +0200614}
615#endif
616
Christopher Collins92ea77f2016-12-12 15:59:26 -0800617/*
Christopher Collins92ea77f2016-12-12 15:59:26 -0800618 * Reset, and (presumably) boot to newly uploaded image. Flush console
619 * before restarting.
620 */
Andrzej Puzdrowski268cdd02018-04-10 12:57:54 +0200621static void
Christopher Collins92ea77f2016-12-12 15:59:26 -0800622bs_reset(char *buf, int len)
623{
Dominik Ermelc9dc2242021-07-28 17:08:23 +0000624 bs_rc_rsp(0);
Christopher Collins92ea77f2016-12-12 15:59:26 -0800625
Andrzej Puzdrowski8e96b832017-09-08 16:49:14 +0200626#ifdef __ZEPHYR__
Andrzej Puzdrowski0cf0dbd2021-05-14 11:55:57 +0200627#ifdef CONFIG_MULTITHREADING
Carles Cufi7e7b4ad2020-03-30 19:12:02 +0200628 k_sleep(K_MSEC(250));
Andrzej Puzdrowski0cf0dbd2021-05-14 11:55:57 +0200629#else
630 k_busy_wait(250000);
631#endif
Andrzej Puzdrowski8e96b832017-09-08 16:49:14 +0200632 sys_reboot(SYS_REBOOT_COLD);
Almir Okatoe8cbc0d2022-06-13 10:45:39 -0300633#elif __ESPRESSIF__
634 esp_rom_delay_us(250000);
635 bootloader_reset();
Andrzej Puzdrowski8e96b832017-09-08 16:49:14 +0200636#else
Christopher Collins92ea77f2016-12-12 15:59:26 -0800637 os_cputime_delay_usecs(250000);
638 hal_system_reset();
Andrzej Puzdrowski8e96b832017-09-08 16:49:14 +0200639#endif
Christopher Collins92ea77f2016-12-12 15:59:26 -0800640}
641
642/*
643 * Parse incoming line of input from console.
644 * Expect newtmgr protocol with serial transport.
645 */
646void
647boot_serial_input(char *buf, int len)
648{
649 struct nmgr_hdr *hdr;
650
651 hdr = (struct nmgr_hdr *)buf;
652 if (len < sizeof(*hdr) ||
653 (hdr->nh_op != NMGR_OP_READ && hdr->nh_op != NMGR_OP_WRITE) ||
654 (ntohs(hdr->nh_len) < len - sizeof(*hdr))) {
655 return;
656 }
657 bs_hdr = hdr;
658 hdr->nh_group = ntohs(hdr->nh_group);
659
660 buf += sizeof(*hdr);
661 len -= sizeof(*hdr);
Marko Kiiskilace50ab02018-06-06 11:33:33 +0300662
Dominik Ermel4c0f6c12022-03-04 15:47:37 +0000663 reset_cbor_state();
Christopher Collins92ea77f2016-12-12 15:59:26 -0800664
665 /*
666 * Limited support for commands.
667 */
668 if (hdr->nh_group == MGMT_GROUP_ID_IMAGE) {
669 switch (hdr->nh_id) {
Marko Kiiskilace50ab02018-06-06 11:33:33 +0300670 case IMGMGR_NMGR_ID_STATE:
Christopher Collins92ea77f2016-12-12 15:59:26 -0800671 bs_list(buf, len);
672 break;
Marko Kiiskilace50ab02018-06-06 11:33:33 +0300673 case IMGMGR_NMGR_ID_UPLOAD:
Christopher Collins92ea77f2016-12-12 15:59:26 -0800674 bs_upload(buf, len);
675 break;
676 default:
Dominik Ermelc9dc2242021-07-28 17:08:23 +0000677 bs_rc_rsp(MGMT_ERR_ENOTSUP);
Christopher Collins92ea77f2016-12-12 15:59:26 -0800678 break;
679 }
680 } else if (hdr->nh_group == MGMT_GROUP_ID_DEFAULT) {
681 switch (hdr->nh_id) {
Wouter Cappellee3ff1752021-05-03 16:36:22 +0200682 case NMGR_ID_ECHO:
683#ifdef MCUBOOT_BOOT_MGMT_ECHO
684 bs_echo(buf, len);
685#endif
686 break;
Christopher Collins92ea77f2016-12-12 15:59:26 -0800687 case NMGR_ID_CONS_ECHO_CTRL:
Dominik Ermelc9dc2242021-07-28 17:08:23 +0000688 bs_rc_rsp(0);
Christopher Collins92ea77f2016-12-12 15:59:26 -0800689 break;
690 case NMGR_ID_RESET:
691 bs_reset(buf, len);
692 break;
693 default:
Dominik Ermelc9dc2242021-07-28 17:08:23 +0000694 bs_rc_rsp(MGMT_ERR_ENOTSUP);
Christopher Collins92ea77f2016-12-12 15:59:26 -0800695 break;
696 }
Dominik Ermelbd69c3d2021-07-28 11:27:31 +0000697 } else if (MCUBOOT_PERUSER_MGMT_GROUP_ENABLED == 1) {
Øyvind Rønningstada7d34ca2022-02-28 13:47:57 +0100698 if (bs_peruser_system_specific(hdr, buf, len, cbor_state) == 0) {
Dominik Ermel3d51e432021-06-25 17:29:50 +0000699 boot_serial_output();
700 }
Dominik Ermelc9dc2242021-07-28 17:08:23 +0000701 } else {
702 bs_rc_rsp(MGMT_ERR_ENOTSUP);
Christopher Collins92ea77f2016-12-12 15:59:26 -0800703 }
Wouter Cappellee3822f82022-01-19 15:39:43 +0100704#ifdef MCUBOOT_SERIAL_WAIT_FOR_DFU
705 bs_entry = true;
706#endif
Christopher Collins92ea77f2016-12-12 15:59:26 -0800707}
708
709static void
710boot_serial_output(void)
711{
712 char *data;
713 int len;
714 uint16_t crc;
715 uint16_t totlen;
716 char pkt_start[2] = { SHELL_NLIP_PKT_START1, SHELL_NLIP_PKT_START2 };
Dominik Ermel5ff89582022-03-03 17:09:07 +0000717 char buf[BOOT_SERIAL_OUT_MAX + sizeof(*bs_hdr) + sizeof(crc) + sizeof(totlen)];
718 char encoded_buf[BASE64_ENCODE_SIZE(sizeof(buf))];
Christopher Collins92ea77f2016-12-12 15:59:26 -0800719
720 data = bs_obuf;
Øyvind Rønningstada7d34ca2022-02-28 13:47:57 +0100721 len = (uint32_t)cbor_state->payload_mut - (uint32_t)bs_obuf;
Christopher Collins92ea77f2016-12-12 15:59:26 -0800722
723 bs_hdr->nh_op++;
Marko Kiiskilace50ab02018-06-06 11:33:33 +0300724 bs_hdr->nh_flags = 0;
Christopher Collins92ea77f2016-12-12 15:59:26 -0800725 bs_hdr->nh_len = htons(len);
726 bs_hdr->nh_group = htons(bs_hdr->nh_group);
727
Andrzej Puzdrowski8e96b832017-09-08 16:49:14 +0200728#ifdef __ZEPHYR__
Carles Cufib9192a42022-02-10 11:41:57 +0100729 crc = crc16_itu_t(CRC16_INITIAL_CRC, (uint8_t *)bs_hdr, sizeof(*bs_hdr));
730 crc = crc16_itu_t(crc, data, len);
Almir Okatoe8cbc0d2022-06-13 10:45:39 -0300731#elif __ESPRESSIF__
732 /* For ESP32 it was used the CRC API in rom/crc.h */
733 crc = ~crc16_be(~CRC16_INITIAL_CRC, (uint8_t *)bs_hdr, sizeof(*bs_hdr));
734 crc = ~crc16_be(~crc, (uint8_t *)data, len);
Andrzej Puzdrowski8e96b832017-09-08 16:49:14 +0200735#else
Christopher Collins92ea77f2016-12-12 15:59:26 -0800736 crc = crc16_ccitt(CRC16_INITIAL_CRC, bs_hdr, sizeof(*bs_hdr));
737 crc = crc16_ccitt(crc, data, len);
Andrzej Puzdrowski8e96b832017-09-08 16:49:14 +0200738#endif
Christopher Collins92ea77f2016-12-12 15:59:26 -0800739 crc = htons(crc);
740
Marko Kiiskila149b4572018-06-06 14:18:54 +0300741 boot_uf->write(pkt_start, sizeof(pkt_start));
Christopher Collins92ea77f2016-12-12 15:59:26 -0800742
743 totlen = len + sizeof(*bs_hdr) + sizeof(crc);
744 totlen = htons(totlen);
745
746 memcpy(buf, &totlen, sizeof(totlen));
747 totlen = sizeof(totlen);
748 memcpy(&buf[totlen], bs_hdr, sizeof(*bs_hdr));
749 totlen += sizeof(*bs_hdr);
750 memcpy(&buf[totlen], data, len);
751 totlen += len;
752 memcpy(&buf[totlen], &crc, sizeof(crc));
753 totlen += sizeof(crc);
Andrzej Puzdrowski8e96b832017-09-08 16:49:14 +0200754#ifdef __ZEPHYR__
755 size_t enc_len;
Carles Cufi0165be82018-03-26 17:43:51 +0200756 base64_encode(encoded_buf, sizeof(encoded_buf), &enc_len, buf, totlen);
Andrzej Puzdrowski8e96b832017-09-08 16:49:14 +0200757 totlen = enc_len;
Almir Okatoe8cbc0d2022-06-13 10:45:39 -0300758#elif __ESPRESSIF__
759 size_t enc_len;
760 base64_encode((unsigned char *)encoded_buf, sizeof(encoded_buf), &enc_len, (unsigned char *)buf, totlen);
761 totlen = enc_len;
Andrzej Puzdrowski8e96b832017-09-08 16:49:14 +0200762#else
Christopher Collins92ea77f2016-12-12 15:59:26 -0800763 totlen = base64_encode(buf, totlen, encoded_buf, 1);
Andrzej Puzdrowski8e96b832017-09-08 16:49:14 +0200764#endif
Marko Kiiskila149b4572018-06-06 14:18:54 +0300765 boot_uf->write(encoded_buf, totlen);
Dominik Ermel2f2b31c2022-03-03 12:39:27 +0000766 boot_uf->write("\n", 1);
Andrzej Puzdrowski8e96b832017-09-08 16:49:14 +0200767 BOOT_LOG_INF("TX");
Christopher Collins92ea77f2016-12-12 15:59:26 -0800768}
769
770/*
771 * Returns 1 if full packet has been received.
772 */
773static int
774boot_serial_in_dec(char *in, int inlen, char *out, int *out_off, int maxout)
775{
776 int rc;
777 uint16_t crc;
778 uint16_t len;
Marko Kiiskilae5aeee42018-12-21 15:00:16 +0200779
Andrzej Puzdrowski8e96b832017-09-08 16:49:14 +0200780#ifdef __ZEPHYR__
781 int err;
Andrzej Puzdrowskiec1e4d12018-06-18 14:36:14 +0200782 err = base64_decode( &out[*out_off], maxout - *out_off, &rc, in, inlen - 2);
Andrzej Puzdrowski8e96b832017-09-08 16:49:14 +0200783 if (err) {
784 return -1;
785 }
Almir Okatoe8cbc0d2022-06-13 10:45:39 -0300786#elif __ESPRESSIF__
787 int err;
788 err = base64_decode((unsigned char *)&out[*out_off], maxout - *out_off, (size_t *)&rc, (unsigned char *)in, inlen);
789 if (err) {
790 return -1;
791 }
Andrzej Puzdrowski8e96b832017-09-08 16:49:14 +0200792#else
Christopher Collins92ea77f2016-12-12 15:59:26 -0800793 if (*out_off + base64_decode_len(in) >= maxout) {
794 return -1;
795 }
796 rc = base64_decode(in, &out[*out_off]);
797 if (rc < 0) {
798 return -1;
799 }
Andrzej Puzdrowski8e96b832017-09-08 16:49:14 +0200800#endif
Fabio Utzig6f49c272019-08-23 11:42:58 -0300801
Christopher Collins92ea77f2016-12-12 15:59:26 -0800802 *out_off += rc;
Fabio Utzig6f49c272019-08-23 11:42:58 -0300803 if (*out_off <= sizeof(uint16_t)) {
804 return 0;
Christopher Collins92ea77f2016-12-12 15:59:26 -0800805 }
Fabio Utzig6f49c272019-08-23 11:42:58 -0300806
807 len = ntohs(*(uint16_t *)out);
808 if (len != *out_off - sizeof(uint16_t)) {
809 return 0;
810 }
811
812 if (len > *out_off - sizeof(uint16_t)) {
813 len = *out_off - sizeof(uint16_t);
814 }
815
816 out += sizeof(uint16_t);
817#ifdef __ZEPHYR__
Carles Cufib9192a42022-02-10 11:41:57 +0100818 crc = crc16_itu_t(CRC16_INITIAL_CRC, out, len);
Almir Okatoe8cbc0d2022-06-13 10:45:39 -0300819#elif __ESPRESSIF__
820 crc = ~crc16_be(~CRC16_INITIAL_CRC, (uint8_t *)out, len);
Fabio Utzig6f49c272019-08-23 11:42:58 -0300821#else
822 crc = crc16_ccitt(CRC16_INITIAL_CRC, out, len);
823#endif
824 if (crc || len <= sizeof(crc)) {
825 return 0;
826 }
827 *out_off -= sizeof(crc);
828 out[*out_off] = '\0';
829
830 return 1;
Christopher Collins92ea77f2016-12-12 15:59:26 -0800831}
832
833/*
834 * Task which waits reading console, expecting to get image over
835 * serial port.
836 */
Wouter Cappellee3822f82022-01-19 15:39:43 +0100837static void
838boot_serial_read_console(const struct boot_uart_funcs *f,int timeout_in_ms)
Christopher Collins92ea77f2016-12-12 15:59:26 -0800839{
840 int rc;
841 int off;
David Brown57f0df32020-05-12 08:39:21 -0600842 int dec_off = 0;
Christopher Collins92ea77f2016-12-12 15:59:26 -0800843 int full_line;
Marko Kiiskila149b4572018-06-06 14:18:54 +0300844 int max_input;
Wouter Cappellee3822f82022-01-19 15:39:43 +0100845 int elapsed_in_ms = 0;
Christopher Collins92ea77f2016-12-12 15:59:26 -0800846
Marko Kiiskila149b4572018-06-06 14:18:54 +0300847 boot_uf = f;
Marko Kiiskila149b4572018-06-06 14:18:54 +0300848 max_input = sizeof(in_buf);
Christopher Collins92ea77f2016-12-12 15:59:26 -0800849
850 off = 0;
Wouter Cappellee3822f82022-01-19 15:39:43 +0100851 while (timeout_in_ms > 0 || bs_entry) {
Piotr Dymacz067f30a2022-08-12 18:25:34 +0200852 /*
853 * Don't enter CPU idle state here if timeout based serial recovery is
854 * used as otherwise the boot process hangs forever, waiting for input
855 * from serial console (if single-thread mode is used).
856 */
Piotr Dymacz3942e9b2022-07-18 10:19:25 +0200857#ifndef MCUBOOT_SERIAL_WAIT_FOR_DFU
Andrzej Puzdrowskiaea38eb2021-06-11 12:28:59 +0200858 MCUBOOT_CPU_IDLE();
Piotr Dymacz3942e9b2022-07-18 10:19:25 +0200859#endif
Hein Wessels56d28f02021-11-19 08:42:08 +0100860 MCUBOOT_WATCHDOG_FEED();
Wouter Cappellee3822f82022-01-19 15:39:43 +0100861#ifdef MCUBOOT_SERIAL_WAIT_FOR_DFU
862 uint32_t start = k_uptime_get_32();
863#endif
Andrzej Puzdrowskiec1e4d12018-06-18 14:36:14 +0200864 rc = f->read(in_buf + off, sizeof(in_buf) - off, &full_line);
Christopher Collins92ea77f2016-12-12 15:59:26 -0800865 if (rc <= 0 && !full_line) {
Wouter Cappellee3822f82022-01-19 15:39:43 +0100866 goto check_timeout;
Christopher Collins92ea77f2016-12-12 15:59:26 -0800867 }
868 off += rc;
869 if (!full_line) {
Marko Kiiskilace50ab02018-06-06 11:33:33 +0300870 if (off == max_input) {
871 /*
872 * Full line, no newline yet. Reset the input buffer.
873 */
874 off = 0;
875 }
Wouter Cappellee3822f82022-01-19 15:39:43 +0100876 goto check_timeout;
Christopher Collins92ea77f2016-12-12 15:59:26 -0800877 }
Andrzej Puzdrowskiec1e4d12018-06-18 14:36:14 +0200878 if (in_buf[0] == SHELL_NLIP_PKT_START1 &&
879 in_buf[1] == SHELL_NLIP_PKT_START2) {
Christopher Collins92ea77f2016-12-12 15:59:26 -0800880 dec_off = 0;
Andrzej Puzdrowskiec1e4d12018-06-18 14:36:14 +0200881 rc = boot_serial_in_dec(&in_buf[2], off - 2, dec_buf, &dec_off, max_input);
882 } else if (in_buf[0] == SHELL_NLIP_DATA_START1 &&
883 in_buf[1] == SHELL_NLIP_DATA_START2) {
884 rc = boot_serial_in_dec(&in_buf[2], off - 2, dec_buf, &dec_off, max_input);
Christopher Collins92ea77f2016-12-12 15:59:26 -0800885 }
Andrzej Puzdrowskiec1e4d12018-06-18 14:36:14 +0200886
887 /* serve errors: out of decode memory, or bad encoding */
Christopher Collins92ea77f2016-12-12 15:59:26 -0800888 if (rc == 1) {
Andrzej Puzdrowskiec1e4d12018-06-18 14:36:14 +0200889 boot_serial_input(&dec_buf[2], dec_off - 2);
Christopher Collins92ea77f2016-12-12 15:59:26 -0800890 }
891 off = 0;
Wouter Cappellee3822f82022-01-19 15:39:43 +0100892check_timeout:
893 /* Subtract elapsed time */
894#ifdef MCUBOOT_SERIAL_WAIT_FOR_DFU
895 elapsed_in_ms = (k_uptime_get_32() - start);
896#endif
897 timeout_in_ms -= elapsed_in_ms;
Christopher Collins92ea77f2016-12-12 15:59:26 -0800898 }
899}
Wouter Cappellee3822f82022-01-19 15:39:43 +0100900
901/*
902 * Task which waits reading console, expecting to get image over
903 * serial port.
904 */
905void
906boot_serial_start(const struct boot_uart_funcs *f)
907{
908 bs_entry = true;
909 boot_serial_read_console(f,0);
910}
911
912#ifdef MCUBOOT_SERIAL_WAIT_FOR_DFU
913/*
914 * Task which waits reading console for a certain amount of timeout.
915 * If within this timeout no mcumgr command is received, the function is
916 * returning, else the serial boot is never exited
917 */
918void
919boot_serial_check_start(const struct boot_uart_funcs *f, int timeout_in_ms)
920{
921 bs_entry = false;
922 boot_serial_read_console(f,timeout_in_ms);
923}
924#endif