blob: 1ccf30ec1058269c5461e469d01c92cd1f1559e7 [file] [log] [blame]
Christopher Collins92ea77f2016-12-12 15:59:26 -08001/*
2 * Licensed to the Apache Software Foundation (ASF) under one
3 * or more contributor license agreements. See the NOTICE file
4 * distributed with this work for additional information
5 * regarding copyright ownership. The ASF licenses this file
6 * to you under the Apache License, Version 2.0 (the
7 * "License"); you may not use this file except in compliance
8 * with the License. You may obtain a copy of the License at
9 *
10 * http://www.apache.org/licenses/LICENSE-2.0
11 *
12 * Unless required by applicable law or agreed to in writing,
13 * software distributed under the License is distributed on an
14 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
15 * KIND, either express or implied. See the License for the
16 * specific language governing permissions and limitations
17 * under the License.
18 */
19#include <assert.h>
20#include <stddef.h>
21#include <inttypes.h>
22#include <ctype.h>
23#include <stdio.h>
Almir Okato90be6e62022-09-23 14:52:25 -030024#include <errno.h>
Christopher Collins92ea77f2016-12-12 15:59:26 -080025
26#include "sysflash/sysflash.h"
27
Fabio Utzig1a2e41a2017-11-17 12:13:09 -020028#include "bootutil/bootutil_log.h"
Øyvind Rønningstada7d34ca2022-02-28 13:47:57 +010029#include "zcbor_encode.h"
Fabio Utzig1a2e41a2017-11-17 12:13:09 -020030
Andrzej Puzdrowski8e96b832017-09-08 16:49:14 +020031#ifdef __ZEPHYR__
Fabio Baltieri888e2612022-07-19 20:54:26 +000032#include <zephyr/sys/reboot.h>
33#include <zephyr/sys/byteorder.h>
34#include <zephyr/sys/__assert.h>
35#include <zephyr/drivers/flash.h>
36#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>
42#include <rom/crc.h>
43#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
Andrzej Puzdrowskib788c712018-04-12 12:42:49 +020055#include <flash_map_backend/flash_map_backend.h>
Andrzej Puzdrowski8e96b832017-09-08 16:49:14 +020056#include <os/os.h>
57#include <os/os_malloc.h>
Christopher Collins92ea77f2016-12-12 15:59:26 -080058
59#include <bootutil/image.h>
Andrzej Puzdrowskif48de7a2020-10-19 09:42:02 +020060#include <bootutil/bootutil.h>
Christopher Collins92ea77f2016-12-12 15:59:26 -080061
62#include "boot_serial/boot_serial.h"
63#include "boot_serial_priv.h"
Almir Okatoe8cbc0d2022-06-13 10:45:39 -030064#include "mcuboot_config/mcuboot_config.h"
Christopher Collins92ea77f2016-12-12 15:59:26 -080065
Dominik Ermel3d4e55d2021-07-09 11:14:10 +000066#ifdef MCUBOOT_ERASE_PROGRESSIVELY
Andrzej Puzdrowskic2e30cf2018-07-20 16:19:09 +020067#include "bootutil_priv.h"
68#endif
69
Wouter Cappelle953a7612021-05-03 16:53:05 +020070#ifdef MCUBOOT_ENC_IMAGES
71#include "single_loader.h"
72#endif
73
Øyvind Rønningstadf42a8202019-12-13 03:27:54 +010074#include "serial_recovery_cbor.h"
Dominik Ermel88bd5672022-06-07 15:17:06 +000075#include "serial_recovery_echo.h"
Andrzej Puzdrowski4f9c7302021-07-16 17:34:43 +020076#include "bootutil/boot_hooks.h"
Øyvind Rønningstadf42a8202019-12-13 03:27:54 +010077
Carlos Falgueras Garcíaa4b4b0f2021-06-22 10:00:22 +020078BOOT_LOG_MODULE_DECLARE(mcuboot);
Emanuele Di Santo9f1933d2018-11-20 10:59:59 +010079
Marko Kiiskila149b4572018-06-06 14:18:54 +030080#define BOOT_SERIAL_INPUT_MAX 512
Andrzej Puzdrowskic9ac5cc2021-11-19 11:58:05 +010081#define BOOT_SERIAL_OUT_MAX (128 * BOOT_IMAGE_NUMBER)
Christopher Collins92ea77f2016-12-12 15:59:26 -080082
Andrzej Puzdrowski8e96b832017-09-08 16:49:14 +020083#ifdef __ZEPHYR__
Carles Cufi0165be82018-03-26 17:43:51 +020084/* base64 lib encodes data to null-terminated string */
Andrzej Puzdrowski8e96b832017-09-08 16:49:14 +020085#define BASE64_ENCODE_SIZE(in_size) ((((((in_size) - 1) / 3) * 4) + 4) + 1)
86
87#define CRC16_INITIAL_CRC 0 /* what to seed crc16 with */
88#define CRC_CITT_POLYMINAL 0x1021
89
90#define ntohs(x) sys_be16_to_cpu(x)
91#define htons(x) sys_cpu_to_be16(x)
Almir Okatoe8cbc0d2022-06-13 10:45:39 -030092#elif __ESPRESSIF__
93#define BASE64_ENCODE_SIZE(in_size) ((((((in_size) - 1) / 3) * 4) + 4) + 1)
94#define CRC16_INITIAL_CRC 0 /* what to seed crc16 with */
95
96#define ntohs(x) be16toh(x)
97#define htons(x) htobe16(x)
98
99#define base64_decode mbedtls_base64_decode
100#define base64_encode mbedtls_base64_encode
Andrzej Puzdrowski8e96b832017-09-08 16:49:14 +0200101#endif
Emanuele Di Santo9f1933d2018-11-20 10:59:59 +0100102
Fabio Utzig6f49c272019-08-23 11:42:58 -0300103#if (BOOT_IMAGE_NUMBER > 1)
104#define IMAGES_ITER(x) for ((x) = 0; (x) < BOOT_IMAGE_NUMBER; ++(x))
105#else
106#define IMAGES_ITER(x)
107#endif
108
Marko Kiiskila149b4572018-06-06 14:18:54 +0300109static char in_buf[BOOT_SERIAL_INPUT_MAX + 1];
110static char dec_buf[BOOT_SERIAL_INPUT_MAX + 1];
Marko Kiiskila8b1ce3a2018-06-14 13:20:46 -0700111const struct boot_uart_funcs *boot_uf;
Christopher Collins92ea77f2016-12-12 15:59:26 -0800112static struct nmgr_hdr *bs_hdr;
Wouter Cappellee3822f82022-01-19 15:39:43 +0100113static bool bs_entry;
Christopher Collins92ea77f2016-12-12 15:59:26 -0800114
115static char bs_obuf[BOOT_SERIAL_OUT_MAX];
116
Christopher Collins92ea77f2016-12-12 15:59:26 -0800117static void boot_serial_output(void);
118
Øyvind Rønningstada7d34ca2022-02-28 13:47:57 +0100119static zcbor_state_t cbor_state[2];
Christopher Collins92ea77f2016-12-12 15:59:26 -0800120
Dominik Ermel4c0f6c12022-03-04 15:47:37 +0000121void reset_cbor_state(void)
122{
Øyvind Rønningstada7d34ca2022-02-28 13:47:57 +0100123 zcbor_new_encode_state(cbor_state, 2, (uint8_t *)bs_obuf,
124 (size_t)bs_obuf + sizeof(bs_obuf), 0);
Dominik Ermel4c0f6c12022-03-04 15:47:37 +0000125}
126
Dominik Ermel3d51e432021-06-25 17:29:50 +0000127/**
Dominik Ermelbd69c3d2021-07-28 11:27:31 +0000128 * Function that processes MGMT_GROUP_ID_PERUSER mcumgr group and may be
129 * used to process any groups that have not been processed by generic boot
130 * serial implementation.
Dominik Ermel3d51e432021-06-25 17:29:50 +0000131 *
132 * @param[in] hdr -- the decoded header of mcumgr message;
133 * @param[in] buffer -- buffer with first mcumgr message;
134 * @param[in] len -- length of of data in buffer;
135 * @param[out] *cs -- object with encoded response.
136 *
137 * @return 0 on success; non-0 error code otherwise.
138 */
139extern int bs_peruser_system_specific(const struct nmgr_hdr *hdr,
140 const char *buffer,
Øyvind Rønningstada7d34ca2022-02-28 13:47:57 +0100141 int len, zcbor_state_t *cs);
Christopher Collins92ea77f2016-12-12 15:59:26 -0800142
Dominik Ermeld49cfc12022-06-09 08:24:48 +0000143#define zcbor_tstr_put_lit_cast(state, string) \
144 zcbor_tstr_encode_ptr(state, (uint8_t *)string, sizeof(string) - 1)
145
146#ifndef MCUBOOT_USE_SNPRINTF
Christopher Collins92ea77f2016-12-12 15:59:26 -0800147/*
Marko Kiiskilace50ab02018-06-06 11:33:33 +0300148 * Convert version into string without use of snprintf().
Christopher Collins92ea77f2016-12-12 15:59:26 -0800149 */
Marko Kiiskilace50ab02018-06-06 11:33:33 +0300150static int
151u32toa(char *tgt, uint32_t val)
Christopher Collins92ea77f2016-12-12 15:59:26 -0800152{
Marko Kiiskilace50ab02018-06-06 11:33:33 +0300153 char *dst;
154 uint32_t d = 1;
155 uint32_t dgt;
156 int n = 0;
Christopher Collins92ea77f2016-12-12 15:59:26 -0800157
Marko Kiiskilace50ab02018-06-06 11:33:33 +0300158 dst = tgt;
159 while (val / d >= 10) {
160 d *= 10;
Christopher Collins92ea77f2016-12-12 15:59:26 -0800161 }
Marko Kiiskilace50ab02018-06-06 11:33:33 +0300162 while (d) {
163 dgt = val / d;
164 val %= d;
165 d /= 10;
166 if (n || dgt > 0 || d == 0) {
167 *dst++ = dgt + '0';
168 ++n;
Christopher Collins92ea77f2016-12-12 15:59:26 -0800169 }
Christopher Collins92ea77f2016-12-12 15:59:26 -0800170 }
Marko Kiiskilace50ab02018-06-06 11:33:33 +0300171 *dst = '\0';
172
173 return dst - tgt;
174}
175
176/*
177 * dst has to be able to fit "255.255.65535.4294967295" (25 characters).
178 */
179static void
180bs_list_img_ver(char *dst, int maxlen, struct image_version *ver)
181{
182 int off;
183
184 off = u32toa(dst, ver->iv_major);
185 dst[off++] = '.';
186 off += u32toa(dst + off, ver->iv_minor);
187 dst[off++] = '.';
188 off += u32toa(dst + off, ver->iv_revision);
189 dst[off++] = '.';
190 off += u32toa(dst + off, ver->iv_build_num);
Christopher Collins92ea77f2016-12-12 15:59:26 -0800191}
Dominik Ermeld49cfc12022-06-09 08:24:48 +0000192#else
193/*
194 * dst has to be able to fit "255.255.65535.4294967295" (25 characters).
195 */
196static void
197bs_list_img_ver(char *dst, int maxlen, struct image_version *ver)
198{
199 snprintf(dst, maxlen, "%hu.%hu.%hu.%u", (uint16_t)ver->iv_major,
200 (uint16_t)ver->iv_minor, ver->iv_revision, ver->iv_build_num);
201}
202#endif /* !MCUBOOT_USE_SNPRINTF */
Christopher Collins92ea77f2016-12-12 15:59:26 -0800203
204/*
205 * List images.
206 */
207static void
208bs_list(char *buf, int len)
209{
Christopher Collins92ea77f2016-12-12 15:59:26 -0800210 struct image_header hdr;
211 uint8_t tmpbuf[64];
Øyvind Rønningstad9f4aefd2021-03-08 21:11:25 +0100212 uint32_t slot, area_id;
Christopher Collins92ea77f2016-12-12 15:59:26 -0800213 const struct flash_area *fap;
Fabio Utzig6f49c272019-08-23 11:42:58 -0300214 uint8_t image_index;
Christopher Collins92ea77f2016-12-12 15:59:26 -0800215
Øyvind Rønningstada7d34ca2022-02-28 13:47:57 +0100216 zcbor_map_start_encode(cbor_state, 1);
217 zcbor_tstr_put_lit_cast(cbor_state, "images");
218 zcbor_list_start_encode(cbor_state, 5);
Fabio Utzig6f49c272019-08-23 11:42:58 -0300219 image_index = 0;
220 IMAGES_ITER(image_index) {
221 for (slot = 0; slot < 2; slot++) {
222 area_id = flash_area_id_from_multi_image_slot(image_index, slot);
223 if (flash_area_open(area_id, &fap)) {
224 continue;
225 }
Christopher Collins92ea77f2016-12-12 15:59:26 -0800226
Andrzej Puzdrowski4f9c7302021-07-16 17:34:43 +0200227 int rc = BOOT_HOOK_CALL(boot_read_image_header_hook,
228 BOOT_HOOK_REGULAR, image_index, slot, &hdr);
229 if (rc == BOOT_HOOK_REGULAR)
230 {
231 flash_area_read(fap, 0, &hdr, sizeof(hdr));
232 }
Christopher Collins92ea77f2016-12-12 15:59:26 -0800233
Andrzej Puzdrowski4f9c7302021-07-16 17:34:43 +0200234 fih_int fih_rc = FIH_FAILURE;
235
236 if (hdr.ih_magic == IMAGE_MAGIC)
237 {
238 BOOT_HOOK_CALL_FIH(boot_image_check_hook,
239 fih_int_encode(BOOT_HOOK_REGULAR),
240 fih_rc, image_index, slot);
241 if (fih_eq(fih_rc, BOOT_HOOK_REGULAR))
242 {
Wouter Cappelle953a7612021-05-03 16:53:05 +0200243#ifdef MCUBOOT_ENC_IMAGES
244 if (slot == 0 && IS_ENCRYPTED(&hdr)) {
245 /* Clear the encrypted flag we didn't supply a key
246 * This flag could be set if there was a decryption in place
247 * performed before. We will try to validate the image without
248 * decryption by clearing the flag in the heder. If
249 * still encrypted the validation will fail.
250 */
251 hdr.ih_flags &= ~(ENCRYPTIONFLAGS);
252 }
253#endif
Andrzej Puzdrowski4f9c7302021-07-16 17:34:43 +0200254 FIH_CALL(bootutil_img_validate, fih_rc, NULL, 0, &hdr, fap, tmpbuf, sizeof(tmpbuf),
255 NULL, 0, NULL);
256 }
257 }
258
259 flash_area_close(fap);
260
261 if (fih_not_eq(fih_rc, FIH_SUCCESS)) {
Fabio Utzig6f49c272019-08-23 11:42:58 -0300262 continue;
263 }
Fabio Utzig6f49c272019-08-23 11:42:58 -0300264
Øyvind Rønningstada7d34ca2022-02-28 13:47:57 +0100265 zcbor_map_start_encode(cbor_state, 20);
Fabio Utzig6f49c272019-08-23 11:42:58 -0300266
267#if (BOOT_IMAGE_NUMBER > 1)
Øyvind Rønningstada7d34ca2022-02-28 13:47:57 +0100268 zcbor_tstr_put_lit_cast(cbor_state, "image");
269 zcbor_uint32_put(cbor_state, image_index);
Fabio Utzig6f49c272019-08-23 11:42:58 -0300270#endif
271
Øyvind Rønningstada7d34ca2022-02-28 13:47:57 +0100272 zcbor_tstr_put_lit_cast(cbor_state, "slot");
273 zcbor_uint32_put(cbor_state, slot);
274 zcbor_tstr_put_lit_cast(cbor_state, "version");
Fabio Utzig6f49c272019-08-23 11:42:58 -0300275
276 bs_list_img_ver((char *)tmpbuf, sizeof(tmpbuf), &hdr.ih_ver);
Øyvind Rønningstada7d34ca2022-02-28 13:47:57 +0100277 zcbor_tstr_encode_ptr(cbor_state, tmpbuf, strlen((char *)tmpbuf));
278 zcbor_map_end_encode(cbor_state, 20);
Christopher Collins92ea77f2016-12-12 15:59:26 -0800279 }
Christopher Collins92ea77f2016-12-12 15:59:26 -0800280 }
Øyvind Rønningstada7d34ca2022-02-28 13:47:57 +0100281 zcbor_list_end_encode(cbor_state, 5);
282 zcbor_map_end_encode(cbor_state, 1);
Christopher Collins92ea77f2016-12-12 15:59:26 -0800283 boot_serial_output();
284}
285
Dominik Ermelbcc17b42022-06-15 15:33:04 +0000286#ifdef MCUBOOT_ERASE_PROGRESSIVELY
287
288/** Erases range of flash, aligned to sector size
289 *
290 * Function will erase all sectors withing [start, end] range; it does not check
291 * the @p start for alignment, and it will use @p end to find boundaries of las
292 * sector to erase. Function returns offset of the first byte past the last
293 * erased sector, so basically offset of next sector to be erased if needed.
294 * The function is intended to be called iteratively with previously returned
295 * offset as @p start.
296 *
297 * @param start starting offset, aligned to sector offset;
298 * @param end ending offset, maybe anywhere within sector;
299 *
300 * @retval On success: offset of the first byte past last erased sector;
301 * On failure: -EINVAL.
302 */
303static off_t erase_range(const struct flash_area *fap, off_t start, off_t end)
304{
305 struct flash_sector sect;
306 size_t size;
307 int rc;
308
309 if (end >= flash_area_get_size(fap)) {
310 return -EINVAL;
311 }
312
313 if (end < start) {
314 return start;
315 }
316
317 if (flash_area_sector_from_off(end, &sect)) {
318 return -EINVAL;
319 }
320
321 size = flash_sector_get_off(&sect) + flash_sector_get_size(&sect) - start;
Stephanos Ioannidis09e2bd72022-07-11 22:01:49 +0900322 BOOT_LOG_INF("Erasing range 0x%jx:0x%jx", (intmax_t)start,
323 (intmax_t)(start + size - 1));
Dominik Ermelbcc17b42022-06-15 15:33:04 +0000324
325 rc = flash_area_erase(fap, start, size);
326 if (rc != 0) {
327 BOOT_LOG_ERR("Error %d while erasing range", rc);
328 return -EINVAL;
329 }
330
331 return start + size;
332}
333#endif
334
Christopher Collins92ea77f2016-12-12 15:59:26 -0800335/*
336 * Image upload request.
337 */
338static void
339bs_upload(char *buf, int len)
340{
Dominik Ermel5bd87442022-06-13 15:14:01 +0000341 static size_t img_size; /* Total image size, held for duration of upload */
342 static uint32_t curr_off; /* Expected current offset */
343 const uint8_t *img_chunk = NULL; /* Pointer to buffer with received image chunk */
344 size_t img_chunk_len = 0; /* Length of received image chunk */
345 size_t img_chunk_off = SIZE_MAX; /* Offset of image chunk within image */
346 uint8_t rem_bytes; /* Reminder bytes after aligning chunk write to
347 * to flash alignment */
Fabio Utzig6f49c272019-08-23 11:42:58 -0300348 int img_num;
Dominik Ermel5bd87442022-06-13 15:14:01 +0000349 size_t img_size_tmp = SIZE_MAX; /* Temp variable for image size */
Christopher Collins92ea77f2016-12-12 15:59:26 -0800350 const struct flash_area *fap = NULL;
351 int rc;
Dominik Ermel3d4e55d2021-07-09 11:14:10 +0000352#ifdef MCUBOOT_ERASE_PROGRESSIVELY
Dominik Ermelbcc17b42022-06-15 15:33:04 +0000353 static off_t not_yet_erased = 0; /* Offset of next byte to erase; writes to flash
354 * are done in consecutive manner and erases are done
355 * to allow currently received chunk to be written;
356 * this state variable holds information where last
357 * erase has stopped to let us know whether erase
358 * is needed to be able to write current chunk.
359 */
360 static struct flash_sector status_sector;
Emanuele Di Santo205c8c62018-07-20 11:42:31 +0200361#endif
Christopher Collins92ea77f2016-12-12 15:59:26 -0800362
Fabio Utzig6f49c272019-08-23 11:42:58 -0300363 img_num = 0;
Marko Kiiskilace50ab02018-06-06 11:33:33 +0300364
365 /*
366 * Expected data format.
367 * {
Fabio Utzig6f49c272019-08-23 11:42:58 -0300368 * "image":<image number in a multi-image set (OPTIONAL)>
369 * "data":<image data>
Marko Kiiskilace50ab02018-06-06 11:33:33 +0300370 * "len":<image len>
371 * "off":<current offset of image data>
372 * }
373 */
374
Øyvind Rønningstad212a35b2021-05-07 21:06:48 +0200375 struct Upload upload;
Øyvind Rønningstada7d34ca2022-02-28 13:47:57 +0100376 size_t decoded_len;
377 uint_fast8_t result = cbor_decode_Upload((const uint8_t *)buf, len, &upload, &decoded_len);
Øyvind Rønningstad212a35b2021-05-07 21:06:48 +0200378
Øyvind Rønningstada7d34ca2022-02-28 13:47:57 +0100379 if ((result != ZCBOR_SUCCESS) || (len != decoded_len)) {
Øyvind Rønningstadf42a8202019-12-13 03:27:54 +0100380 goto out_invalid_data;
381 }
Dominik Ermel470e2f32020-01-10 13:28:48 +0000382
Øyvind Rønningstadf42a8202019-12-13 03:27:54 +0100383 for (int i = 0; i < upload._Upload_members_count; i++) {
Øyvind Rønningstada7d34ca2022-02-28 13:47:57 +0100384 struct Member_ *member = &upload._Upload_members[i]._Upload_members;
Øyvind Rønningstadf42a8202019-12-13 03:27:54 +0100385 switch(member->_Member_choice) {
386 case _Member_image:
387 img_num = member->_Member_image;
388 break;
389 case _Member_data:
Dominik Ermel5bd87442022-06-13 15:14:01 +0000390 img_chunk = member->_Member_data.value;
391 img_chunk_len = member->_Member_data.len;
Øyvind Rønningstadf42a8202019-12-13 03:27:54 +0100392 break;
393 case _Member_len:
Dominik Ermel5bd87442022-06-13 15:14:01 +0000394 img_size_tmp = member->_Member_len;
Øyvind Rønningstadf42a8202019-12-13 03:27:54 +0100395 break;
396 case _Member_off:
Dominik Ermel5bd87442022-06-13 15:14:01 +0000397 img_chunk_off = member->_Member_off;
Øyvind Rønningstadf42a8202019-12-13 03:27:54 +0100398 break;
399 case _Member_sha:
400 default:
401 /* Nothing to do. */
402 break;
Marko Kiiskilace50ab02018-06-06 11:33:33 +0300403 }
404 }
Øyvind Rønningstadf42a8202019-12-13 03:27:54 +0100405
Dominik Ermel5bd87442022-06-13 15:14:01 +0000406 if (img_chunk_off == SIZE_MAX || img_chunk == NULL) {
Marko Kiiskilace50ab02018-06-06 11:33:33 +0300407 /*
408 * Offset must be set in every block.
409 */
410 goto out_invalid_data;
Christopher Collins92ea77f2016-12-12 15:59:26 -0800411 }
412
Dominik Ermel48decca2021-07-09 10:23:58 +0000413#if !defined(MCUBOOT_SERIAL_DIRECT_IMAGE_UPLOAD)
Fabio Utzig6f49c272019-08-23 11:42:58 -0300414 rc = flash_area_open(flash_area_id_from_multi_image_slot(img_num, 0), &fap);
Dominik Ermel48decca2021-07-09 10:23:58 +0000415#else
416 rc = flash_area_open(flash_area_id_from_direct_image(img_num), &fap);
417#endif
Christopher Collins92ea77f2016-12-12 15:59:26 -0800418 if (rc) {
419 rc = MGMT_ERR_EINVAL;
420 goto out;
421 }
422
Dominik Ermel5bd87442022-06-13 15:14:01 +0000423 if (img_chunk_off == 0) {
Dominik Ermelbcc17b42022-06-15 15:33:04 +0000424 /* Receiving chunk with 0 offset resets the upload state; this basically
425 * means that upload has started from beginning.
426 */
427 const size_t area_size = flash_area_get_size(fap);
Dominik Ermel5bd87442022-06-13 15:14:01 +0000428
Dominik Ermelbcc17b42022-06-15 15:33:04 +0000429 curr_off = 0;
430#ifdef MCUBOOT_ERASE_PROGRESSIVELY
431 /* Get trailer sector information; this is done early because inability to get
432 * that sector information means that upload will not work anyway.
433 * TODO: This is single occurrence issue, it should get detected during tests
434 * and fixed otherwise you are deploying broken mcuboot.
435 */
436 if (flash_area_sector_from_off(boot_status_off(fap), &status_sector)) {
437 rc = MGMT_ERR_EUNKNOWN;
438 BOOT_LOG_ERR("Unable to determine flash sector of the image trailer");
439 goto out;
440 }
441#endif
442
443
Wouter Cappellebb7a39d2021-05-03 16:44:44 +0200444#if defined(MCUBOOT_VALIDATE_PRIMARY_SLOT_ONCE)
445 /* We are using swap state at end of flash area to store validation
446 * result. Make sure the user cannot write it from an image to skip validation.
447 */
Dominik Ermelbcc17b42022-06-15 15:33:04 +0000448 if (img_size_tmp > (area_size - BOOT_MAGIC_SZ)) {
Wouter Cappellebb7a39d2021-05-03 16:44:44 +0200449 goto out_invalid_data;
450 }
Dominik Ermelbcc17b42022-06-15 15:33:04 +0000451#else
452 if (img_size_tmp > area_size) {
453 goto out_invalid_data;
454 }
455
Wouter Cappellebb7a39d2021-05-03 16:44:44 +0200456#endif
Dominik Ermelbcc17b42022-06-15 15:33:04 +0000457
Dominik Ermel3d4e55d2021-07-09 11:14:10 +0000458#ifndef MCUBOOT_ERASE_PROGRESSIVELY
Dominik Ermelbcc17b42022-06-15 15:33:04 +0000459 /* Non-progressive erase erases entire image slot when first chunk of
460 * an image is received.
461 */
462 rc = flash_area_erase(fap, 0, area_size);
Christopher Collins92ea77f2016-12-12 15:59:26 -0800463 if (rc) {
Marko Kiiskilace50ab02018-06-06 11:33:33 +0300464 goto out_invalid_data;
Christopher Collins92ea77f2016-12-12 15:59:26 -0800465 }
Dominik Ermelbcc17b42022-06-15 15:33:04 +0000466#else
467 not_yet_erased = 0;
Emanuele Di Santo205c8c62018-07-20 11:42:31 +0200468#endif
Dominik Ermelbcc17b42022-06-15 15:33:04 +0000469
Dominik Ermel5bd87442022-06-13 15:14:01 +0000470 img_size = img_size_tmp;
Dominik Ermelbcc17b42022-06-15 15:33:04 +0000471 } else if (img_chunk_off != curr_off) {
472 /* If received chunk offset does not match expected one jump, pretend
473 * success and jump to out; out will respond to client with success
474 * and request the expected offset, held by curr_off.
475 */
Christopher Collins92ea77f2016-12-12 15:59:26 -0800476 rc = 0;
477 goto out;
Dominik Ermelbcc17b42022-06-15 15:33:04 +0000478 } else if (curr_off + img_chunk_len > img_size) {
Andrzej Puzdrowskif48de7a2020-10-19 09:42:02 +0200479 rc = MGMT_ERR_EINVAL;
480 goto out;
481 }
482
Dominik Ermelbcc17b42022-06-15 15:33:04 +0000483#ifdef MCUBOOT_ERASE_PROGRESSIVELY
484 /* Progressive erase will erase enough flash, aligned to sector size,
485 * as needed for the current chunk to be written.
486 */
487 not_yet_erased = erase_range(fap, not_yet_erased,
488 curr_off + img_chunk_len - 1);
489
490 if (not_yet_erased < 0) {
491 rc = MGMT_ERR_EINVAL;
492 goto out;
493 }
494#endif
495
496 /* Writes are aligned to flash write alignment, so may drop a few bytes
497 * from the end of the buffer; we will request these bytes again with
498 * new buffer by responding with request for offset after the last aligned
499 * write.
500 */
Dominik Ermel5bd87442022-06-13 15:14:01 +0000501 rem_bytes = img_chunk_len % flash_area_align(fap);
Dominik Ermel7d2f0bf2022-06-21 16:15:34 +0000502 img_chunk_len -= rem_bytes;
Andrzej Puzdrowskif48de7a2020-10-19 09:42:02 +0200503
Dominik Ermel7d2f0bf2022-06-21 16:15:34 +0000504 if (curr_off + img_chunk_len + rem_bytes < img_size) {
Andrzej Puzdrowskif48de7a2020-10-19 09:42:02 +0200505 rem_bytes = 0;
Fabio Utzig30f6b2a2018-03-29 16:18:53 -0300506 }
Emanuele Di Santo205c8c62018-07-20 11:42:31 +0200507
Dominik Ermel5bd87442022-06-13 15:14:01 +0000508 BOOT_LOG_INF("Writing at 0x%x until 0x%x", curr_off, curr_off + img_chunk_len);
Dominik Ermel7d2f0bf2022-06-21 16:15:34 +0000509 /* Write flash aligned chunk, note that img_chunk_len now holds aligned length */
510 rc = flash_area_write(fap, curr_off, img_chunk, img_chunk_len);
511 if (rc == 0 && rem_bytes) {
512 /* Non-zero rem_bytes means that last chunk needs alignment; the aligned
513 * part, in the img_chunk_len - rem_bytes count bytes, has already been
514 * written by the above write, so we are left with the rem_bytes.
515 */
Andrzej Puzdrowskif48de7a2020-10-19 09:42:02 +0200516 uint8_t wbs_aligned[BOOT_MAX_ALIGN];
Andrzej Puzdrowskif48de7a2020-10-19 09:42:02 +0200517
Dominik Ermel7d2f0bf2022-06-21 16:15:34 +0000518 memset(wbs_aligned, flash_area_erased_val(fap), sizeof(wbs_aligned));
519 memcpy(wbs_aligned, img_chunk + img_chunk_len, rem_bytes);
Andrzej Puzdrowskif48de7a2020-10-19 09:42:02 +0200520
Dominik Ermel7d2f0bf2022-06-21 16:15:34 +0000521 rc = flash_area_write(fap, curr_off + img_chunk_len, wbs_aligned,
522 flash_area_align(fap));
Andrzej Puzdrowskif48de7a2020-10-19 09:42:02 +0200523 }
524
Marko Kiiskilace50ab02018-06-06 11:33:33 +0300525 if (rc == 0) {
Dominik Ermel7d2f0bf2022-06-21 16:15:34 +0000526 curr_off += img_chunk_len + rem_bytes;
Andrzej Puzdrowskic2e30cf2018-07-20 16:19:09 +0200527 if (curr_off == img_size) {
Andrzej Puzdrowski4f9c7302021-07-16 17:34:43 +0200528#ifdef MCUBOOT_ERASE_PROGRESSIVELY
Andrzej Puzdrowskic2e30cf2018-07-20 16:19:09 +0200529 /* Assure that sector for image trailer was erased. */
530 /* Check whether it was erased during previous upload. */
Dominik Ermelbcc17b42022-06-15 15:33:04 +0000531 off_t start = flash_sector_get_off(&status_sector);
532
533 if (erase_range(fap, start, start) < 0) {
534 rc = MGMT_ERR_EUNKNOWN;
535 goto out;
Andrzej Puzdrowskic2e30cf2018-07-20 16:19:09 +0200536 }
Andrzej Puzdrowskic2e30cf2018-07-20 16:19:09 +0200537#endif
Andrzej Puzdrowski4f9c7302021-07-16 17:34:43 +0200538 rc = BOOT_HOOK_CALL(boot_serial_uploaded_hook, 0, img_num, fap,
539 img_size);
540 if (rc) {
541 BOOT_LOG_ERR("Error %d post upload hook", rc);
542 goto out;
543 }
544 }
Marko Kiiskilace50ab02018-06-06 11:33:33 +0300545 } else {
546 out_invalid_data:
Christopher Collins92ea77f2016-12-12 15:59:26 -0800547 rc = MGMT_ERR_EINVAL;
Christopher Collins92ea77f2016-12-12 15:59:26 -0800548 }
Emanuele Di Santo205c8c62018-07-20 11:42:31 +0200549
Christopher Collins92ea77f2016-12-12 15:59:26 -0800550out:
Andrzej Puzdrowski8e96b832017-09-08 16:49:14 +0200551 BOOT_LOG_INF("RX: 0x%x", rc);
Øyvind Rønningstada7d34ca2022-02-28 13:47:57 +0100552 zcbor_map_start_encode(cbor_state, 10);
553 zcbor_tstr_put_lit_cast(cbor_state, "rc");
554 zcbor_uint32_put(cbor_state, rc);
Christopher Collins92ea77f2016-12-12 15:59:26 -0800555 if (rc == 0) {
Øyvind Rønningstada7d34ca2022-02-28 13:47:57 +0100556 zcbor_tstr_put_lit_cast(cbor_state, "off");
557 zcbor_uint32_put(cbor_state, curr_off);
Christopher Collins92ea77f2016-12-12 15:59:26 -0800558 }
Øyvind Rønningstada7d34ca2022-02-28 13:47:57 +0100559 zcbor_map_end_encode(cbor_state, 10);
Christopher Collins92ea77f2016-12-12 15:59:26 -0800560
561 boot_serial_output();
562 flash_area_close(fap);
Wouter Cappelle953a7612021-05-03 16:53:05 +0200563
564#ifdef MCUBOOT_ENC_IMAGES
565 if (curr_off == img_size) {
566 /* Last sector received, now start a decryption on the image if it is encrypted*/
567 rc = boot_handle_enc_fw();
568 }
569#endif //#ifdef MCUBOOT_ENC_IMAGES
Christopher Collins92ea77f2016-12-12 15:59:26 -0800570}
571
Dominik Ermel4c0f6c12022-03-04 15:47:37 +0000572/*
573 * Send rc code only.
574 */
575static void
576bs_rc_rsp(int rc_code)
577{
Øyvind Rønningstada7d34ca2022-02-28 13:47:57 +0100578 zcbor_map_start_encode(cbor_state, 10);
579 zcbor_tstr_put_lit_cast(cbor_state, "rc");
580 zcbor_uint32_put(cbor_state, rc_code);
581 zcbor_map_end_encode(cbor_state, 10);
Dominik Ermel4c0f6c12022-03-04 15:47:37 +0000582 boot_serial_output();
583}
584
585
Wouter Cappellee3ff1752021-05-03 16:36:22 +0200586#ifdef MCUBOOT_BOOT_MGMT_ECHO
Wouter Cappellee3ff1752021-05-03 16:36:22 +0200587static void
588bs_echo(char *buf, int len)
589{
Dominik Ermel88bd5672022-06-07 15:17:06 +0000590 struct Echo echo = { 0 };
591 size_t decoded_len;
592 uint32_t rc = MGMT_ERR_EINVAL;
593 uint_fast8_t result = cbor_decode_Echo((const uint8_t *)buf, len, &echo, &decoded_len);
Wouter Cappellee3ff1752021-05-03 16:36:22 +0200594
Dominik Ermel88bd5672022-06-07 15:17:06 +0000595 if ((result != ZCBOR_SUCCESS) || (len != decoded_len)) {
596 goto out;
Wouter Cappellee3ff1752021-05-03 16:36:22 +0200597 }
Dominik Ermel88bd5672022-06-07 15:17:06 +0000598
599 if (echo._Echo_d.value == NULL) {
600 goto out;
601 }
602
603 zcbor_map_start_encode(cbor_state, 10);
604 zcbor_tstr_put_term(cbor_state, "r");
605 if (zcbor_tstr_encode(cbor_state, &echo._Echo_d) && zcbor_map_end_encode(cbor_state, 10)) {
606 boot_serial_output();
607 return;
608 } else {
609 rc = MGMT_ERR_ENOMEM;
610 }
611
612out:
613 reset_cbor_state();
614 bs_rc_rsp(rc);
Wouter Cappellee3ff1752021-05-03 16:36:22 +0200615}
616#endif
617
Christopher Collins92ea77f2016-12-12 15:59:26 -0800618/*
Christopher Collins92ea77f2016-12-12 15:59:26 -0800619 * Reset, and (presumably) boot to newly uploaded image. Flush console
620 * before restarting.
621 */
Andrzej Puzdrowski268cdd02018-04-10 12:57:54 +0200622static void
Christopher Collins92ea77f2016-12-12 15:59:26 -0800623bs_reset(char *buf, int len)
624{
Dominik Ermelc9dc2242021-07-28 17:08:23 +0000625 bs_rc_rsp(0);
Christopher Collins92ea77f2016-12-12 15:59:26 -0800626
Andrzej Puzdrowski8e96b832017-09-08 16:49:14 +0200627#ifdef __ZEPHYR__
Andrzej Puzdrowski0cf0dbd2021-05-14 11:55:57 +0200628#ifdef CONFIG_MULTITHREADING
Carles Cufi7e7b4ad2020-03-30 19:12:02 +0200629 k_sleep(K_MSEC(250));
Andrzej Puzdrowski0cf0dbd2021-05-14 11:55:57 +0200630#else
631 k_busy_wait(250000);
632#endif
Andrzej Puzdrowski8e96b832017-09-08 16:49:14 +0200633 sys_reboot(SYS_REBOOT_COLD);
Almir Okatoe8cbc0d2022-06-13 10:45:39 -0300634#elif __ESPRESSIF__
635 esp_rom_delay_us(250000);
636 bootloader_reset();
Andrzej Puzdrowski8e96b832017-09-08 16:49:14 +0200637#else
Christopher Collins92ea77f2016-12-12 15:59:26 -0800638 os_cputime_delay_usecs(250000);
639 hal_system_reset();
Andrzej Puzdrowski8e96b832017-09-08 16:49:14 +0200640#endif
Christopher Collins92ea77f2016-12-12 15:59:26 -0800641}
642
643/*
644 * Parse incoming line of input from console.
645 * Expect newtmgr protocol with serial transport.
646 */
647void
648boot_serial_input(char *buf, int len)
649{
650 struct nmgr_hdr *hdr;
651
652 hdr = (struct nmgr_hdr *)buf;
653 if (len < sizeof(*hdr) ||
654 (hdr->nh_op != NMGR_OP_READ && hdr->nh_op != NMGR_OP_WRITE) ||
655 (ntohs(hdr->nh_len) < len - sizeof(*hdr))) {
656 return;
657 }
658 bs_hdr = hdr;
659 hdr->nh_group = ntohs(hdr->nh_group);
660
661 buf += sizeof(*hdr);
662 len -= sizeof(*hdr);
Marko Kiiskilace50ab02018-06-06 11:33:33 +0300663
Dominik Ermel4c0f6c12022-03-04 15:47:37 +0000664 reset_cbor_state();
Christopher Collins92ea77f2016-12-12 15:59:26 -0800665
666 /*
667 * Limited support for commands.
668 */
669 if (hdr->nh_group == MGMT_GROUP_ID_IMAGE) {
670 switch (hdr->nh_id) {
Marko Kiiskilace50ab02018-06-06 11:33:33 +0300671 case IMGMGR_NMGR_ID_STATE:
Christopher Collins92ea77f2016-12-12 15:59:26 -0800672 bs_list(buf, len);
673 break;
Marko Kiiskilace50ab02018-06-06 11:33:33 +0300674 case IMGMGR_NMGR_ID_UPLOAD:
Christopher Collins92ea77f2016-12-12 15:59:26 -0800675 bs_upload(buf, len);
676 break;
677 default:
Dominik Ermelc9dc2242021-07-28 17:08:23 +0000678 bs_rc_rsp(MGMT_ERR_ENOTSUP);
Christopher Collins92ea77f2016-12-12 15:59:26 -0800679 break;
680 }
681 } else if (hdr->nh_group == MGMT_GROUP_ID_DEFAULT) {
682 switch (hdr->nh_id) {
Wouter Cappellee3ff1752021-05-03 16:36:22 +0200683 case NMGR_ID_ECHO:
684#ifdef MCUBOOT_BOOT_MGMT_ECHO
685 bs_echo(buf, len);
686#endif
687 break;
Christopher Collins92ea77f2016-12-12 15:59:26 -0800688 case NMGR_ID_CONS_ECHO_CTRL:
Dominik Ermelc9dc2242021-07-28 17:08:23 +0000689 bs_rc_rsp(0);
Christopher Collins92ea77f2016-12-12 15:59:26 -0800690 break;
691 case NMGR_ID_RESET:
692 bs_reset(buf, len);
693 break;
694 default:
Dominik Ermelc9dc2242021-07-28 17:08:23 +0000695 bs_rc_rsp(MGMT_ERR_ENOTSUP);
Christopher Collins92ea77f2016-12-12 15:59:26 -0800696 break;
697 }
Dominik Ermelbd69c3d2021-07-28 11:27:31 +0000698 } else if (MCUBOOT_PERUSER_MGMT_GROUP_ENABLED == 1) {
Øyvind Rønningstada7d34ca2022-02-28 13:47:57 +0100699 if (bs_peruser_system_specific(hdr, buf, len, cbor_state) == 0) {
Dominik Ermel3d51e432021-06-25 17:29:50 +0000700 boot_serial_output();
701 }
Dominik Ermelc9dc2242021-07-28 17:08:23 +0000702 } else {
703 bs_rc_rsp(MGMT_ERR_ENOTSUP);
Christopher Collins92ea77f2016-12-12 15:59:26 -0800704 }
Wouter Cappellee3822f82022-01-19 15:39:43 +0100705#ifdef MCUBOOT_SERIAL_WAIT_FOR_DFU
706 bs_entry = true;
707#endif
Christopher Collins92ea77f2016-12-12 15:59:26 -0800708}
709
710static void
711boot_serial_output(void)
712{
713 char *data;
714 int len;
715 uint16_t crc;
716 uint16_t totlen;
717 char pkt_start[2] = { SHELL_NLIP_PKT_START1, SHELL_NLIP_PKT_START2 };
Dominik Ermel5ff89582022-03-03 17:09:07 +0000718 char buf[BOOT_SERIAL_OUT_MAX + sizeof(*bs_hdr) + sizeof(crc) + sizeof(totlen)];
719 char encoded_buf[BASE64_ENCODE_SIZE(sizeof(buf))];
Christopher Collins92ea77f2016-12-12 15:59:26 -0800720
721 data = bs_obuf;
Øyvind Rønningstada7d34ca2022-02-28 13:47:57 +0100722 len = (uint32_t)cbor_state->payload_mut - (uint32_t)bs_obuf;
Christopher Collins92ea77f2016-12-12 15:59:26 -0800723
724 bs_hdr->nh_op++;
Marko Kiiskilace50ab02018-06-06 11:33:33 +0300725 bs_hdr->nh_flags = 0;
Christopher Collins92ea77f2016-12-12 15:59:26 -0800726 bs_hdr->nh_len = htons(len);
727 bs_hdr->nh_group = htons(bs_hdr->nh_group);
728
Andrzej Puzdrowski8e96b832017-09-08 16:49:14 +0200729#ifdef __ZEPHYR__
Carles Cufib9192a42022-02-10 11:41:57 +0100730 crc = crc16_itu_t(CRC16_INITIAL_CRC, (uint8_t *)bs_hdr, sizeof(*bs_hdr));
731 crc = crc16_itu_t(crc, data, len);
Almir Okatoe8cbc0d2022-06-13 10:45:39 -0300732#elif __ESPRESSIF__
733 /* For ESP32 it was used the CRC API in rom/crc.h */
734 crc = ~crc16_be(~CRC16_INITIAL_CRC, (uint8_t *)bs_hdr, sizeof(*bs_hdr));
735 crc = ~crc16_be(~crc, (uint8_t *)data, len);
Andrzej Puzdrowski8e96b832017-09-08 16:49:14 +0200736#else
Christopher Collins92ea77f2016-12-12 15:59:26 -0800737 crc = crc16_ccitt(CRC16_INITIAL_CRC, bs_hdr, sizeof(*bs_hdr));
738 crc = crc16_ccitt(crc, data, len);
Andrzej Puzdrowski8e96b832017-09-08 16:49:14 +0200739#endif
Christopher Collins92ea77f2016-12-12 15:59:26 -0800740 crc = htons(crc);
741
Marko Kiiskila149b4572018-06-06 14:18:54 +0300742 boot_uf->write(pkt_start, sizeof(pkt_start));
Christopher Collins92ea77f2016-12-12 15:59:26 -0800743
744 totlen = len + sizeof(*bs_hdr) + sizeof(crc);
745 totlen = htons(totlen);
746
747 memcpy(buf, &totlen, sizeof(totlen));
748 totlen = sizeof(totlen);
749 memcpy(&buf[totlen], bs_hdr, sizeof(*bs_hdr));
750 totlen += sizeof(*bs_hdr);
751 memcpy(&buf[totlen], data, len);
752 totlen += len;
753 memcpy(&buf[totlen], &crc, sizeof(crc));
754 totlen += sizeof(crc);
Andrzej Puzdrowski8e96b832017-09-08 16:49:14 +0200755#ifdef __ZEPHYR__
756 size_t enc_len;
Carles Cufi0165be82018-03-26 17:43:51 +0200757 base64_encode(encoded_buf, sizeof(encoded_buf), &enc_len, buf, totlen);
Andrzej Puzdrowski8e96b832017-09-08 16:49:14 +0200758 totlen = enc_len;
Almir Okatoe8cbc0d2022-06-13 10:45:39 -0300759#elif __ESPRESSIF__
760 size_t enc_len;
761 base64_encode((unsigned char *)encoded_buf, sizeof(encoded_buf), &enc_len, (unsigned char *)buf, totlen);
762 totlen = enc_len;
Andrzej Puzdrowski8e96b832017-09-08 16:49:14 +0200763#else
Christopher Collins92ea77f2016-12-12 15:59:26 -0800764 totlen = base64_encode(buf, totlen, encoded_buf, 1);
Andrzej Puzdrowski8e96b832017-09-08 16:49:14 +0200765#endif
Marko Kiiskila149b4572018-06-06 14:18:54 +0300766 boot_uf->write(encoded_buf, totlen);
Dominik Ermel2f2b31c2022-03-03 12:39:27 +0000767 boot_uf->write("\n", 1);
Andrzej Puzdrowski8e96b832017-09-08 16:49:14 +0200768 BOOT_LOG_INF("TX");
Christopher Collins92ea77f2016-12-12 15:59:26 -0800769}
770
771/*
772 * Returns 1 if full packet has been received.
773 */
774static int
775boot_serial_in_dec(char *in, int inlen, char *out, int *out_off, int maxout)
776{
777 int rc;
778 uint16_t crc;
779 uint16_t len;
Marko Kiiskilae5aeee42018-12-21 15:00:16 +0200780
Andrzej Puzdrowski8e96b832017-09-08 16:49:14 +0200781#ifdef __ZEPHYR__
782 int err;
Andrzej Puzdrowskiec1e4d12018-06-18 14:36:14 +0200783 err = base64_decode( &out[*out_off], maxout - *out_off, &rc, in, inlen - 2);
Andrzej Puzdrowski8e96b832017-09-08 16:49:14 +0200784 if (err) {
785 return -1;
786 }
Almir Okatoe8cbc0d2022-06-13 10:45:39 -0300787#elif __ESPRESSIF__
788 int err;
789 err = base64_decode((unsigned char *)&out[*out_off], maxout - *out_off, (size_t *)&rc, (unsigned char *)in, inlen);
790 if (err) {
791 return -1;
792 }
Andrzej Puzdrowski8e96b832017-09-08 16:49:14 +0200793#else
Christopher Collins92ea77f2016-12-12 15:59:26 -0800794 if (*out_off + base64_decode_len(in) >= maxout) {
795 return -1;
796 }
797 rc = base64_decode(in, &out[*out_off]);
798 if (rc < 0) {
799 return -1;
800 }
Andrzej Puzdrowski8e96b832017-09-08 16:49:14 +0200801#endif
Fabio Utzig6f49c272019-08-23 11:42:58 -0300802
Christopher Collins92ea77f2016-12-12 15:59:26 -0800803 *out_off += rc;
Fabio Utzig6f49c272019-08-23 11:42:58 -0300804 if (*out_off <= sizeof(uint16_t)) {
805 return 0;
Christopher Collins92ea77f2016-12-12 15:59:26 -0800806 }
Fabio Utzig6f49c272019-08-23 11:42:58 -0300807
808 len = ntohs(*(uint16_t *)out);
809 if (len != *out_off - sizeof(uint16_t)) {
810 return 0;
811 }
812
813 if (len > *out_off - sizeof(uint16_t)) {
814 len = *out_off - sizeof(uint16_t);
815 }
816
817 out += sizeof(uint16_t);
818#ifdef __ZEPHYR__
Carles Cufib9192a42022-02-10 11:41:57 +0100819 crc = crc16_itu_t(CRC16_INITIAL_CRC, out, len);
Almir Okatoe8cbc0d2022-06-13 10:45:39 -0300820#elif __ESPRESSIF__
821 crc = ~crc16_be(~CRC16_INITIAL_CRC, (uint8_t *)out, len);
Fabio Utzig6f49c272019-08-23 11:42:58 -0300822#else
823 crc = crc16_ccitt(CRC16_INITIAL_CRC, out, len);
824#endif
825 if (crc || len <= sizeof(crc)) {
826 return 0;
827 }
828 *out_off -= sizeof(crc);
829 out[*out_off] = '\0';
830
831 return 1;
Christopher Collins92ea77f2016-12-12 15:59:26 -0800832}
833
834/*
835 * Task which waits reading console, expecting to get image over
836 * serial port.
837 */
Wouter Cappellee3822f82022-01-19 15:39:43 +0100838static void
839boot_serial_read_console(const struct boot_uart_funcs *f,int timeout_in_ms)
Christopher Collins92ea77f2016-12-12 15:59:26 -0800840{
841 int rc;
842 int off;
David Brown57f0df32020-05-12 08:39:21 -0600843 int dec_off = 0;
Christopher Collins92ea77f2016-12-12 15:59:26 -0800844 int full_line;
Marko Kiiskila149b4572018-06-06 14:18:54 +0300845 int max_input;
Wouter Cappellee3822f82022-01-19 15:39:43 +0100846 int elapsed_in_ms = 0;
Christopher Collins92ea77f2016-12-12 15:59:26 -0800847
Marko Kiiskila149b4572018-06-06 14:18:54 +0300848 boot_uf = f;
Marko Kiiskila149b4572018-06-06 14:18:54 +0300849 max_input = sizeof(in_buf);
Christopher Collins92ea77f2016-12-12 15:59:26 -0800850
851 off = 0;
Wouter Cappellee3822f82022-01-19 15:39:43 +0100852 while (timeout_in_ms > 0 || bs_entry) {
Piotr Dymacz067f30a2022-08-12 18:25:34 +0200853 /*
854 * Don't enter CPU idle state here if timeout based serial recovery is
855 * used as otherwise the boot process hangs forever, waiting for input
856 * from serial console (if single-thread mode is used).
857 */
Piotr Dymacz3942e9b2022-07-18 10:19:25 +0200858#ifndef MCUBOOT_SERIAL_WAIT_FOR_DFU
Andrzej Puzdrowskiaea38eb2021-06-11 12:28:59 +0200859 MCUBOOT_CPU_IDLE();
Piotr Dymacz3942e9b2022-07-18 10:19:25 +0200860#endif
Hein Wessels56d28f02021-11-19 08:42:08 +0100861 MCUBOOT_WATCHDOG_FEED();
Wouter Cappellee3822f82022-01-19 15:39:43 +0100862#ifdef MCUBOOT_SERIAL_WAIT_FOR_DFU
863 uint32_t start = k_uptime_get_32();
864#endif
Andrzej Puzdrowskiec1e4d12018-06-18 14:36:14 +0200865 rc = f->read(in_buf + off, sizeof(in_buf) - off, &full_line);
Christopher Collins92ea77f2016-12-12 15:59:26 -0800866 if (rc <= 0 && !full_line) {
Wouter Cappellee3822f82022-01-19 15:39:43 +0100867 goto check_timeout;
Christopher Collins92ea77f2016-12-12 15:59:26 -0800868 }
869 off += rc;
870 if (!full_line) {
Marko Kiiskilace50ab02018-06-06 11:33:33 +0300871 if (off == max_input) {
872 /*
873 * Full line, no newline yet. Reset the input buffer.
874 */
875 off = 0;
876 }
Wouter Cappellee3822f82022-01-19 15:39:43 +0100877 goto check_timeout;
Christopher Collins92ea77f2016-12-12 15:59:26 -0800878 }
Andrzej Puzdrowskiec1e4d12018-06-18 14:36:14 +0200879 if (in_buf[0] == SHELL_NLIP_PKT_START1 &&
880 in_buf[1] == SHELL_NLIP_PKT_START2) {
Christopher Collins92ea77f2016-12-12 15:59:26 -0800881 dec_off = 0;
Andrzej Puzdrowskiec1e4d12018-06-18 14:36:14 +0200882 rc = boot_serial_in_dec(&in_buf[2], off - 2, dec_buf, &dec_off, max_input);
883 } else if (in_buf[0] == SHELL_NLIP_DATA_START1 &&
884 in_buf[1] == SHELL_NLIP_DATA_START2) {
885 rc = boot_serial_in_dec(&in_buf[2], off - 2, dec_buf, &dec_off, max_input);
Christopher Collins92ea77f2016-12-12 15:59:26 -0800886 }
Andrzej Puzdrowskiec1e4d12018-06-18 14:36:14 +0200887
888 /* serve errors: out of decode memory, or bad encoding */
Christopher Collins92ea77f2016-12-12 15:59:26 -0800889 if (rc == 1) {
Andrzej Puzdrowskiec1e4d12018-06-18 14:36:14 +0200890 boot_serial_input(&dec_buf[2], dec_off - 2);
Christopher Collins92ea77f2016-12-12 15:59:26 -0800891 }
892 off = 0;
Wouter Cappellee3822f82022-01-19 15:39:43 +0100893check_timeout:
894 /* Subtract elapsed time */
895#ifdef MCUBOOT_SERIAL_WAIT_FOR_DFU
896 elapsed_in_ms = (k_uptime_get_32() - start);
897#endif
898 timeout_in_ms -= elapsed_in_ms;
Christopher Collins92ea77f2016-12-12 15:59:26 -0800899 }
900}
Wouter Cappellee3822f82022-01-19 15:39:43 +0100901
902/*
903 * Task which waits reading console, expecting to get image over
904 * serial port.
905 */
906void
907boot_serial_start(const struct boot_uart_funcs *f)
908{
909 bs_entry = true;
910 boot_serial_read_console(f,0);
911}
912
913#ifdef MCUBOOT_SERIAL_WAIT_FOR_DFU
914/*
915 * Task which waits reading console for a certain amount of timeout.
916 * If within this timeout no mcumgr command is received, the function is
917 * returning, else the serial boot is never exited
918 */
919void
920boot_serial_check_start(const struct boot_uart_funcs *f, int timeout_in_ms)
921{
922 bs_entry = false;
923 boot_serial_read_console(f,timeout_in_ms);
924}
925#endif