static bool _set_token_and_mid(struct sol_coap_packet *pkt, int64_t *token) { static struct sol_random *random = NULL; int32_t mid; if (SOL_UNLIKELY(!random)) { random = sol_random_new(SOL_RANDOM_DEFAULT, 0); SOL_NULL_CHECK(random, false); } if (!sol_random_get_int64(random, token)) { SOL_WRN("Could not generate CoAP token"); return false; } if (!sol_random_get_int32(random, &mid)) { SOL_WRN("Could not generate CoAP message id"); return false; } if (!sol_coap_header_set_token(pkt, (uint8_t *)token, (uint8_t)sizeof(*token))) { SOL_WRN("Could not set CoAP packet token"); return false; } sol_coap_header_set_id(pkt, (int16_t)mid); return true; }
static void test_coap_token_simple(void) { uint8_t token[] = { 't', 'o', 'k', 'e', 'n' }; uint8_t token_length; uint8_t *token_ptr; struct sol_coap_packet *pkt; pkt = sol_coap_packet_new(NULL); ASSERT(pkt); ASSERT(!sol_coap_header_set_token(pkt, token, sizeof(token))); token_ptr = sol_coap_header_get_token(pkt, &token_length); ASSERT(token_ptr); ASSERT_INT_EQ(token_length, sizeof(token)); ASSERT(streqn((char *)token_ptr, (char *)token, sizeof(token))); ASSERT(!coap_packet_parse(pkt)); sol_coap_packet_unref(pkt); }
int main(int argc, char *argv[]) { struct sol_coap_server *server; struct sol_str_slice *path; struct sol_network_link_addr cliaddr = { }; struct sol_coap_packet *req; uint8_t observe = 0; int i, r; struct sol_network_link_addr servaddr = { .family = SOL_NETWORK_FAMILY_INET6, .port = 0 }; uint8_t token[4] = { 0x41, 0x42, 0x43, 0x44 }; sol_init(); if (argc < 3) { printf("Usage: %s <address> <path> [path]\n", argv[0]); return 0; } server = sol_coap_server_new(&servaddr); if (!server) { SOL_WRN("Could not create a coap server."); return -1; } req = sol_coap_packet_request_new(SOL_COAP_METHOD_GET, SOL_COAP_TYPE_CON); if (!req) { SOL_WRN("Could not make a GET request to resource %s", argv[2]); return -1; } r = sol_coap_header_set_token(req, token, sizeof(token)); if (r < 0) { SOL_WRN("Could not set coap header token."); return -1; } path = calloc(argc - 1, sizeof(*path)); if (!path) { sol_coap_packet_unref(req); return -1; } for (i = 2; i < argc; i++) { path[i - 2] = sol_str_slice_from_str(argv[i]); } sol_coap_add_option(req, SOL_COAP_OPTION_OBSERVE, &observe, sizeof(observe)); for (i = 0; path[i].data; i++) sol_coap_add_option(req, SOL_COAP_OPTION_URI_PATH, path[i].data, path[i].len); cliaddr.family = SOL_NETWORK_FAMILY_INET6; if (!sol_network_link_addr_from_str(&cliaddr, argv[1])) { SOL_WRN("%s is an invalid IPv6 address", argv[1]); free(path); sol_coap_packet_unref(req); return -1; } cliaddr.port = DEFAULT_UDP_PORT; /* Takes the ownership of 'req'. */ sol_coap_send_packet_with_reply(server, req, &cliaddr, reply_cb, path); sol_run(); sol_coap_server_unref(server); free(path); return 0; }