diff --git a/src/image.c b/src/image.c index 35c347d..66ebb58 100644 --- a/src/image.c +++ b/src/image.c @@ -15,9 +15,10 @@ #include "image.h" #include "nmgr.h" #include "cbor.h" +#include "sha256.h" #define IMAGE_CHUNK_SIZE 124 -#define MACRO_CHUNK_SIZE 340 +#define MACRO_CHUNK_SIZE 512 #define CRC16_INITIAL_CRC 0 /* what to seed crc16 with */ #define CRC_CITT_POLYMINAL 0x1021 @@ -172,27 +173,37 @@ static void do_version(void) { } static void wrap_and_send_pkt(uint8_t *data, size_t len) { - fprintf(stderr, "Trying to wrap %d bytes", len); + static uint8_t seq = 66; uint8_t b64_buf[BOOT_SERIAL_OUT_MAX*2]; - struct nmgr_hdr hdr; + uint16_t tot_len = len + sizeof(struct nmgr_hdr) + 2; // 2 is crc + struct nmgr_hdr hdr = {0}; hdr.nh_op = NMGR_OP_WRITE; hdr.nh_group = htons(MGMT_GROUP_ID_IMAGE); hdr.nh_id = IMGMGR_NMGR_ID_UPLOAD; - hdr.nh_seq = 66; + hdr.nh_seq = seq++; + hdr.nh_len = htons(573); uint16_t crc = crc16((uint8_t*)&hdr, sizeof(struct nmgr_hdr), CRC_CITT_POLYMINAL, CRC16_INITIAL_CRC, false); crc = crc16(data, len, CRC_CITT_POLYMINAL, crc, true); crc = htons(crc); - - uint16_t tot_len = len + sizeof(struct nmgr_hdr) + sizeof(crc); + uint16_t net_len = htons(tot_len); uint8_t *pos = b64_buf; - memcpy(b64_buf, &net_len, sizeof(tot_len)); - pos += sizeof(tot_len); + memcpy(pos, &net_len, sizeof(tot_len)); + pos += sizeof(net_len); + + memcpy(pos, &hdr, sizeof(struct nmgr_hdr)); + pos += sizeof(struct nmgr_hdr); memcpy(pos, data, len); pos += len; memcpy(pos, &crc, sizeof(crc)); + printlen(b64_buf + 2, tot_len); + fflush(stdout); + + // Check CRC + uint16_t crc2 = crc16(b64_buf+2, tot_len, CRC_CITT_POLYMINAL, CRC16_INITIAL_CRC, true); + assert(!crc2); size_t out_len; uint8_t *out_buf = base64_encode(b64_buf, tot_len, &out_len); @@ -233,10 +244,9 @@ void do_upload(char *filename){ CborEncoder root, map; uint8_t cbor_buf[BOOT_SERIAL_OUT_MAX*2]; cbor_encoder_init(&root, cbor_buf, BOOT_SERIAL_OUT_MAX*2, 0); - cbor_encoder_create_map(&root, &map, pos == 0 ? 3 : 2); + cbor_encoder_create_map(&root, &map, pos == 0 ? 4 : 3); cbor_encode_text_stringz(&map, "data"); - uint8_t data[MACRO_CHUNK_SIZE]; int actual_size; if ((actual_size = read(fd, data, MACRO_CHUNK_SIZE)) < MACRO_CHUNK_SIZE) { @@ -255,8 +265,16 @@ void do_upload(char *filename){ cbor_encode_text_stringz(&map, "off"); cbor_encode_uint(&map, pos); + cbor_encode_text_stringz(&map, "sha"); + SHA256_CTX sha_ctx; + sha256_init(&sha_ctx); + sha256_update(&sha_ctx, data, actual_size); + uint8_t sha[32]; + sha256_final(&sha_ctx, (BYTE *)&sha); + cbor_encode_byte_string(&map, sha, 32); + cbor_encoder_close_container(&root, &map); - wrap_and_send_pkt(data, cbor_encoder_get_buffer_size(&root, cbor_buf)); + wrap_and_send_pkt(cbor_buf, cbor_encoder_get_buffer_size(&root, cbor_buf)); uint8_t resp_buf[BOOT_SERIAL_IN_MAX]; size_t in_len;