|
12 | 12 |
|
13 | 13 | #include "fmt.h" |
14 | 14 | #include "net/nanocoap.h" |
| 15 | +#include "hashes/sha256.h" |
15 | 16 |
|
16 | 17 | /* internal value that can be read/written via CoAP */ |
17 | 18 | static uint8_t internal_value = 0; |
@@ -55,9 +56,58 @@ static ssize_t _riot_value_handler(coap_pkt_t *pkt, uint8_t *buf, size_t len, vo |
55 | 56 | COAP_FORMAT_TEXT, (uint8_t*)rsp, p); |
56 | 57 | } |
57 | 58 |
|
| 59 | +ssize_t _sha256_handler(coap_pkt_t* pkt, uint8_t *buf, size_t len, void *context) |
| 60 | +{ |
| 61 | + (void)context; |
| 62 | + |
| 63 | + /* using a shared sha256 context *will* break if two requests are handled |
| 64 | + * at the same time. doing it anyways, as this is meant to showcase block1 |
| 65 | + * support, not proper synchronisation. */ |
| 66 | + static sha256_context_t sha256; |
| 67 | + |
| 68 | + uint8_t digest[SHA256_DIGEST_LENGTH]; |
| 69 | + |
| 70 | + uint32_t result = COAP_CODE_204; |
| 71 | + |
| 72 | + coap_block1_t block1; |
| 73 | + int blockwise = coap_get_block1(pkt, &block1); |
| 74 | + |
| 75 | + printf("_sha256_handler(): received data: offset=%u len=%u blockwise=%i more=%i\n", \ |
| 76 | + (unsigned)block1.offset, pkt->payload_len, blockwise, block1.more); |
| 77 | + |
| 78 | + if (block1.offset == 0) { |
| 79 | + puts("_sha256_handler(): init"); |
| 80 | + sha256_init(&sha256); |
| 81 | + } |
| 82 | + |
| 83 | + sha256_update(&sha256, pkt->payload, pkt->payload_len); |
| 84 | + |
| 85 | + if (block1.more == 1) { |
| 86 | + result = COAP_CODE_231; |
| 87 | + } |
| 88 | + |
| 89 | + size_t result_len = 0; |
| 90 | + if (!blockwise || !block1.more) { |
| 91 | + puts("_sha256_handler(): finish"); |
| 92 | + sha256_final(&sha256, digest); |
| 93 | + result_len = SHA256_DIGEST_LENGTH * 2; |
| 94 | + } |
| 95 | + |
| 96 | + ssize_t reply_len = coap_build_reply(pkt, result, buf, len, 0); |
| 97 | + uint8_t *pkt_pos = (uint8_t*)pkt->hdr + reply_len; |
| 98 | + pkt_pos += coap_put_block1_ok(pkt_pos, &block1, 0); |
| 99 | + if (result_len) { |
| 100 | + *pkt_pos++ = 0xFF; |
| 101 | + pkt_pos += fmt_bytes_hex((char *)pkt_pos, digest, sizeof(digest)); |
| 102 | + } |
| 103 | + |
| 104 | + return pkt_pos - (uint8_t*)pkt->hdr; |
| 105 | +} |
| 106 | + |
58 | 107 | /* must be sorted by path (alphabetically) */ |
59 | 108 | const coap_resource_t coap_resources[] = { |
60 | 109 | COAP_WELL_KNOWN_CORE_DEFAULT_HANDLER, |
| 110 | + { "/sha256", COAP_POST | COAP_PUT, _sha256_handler, NULL }, |
61 | 111 | { "/riot/board", COAP_GET, _riot_board_handler, NULL }, |
62 | 112 | { "/riot/value", COAP_GET | COAP_PUT | COAP_POST, _riot_value_handler, NULL }, |
63 | 113 | }; |
|
0 commit comments