blob: 9a79926ad3bbb1fe73c65636679ad102b79f66e2 [file] [log] [blame]
Christopher Collins92ea77f2016-12-12 15:59:26 -08001/*
2 * Licensed to the Apache Software Foundation (ASF) under one
3 * or more contributor license agreements. See the NOTICE file
4 * distributed with this work for additional information
5 * regarding copyright ownership. The ASF licenses this file
6 * to you under the Apache License, Version 2.0 (the
7 * "License"); you may not use this file except in compliance
8 * with the License. You may obtain a copy of the License at
9 *
10 * http://www.apache.org/licenses/LICENSE-2.0
11 *
12 * Unless required by applicable law or agreed to in writing,
13 * software distributed under the License is distributed on an
14 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
15 * KIND, either express or implied. See the License for the
16 * specific language governing permissions and limitations
17 * under the License.
18 */
19#include <assert.h>
20#include <stddef.h>
21#include <inttypes.h>
22#include <ctype.h>
23#include <stdio.h>
Almir Okato90be6e62022-09-23 14:52:25 -030024#include <errno.h>
Christopher Collins92ea77f2016-12-12 15:59:26 -080025
26#include "sysflash/sysflash.h"
27
Fabio Utzig1a2e41a2017-11-17 12:13:09 -020028#include "bootutil/bootutil_log.h"
Øyvind Rønningstada7d34ca2022-02-28 13:47:57 +010029#include "zcbor_encode.h"
Fabio Utzig1a2e41a2017-11-17 12:13:09 -020030
Andrzej Puzdrowski8e96b832017-09-08 16:49:14 +020031#ifdef __ZEPHYR__
Fabio Baltieri888e2612022-07-19 20:54:26 +000032#include <zephyr/sys/reboot.h>
33#include <zephyr/sys/byteorder.h>
34#include <zephyr/sys/__assert.h>
35#include <zephyr/drivers/flash.h>
Gerard Marull-Paretas4eca54f2022-10-06 11:45:11 +020036#include <zephyr/kernel.h>
Fabio Baltieri888e2612022-07-19 20:54:26 +000037#include <zephyr/sys/crc.h>
38#include <zephyr/sys/base64.h>
Almir Okatoe8cbc0d2022-06-13 10:45:39 -030039#include <hal/hal_flash.h>
40#elif __ESPRESSIF__
41#include <bootloader_utility.h>
42#include <esp_rom_sys.h>
Almir Okato7d3622f2022-10-20 12:44:58 -030043#include <esp_crc.h>
Almir Okatoe8cbc0d2022-06-13 10:45:39 -030044#include <endian.h>
45#include <mbedtls/base64.h>
Andrzej Puzdrowski8e96b832017-09-08 16:49:14 +020046#else
Christopher Collins92ea77f2016-12-12 15:59:26 -080047#include <bsp/bsp.h>
Christopher Collins92ea77f2016-12-12 15:59:26 -080048#include <hal/hal_system.h>
Almir Okatoe8cbc0d2022-06-13 10:45:39 -030049#include <hal/hal_flash.h>
Christopher Collins92ea77f2016-12-12 15:59:26 -080050#include <os/endian.h>
Christopher Collins92ea77f2016-12-12 15:59:26 -080051#include <os/os_cputime.h>
Andrzej Puzdrowski8e96b832017-09-08 16:49:14 +020052#include <crc/crc16.h>
53#include <base64/base64.h>
Andrzej Puzdrowski386b5922018-04-06 19:26:24 +020054#endif /* __ZEPHYR__ */
55
Andrzej Puzdrowskib788c712018-04-12 12:42:49 +020056#include <flash_map_backend/flash_map_backend.h>
Andrzej Puzdrowski8e96b832017-09-08 16:49:14 +020057#include <os/os.h>
58#include <os/os_malloc.h>
Christopher Collins92ea77f2016-12-12 15:59:26 -080059
60#include <bootutil/image.h>
Andrzej Puzdrowskif48de7a2020-10-19 09:42:02 +020061#include <bootutil/bootutil.h>
Christopher Collins92ea77f2016-12-12 15:59:26 -080062
63#include "boot_serial/boot_serial.h"
64#include "boot_serial_priv.h"
Almir Okatoe8cbc0d2022-06-13 10:45:39 -030065#include "mcuboot_config/mcuboot_config.h"
Christopher Collins92ea77f2016-12-12 15:59:26 -080066
Dominik Ermel3d4e55d2021-07-09 11:14:10 +000067#ifdef MCUBOOT_ERASE_PROGRESSIVELY
Andrzej Puzdrowskic2e30cf2018-07-20 16:19:09 +020068#include "bootutil_priv.h"
69#endif
70
Wouter Cappelle953a7612021-05-03 16:53:05 +020071#ifdef MCUBOOT_ENC_IMAGES
72#include "single_loader.h"
73#endif
74
Øyvind Rønningstadf42a8202019-12-13 03:27:54 +010075#include "serial_recovery_cbor.h"
Dominik Ermel88bd5672022-06-07 15:17:06 +000076#include "serial_recovery_echo.h"
Andrzej Puzdrowski4f9c7302021-07-16 17:34:43 +020077#include "bootutil/boot_hooks.h"
Øyvind Rønningstadf42a8202019-12-13 03:27:54 +010078
Carlos Falgueras Garcíaa4b4b0f2021-06-22 10:00:22 +020079BOOT_LOG_MODULE_DECLARE(mcuboot);
Emanuele Di Santo9f1933d2018-11-20 10:59:59 +010080
Jamie McCraead1fb3d2022-12-01 14:24:37 +000081#ifndef MCUBOOT_SERIAL_MAX_RECEIVE_SIZE
82#define MCUBOOT_SERIAL_MAX_RECEIVE_SIZE 512
83#endif
84
Andrzej Puzdrowskic9ac5cc2021-11-19 11:58:05 +010085#define BOOT_SERIAL_OUT_MAX (128 * BOOT_IMAGE_NUMBER)
Christopher Collins92ea77f2016-12-12 15:59:26 -080086
Andrzej Puzdrowski8e96b832017-09-08 16:49:14 +020087#ifdef __ZEPHYR__
Carles Cufi0165be82018-03-26 17:43:51 +020088/* base64 lib encodes data to null-terminated string */
Andrzej Puzdrowski8e96b832017-09-08 16:49:14 +020089#define BASE64_ENCODE_SIZE(in_size) ((((((in_size) - 1) / 3) * 4) + 4) + 1)
90
91#define CRC16_INITIAL_CRC 0 /* what to seed crc16 with */
92#define CRC_CITT_POLYMINAL 0x1021
93
94#define ntohs(x) sys_be16_to_cpu(x)
95#define htons(x) sys_cpu_to_be16(x)
Almir Okatoe8cbc0d2022-06-13 10:45:39 -030096#elif __ESPRESSIF__
97#define BASE64_ENCODE_SIZE(in_size) ((((((in_size) - 1) / 3) * 4) + 4) + 1)
98#define CRC16_INITIAL_CRC 0 /* what to seed crc16 with */
99
100#define ntohs(x) be16toh(x)
101#define htons(x) htobe16(x)
102
103#define base64_decode mbedtls_base64_decode
104#define base64_encode mbedtls_base64_encode
Andrzej Puzdrowski8e96b832017-09-08 16:49:14 +0200105#endif
Emanuele Di Santo9f1933d2018-11-20 10:59:59 +0100106
Fabio Utzig6f49c272019-08-23 11:42:58 -0300107#if (BOOT_IMAGE_NUMBER > 1)
108#define IMAGES_ITER(x) for ((x) = 0; (x) < BOOT_IMAGE_NUMBER; ++(x))
109#else
110#define IMAGES_ITER(x)
111#endif
112
Jamie McCraead1fb3d2022-12-01 14:24:37 +0000113static char in_buf[MCUBOOT_SERIAL_MAX_RECEIVE_SIZE + 1];
114static char dec_buf[MCUBOOT_SERIAL_MAX_RECEIVE_SIZE + 1];
Marko Kiiskila8b1ce3a2018-06-14 13:20:46 -0700115const struct boot_uart_funcs *boot_uf;
Christopher Collins92ea77f2016-12-12 15:59:26 -0800116static struct nmgr_hdr *bs_hdr;
Wouter Cappellee3822f82022-01-19 15:39:43 +0100117static bool bs_entry;
Christopher Collins92ea77f2016-12-12 15:59:26 -0800118
119static char bs_obuf[BOOT_SERIAL_OUT_MAX];
120
Christopher Collins92ea77f2016-12-12 15:59:26 -0800121static void boot_serial_output(void);
122
Øyvind Rønningstada7d34ca2022-02-28 13:47:57 +0100123static zcbor_state_t cbor_state[2];
Christopher Collins92ea77f2016-12-12 15:59:26 -0800124
Dominik Ermel4c0f6c12022-03-04 15:47:37 +0000125void reset_cbor_state(void)
126{
Øyvind Rønningstada7d34ca2022-02-28 13:47:57 +0100127 zcbor_new_encode_state(cbor_state, 2, (uint8_t *)bs_obuf,
128 (size_t)bs_obuf + sizeof(bs_obuf), 0);
Dominik Ermel4c0f6c12022-03-04 15:47:37 +0000129}
130
Dominik Ermel3d51e432021-06-25 17:29:50 +0000131/**
Dominik Ermelbd69c3d2021-07-28 11:27:31 +0000132 * Function that processes MGMT_GROUP_ID_PERUSER mcumgr group and may be
133 * used to process any groups that have not been processed by generic boot
134 * serial implementation.
Dominik Ermel3d51e432021-06-25 17:29:50 +0000135 *
136 * @param[in] hdr -- the decoded header of mcumgr message;
137 * @param[in] buffer -- buffer with first mcumgr message;
138 * @param[in] len -- length of of data in buffer;
139 * @param[out] *cs -- object with encoded response.
140 *
141 * @return 0 on success; non-0 error code otherwise.
142 */
143extern int bs_peruser_system_specific(const struct nmgr_hdr *hdr,
144 const char *buffer,
Øyvind Rønningstada7d34ca2022-02-28 13:47:57 +0100145 int len, zcbor_state_t *cs);
Christopher Collins92ea77f2016-12-12 15:59:26 -0800146
Dominik Ermeld49cfc12022-06-09 08:24:48 +0000147#define zcbor_tstr_put_lit_cast(state, string) \
148 zcbor_tstr_encode_ptr(state, (uint8_t *)string, sizeof(string) - 1)
149
150#ifndef MCUBOOT_USE_SNPRINTF
Christopher Collins92ea77f2016-12-12 15:59:26 -0800151/*
Marko Kiiskilace50ab02018-06-06 11:33:33 +0300152 * Convert version into string without use of snprintf().
Christopher Collins92ea77f2016-12-12 15:59:26 -0800153 */
Marko Kiiskilace50ab02018-06-06 11:33:33 +0300154static int
155u32toa(char *tgt, uint32_t val)
Christopher Collins92ea77f2016-12-12 15:59:26 -0800156{
Marko Kiiskilace50ab02018-06-06 11:33:33 +0300157 char *dst;
158 uint32_t d = 1;
159 uint32_t dgt;
160 int n = 0;
Christopher Collins92ea77f2016-12-12 15:59:26 -0800161
Marko Kiiskilace50ab02018-06-06 11:33:33 +0300162 dst = tgt;
163 while (val / d >= 10) {
164 d *= 10;
Christopher Collins92ea77f2016-12-12 15:59:26 -0800165 }
Marko Kiiskilace50ab02018-06-06 11:33:33 +0300166 while (d) {
167 dgt = val / d;
168 val %= d;
169 d /= 10;
170 if (n || dgt > 0 || d == 0) {
171 *dst++ = dgt + '0';
172 ++n;
Christopher Collins92ea77f2016-12-12 15:59:26 -0800173 }
Christopher Collins92ea77f2016-12-12 15:59:26 -0800174 }
Marko Kiiskilace50ab02018-06-06 11:33:33 +0300175 *dst = '\0';
176
177 return dst - tgt;
178}
179
180/*
181 * dst has to be able to fit "255.255.65535.4294967295" (25 characters).
182 */
183static void
184bs_list_img_ver(char *dst, int maxlen, struct image_version *ver)
185{
186 int off;
187
188 off = u32toa(dst, ver->iv_major);
189 dst[off++] = '.';
190 off += u32toa(dst + off, ver->iv_minor);
191 dst[off++] = '.';
192 off += u32toa(dst + off, ver->iv_revision);
193 dst[off++] = '.';
194 off += u32toa(dst + off, ver->iv_build_num);
Christopher Collins92ea77f2016-12-12 15:59:26 -0800195}
Dominik Ermeld49cfc12022-06-09 08:24:48 +0000196#else
197/*
198 * dst has to be able to fit "255.255.65535.4294967295" (25 characters).
199 */
200static void
201bs_list_img_ver(char *dst, int maxlen, struct image_version *ver)
202{
203 snprintf(dst, maxlen, "%hu.%hu.%hu.%u", (uint16_t)ver->iv_major,
204 (uint16_t)ver->iv_minor, ver->iv_revision, ver->iv_build_num);
205}
206#endif /* !MCUBOOT_USE_SNPRINTF */
Christopher Collins92ea77f2016-12-12 15:59:26 -0800207
208/*
209 * List images.
210 */
211static void
212bs_list(char *buf, int len)
213{
Christopher Collins92ea77f2016-12-12 15:59:26 -0800214 struct image_header hdr;
215 uint8_t tmpbuf[64];
Øyvind Rønningstad9f4aefd2021-03-08 21:11:25 +0100216 uint32_t slot, area_id;
Christopher Collins92ea77f2016-12-12 15:59:26 -0800217 const struct flash_area *fap;
Fabio Utzig6f49c272019-08-23 11:42:58 -0300218 uint8_t image_index;
Christopher Collins92ea77f2016-12-12 15:59:26 -0800219
Øyvind Rønningstada7d34ca2022-02-28 13:47:57 +0100220 zcbor_map_start_encode(cbor_state, 1);
221 zcbor_tstr_put_lit_cast(cbor_state, "images");
222 zcbor_list_start_encode(cbor_state, 5);
Fabio Utzig6f49c272019-08-23 11:42:58 -0300223 image_index = 0;
224 IMAGES_ITER(image_index) {
225 for (slot = 0; slot < 2; slot++) {
226 area_id = flash_area_id_from_multi_image_slot(image_index, slot);
227 if (flash_area_open(area_id, &fap)) {
228 continue;
229 }
Christopher Collins92ea77f2016-12-12 15:59:26 -0800230
Andrzej Puzdrowski4f9c7302021-07-16 17:34:43 +0200231 int rc = BOOT_HOOK_CALL(boot_read_image_header_hook,
232 BOOT_HOOK_REGULAR, image_index, slot, &hdr);
233 if (rc == BOOT_HOOK_REGULAR)
234 {
235 flash_area_read(fap, 0, &hdr, sizeof(hdr));
236 }
Christopher Collins92ea77f2016-12-12 15:59:26 -0800237
Andrzej Puzdrowski4f9c7302021-07-16 17:34:43 +0200238 fih_int fih_rc = FIH_FAILURE;
239
240 if (hdr.ih_magic == IMAGE_MAGIC)
241 {
242 BOOT_HOOK_CALL_FIH(boot_image_check_hook,
243 fih_int_encode(BOOT_HOOK_REGULAR),
244 fih_rc, image_index, slot);
245 if (fih_eq(fih_rc, BOOT_HOOK_REGULAR))
246 {
Wouter Cappelle953a7612021-05-03 16:53:05 +0200247#ifdef MCUBOOT_ENC_IMAGES
248 if (slot == 0 && IS_ENCRYPTED(&hdr)) {
249 /* Clear the encrypted flag we didn't supply a key
250 * This flag could be set if there was a decryption in place
251 * performed before. We will try to validate the image without
252 * decryption by clearing the flag in the heder. If
253 * still encrypted the validation will fail.
254 */
255 hdr.ih_flags &= ~(ENCRYPTIONFLAGS);
256 }
257#endif
Andrzej Puzdrowski4f9c7302021-07-16 17:34:43 +0200258 FIH_CALL(bootutil_img_validate, fih_rc, NULL, 0, &hdr, fap, tmpbuf, sizeof(tmpbuf),
259 NULL, 0, NULL);
260 }
261 }
262
263 flash_area_close(fap);
264
265 if (fih_not_eq(fih_rc, FIH_SUCCESS)) {
Fabio Utzig6f49c272019-08-23 11:42:58 -0300266 continue;
267 }
Fabio Utzig6f49c272019-08-23 11:42:58 -0300268
Øyvind Rønningstada7d34ca2022-02-28 13:47:57 +0100269 zcbor_map_start_encode(cbor_state, 20);
Fabio Utzig6f49c272019-08-23 11:42:58 -0300270
271#if (BOOT_IMAGE_NUMBER > 1)
Øyvind Rønningstada7d34ca2022-02-28 13:47:57 +0100272 zcbor_tstr_put_lit_cast(cbor_state, "image");
273 zcbor_uint32_put(cbor_state, image_index);
Fabio Utzig6f49c272019-08-23 11:42:58 -0300274#endif
275
Øyvind Rønningstada7d34ca2022-02-28 13:47:57 +0100276 zcbor_tstr_put_lit_cast(cbor_state, "slot");
277 zcbor_uint32_put(cbor_state, slot);
278 zcbor_tstr_put_lit_cast(cbor_state, "version");
Fabio Utzig6f49c272019-08-23 11:42:58 -0300279
280 bs_list_img_ver((char *)tmpbuf, sizeof(tmpbuf), &hdr.ih_ver);
Øyvind Rønningstada7d34ca2022-02-28 13:47:57 +0100281 zcbor_tstr_encode_ptr(cbor_state, tmpbuf, strlen((char *)tmpbuf));
282 zcbor_map_end_encode(cbor_state, 20);
Christopher Collins92ea77f2016-12-12 15:59:26 -0800283 }
Christopher Collins92ea77f2016-12-12 15:59:26 -0800284 }
Øyvind Rønningstada7d34ca2022-02-28 13:47:57 +0100285 zcbor_list_end_encode(cbor_state, 5);
286 zcbor_map_end_encode(cbor_state, 1);
Christopher Collins92ea77f2016-12-12 15:59:26 -0800287 boot_serial_output();
288}
289
Dominik Ermelbcc17b42022-06-15 15:33:04 +0000290#ifdef MCUBOOT_ERASE_PROGRESSIVELY
291
292/** Erases range of flash, aligned to sector size
293 *
294 * Function will erase all sectors withing [start, end] range; it does not check
295 * the @p start for alignment, and it will use @p end to find boundaries of las
296 * sector to erase. Function returns offset of the first byte past the last
297 * erased sector, so basically offset of next sector to be erased if needed.
298 * The function is intended to be called iteratively with previously returned
299 * offset as @p start.
300 *
301 * @param start starting offset, aligned to sector offset;
302 * @param end ending offset, maybe anywhere within sector;
303 *
304 * @retval On success: offset of the first byte past last erased sector;
305 * On failure: -EINVAL.
306 */
307static off_t erase_range(const struct flash_area *fap, off_t start, off_t end)
308{
309 struct flash_sector sect;
310 size_t size;
311 int rc;
312
313 if (end >= flash_area_get_size(fap)) {
314 return -EINVAL;
315 }
316
317 if (end < start) {
318 return start;
319 }
320
321 if (flash_area_sector_from_off(end, &sect)) {
322 return -EINVAL;
323 }
324
325 size = flash_sector_get_off(&sect) + flash_sector_get_size(&sect) - start;
Stephanos Ioannidis09e2bd72022-07-11 22:01:49 +0900326 BOOT_LOG_INF("Erasing range 0x%jx:0x%jx", (intmax_t)start,
327 (intmax_t)(start + size - 1));
Dominik Ermelbcc17b42022-06-15 15:33:04 +0000328
329 rc = flash_area_erase(fap, start, size);
330 if (rc != 0) {
331 BOOT_LOG_ERR("Error %d while erasing range", rc);
332 return -EINVAL;
333 }
334
335 return start + size;
336}
337#endif
338
Christopher Collins92ea77f2016-12-12 15:59:26 -0800339/*
340 * Image upload request.
341 */
342static void
343bs_upload(char *buf, int len)
344{
Dominik Ermel5bd87442022-06-13 15:14:01 +0000345 static size_t img_size; /* Total image size, held for duration of upload */
346 static uint32_t curr_off; /* Expected current offset */
347 const uint8_t *img_chunk = NULL; /* Pointer to buffer with received image chunk */
348 size_t img_chunk_len = 0; /* Length of received image chunk */
349 size_t img_chunk_off = SIZE_MAX; /* Offset of image chunk within image */
350 uint8_t rem_bytes; /* Reminder bytes after aligning chunk write to
351 * to flash alignment */
Fabio Utzig6f49c272019-08-23 11:42:58 -0300352 int img_num;
Dominik Ermel5bd87442022-06-13 15:14:01 +0000353 size_t img_size_tmp = SIZE_MAX; /* Temp variable for image size */
Christopher Collins92ea77f2016-12-12 15:59:26 -0800354 const struct flash_area *fap = NULL;
355 int rc;
Dominik Ermel3d4e55d2021-07-09 11:14:10 +0000356#ifdef MCUBOOT_ERASE_PROGRESSIVELY
Dominik Ermelbcc17b42022-06-15 15:33:04 +0000357 static off_t not_yet_erased = 0; /* Offset of next byte to erase; writes to flash
358 * are done in consecutive manner and erases are done
359 * to allow currently received chunk to be written;
360 * this state variable holds information where last
361 * erase has stopped to let us know whether erase
362 * is needed to be able to write current chunk.
363 */
364 static struct flash_sector status_sector;
Emanuele Di Santo205c8c62018-07-20 11:42:31 +0200365#endif
Christopher Collins92ea77f2016-12-12 15:59:26 -0800366
Fabio Utzig6f49c272019-08-23 11:42:58 -0300367 img_num = 0;
Marko Kiiskilace50ab02018-06-06 11:33:33 +0300368
369 /*
370 * Expected data format.
371 * {
Fabio Utzig6f49c272019-08-23 11:42:58 -0300372 * "image":<image number in a multi-image set (OPTIONAL)>
373 * "data":<image data>
Marko Kiiskilace50ab02018-06-06 11:33:33 +0300374 * "len":<image len>
375 * "off":<current offset of image data>
376 * }
377 */
378
Øyvind Rønningstad212a35b2021-05-07 21:06:48 +0200379 struct Upload upload;
Øyvind Rønningstada7d34ca2022-02-28 13:47:57 +0100380 size_t decoded_len;
381 uint_fast8_t result = cbor_decode_Upload((const uint8_t *)buf, len, &upload, &decoded_len);
Øyvind Rønningstad212a35b2021-05-07 21:06:48 +0200382
Øyvind Rønningstada7d34ca2022-02-28 13:47:57 +0100383 if ((result != ZCBOR_SUCCESS) || (len != decoded_len)) {
Øyvind Rønningstadf42a8202019-12-13 03:27:54 +0100384 goto out_invalid_data;
385 }
Dominik Ermel470e2f32020-01-10 13:28:48 +0000386
Øyvind Rønningstadf42a8202019-12-13 03:27:54 +0100387 for (int i = 0; i < upload._Upload_members_count; i++) {
Øyvind Rønningstada7d34ca2022-02-28 13:47:57 +0100388 struct Member_ *member = &upload._Upload_members[i]._Upload_members;
Øyvind Rønningstadf42a8202019-12-13 03:27:54 +0100389 switch(member->_Member_choice) {
390 case _Member_image:
391 img_num = member->_Member_image;
392 break;
393 case _Member_data:
Dominik Ermel5bd87442022-06-13 15:14:01 +0000394 img_chunk = member->_Member_data.value;
395 img_chunk_len = member->_Member_data.len;
Øyvind Rønningstadf42a8202019-12-13 03:27:54 +0100396 break;
397 case _Member_len:
Dominik Ermel5bd87442022-06-13 15:14:01 +0000398 img_size_tmp = member->_Member_len;
Øyvind Rønningstadf42a8202019-12-13 03:27:54 +0100399 break;
400 case _Member_off:
Dominik Ermel5bd87442022-06-13 15:14:01 +0000401 img_chunk_off = member->_Member_off;
Øyvind Rønningstadf42a8202019-12-13 03:27:54 +0100402 break;
403 case _Member_sha:
404 default:
405 /* Nothing to do. */
406 break;
Marko Kiiskilace50ab02018-06-06 11:33:33 +0300407 }
408 }
Øyvind Rønningstadf42a8202019-12-13 03:27:54 +0100409
Dominik Ermel5bd87442022-06-13 15:14:01 +0000410 if (img_chunk_off == SIZE_MAX || img_chunk == NULL) {
Marko Kiiskilace50ab02018-06-06 11:33:33 +0300411 /*
412 * Offset must be set in every block.
413 */
414 goto out_invalid_data;
Christopher Collins92ea77f2016-12-12 15:59:26 -0800415 }
416
Dominik Ermel48decca2021-07-09 10:23:58 +0000417#if !defined(MCUBOOT_SERIAL_DIRECT_IMAGE_UPLOAD)
Fabio Utzig6f49c272019-08-23 11:42:58 -0300418 rc = flash_area_open(flash_area_id_from_multi_image_slot(img_num, 0), &fap);
Dominik Ermel48decca2021-07-09 10:23:58 +0000419#else
420 rc = flash_area_open(flash_area_id_from_direct_image(img_num), &fap);
421#endif
Christopher Collins92ea77f2016-12-12 15:59:26 -0800422 if (rc) {
423 rc = MGMT_ERR_EINVAL;
424 goto out;
425 }
426
Dominik Ermel5bd87442022-06-13 15:14:01 +0000427 if (img_chunk_off == 0) {
Dominik Ermelbcc17b42022-06-15 15:33:04 +0000428 /* Receiving chunk with 0 offset resets the upload state; this basically
429 * means that upload has started from beginning.
430 */
431 const size_t area_size = flash_area_get_size(fap);
Dominik Ermel5bd87442022-06-13 15:14:01 +0000432
Dominik Ermelbcc17b42022-06-15 15:33:04 +0000433 curr_off = 0;
434#ifdef MCUBOOT_ERASE_PROGRESSIVELY
435 /* Get trailer sector information; this is done early because inability to get
436 * that sector information means that upload will not work anyway.
437 * TODO: This is single occurrence issue, it should get detected during tests
438 * and fixed otherwise you are deploying broken mcuboot.
439 */
440 if (flash_area_sector_from_off(boot_status_off(fap), &status_sector)) {
441 rc = MGMT_ERR_EUNKNOWN;
442 BOOT_LOG_ERR("Unable to determine flash sector of the image trailer");
443 goto out;
444 }
445#endif
446
447
Wouter Cappellebb7a39d2021-05-03 16:44:44 +0200448#if defined(MCUBOOT_VALIDATE_PRIMARY_SLOT_ONCE)
449 /* We are using swap state at end of flash area to store validation
450 * result. Make sure the user cannot write it from an image to skip validation.
451 */
Dominik Ermelbcc17b42022-06-15 15:33:04 +0000452 if (img_size_tmp > (area_size - BOOT_MAGIC_SZ)) {
Wouter Cappellebb7a39d2021-05-03 16:44:44 +0200453 goto out_invalid_data;
454 }
Dominik Ermelbcc17b42022-06-15 15:33:04 +0000455#else
456 if (img_size_tmp > area_size) {
457 goto out_invalid_data;
458 }
459
Wouter Cappellebb7a39d2021-05-03 16:44:44 +0200460#endif
Dominik Ermelbcc17b42022-06-15 15:33:04 +0000461
Dominik Ermel3d4e55d2021-07-09 11:14:10 +0000462#ifndef MCUBOOT_ERASE_PROGRESSIVELY
Dominik Ermelbcc17b42022-06-15 15:33:04 +0000463 /* Non-progressive erase erases entire image slot when first chunk of
464 * an image is received.
465 */
466 rc = flash_area_erase(fap, 0, area_size);
Christopher Collins92ea77f2016-12-12 15:59:26 -0800467 if (rc) {
Marko Kiiskilace50ab02018-06-06 11:33:33 +0300468 goto out_invalid_data;
Christopher Collins92ea77f2016-12-12 15:59:26 -0800469 }
Dominik Ermelbcc17b42022-06-15 15:33:04 +0000470#else
471 not_yet_erased = 0;
Emanuele Di Santo205c8c62018-07-20 11:42:31 +0200472#endif
Dominik Ermelbcc17b42022-06-15 15:33:04 +0000473
Dominik Ermel5bd87442022-06-13 15:14:01 +0000474 img_size = img_size_tmp;
Dominik Ermelbcc17b42022-06-15 15:33:04 +0000475 } else if (img_chunk_off != curr_off) {
476 /* If received chunk offset does not match expected one jump, pretend
477 * success and jump to out; out will respond to client with success
478 * and request the expected offset, held by curr_off.
479 */
Christopher Collins92ea77f2016-12-12 15:59:26 -0800480 rc = 0;
481 goto out;
Dominik Ermelbcc17b42022-06-15 15:33:04 +0000482 } else if (curr_off + img_chunk_len > img_size) {
Andrzej Puzdrowskif48de7a2020-10-19 09:42:02 +0200483 rc = MGMT_ERR_EINVAL;
484 goto out;
485 }
486
Dominik Ermelbcc17b42022-06-15 15:33:04 +0000487#ifdef MCUBOOT_ERASE_PROGRESSIVELY
488 /* Progressive erase will erase enough flash, aligned to sector size,
489 * as needed for the current chunk to be written.
490 */
491 not_yet_erased = erase_range(fap, not_yet_erased,
492 curr_off + img_chunk_len - 1);
493
494 if (not_yet_erased < 0) {
495 rc = MGMT_ERR_EINVAL;
496 goto out;
497 }
498#endif
499
500 /* Writes are aligned to flash write alignment, so may drop a few bytes
501 * from the end of the buffer; we will request these bytes again with
502 * new buffer by responding with request for offset after the last aligned
503 * write.
504 */
Dominik Ermel5bd87442022-06-13 15:14:01 +0000505 rem_bytes = img_chunk_len % flash_area_align(fap);
Dominik Ermel7d2f0bf2022-06-21 16:15:34 +0000506 img_chunk_len -= rem_bytes;
Andrzej Puzdrowskif48de7a2020-10-19 09:42:02 +0200507
Dominik Ermel7d2f0bf2022-06-21 16:15:34 +0000508 if (curr_off + img_chunk_len + rem_bytes < img_size) {
Andrzej Puzdrowskif48de7a2020-10-19 09:42:02 +0200509 rem_bytes = 0;
Fabio Utzig30f6b2a2018-03-29 16:18:53 -0300510 }
Emanuele Di Santo205c8c62018-07-20 11:42:31 +0200511
Dominik Ermel5bd87442022-06-13 15:14:01 +0000512 BOOT_LOG_INF("Writing at 0x%x until 0x%x", curr_off, curr_off + img_chunk_len);
Dominik Ermel7d2f0bf2022-06-21 16:15:34 +0000513 /* Write flash aligned chunk, note that img_chunk_len now holds aligned length */
Jamie McCrae9d3fd7f2022-11-30 15:44:44 +0000514#if defined(MCUBOOT_SERIAL_UNALIGNED_BUFFER_SIZE) && MCUBOOT_SERIAL_UNALIGNED_BUFFER_SIZE > 0
515 if (flash_area_align(fap) > 1 &&
516 (((size_t)img_chunk) & (flash_area_align(fap) - 1)) != 0) {
517 /* Buffer address incompatible with write address, use buffer to write */
518 uint8_t write_size = MCUBOOT_SERIAL_UNALIGNED_BUFFER_SIZE;
519 uint8_t wbs_aligned[MCUBOOT_SERIAL_UNALIGNED_BUFFER_SIZE];
520
521 while (img_chunk_len >= flash_area_align(fap)) {
522 if (write_size > img_chunk_len) {
523 write_size = img_chunk_len;
524 }
525
526 memset(wbs_aligned, flash_area_erased_val(fap), sizeof(wbs_aligned));
527 memcpy(wbs_aligned, img_chunk, write_size);
528
529 rc = flash_area_write(fap, curr_off, wbs_aligned, write_size);
530
531 if (rc != 0) {
532 goto out;
533 }
534
535 curr_off += write_size;
536 img_chunk += write_size;
537 img_chunk_len -= write_size;
538 }
539 } else {
540 rc = flash_area_write(fap, curr_off, img_chunk, img_chunk_len);
541 }
542#else
Dominik Ermel7d2f0bf2022-06-21 16:15:34 +0000543 rc = flash_area_write(fap, curr_off, img_chunk, img_chunk_len);
Jamie McCrae9d3fd7f2022-11-30 15:44:44 +0000544#endif
545
Dominik Ermel7d2f0bf2022-06-21 16:15:34 +0000546 if (rc == 0 && rem_bytes) {
547 /* Non-zero rem_bytes means that last chunk needs alignment; the aligned
548 * part, in the img_chunk_len - rem_bytes count bytes, has already been
549 * written by the above write, so we are left with the rem_bytes.
550 */
Andrzej Puzdrowskif48de7a2020-10-19 09:42:02 +0200551 uint8_t wbs_aligned[BOOT_MAX_ALIGN];
Andrzej Puzdrowskif48de7a2020-10-19 09:42:02 +0200552
Dominik Ermel7d2f0bf2022-06-21 16:15:34 +0000553 memset(wbs_aligned, flash_area_erased_val(fap), sizeof(wbs_aligned));
554 memcpy(wbs_aligned, img_chunk + img_chunk_len, rem_bytes);
Andrzej Puzdrowskif48de7a2020-10-19 09:42:02 +0200555
Dominik Ermel7d2f0bf2022-06-21 16:15:34 +0000556 rc = flash_area_write(fap, curr_off + img_chunk_len, wbs_aligned,
557 flash_area_align(fap));
Andrzej Puzdrowskif48de7a2020-10-19 09:42:02 +0200558 }
559
Marko Kiiskilace50ab02018-06-06 11:33:33 +0300560 if (rc == 0) {
Dominik Ermel7d2f0bf2022-06-21 16:15:34 +0000561 curr_off += img_chunk_len + rem_bytes;
Andrzej Puzdrowskic2e30cf2018-07-20 16:19:09 +0200562 if (curr_off == img_size) {
Andrzej Puzdrowski4f9c7302021-07-16 17:34:43 +0200563#ifdef MCUBOOT_ERASE_PROGRESSIVELY
Andrzej Puzdrowskic2e30cf2018-07-20 16:19:09 +0200564 /* Assure that sector for image trailer was erased. */
565 /* Check whether it was erased during previous upload. */
Dominik Ermelbcc17b42022-06-15 15:33:04 +0000566 off_t start = flash_sector_get_off(&status_sector);
567
568 if (erase_range(fap, start, start) < 0) {
569 rc = MGMT_ERR_EUNKNOWN;
570 goto out;
Andrzej Puzdrowskic2e30cf2018-07-20 16:19:09 +0200571 }
Andrzej Puzdrowskic2e30cf2018-07-20 16:19:09 +0200572#endif
Andrzej Puzdrowski4f9c7302021-07-16 17:34:43 +0200573 rc = BOOT_HOOK_CALL(boot_serial_uploaded_hook, 0, img_num, fap,
574 img_size);
575 if (rc) {
576 BOOT_LOG_ERR("Error %d post upload hook", rc);
577 goto out;
578 }
579 }
Marko Kiiskilace50ab02018-06-06 11:33:33 +0300580 } else {
581 out_invalid_data:
Christopher Collins92ea77f2016-12-12 15:59:26 -0800582 rc = MGMT_ERR_EINVAL;
Christopher Collins92ea77f2016-12-12 15:59:26 -0800583 }
Emanuele Di Santo205c8c62018-07-20 11:42:31 +0200584
Christopher Collins92ea77f2016-12-12 15:59:26 -0800585out:
Andrzej Puzdrowski8e96b832017-09-08 16:49:14 +0200586 BOOT_LOG_INF("RX: 0x%x", rc);
Øyvind Rønningstada7d34ca2022-02-28 13:47:57 +0100587 zcbor_map_start_encode(cbor_state, 10);
588 zcbor_tstr_put_lit_cast(cbor_state, "rc");
Jamie McCrae0b6d3432022-12-02 09:24:10 +0000589 zcbor_int32_put(cbor_state, rc);
Christopher Collins92ea77f2016-12-12 15:59:26 -0800590 if (rc == 0) {
Øyvind Rønningstada7d34ca2022-02-28 13:47:57 +0100591 zcbor_tstr_put_lit_cast(cbor_state, "off");
592 zcbor_uint32_put(cbor_state, curr_off);
Christopher Collins92ea77f2016-12-12 15:59:26 -0800593 }
Øyvind Rønningstada7d34ca2022-02-28 13:47:57 +0100594 zcbor_map_end_encode(cbor_state, 10);
Christopher Collins92ea77f2016-12-12 15:59:26 -0800595
596 boot_serial_output();
597 flash_area_close(fap);
Wouter Cappelle953a7612021-05-03 16:53:05 +0200598
599#ifdef MCUBOOT_ENC_IMAGES
600 if (curr_off == img_size) {
601 /* Last sector received, now start a decryption on the image if it is encrypted*/
602 rc = boot_handle_enc_fw();
603 }
604#endif //#ifdef MCUBOOT_ENC_IMAGES
Christopher Collins92ea77f2016-12-12 15:59:26 -0800605}
606
Dominik Ermel4c0f6c12022-03-04 15:47:37 +0000607/*
608 * Send rc code only.
609 */
610static void
611bs_rc_rsp(int rc_code)
612{
Øyvind Rønningstada7d34ca2022-02-28 13:47:57 +0100613 zcbor_map_start_encode(cbor_state, 10);
614 zcbor_tstr_put_lit_cast(cbor_state, "rc");
Jamie McCrae0b6d3432022-12-02 09:24:10 +0000615 zcbor_int32_put(cbor_state, rc_code);
Øyvind Rønningstada7d34ca2022-02-28 13:47:57 +0100616 zcbor_map_end_encode(cbor_state, 10);
Dominik Ermel4c0f6c12022-03-04 15:47:37 +0000617 boot_serial_output();
618}
619
620
Wouter Cappellee3ff1752021-05-03 16:36:22 +0200621#ifdef MCUBOOT_BOOT_MGMT_ECHO
Wouter Cappellee3ff1752021-05-03 16:36:22 +0200622static void
623bs_echo(char *buf, int len)
624{
Dominik Ermel88bd5672022-06-07 15:17:06 +0000625 struct Echo echo = { 0 };
626 size_t decoded_len;
627 uint32_t rc = MGMT_ERR_EINVAL;
628 uint_fast8_t result = cbor_decode_Echo((const uint8_t *)buf, len, &echo, &decoded_len);
Wouter Cappellee3ff1752021-05-03 16:36:22 +0200629
Dominik Ermel88bd5672022-06-07 15:17:06 +0000630 if ((result != ZCBOR_SUCCESS) || (len != decoded_len)) {
631 goto out;
Wouter Cappellee3ff1752021-05-03 16:36:22 +0200632 }
Dominik Ermel88bd5672022-06-07 15:17:06 +0000633
634 if (echo._Echo_d.value == NULL) {
635 goto out;
636 }
637
638 zcbor_map_start_encode(cbor_state, 10);
639 zcbor_tstr_put_term(cbor_state, "r");
640 if (zcbor_tstr_encode(cbor_state, &echo._Echo_d) && zcbor_map_end_encode(cbor_state, 10)) {
641 boot_serial_output();
642 return;
643 } else {
644 rc = MGMT_ERR_ENOMEM;
645 }
646
647out:
648 reset_cbor_state();
649 bs_rc_rsp(rc);
Wouter Cappellee3ff1752021-05-03 16:36:22 +0200650}
651#endif
652
Christopher Collins92ea77f2016-12-12 15:59:26 -0800653/*
Christopher Collins92ea77f2016-12-12 15:59:26 -0800654 * Reset, and (presumably) boot to newly uploaded image. Flush console
655 * before restarting.
656 */
Andrzej Puzdrowski268cdd02018-04-10 12:57:54 +0200657static void
Christopher Collins92ea77f2016-12-12 15:59:26 -0800658bs_reset(char *buf, int len)
659{
Dominik Ermelc9dc2242021-07-28 17:08:23 +0000660 bs_rc_rsp(0);
Christopher Collins92ea77f2016-12-12 15:59:26 -0800661
Andrzej Puzdrowski8e96b832017-09-08 16:49:14 +0200662#ifdef __ZEPHYR__
Andrzej Puzdrowski0cf0dbd2021-05-14 11:55:57 +0200663#ifdef CONFIG_MULTITHREADING
Carles Cufi7e7b4ad2020-03-30 19:12:02 +0200664 k_sleep(K_MSEC(250));
Andrzej Puzdrowski0cf0dbd2021-05-14 11:55:57 +0200665#else
666 k_busy_wait(250000);
667#endif
Andrzej Puzdrowski8e96b832017-09-08 16:49:14 +0200668 sys_reboot(SYS_REBOOT_COLD);
Almir Okatoe8cbc0d2022-06-13 10:45:39 -0300669#elif __ESPRESSIF__
670 esp_rom_delay_us(250000);
671 bootloader_reset();
Andrzej Puzdrowski8e96b832017-09-08 16:49:14 +0200672#else
Christopher Collins92ea77f2016-12-12 15:59:26 -0800673 os_cputime_delay_usecs(250000);
674 hal_system_reset();
Andrzej Puzdrowski8e96b832017-09-08 16:49:14 +0200675#endif
Christopher Collins92ea77f2016-12-12 15:59:26 -0800676}
677
678/*
679 * Parse incoming line of input from console.
680 * Expect newtmgr protocol with serial transport.
681 */
682void
683boot_serial_input(char *buf, int len)
684{
685 struct nmgr_hdr *hdr;
686
687 hdr = (struct nmgr_hdr *)buf;
688 if (len < sizeof(*hdr) ||
689 (hdr->nh_op != NMGR_OP_READ && hdr->nh_op != NMGR_OP_WRITE) ||
690 (ntohs(hdr->nh_len) < len - sizeof(*hdr))) {
691 return;
692 }
693 bs_hdr = hdr;
694 hdr->nh_group = ntohs(hdr->nh_group);
695
696 buf += sizeof(*hdr);
697 len -= sizeof(*hdr);
Marko Kiiskilace50ab02018-06-06 11:33:33 +0300698
Dominik Ermel4c0f6c12022-03-04 15:47:37 +0000699 reset_cbor_state();
Christopher Collins92ea77f2016-12-12 15:59:26 -0800700
701 /*
702 * Limited support for commands.
703 */
704 if (hdr->nh_group == MGMT_GROUP_ID_IMAGE) {
705 switch (hdr->nh_id) {
Marko Kiiskilace50ab02018-06-06 11:33:33 +0300706 case IMGMGR_NMGR_ID_STATE:
Christopher Collins92ea77f2016-12-12 15:59:26 -0800707 bs_list(buf, len);
708 break;
Marko Kiiskilace50ab02018-06-06 11:33:33 +0300709 case IMGMGR_NMGR_ID_UPLOAD:
Christopher Collins92ea77f2016-12-12 15:59:26 -0800710 bs_upload(buf, len);
711 break;
712 default:
Dominik Ermelc9dc2242021-07-28 17:08:23 +0000713 bs_rc_rsp(MGMT_ERR_ENOTSUP);
Christopher Collins92ea77f2016-12-12 15:59:26 -0800714 break;
715 }
716 } else if (hdr->nh_group == MGMT_GROUP_ID_DEFAULT) {
717 switch (hdr->nh_id) {
Wouter Cappellee3ff1752021-05-03 16:36:22 +0200718 case NMGR_ID_ECHO:
719#ifdef MCUBOOT_BOOT_MGMT_ECHO
720 bs_echo(buf, len);
721#endif
722 break;
Christopher Collins92ea77f2016-12-12 15:59:26 -0800723 case NMGR_ID_CONS_ECHO_CTRL:
Dominik Ermelc9dc2242021-07-28 17:08:23 +0000724 bs_rc_rsp(0);
Christopher Collins92ea77f2016-12-12 15:59:26 -0800725 break;
726 case NMGR_ID_RESET:
727 bs_reset(buf, len);
728 break;
729 default:
Dominik Ermelc9dc2242021-07-28 17:08:23 +0000730 bs_rc_rsp(MGMT_ERR_ENOTSUP);
Christopher Collins92ea77f2016-12-12 15:59:26 -0800731 break;
732 }
Dominik Ermelbd69c3d2021-07-28 11:27:31 +0000733 } else if (MCUBOOT_PERUSER_MGMT_GROUP_ENABLED == 1) {
Øyvind Rønningstada7d34ca2022-02-28 13:47:57 +0100734 if (bs_peruser_system_specific(hdr, buf, len, cbor_state) == 0) {
Dominik Ermel3d51e432021-06-25 17:29:50 +0000735 boot_serial_output();
736 }
Dominik Ermelc9dc2242021-07-28 17:08:23 +0000737 } else {
738 bs_rc_rsp(MGMT_ERR_ENOTSUP);
Christopher Collins92ea77f2016-12-12 15:59:26 -0800739 }
Wouter Cappellee3822f82022-01-19 15:39:43 +0100740#ifdef MCUBOOT_SERIAL_WAIT_FOR_DFU
741 bs_entry = true;
742#endif
Christopher Collins92ea77f2016-12-12 15:59:26 -0800743}
744
745static void
746boot_serial_output(void)
747{
748 char *data;
749 int len;
750 uint16_t crc;
751 uint16_t totlen;
752 char pkt_start[2] = { SHELL_NLIP_PKT_START1, SHELL_NLIP_PKT_START2 };
Dominik Ermel5ff89582022-03-03 17:09:07 +0000753 char buf[BOOT_SERIAL_OUT_MAX + sizeof(*bs_hdr) + sizeof(crc) + sizeof(totlen)];
754 char encoded_buf[BASE64_ENCODE_SIZE(sizeof(buf))];
Christopher Collins92ea77f2016-12-12 15:59:26 -0800755
756 data = bs_obuf;
Øyvind Rønningstada7d34ca2022-02-28 13:47:57 +0100757 len = (uint32_t)cbor_state->payload_mut - (uint32_t)bs_obuf;
Christopher Collins92ea77f2016-12-12 15:59:26 -0800758
759 bs_hdr->nh_op++;
Marko Kiiskilace50ab02018-06-06 11:33:33 +0300760 bs_hdr->nh_flags = 0;
Christopher Collins92ea77f2016-12-12 15:59:26 -0800761 bs_hdr->nh_len = htons(len);
762 bs_hdr->nh_group = htons(bs_hdr->nh_group);
763
Andrzej Puzdrowski8e96b832017-09-08 16:49:14 +0200764#ifdef __ZEPHYR__
Carles Cufib9192a42022-02-10 11:41:57 +0100765 crc = crc16_itu_t(CRC16_INITIAL_CRC, (uint8_t *)bs_hdr, sizeof(*bs_hdr));
766 crc = crc16_itu_t(crc, data, len);
Almir Okatoe8cbc0d2022-06-13 10:45:39 -0300767#elif __ESPRESSIF__
768 /* For ESP32 it was used the CRC API in rom/crc.h */
Almir Okato7d3622f2022-10-20 12:44:58 -0300769 crc = ~esp_crc16_be(~CRC16_INITIAL_CRC, (uint8_t *)bs_hdr, sizeof(*bs_hdr));
770 crc = ~esp_crc16_be(~crc, (uint8_t *)data, len);
Andrzej Puzdrowski8e96b832017-09-08 16:49:14 +0200771#else
Christopher Collins92ea77f2016-12-12 15:59:26 -0800772 crc = crc16_ccitt(CRC16_INITIAL_CRC, bs_hdr, sizeof(*bs_hdr));
773 crc = crc16_ccitt(crc, data, len);
Andrzej Puzdrowski8e96b832017-09-08 16:49:14 +0200774#endif
Christopher Collins92ea77f2016-12-12 15:59:26 -0800775 crc = htons(crc);
776
Marko Kiiskila149b4572018-06-06 14:18:54 +0300777 boot_uf->write(pkt_start, sizeof(pkt_start));
Christopher Collins92ea77f2016-12-12 15:59:26 -0800778
779 totlen = len + sizeof(*bs_hdr) + sizeof(crc);
780 totlen = htons(totlen);
781
782 memcpy(buf, &totlen, sizeof(totlen));
783 totlen = sizeof(totlen);
784 memcpy(&buf[totlen], bs_hdr, sizeof(*bs_hdr));
785 totlen += sizeof(*bs_hdr);
786 memcpy(&buf[totlen], data, len);
787 totlen += len;
788 memcpy(&buf[totlen], &crc, sizeof(crc));
789 totlen += sizeof(crc);
Andrzej Puzdrowski8e96b832017-09-08 16:49:14 +0200790#ifdef __ZEPHYR__
791 size_t enc_len;
Carles Cufi0165be82018-03-26 17:43:51 +0200792 base64_encode(encoded_buf, sizeof(encoded_buf), &enc_len, buf, totlen);
Andrzej Puzdrowski8e96b832017-09-08 16:49:14 +0200793 totlen = enc_len;
Almir Okatoe8cbc0d2022-06-13 10:45:39 -0300794#elif __ESPRESSIF__
795 size_t enc_len;
796 base64_encode((unsigned char *)encoded_buf, sizeof(encoded_buf), &enc_len, (unsigned char *)buf, totlen);
797 totlen = enc_len;
Andrzej Puzdrowski8e96b832017-09-08 16:49:14 +0200798#else
Christopher Collins92ea77f2016-12-12 15:59:26 -0800799 totlen = base64_encode(buf, totlen, encoded_buf, 1);
Andrzej Puzdrowski8e96b832017-09-08 16:49:14 +0200800#endif
Marko Kiiskila149b4572018-06-06 14:18:54 +0300801 boot_uf->write(encoded_buf, totlen);
Dominik Ermel2f2b31c2022-03-03 12:39:27 +0000802 boot_uf->write("\n", 1);
Andrzej Puzdrowski8e96b832017-09-08 16:49:14 +0200803 BOOT_LOG_INF("TX");
Christopher Collins92ea77f2016-12-12 15:59:26 -0800804}
805
806/*
807 * Returns 1 if full packet has been received.
808 */
809static int
810boot_serial_in_dec(char *in, int inlen, char *out, int *out_off, int maxout)
811{
812 int rc;
813 uint16_t crc;
814 uint16_t len;
Marko Kiiskilae5aeee42018-12-21 15:00:16 +0200815
Andrzej Puzdrowski8e96b832017-09-08 16:49:14 +0200816#ifdef __ZEPHYR__
817 int err;
Andrzej Puzdrowskiec1e4d12018-06-18 14:36:14 +0200818 err = base64_decode( &out[*out_off], maxout - *out_off, &rc, in, inlen - 2);
Andrzej Puzdrowski8e96b832017-09-08 16:49:14 +0200819 if (err) {
820 return -1;
821 }
Almir Okatoe8cbc0d2022-06-13 10:45:39 -0300822#elif __ESPRESSIF__
823 int err;
824 err = base64_decode((unsigned char *)&out[*out_off], maxout - *out_off, (size_t *)&rc, (unsigned char *)in, inlen);
825 if (err) {
826 return -1;
827 }
Andrzej Puzdrowski8e96b832017-09-08 16:49:14 +0200828#else
Christopher Collins92ea77f2016-12-12 15:59:26 -0800829 if (*out_off + base64_decode_len(in) >= maxout) {
830 return -1;
831 }
832 rc = base64_decode(in, &out[*out_off]);
833 if (rc < 0) {
834 return -1;
835 }
Andrzej Puzdrowski8e96b832017-09-08 16:49:14 +0200836#endif
Fabio Utzig6f49c272019-08-23 11:42:58 -0300837
Christopher Collins92ea77f2016-12-12 15:59:26 -0800838 *out_off += rc;
Fabio Utzig6f49c272019-08-23 11:42:58 -0300839 if (*out_off <= sizeof(uint16_t)) {
840 return 0;
Christopher Collins92ea77f2016-12-12 15:59:26 -0800841 }
Fabio Utzig6f49c272019-08-23 11:42:58 -0300842
843 len = ntohs(*(uint16_t *)out);
844 if (len != *out_off - sizeof(uint16_t)) {
845 return 0;
846 }
847
848 if (len > *out_off - sizeof(uint16_t)) {
849 len = *out_off - sizeof(uint16_t);
850 }
851
852 out += sizeof(uint16_t);
853#ifdef __ZEPHYR__
Carles Cufib9192a42022-02-10 11:41:57 +0100854 crc = crc16_itu_t(CRC16_INITIAL_CRC, out, len);
Almir Okatoe8cbc0d2022-06-13 10:45:39 -0300855#elif __ESPRESSIF__
Almir Okato7d3622f2022-10-20 12:44:58 -0300856 crc = ~esp_crc16_be(~CRC16_INITIAL_CRC, (uint8_t *)out, len);
Fabio Utzig6f49c272019-08-23 11:42:58 -0300857#else
858 crc = crc16_ccitt(CRC16_INITIAL_CRC, out, len);
859#endif
860 if (crc || len <= sizeof(crc)) {
861 return 0;
862 }
863 *out_off -= sizeof(crc);
864 out[*out_off] = '\0';
865
866 return 1;
Christopher Collins92ea77f2016-12-12 15:59:26 -0800867}
868
869/*
870 * Task which waits reading console, expecting to get image over
871 * serial port.
872 */
Wouter Cappellee3822f82022-01-19 15:39:43 +0100873static void
874boot_serial_read_console(const struct boot_uart_funcs *f,int timeout_in_ms)
Christopher Collins92ea77f2016-12-12 15:59:26 -0800875{
876 int rc;
877 int off;
David Brown57f0df32020-05-12 08:39:21 -0600878 int dec_off = 0;
Christopher Collins92ea77f2016-12-12 15:59:26 -0800879 int full_line;
Marko Kiiskila149b4572018-06-06 14:18:54 +0300880 int max_input;
Wouter Cappellee3822f82022-01-19 15:39:43 +0100881 int elapsed_in_ms = 0;
Christopher Collins92ea77f2016-12-12 15:59:26 -0800882
Marko Kiiskila149b4572018-06-06 14:18:54 +0300883 boot_uf = f;
Marko Kiiskila149b4572018-06-06 14:18:54 +0300884 max_input = sizeof(in_buf);
Christopher Collins92ea77f2016-12-12 15:59:26 -0800885
886 off = 0;
Wouter Cappellee3822f82022-01-19 15:39:43 +0100887 while (timeout_in_ms > 0 || bs_entry) {
Piotr Dymacz067f30a2022-08-12 18:25:34 +0200888 /*
889 * Don't enter CPU idle state here if timeout based serial recovery is
890 * used as otherwise the boot process hangs forever, waiting for input
891 * from serial console (if single-thread mode is used).
892 */
Piotr Dymacz3942e9b2022-07-18 10:19:25 +0200893#ifndef MCUBOOT_SERIAL_WAIT_FOR_DFU
Andrzej Puzdrowskiaea38eb2021-06-11 12:28:59 +0200894 MCUBOOT_CPU_IDLE();
Piotr Dymacz3942e9b2022-07-18 10:19:25 +0200895#endif
Hein Wessels56d28f02021-11-19 08:42:08 +0100896 MCUBOOT_WATCHDOG_FEED();
Wouter Cappellee3822f82022-01-19 15:39:43 +0100897#ifdef MCUBOOT_SERIAL_WAIT_FOR_DFU
898 uint32_t start = k_uptime_get_32();
899#endif
Andrzej Puzdrowskiec1e4d12018-06-18 14:36:14 +0200900 rc = f->read(in_buf + off, sizeof(in_buf) - off, &full_line);
Christopher Collins92ea77f2016-12-12 15:59:26 -0800901 if (rc <= 0 && !full_line) {
Wouter Cappellee3822f82022-01-19 15:39:43 +0100902 goto check_timeout;
Christopher Collins92ea77f2016-12-12 15:59:26 -0800903 }
904 off += rc;
905 if (!full_line) {
Marko Kiiskilace50ab02018-06-06 11:33:33 +0300906 if (off == max_input) {
907 /*
908 * Full line, no newline yet. Reset the input buffer.
909 */
910 off = 0;
911 }
Wouter Cappellee3822f82022-01-19 15:39:43 +0100912 goto check_timeout;
Christopher Collins92ea77f2016-12-12 15:59:26 -0800913 }
Andrzej Puzdrowskiec1e4d12018-06-18 14:36:14 +0200914 if (in_buf[0] == SHELL_NLIP_PKT_START1 &&
915 in_buf[1] == SHELL_NLIP_PKT_START2) {
Christopher Collins92ea77f2016-12-12 15:59:26 -0800916 dec_off = 0;
Andrzej Puzdrowskiec1e4d12018-06-18 14:36:14 +0200917 rc = boot_serial_in_dec(&in_buf[2], off - 2, dec_buf, &dec_off, max_input);
918 } else if (in_buf[0] == SHELL_NLIP_DATA_START1 &&
919 in_buf[1] == SHELL_NLIP_DATA_START2) {
920 rc = boot_serial_in_dec(&in_buf[2], off - 2, dec_buf, &dec_off, max_input);
Christopher Collins92ea77f2016-12-12 15:59:26 -0800921 }
Andrzej Puzdrowskiec1e4d12018-06-18 14:36:14 +0200922
923 /* serve errors: out of decode memory, or bad encoding */
Christopher Collins92ea77f2016-12-12 15:59:26 -0800924 if (rc == 1) {
Andrzej Puzdrowskiec1e4d12018-06-18 14:36:14 +0200925 boot_serial_input(&dec_buf[2], dec_off - 2);
Christopher Collins92ea77f2016-12-12 15:59:26 -0800926 }
927 off = 0;
Wouter Cappellee3822f82022-01-19 15:39:43 +0100928check_timeout:
929 /* Subtract elapsed time */
930#ifdef MCUBOOT_SERIAL_WAIT_FOR_DFU
931 elapsed_in_ms = (k_uptime_get_32() - start);
932#endif
933 timeout_in_ms -= elapsed_in_ms;
Christopher Collins92ea77f2016-12-12 15:59:26 -0800934 }
935}
Wouter Cappellee3822f82022-01-19 15:39:43 +0100936
937/*
938 * Task which waits reading console, expecting to get image over
939 * serial port.
940 */
941void
942boot_serial_start(const struct boot_uart_funcs *f)
943{
944 bs_entry = true;
945 boot_serial_read_console(f,0);
946}
947
948#ifdef MCUBOOT_SERIAL_WAIT_FOR_DFU
949/*
950 * Task which waits reading console for a certain amount of timeout.
951 * If within this timeout no mcumgr command is received, the function is
952 * returning, else the serial boot is never exited
953 */
954void
955boot_serial_check_start(const struct boot_uart_funcs *f, int timeout_in_ms)
956{
957 bs_entry = false;
958 boot_serial_read_console(f,timeout_in_ms);
959}
960#endif