diff --git a/Makefile.dep b/Makefile.dep index 19d50e66d2..80c05d457d 100644 --- a/Makefile.dep +++ b/Makefile.dep @@ -47,6 +47,15 @@ ifneq (,$(filter gnrc_gomach,$(USEMODULE))) FEATURES_REQUIRED += periph_rtt endif +ifneq (,$(filter gnrc_lorawan,$(USEMODULE))) + USEMODULE += xtimer + USEMODULE += random + USEMODULE += hashes + USEMODULE += crypto + USEMODULE += netdev_layer + USEMODULE += gnrc_neterr +endif + ifneq (,$(filter nhdp,$(USEMODULE))) USEMODULE += sock_udp USEMODULE += xtimer diff --git a/sys/Makefile.include b/sys/Makefile.include index cde195f739..f156b65224 100644 --- a/sys/Makefile.include +++ b/sys/Makefile.include @@ -6,6 +6,10 @@ ifneq (,$(filter gnrc_sixlowpan_frag_rb,$(USEMODULE))) USEMODULE_INCLUDES += $(RIOTBASE)/sys/net/gnrc/network_layer/sixlowpan/frag endif +ifneq (,$(filter gnrc_lorawan,$(USEMODULE))) + USEMODULE_INCLUDES += $(RIOTBASE)/sys/net/gnrc/link_layer/lorawan/include +endif + ifneq (,$(filter gnrc_sock,$(USEMODULE))) USEMODULE_INCLUDES += $(RIOTBASE)/sys/net/gnrc/sock/include ifneq (,$(filter gnrc_ipv6,$(USEMODULE))) diff --git a/sys/net/gnrc/Makefile b/sys/net/gnrc/Makefile index cea412af33..f2a2956131 100644 --- a/sys/net/gnrc/Makefile +++ b/sys/net/gnrc/Makefile @@ -58,6 +58,9 @@ endif ifneq (,$(filter gnrc_pktbuf_malloc,$(USEMODULE))) DIRS += pktbuf_malloc endif +ifneq (,$(filter gnrc_lorawan,$(USEMODULE))) + DIRS += link_layer/lorawan +endif ifneq (,$(filter gnrc_gomach,$(USEMODULE))) DIRS += link_layer/gomach endif diff --git a/sys/net/gnrc/link_layer/lorawan/Makefile b/sys/net/gnrc/link_layer/lorawan/Makefile new file mode 100644 index 0000000000..d06929c43e --- /dev/null +++ b/sys/net/gnrc/link_layer/lorawan/Makefile @@ -0,0 +1,3 @@ +MODULE = gnrc_lorawan + +include $(RIOTBASE)/Makefile.base diff --git a/sys/net/gnrc/link_layer/lorawan/gnrc_lorawan.c b/sys/net/gnrc/link_layer/lorawan/gnrc_lorawan.c new file mode 100644 index 0000000000..36f0d24736 --- /dev/null +++ b/sys/net/gnrc/link_layer/lorawan/gnrc_lorawan.c @@ -0,0 +1,352 @@ +/* + * Copyright (C) 2019 HAW Hamburg + * + * This file is subject to the terms and conditions of the GNU Lesser + * General Public License v2.1. See the file LICENSE in the top level + * directory for more details. + */ + +/** + * @{ + * + * @file + * @author José Ignacio Alamos + * @} + */ +#include +#include +#include "net/lora.h" +#include "net/gnrc/lorawan.h" +#include "errno.h" +#include "net/gnrc/pktbuf.h" + +#include "net/lorawan/hdr.h" +#include "net/loramac.h" +#include "net/gnrc/lorawan/region.h" + +#define ENABLE_DEBUG (0) +#include "debug.h" + +/* This factor is used for converting "real" seconds into microcontroller + * microseconds. This is done in order to correct timer drift. + */ +#define _DRIFT_FACTOR (int) (US_PER_SEC * 100 / (100 + CONFIG_GNRC_LORAWAN_TIMER_DRIFT)) + +#define GNRC_LORAWAN_DL_RX2_DR_MASK (0x0F) /**< DL Settings DR Offset mask */ +#define GNRC_LORAWAN_DL_RX2_DR_POS (0) /**< DL Settings DR Offset pos */ +#define GNRC_LORAWAN_DL_DR_OFFSET_MASK (0x70) /**< DL Settings RX2 DR mask */ +#define GNRC_LORAWAN_DL_DR_OFFSET_POS (4) /**< DL Settings RX2 DR pos */ + +static inline void gnrc_lorawan_mlme_reset(gnrc_lorawan_t *mac) +{ + mac->mlme.activation = MLME_ACTIVATION_NONE; + mac->mlme.pending_mlme_opts = 0; + mac->rx_delay = (LORAMAC_DEFAULT_RX1_DELAY/MS_PER_SEC); + mac->mlme.nid = LORAMAC_DEFAULT_NETID; +} + +static inline void gnrc_lorawan_mlme_backoff_init(gnrc_lorawan_t *mac) +{ + mac->mlme.backoff_msg.type = MSG_TYPE_MLME_BACKOFF_EXPIRE; + mac->mlme.backoff_state = 0; + + gnrc_lorawan_mlme_backoff_expire(mac); +} + +static inline void gnrc_lorawan_mcps_reset(gnrc_lorawan_t *mac) +{ + mac->mcps.ack_requested = false; + mac->mcps.waiting_for_ack = false; + mac->mcps.fcnt = 0; + mac->mcps.fcnt_down = 0; +} + +static inline void _set_rx2_dr(gnrc_lorawan_t *mac, uint8_t rx2_dr) +{ + mac->dl_settings &= ~GNRC_LORAWAN_DL_RX2_DR_MASK; + mac->dl_settings |= (rx2_dr << GNRC_LORAWAN_DL_RX2_DR_POS) & + GNRC_LORAWAN_DL_RX2_DR_MASK; +} + +static void _sleep_radio(gnrc_lorawan_t *mac) +{ + netopt_state_t state = NETOPT_STATE_SLEEP; + + netdev_set_pass((netdev_t *) mac, NETOPT_STATE, &state, sizeof(state)); +} + +void gnrc_lorawan_init(gnrc_lorawan_t *mac, uint8_t *nwkskey, uint8_t *appskey) +{ + mac->nwkskey = nwkskey; + mac->appskey = appskey; + mac->busy = false; + gnrc_lorawan_mlme_backoff_init(mac); + gnrc_lorawan_reset(mac); +} + +void gnrc_lorawan_reset(gnrc_lorawan_t *mac) +{ + uint8_t cr = LORA_CR_4_5; + + netdev_set_pass(&mac->netdev, NETOPT_CODING_RATE, &cr, sizeof(cr)); + + uint8_t syncword = LORAMAC_DEFAULT_PUBLIC_NETWORK ? LORA_SYNCWORD_PUBLIC + : LORA_SYNCWORD_PRIVATE; + netdev_set_pass(&mac->netdev, NETOPT_SYNCWORD, &syncword, sizeof(syncword)); + + /* Continuous reception */ + uint32_t rx_timeout = 0; + netdev_set_pass(&mac->netdev, NETOPT_RX_TIMEOUT, &rx_timeout, sizeof(rx_timeout)); + + _set_rx2_dr(mac, LORAMAC_DEFAULT_RX2_DR); + + mac->toa = 0; + gnrc_lorawan_mcps_reset(mac); + gnrc_lorawan_mlme_reset(mac); + gnrc_lorawan_channels_init(mac); +} + +static void _config_radio(gnrc_lorawan_t *mac, uint32_t channel_freq, uint8_t dr, int rx) +{ + if (channel_freq != 0) { + netdev_set_pass(&mac->netdev, NETOPT_CHANNEL_FREQUENCY, &channel_freq, sizeof(channel_freq)); + } + + netopt_enable_t iq_invert = rx; + netdev_set_pass(&mac->netdev, NETOPT_IQ_INVERT, &iq_invert, sizeof(iq_invert)); + + gnrc_lorawan_set_dr(mac, dr); + + if (rx) { + /* Switch to single listen mode */ + const netopt_enable_t single = true; + netdev_set_pass(&mac->netdev, NETOPT_SINGLE_RECEIVE, &single, sizeof(single)); + const uint16_t timeout = CONFIG_GNRC_LORAWAN_MIN_SYMBOLS_TIMEOUT; + netdev_set_pass(&mac->netdev, NETOPT_RX_SYMBOL_TIMEOUT, &timeout, sizeof(timeout)); + } +} + +static void _configure_rx_window(gnrc_lorawan_t *mac, uint32_t channel_freq, uint8_t dr) +{ + _config_radio(mac, channel_freq, dr, true); +} + +void gnrc_lorawan_open_rx_window(gnrc_lorawan_t *mac) +{ + mac->msg.type = MSG_TYPE_TIMEOUT; + /* Switch to RX state */ + if (mac->state == LORAWAN_STATE_RX_1) { + xtimer_set_msg(&mac->rx, _DRIFT_FACTOR, &mac->msg, thread_getpid()); + } + uint8_t state = NETOPT_STATE_RX; + netdev_set_pass(&mac->netdev, NETOPT_STATE, &state, sizeof(state)); +} + +void gnrc_lorawan_event_tx_complete(gnrc_lorawan_t *mac) +{ + mac->msg.type = MSG_TYPE_TIMEOUT; + mac->state = LORAWAN_STATE_RX_1; + + int rx_1; + /* if the MAC is not activated, then this is a Join Request */ + rx_1 = mac->mlme.activation == MLME_ACTIVATION_NONE ? + LORAMAC_DEFAULT_JOIN_DELAY1 : mac->rx_delay; + + xtimer_set_msg(&mac->rx, rx_1 * _DRIFT_FACTOR, &mac->msg, thread_getpid()); + + uint8_t dr_offset = (mac->dl_settings & GNRC_LORAWAN_DL_DR_OFFSET_MASK) >> + GNRC_LORAWAN_DL_DR_OFFSET_POS; + _configure_rx_window(mac, 0, gnrc_lorawan_rx1_get_dr_offset(mac->last_dr, dr_offset)); + + _sleep_radio(mac); +} + +void gnrc_lorawan_event_timeout(gnrc_lorawan_t *mac) +{ + (void) mac; + switch (mac->state) { + case LORAWAN_STATE_RX_1: + _configure_rx_window(mac, LORAMAC_DEFAULT_RX2_FREQ, mac->dl_settings & GNRC_LORAWAN_DL_RX2_DR_MASK); + mac->state = LORAWAN_STATE_RX_2; + break; + case LORAWAN_STATE_RX_2: + gnrc_lorawan_mlme_no_rx(mac); + gnrc_lorawan_mcps_event(mac, MCPS_EVENT_NO_RX, 0); + mac->state = LORAWAN_STATE_IDLE; + gnrc_lorawan_mac_release(mac); + break; + default: + assert(false); + break; + } + _sleep_radio(mac); +} + +/* This function uses a precomputed table to calculate time on air without + * using floating point arithmetics */ +static uint32_t lora_time_on_air(size_t payload_size, uint8_t dr, uint8_t cr) +{ + assert(dr <= LORAMAC_DR_6); + uint8_t _K[6][4] = { { 0, 1, 5, 5 }, + { 0, 1, 4, 5 }, + { 1, 5, 5, 5 }, + { 1, 4, 5, 4 }, + { 1, 3, 4, 4 }, + { 1, 2, 4, 3 } }; + + uint32_t t_sym = 1 << (15 - dr); + uint32_t t_preamble = (t_sym << 3) + (t_sym << 2) + (t_sym >> 2); + + int index = (dr < LORAMAC_DR_6) ? dr : LORAMAC_DR_5; + uint8_t n0 = _K[index][0]; + int nb_symbols; + + uint8_t offset = _K[index][1]; + if (payload_size < offset) { + nb_symbols = 8 + n0 * cr; + } + else { + uint8_t c1 = _K[index][2]; + uint8_t c2 = _K[index][3]; + uint8_t pos = (payload_size - offset) % (c1 + c2); + uint8_t cycle = (payload_size - offset) / (c1 + c2); + nb_symbols = 8 + (n0 + 2 * cycle + 1 + (pos > (c1 - 1))) * cr; + } + + uint32_t t_payload = t_sym * nb_symbols; + return t_preamble + t_payload; +} + +void gnrc_lorawan_send_pkt(gnrc_lorawan_t *mac, gnrc_pktsnip_t *pkt, uint8_t dr) +{ + mac->state = LORAWAN_STATE_TX; + + iolist_t iolist = { + .iol_base = pkt->data, + .iol_len = pkt->size, + .iol_next = (iolist_t *) pkt->next + }; + + uint32_t chan = gnrc_lorawan_pick_channel(mac); + _config_radio(mac, chan, dr, false); + + mac->last_dr = dr; + + uint8_t cr; + netdev_get_pass(&mac->netdev, NETOPT_CODING_RATE, &cr, sizeof(cr)); + + mac->toa = lora_time_on_air(gnrc_pkt_len(pkt), dr, cr + 4); + + if (netdev_send_pass(&mac->netdev, &iolist) == -ENOTSUP) { + DEBUG("gnrc_lorawan: Cannot send: radio is still transmitting"); + } + +} + +void gnrc_lorawan_process_pkt(gnrc_lorawan_t *mac, gnrc_pktsnip_t *pkt) +{ + mac->state = LORAWAN_STATE_IDLE; + xtimer_remove(&mac->rx); + + uint8_t *p = pkt->data; + + uint8_t mtype = (*p & MTYPE_MASK) >> 5; + switch (mtype) { + case MTYPE_JOIN_ACCEPT: + gnrc_lorawan_mlme_process_join(mac, pkt); + break; + case MTYPE_CNF_DOWNLINK: + case MTYPE_UNCNF_DOWNLINK: + gnrc_lorawan_mcps_process_downlink(mac, pkt); + break; + default: + gnrc_pktbuf_release(pkt); + break; + } + + gnrc_lorawan_mac_release(mac); +} + +int gnrc_lorawan_netdev_get(netdev_t *dev, netopt_t opt, void *value, size_t max_len) +{ + int res = 0; + gnrc_lorawan_t *mac = (gnrc_lorawan_t *) dev; + uint32_t tmp; + + switch (opt) { + case NETOPT_ADDRESS: + assert(max_len >= sizeof(mac->dev_addr)); + tmp = byteorder_swapl(mac->dev_addr.u32); + memcpy(value, &tmp, sizeof(mac->dev_addr)); + res = sizeof(mac->dev_addr); + break; + default: + res = netdev_get_pass(dev, opt, value, max_len); + break; + } + return res; +} + +int gnrc_lorawan_netdev_set(netdev_t *dev, netopt_t opt, const void *value, size_t len) +{ + gnrc_lorawan_t *mac = (gnrc_lorawan_t *) dev; + uint32_t tmp; + + if (mac->busy) { + return -EBUSY; + } + + switch (opt) { + case NETOPT_ADDRESS: + assert(len == sizeof(uint32_t)); + tmp = byteorder_swapl(*((uint32_t *) value)); + memcpy(&mac->dev_addr, &tmp, sizeof(uint32_t)); + break; + case NETOPT_LORAWAN_RX2_DR: + assert(len == sizeof(uint8_t)); + _set_rx2_dr(mac, *((uint8_t *) value)); + break; + default: + netdev_set_pass(dev, opt, value, len); + break; + } + return 0; +} + +const netdev_driver_t gnrc_lorawan_driver = { + .init = netdev_init_pass, + .send = netdev_send_pass, + .recv = netdev_recv_pass, + .get = gnrc_lorawan_netdev_get, + .set = gnrc_lorawan_netdev_set, + .isr = netdev_isr_pass, +}; + +void gnrc_lorawan_setup(gnrc_lorawan_t *mac, netdev_t *lower) +{ + mac->netdev.driver = &gnrc_lorawan_driver; + mac->netdev.lower = lower; + lower->context = mac; +} + +void gnrc_lorawan_recv(gnrc_lorawan_t *mac) +{ + int bytes_expected = netdev_recv_pass((netdev_t *) mac, NULL, 0, 0); + int nread; + struct netdev_radio_rx_info rx_info; + gnrc_pktsnip_t *pkt = gnrc_pktbuf_add(NULL, NULL, bytes_expected, GNRC_NETTYPE_UNDEF); + if (pkt == NULL) { + DEBUG("_recv_ieee802154: cannot allocate pktsnip.\n"); + /* Discard packet on netdev device */ + netdev_recv_pass((netdev_t *) mac, NULL, bytes_expected, NULL); + return; + } + nread = netdev_recv_pass((netdev_t *) mac, pkt->data, bytes_expected, &rx_info); + _sleep_radio(mac); + if (nread <= 0) { + gnrc_pktbuf_release(pkt); + return; + } + + gnrc_lorawan_process_pkt(mac, pkt); +} diff --git a/sys/net/gnrc/link_layer/lorawan/gnrc_lorawan_crypto.c b/sys/net/gnrc/link_layer/lorawan/gnrc_lorawan_crypto.c new file mode 100644 index 0000000000..f6b74ca817 --- /dev/null +++ b/sys/net/gnrc/link_layer/lorawan/gnrc_lorawan_crypto.c @@ -0,0 +1,151 @@ +/* + * Copyright (C) 2019 HAW Hamburg + * + * This file is subject to the terms and conditions of the GNU Lesser + * General Public License v2.1. See the file LICENSE in the top level + * directory for more details. + */ + +/** + * @{ + * + * @file + * @author José Ignacio Alamos + * @author Francisco Molina + */ +#include +#include + +#include "hashes/cmac.h" +#include "crypto/ciphers.h" + +#include "net/gnrc/lorawan.h" +#include "byteorder.h" +#include "net/lorawan/hdr.h" + +#define MIC_B0_START (0x49) +#define CRYPT_B0_START (0x01) +#define DIR_MASK (0x1) +#define SBIT_MASK (0xF) + +#define APP_SKEY_B0_START (0x1) +#define NWK_SKEY_B0_START (0x2) + +static cmac_context_t CmacContext; +static uint8_t digest[LORAMAC_APPKEY_LEN]; +static cipher_t AesContext; + +typedef struct __attribute__((packed)) { + uint8_t fb; + uint32_t u8_pad; + uint8_t dir; + le_uint32_t dev_addr; + le_uint32_t fcnt; + uint8_t u32_pad; + uint8_t len; +} lorawan_block_t; + +void gnrc_lorawan_calculate_join_mic(const iolist_t *io, const uint8_t *key, le_uint32_t *out) +{ + cmac_init(&CmacContext, key, LORAMAC_APPKEY_LEN); + while (io != NULL) { + cmac_update(&CmacContext, io->iol_base, io->iol_len); + io = io->iol_next; + } + cmac_final(&CmacContext, digest); + + memcpy(out, digest, sizeof(le_uint32_t)); +} + +void gnrc_lorawan_calculate_mic(const le_uint32_t *dev_addr, uint32_t fcnt, + uint8_t dir, iolist_t *pkt, const uint8_t *nwkskey, le_uint32_t *out) +{ + lorawan_block_t block; + + block.fb = MIC_B0_START; + block.u8_pad = 0; + block.dir = dir & DIR_MASK; + + memcpy(&block.dev_addr, dev_addr, sizeof(le_uint32_t)); + + block.fcnt = byteorder_btoll(byteorder_htonl(fcnt)); + + block.u32_pad = 0; + + block.len = iolist_size(pkt); + + iolist_t io = { .iol_base = &block, .iol_len = sizeof(block), + .iol_next = pkt }; + gnrc_lorawan_calculate_join_mic(&io, nwkskey, out); +} + +void gnrc_lorawan_encrypt_payload(iolist_t *iolist, const le_uint32_t *dev_addr, uint32_t fcnt, uint8_t dir, const uint8_t *appskey) +{ + uint8_t s_block[16]; + uint8_t a_block[16]; + + memset(s_block, 0, sizeof(s_block)); + memset(a_block, 0, sizeof(a_block)); + + lorawan_block_t *block = (lorawan_block_t *) a_block; + + cipher_init(&AesContext, CIPHER_AES_128, appskey, LORAMAC_APPKEY_LEN); + + block->fb = CRYPT_B0_START; + + block->u8_pad = 0; + block->dir = dir & DIR_MASK; + + block->dev_addr = *dev_addr; + block->fcnt = byteorder_btoll(byteorder_htonl(fcnt)); + + block->u32_pad = 0; + + int c = 0; + for (iolist_t *io = iolist; io != NULL; io = io->iol_next) { + for (unsigned i = 0; i < io->iol_len; i++) { + uint8_t *v = io->iol_base; + + if ((c & SBIT_MASK) == 0) { + block->len = (c >> 4) + 1; + cipher_encrypt(&AesContext, a_block, s_block); + } + + v[i] = v[i] ^ s_block[c & SBIT_MASK]; + c++; + } + } +} + +void gnrc_lorawan_decrypt_join_accept(const uint8_t *key, uint8_t *pkt, int has_clist, uint8_t *out) +{ + cipher_init(&AesContext, CIPHER_AES_128, key, LORAMAC_APPKEY_LEN); + cipher_encrypt(&AesContext, pkt, out); + + if (has_clist) { + cipher_encrypt(&AesContext, pkt + LORAMAC_APPKEY_LEN, out + LORAMAC_APPKEY_LEN); + } +} + +void gnrc_lorawan_generate_session_keys(const uint8_t *app_nonce, const uint8_t *dev_nonce, const uint8_t *appkey, uint8_t *nwkskey, uint8_t *appskey) +{ + uint8_t buf[LORAMAC_APPSKEY_LEN]; + + memset(buf, 0, sizeof(buf)); + + cipher_init(&AesContext, CIPHER_AES_128, appkey, LORAMAC_APPSKEY_LEN); + + /* net_id comes right after app_nonce */ + memcpy(buf + 1, app_nonce, GNRC_LORAWAN_APP_NONCE_SIZE + GNRC_LORAWAN_NET_ID_SIZE); + memcpy(buf + 1 + GNRC_LORAWAN_APP_NONCE_SIZE + GNRC_LORAWAN_NET_ID_SIZE, dev_nonce, GNRC_LORAWAN_DEV_NONCE_SIZE); + + /* Calculate Application Session Key */ + buf[0] = APP_SKEY_B0_START; + cipher_encrypt(&AesContext, buf, nwkskey); + + /* Calculate Network Session Key */ + buf[0] = NWK_SKEY_B0_START; + cipher_encrypt(&AesContext, buf, appskey); +} + +/** @} */ diff --git a/sys/net/gnrc/link_layer/lorawan/gnrc_lorawan_mcps.c b/sys/net/gnrc/link_layer/lorawan/gnrc_lorawan_mcps.c new file mode 100644 index 0000000000..48fd6628fd --- /dev/null +++ b/sys/net/gnrc/link_layer/lorawan/gnrc_lorawan_mcps.c @@ -0,0 +1,334 @@ +/* + * Copyright (C) 2019 HAW Hamburg + * + * This file is subject to the terms and conditions of the GNU Lesser + * General Public License v2.1. See the file LICENSE in the top level + * directory for more details. + */ + +/** + * @{ + * + * @file + * @author José Ignacio Alamos + */ +#include +#include +#include "net/lora.h" +#include "net/gnrc/lorawan.h" +#include "net/gnrc/lorawan/region.h" +#include "errno.h" +#include "net/gnrc/pktbuf.h" + +#include "net/lorawan/hdr.h" + +#include "random.h" + +#define ENABLE_DEBUG (0) +#include "debug.h" + +#define _16_UPPER_BITMASK 0xFFFF0000 +#define _16_LOWER_BITMASK 0xFFFF + +int gnrc_lorawan_mic_is_valid(gnrc_pktsnip_t *mic, uint8_t *nwkskey) +{ + le_uint32_t calc_mic; + + assert(mic->size == MIC_SIZE); + assert(mic->next->data); + lorawan_hdr_t *lw_hdr = (lorawan_hdr_t *) mic->next->data; + + uint32_t fcnt = byteorder_ntohs(byteorder_ltobs(lw_hdr->fcnt)); + gnrc_lorawan_calculate_mic(&lw_hdr->addr, fcnt, GNRC_LORAWAN_DIR_DOWNLINK, (iolist_t *) mic->next, nwkskey, &calc_mic); + return calc_mic.u32 == ((le_uint32_t *) mic->data)->u32; +} + +uint32_t gnrc_lorawan_fcnt_stol(uint32_t fcnt_down, uint16_t s_fcnt) +{ + uint32_t u32_fcnt = (fcnt_down & _16_UPPER_BITMASK) | s_fcnt; + + if (fcnt_down + LORAMAC_DEFAULT_MAX_FCNT_GAP >= _16_LOWER_BITMASK + && s_fcnt < (fcnt_down & _16_LOWER_BITMASK)) { + u32_fcnt += _16_LOWER_BITMASK; + } + return u32_fcnt; +} + +void gnrc_lorawan_mcps_process_downlink(gnrc_lorawan_t *mac, gnrc_pktsnip_t *pkt) +{ + gnrc_pktsnip_t *hdr, *data, *fopts = NULL, *fport = NULL; + int release = true; + int error = true; + + /* mark MIC */ + if (!(data = gnrc_pktbuf_mark(pkt, (pkt->size - MIC_SIZE > 0) ? pkt->size - MIC_SIZE : 0, GNRC_NETTYPE_UNDEF))) { + DEBUG("gnrc_lorawan: failed to mark MIC\n"); + goto out; + } + + /* NOTE: MIC is in pkt */ + if (!gnrc_lorawan_mic_is_valid(pkt, mac->nwkskey)) { + DEBUG("gnrc_lorawan: invalid MIC\n"); + goto out; + } + + /* remove snip */ + pkt = gnrc_pktbuf_remove_snip(pkt, pkt); + + if (!(hdr = gnrc_pktbuf_mark(pkt, sizeof(lorawan_hdr_t), GNRC_NETTYPE_UNDEF))) { + DEBUG("gnrc_lorawan: failed to allocate hdr\n"); + goto out; + } + + int _fopts_length = lorawan_hdr_get_frame_opts_len((lorawan_hdr_t *) hdr->data); + if (_fopts_length && !(fopts = gnrc_pktbuf_mark(pkt, _fopts_length, GNRC_NETTYPE_UNDEF))) { + DEBUG("gnrc_lorawan: failed to allocate fopts\n"); + goto out; + } + + if (pkt->size && !(fport = gnrc_pktbuf_mark(pkt, 1, GNRC_NETTYPE_UNDEF))) { + DEBUG("gnrc_lorawan: failed to allocate fport\n"); + goto out; + } + + assert(pkt != NULL && fport->data); + + int fopts_in_payload = *((uint8_t *) fport->data) == 0; + if (fopts && fopts_in_payload) { + DEBUG("gnrc_lorawan: packet with fopts and port == 0. Drop\n"); + goto out; + } + + lorawan_hdr_t *lw_hdr = hdr->data; + + if (lw_hdr->addr.u32 != mac->dev_addr.u32) { + DEBUG("gnrc_lorawan: received packet with wrong dev addr. Drop\n"); + goto out; + } + + uint32_t fcnt = gnrc_lorawan_fcnt_stol(mac->mcps.fcnt_down, lw_hdr->fcnt.u16); + if (mac->mcps.fcnt_down > fcnt || mac->mcps.fcnt_down + + LORAMAC_DEFAULT_MAX_FCNT_GAP < fcnt) { + goto out; + } + + mac->mcps.fcnt_down = fcnt; + error = false; + + int ack_req = lorawan_hdr_get_mtype(lw_hdr) == MTYPE_CNF_DOWNLINK; + if (ack_req) { + mac->mcps.ack_requested = true; + } + + iolist_t payload = { .iol_base = pkt->data, .iol_len = pkt->size }; + if (pkt->data) { + gnrc_lorawan_encrypt_payload(&payload, &lw_hdr->addr, byteorder_ntohs(byteorder_ltobs(lw_hdr->fcnt)), GNRC_LORAWAN_DIR_DOWNLINK, fopts_in_payload ? mac->nwkskey : mac->appskey); + } + + /* if there are fopts, it's either an empty packet or application payload */ + if (fopts) { + gnrc_lorawan_process_fopts(mac, fopts->data, fopts->size); + } + else if (fopts_in_payload) { + gnrc_lorawan_process_fopts(mac, pkt->data, pkt->size); + } + + gnrc_lorawan_mcps_event(mac, MCPS_EVENT_RX, lorawan_hdr_get_ack(lw_hdr)); + if (pkt->data && *((uint8_t *) fport->data) != 0) { + pkt->type = GNRC_NETTYPE_LORAWAN; + release = false; + + mcps_indication_t *mcps_indication = gnrc_lorawan_mcps_allocate(mac); + mcps_indication->type = ack_req; + mcps_indication->data.pkt = pkt; + mcps_indication->data.port = *((uint8_t *) fport->data); + mac->netdev.event_callback((netdev_t *) mac, NETDEV_EVENT_MCPS_INDICATION); + } + + if (lorawan_hdr_get_frame_pending(lw_hdr)) { + mlme_indication_t *mlme_indication = gnrc_lorawan_mlme_allocate(mac); + mlme_indication->type = MLME_SCHEDULE_UPLINK; + mac->netdev.event_callback((netdev_t *) mac, NETDEV_EVENT_MLME_INDICATION); + } + +out: + if (error) { + gnrc_lorawan_mcps_event(mac, MCPS_EVENT_NO_RX, 0); + } + + if (release) { + DEBUG("gnrc_lorawan: release packet\n"); + gnrc_pktbuf_release(pkt); + } +} + +size_t gnrc_lorawan_build_hdr(uint8_t mtype, le_uint32_t *dev_addr, uint32_t fcnt, uint8_t ack, uint8_t fopts_length, lorawan_buffer_t *buf) +{ + assert(fopts_length < 16); + lorawan_hdr_t *lw_hdr = (lorawan_hdr_t *) buf->data; + + lw_hdr->mt_maj = 0; + lorawan_hdr_set_mtype(lw_hdr, mtype); + lorawan_hdr_set_maj(lw_hdr, MAJOR_LRWAN_R1); + + lw_hdr->addr = *dev_addr; + lw_hdr->fctrl = 0; + + lorawan_hdr_set_ack(lw_hdr, ack); + lorawan_hdr_set_frame_opts_len(lw_hdr, fopts_length); + + lw_hdr->fcnt = byteorder_btols(byteorder_htons(fcnt)); + + buf->index += sizeof(lorawan_hdr_t); + + return sizeof(lorawan_hdr_t); +} + +gnrc_pktsnip_t *gnrc_lorawan_build_uplink(gnrc_lorawan_t *mac, gnrc_pktsnip_t *payload, int confirmed_data, uint8_t port) +{ + /* Encrypt payload (it's block encryption so we can use the same buffer!) */ + gnrc_lorawan_encrypt_payload((iolist_t *) payload, &mac->dev_addr, mac->mcps.fcnt, GNRC_LORAWAN_DIR_UPLINK, port ? mac->appskey : mac->nwkskey); + + /* We try to allocate the whole header with fopts at once */ + uint8_t fopts_length = gnrc_lorawan_build_options(mac, NULL); + + gnrc_pktsnip_t *mac_hdr = gnrc_pktbuf_add(payload, NULL, sizeof(lorawan_hdr_t) + fopts_length + 1, GNRC_NETTYPE_UNDEF); + + if (!mac_hdr) { + gnrc_pktbuf_release_error(payload, -ENOBUFS); + return NULL; + } + + gnrc_pktsnip_t *mic = gnrc_pktbuf_add(NULL, NULL, MIC_SIZE, GNRC_NETTYPE_UNDEF); + if (!mic) { + gnrc_pktbuf_release_error(mac_hdr, -ENOBUFS); + return NULL; + } + + lorawan_buffer_t buf = { + .data = (uint8_t *) mac_hdr->data, + .size = mac_hdr->size, + .index = 0 + }; + + gnrc_lorawan_build_hdr(confirmed_data ? MTYPE_CNF_UPLINK : MTYPE_UNCNF_UPLINK, + &mac->dev_addr, mac->mcps.fcnt, mac->mcps.ack_requested, fopts_length, &buf); + + gnrc_lorawan_build_options(mac, &buf); + + assert(buf.index == mac_hdr->size - 1); + + buf.data[buf.index++] = port; + + gnrc_lorawan_calculate_mic(&mac->dev_addr, mac->mcps.fcnt, GNRC_LORAWAN_DIR_UPLINK, + (iolist_t *) mac_hdr, mac->nwkskey, mic->data); + + LL_APPEND(payload, mic); + + return mac_hdr; +} + +static void _end_of_tx(gnrc_lorawan_t *mac, int type, int status) +{ + mac->mcps.waiting_for_ack = false; + + mcps_confirm_t *mcps_confirm = gnrc_lorawan_mcps_allocate(mac); + + mcps_confirm->type = type; + mcps_confirm->status = status; + mac->netdev.event_callback((netdev_t *) mac, NETDEV_EVENT_MCPS_CONFIRM); + + mac->mcps.fcnt += 1; +} + +void gnrc_lorawan_mcps_event(gnrc_lorawan_t *mac, int event, int data) +{ + if (mac->mlme.activation == MLME_ACTIVATION_NONE) { + return; + } + + if (event == MCPS_EVENT_ACK_TIMEOUT) { + gnrc_lorawan_send_pkt(mac, mac->mcps.outgoing_pkt, mac->last_dr); + } + else { + int state = mac->mcps.waiting_for_ack ? MCPS_CONFIRMED : MCPS_UNCONFIRMED; + if (state == MCPS_CONFIRMED && ((event == MCPS_EVENT_RX && !data) || + event == MCPS_EVENT_NO_RX)) { + if (mac->mcps.nb_trials-- == 0) { + _end_of_tx(mac, MCPS_CONFIRMED, -ETIMEDOUT); + } + } + else { + _end_of_tx(mac, state, GNRC_LORAWAN_REQ_STATUS_SUCCESS); + } + + mac->msg.type = MSG_TYPE_MCPS_ACK_TIMEOUT; + if (mac->mcps.outgoing_pkt) { + xtimer_set_msg(&mac->rx, 1000000 + random_uint32_range(0, 2000000), &mac->msg, thread_getpid()); + } + } +} + +void gnrc_lorawan_mcps_request(gnrc_lorawan_t *mac, const mcps_request_t *mcps_request, mcps_confirm_t *mcps_confirm) +{ + int release = true; + gnrc_pktsnip_t *pkt = mcps_request->data.pkt; + + if (mac->mlme.activation == MLME_ACTIVATION_NONE) { + DEBUG("gnrc_lorawan_mcps: LoRaWAN not activated\n"); + mcps_confirm->status = -ENOTCONN; + goto out; + } + + if (!gnrc_lorawan_mac_acquire(mac)) { + mcps_confirm->status = -EBUSY; + goto out; + } + + if (mcps_request->data.port < LORAMAC_PORT_MIN || + mcps_request->data.port > LORAMAC_PORT_MAX) { + mcps_confirm->status = -EBADMSG; + goto out; + } + + if (!gnrc_lorawan_validate_dr(mcps_request->data.dr)) { + mcps_confirm->status = -EINVAL; + goto out; + } + + int waiting_for_ack = mcps_request->type == MCPS_CONFIRMED; + if (!(pkt = gnrc_lorawan_build_uplink(mac, pkt, waiting_for_ack, mcps_request->data.port))) { + /* This function releases the pkt if fails */ + release = false; + mcps_confirm->status = -ENOBUFS; + goto out; + } + + if ((gnrc_pkt_len(pkt) - MIC_SIZE - 1) > gnrc_lorawan_region_mac_payload_max(mcps_request->data.dr)) { + mcps_confirm->status = -EMSGSIZE; + goto out; + } + + release = false; + mac->mcps.waiting_for_ack = waiting_for_ack; + mac->mcps.ack_requested = false; + + mac->mcps.nb_trials = LORAMAC_DEFAULT_RETX; + + assert(mac->mcps.outgoing_pkt == NULL); + mac->mcps.outgoing_pkt = pkt; + + gnrc_lorawan_send_pkt(mac, pkt, mcps_request->data.dr); + mcps_confirm->status = GNRC_LORAWAN_REQ_STATUS_DEFERRED; +out: + + if (mcps_confirm->status != GNRC_LORAWAN_REQ_STATUS_DEFERRED) { + gnrc_lorawan_mac_release(mac); + } + + if (release) { + gnrc_pktbuf_release_error(pkt, mcps_confirm->status); + } +} + +/** @} */ diff --git a/sys/net/gnrc/link_layer/lorawan/gnrc_lorawan_mlme.c b/sys/net/gnrc/link_layer/lorawan/gnrc_lorawan_mlme.c new file mode 100644 index 0000000000..c1c8cdd5c9 --- /dev/null +++ b/sys/net/gnrc/link_layer/lorawan/gnrc_lorawan_mlme.c @@ -0,0 +1,328 @@ +/* + * Copyright (C) 2019 HAW Hamburg + * + * This file is subject to the terms and conditions of the GNU Lesser + * General Public License v2.1. See the file LICENSE in the top level + * directory for more details. + */ + +/** + * @{ + * + * @file + * @author José Ignacio Alamos + * + * @} + */ +#include +#include +#include "net/lora.h" +#include "net/gnrc/lorawan.h" +#include "net/gnrc/lorawan/region.h" +#include "errno.h" +#include "net/gnrc/pktbuf.h" +#include "random.h" + +#include "net/lorawan/hdr.h" + +#define ENABLE_DEBUG (0) +#include "debug.h" + +static gnrc_pktsnip_t *_build_join_req_pkt(uint8_t *appeui, uint8_t *deveui, uint8_t *appkey, uint8_t *dev_nonce) +{ + gnrc_pktsnip_t *pkt = gnrc_pktbuf_add(NULL, NULL, sizeof(lorawan_join_request_t), GNRC_NETTYPE_UNDEF); + + if (pkt) { + lorawan_join_request_t *hdr = (lorawan_join_request_t *) pkt->data; + + hdr->mt_maj = 0; + lorawan_hdr_set_mtype((lorawan_hdr_t *) hdr, MTYPE_JOIN_REQUEST); + lorawan_hdr_set_maj((lorawan_hdr_t *) hdr, MAJOR_LRWAN_R1); + + le_uint64_t l_appeui = *((le_uint64_t *) appeui); + le_uint64_t l_deveui = *((le_uint64_t *) deveui); + + hdr->app_eui = l_appeui; + hdr->dev_eui = l_deveui; + + le_uint16_t l_dev_nonce = *((le_uint16_t *) dev_nonce); + hdr->dev_nonce = l_dev_nonce; + + iolist_t io = { .iol_base = pkt->data, .iol_len = JOIN_REQUEST_SIZE - MIC_SIZE, + .iol_next = NULL }; + gnrc_lorawan_calculate_join_mic(&io, appkey, &hdr->mic); + } + + return pkt; +} + +static int gnrc_lorawan_send_join_request(gnrc_lorawan_t *mac, uint8_t *deveui, + uint8_t *appeui, uint8_t *appkey, uint8_t dr) +{ + netdev_t *dev = mac->netdev.lower; + + /* Dev Nonce */ + uint32_t random_number; + dev->driver->get(dev, NETOPT_RANDOM, &random_number, sizeof(random_number)); + + mac->mlme.dev_nonce[0] = random_number & 0xFF; + mac->mlme.dev_nonce[1] = (random_number >> 8) & 0xFF; + + /* build join request */ + gnrc_pktsnip_t *pkt = _build_join_req_pkt(appeui, deveui, appkey, mac->mlme.dev_nonce); + if (!pkt) { + return -ENOBUFS; + } + + /* We need a random delay for join request. Otherwise there might be + * network congestion if a group of nodes start at the same time */ + xtimer_usleep(random_uint32() & GNRC_LORAWAN_JOIN_DELAY_U32_MASK); + gnrc_lorawan_send_pkt(mac, pkt, dr); + + mac->mlme.backoff_budget -= mac->toa; + gnrc_pktbuf_release(pkt); + + return GNRC_LORAWAN_REQ_STATUS_DEFERRED; +} + +void gnrc_lorawan_mlme_process_join(gnrc_lorawan_t *mac, gnrc_pktsnip_t *pkt) +{ + int status; + + if (mac->mlme.activation != MLME_ACTIVATION_NONE) { + status = -EBADMSG; + goto out; + } + + if (pkt->size != GNRC_LORAWAN_JOIN_ACCEPT_MAX_SIZE - CFLIST_SIZE && + pkt->size != GNRC_LORAWAN_JOIN_ACCEPT_MAX_SIZE) { + status = -EBADMSG; + goto out; + } + + /* Substract 1 from join accept max size, since the MHDR was already read */ + uint8_t out[GNRC_LORAWAN_JOIN_ACCEPT_MAX_SIZE - 1]; + uint8_t has_cflist = (pkt->size - 1) >= CFLIST_SIZE; + gnrc_lorawan_decrypt_join_accept(mac->appskey, ((uint8_t *) pkt->data) + 1, + has_cflist, out); + memcpy(((uint8_t *) pkt->data) + 1, out, pkt->size - 1); + + iolist_t io = { .iol_base = pkt->data, .iol_len = pkt->size - MIC_SIZE, + .iol_next = NULL }; + le_uint32_t mic; + le_uint32_t *expected_mic = (le_uint32_t *) (((uint8_t *) pkt->data) + pkt->size - MIC_SIZE); + gnrc_lorawan_calculate_join_mic(&io, mac->appskey, &mic); + if (mic.u32 != expected_mic->u32) { + DEBUG("gnrc_lorawan_mlme: wrong MIC.\n"); + status = -EBADMSG; + goto out; + } + + lorawan_join_accept_t *ja_hdr = (lorawan_join_accept_t *) pkt->data; + gnrc_lorawan_generate_session_keys(ja_hdr->app_nonce, mac->mlme.dev_nonce, mac->appskey, mac->nwkskey, mac->appskey); + + le_uint32_t le_nid; + le_nid.u32 = 0; + memcpy(&le_nid, ja_hdr->net_id, 3); + mac->mlme.nid = byteorder_ntohl(byteorder_ltobl(le_nid)); + /* Copy devaddr */ + memcpy(&mac->dev_addr, ja_hdr->dev_addr, sizeof(mac->dev_addr)); + + mac->dl_settings = ja_hdr->dl_settings; + + /* delay 0 maps to 1 second */ + mac->rx_delay = ja_hdr->rx_delay ? ja_hdr->rx_delay : 1; + + gnrc_lorawan_process_cflist(mac, out + sizeof(lorawan_join_accept_t) - 1); + mac->mlme.activation = MLME_ACTIVATION_OTAA; + status = GNRC_LORAWAN_REQ_STATUS_SUCCESS; + +out: + gnrc_pktbuf_release(pkt); + mlme_confirm_t *mlme_confirm = gnrc_lorawan_mlme_allocate(mac); + mlme_confirm->type = MLME_JOIN; + mlme_confirm->status = status; + + mac->netdev.event_callback((netdev_t *) mac, NETDEV_EVENT_MLME_CONFIRM); +} + +void gnrc_lorawan_mlme_backoff_expire(gnrc_lorawan_t *mac) +{ + uint8_t counter = mac->mlme.backoff_state & 0x1F; + uint8_t state = mac->mlme.backoff_state >> 5; + + if (counter == 0) { + switch (state) { + case GNRC_LORAWAN_BACKOFF_STATE_1: + counter = GNRC_LORAWAN_BACKOFF_TIME_1; + state = GNRC_LORAWAN_BACKOFF_STATE_2; + mac->mlme.backoff_budget = GNRC_LORAWAN_BACKOFF_BUDGET_1; + break; + case GNRC_LORAWAN_BACKOFF_STATE_2: + counter = GNRC_LORAWAN_BACKOFF_TIME_2; + state = GNRC_LORAWAN_BACKOFF_STATE_3; + mac->mlme.backoff_budget = GNRC_LORAWAN_BACKOFF_BUDGET_2; + break; + case GNRC_LORAWAN_BACKOFF_STATE_3: + default: + counter = GNRC_LORAWAN_BACKOFF_TIME_3; + mac->mlme.backoff_budget = GNRC_LORAWAN_BACKOFF_BUDGET_3; + break; + } + } + + counter--; + mac->mlme.backoff_state = state << 5 | (counter & 0x1F); + xtimer_set_msg(&mac->mlme.backoff_timer, + GNRC_LORAWAN_BACKOFF_WINDOW_TICK, + &mac->mlme.backoff_msg, thread_getpid()); +} + +static void _mlme_set(gnrc_lorawan_t *mac, const mlme_request_t *mlme_request, + mlme_confirm_t *mlme_confirm) +{ + mlme_confirm->status = -EINVAL; + switch(mlme_request->mib.type) { + case MIB_ACTIVATION_METHOD: + if(mlme_request->mib.activation != MLME_ACTIVATION_OTAA) { + mlme_confirm->status = GNRC_LORAWAN_REQ_STATUS_SUCCESS; + mac->mlme.activation = mlme_request->mib.activation; + } + break; + default: + break; + } +} + +static void _mlme_get(gnrc_lorawan_t *mac, const mlme_request_t *mlme_request, + mlme_confirm_t *mlme_confirm) +{ + switch(mlme_request->mib.type) { + case MIB_ACTIVATION_METHOD: + mlme_confirm->status = GNRC_LORAWAN_REQ_STATUS_SUCCESS; + mlme_confirm->mib.activation = mac->mlme.activation; + break; + default: + mlme_confirm->status = -EINVAL; + break; + } +} + +void gnrc_lorawan_mlme_request(gnrc_lorawan_t *mac, const mlme_request_t *mlme_request, + mlme_confirm_t *mlme_confirm) +{ + switch (mlme_request->type) { + case MLME_JOIN: + if(mac->mlme.activation != MLME_ACTIVATION_NONE) { + mlme_confirm->status = -EINVAL; + break; + } + if (!gnrc_lorawan_mac_acquire(mac)) { + mlme_confirm->status = -EBUSY; + break; + } + + if (mac->mlme.backoff_budget < 0) { + mlme_confirm->status = -EDQUOT; + break; + } + memcpy(mac->appskey, mlme_request->join.appkey, LORAMAC_APPKEY_LEN); + mlme_confirm->status = gnrc_lorawan_send_join_request(mac, mlme_request->join.deveui, + mlme_request->join.appeui, mlme_request->join.appkey, mlme_request->join.dr); + break; + case MLME_LINK_CHECK: + mac->mlme.pending_mlme_opts |= GNRC_LORAWAN_MLME_OPTS_LINK_CHECK_REQ; + mlme_confirm->status = GNRC_LORAWAN_REQ_STATUS_DEFERRED; + break; + case MLME_SET: + _mlme_set(mac, mlme_request, mlme_confirm); + break; + case MLME_GET: + _mlme_get(mac, mlme_request, mlme_confirm); + break; + case MLME_RESET: + gnrc_lorawan_reset(mac); + mlme_confirm->status = GNRC_LORAWAN_REQ_STATUS_SUCCESS; + break; + default: + break; + } +} + +int _fopts_mlme_link_check_req(lorawan_buffer_t *buf) +{ + if (buf) { + assert(buf->index + GNRC_LORAWAN_CID_SIZE <= buf->size); + buf->data[buf->index++] = GNRC_LORAWAN_CID_LINK_CHECK_ANS; + } + + return GNRC_LORAWAN_CID_SIZE; +} + +static void _mlme_link_check_ans(gnrc_lorawan_t *mac, uint8_t *p) +{ + mlme_confirm_t *mlme_confirm = gnrc_lorawan_mlme_allocate(mac); + mlme_confirm->link_req.margin = p[1]; + mlme_confirm->link_req.num_gateways = p[2]; + + mlme_confirm->type = MLME_LINK_CHECK; + mlme_confirm->status = GNRC_LORAWAN_REQ_STATUS_SUCCESS; + mac->netdev.event_callback(&mac->netdev, NETDEV_EVENT_MLME_CONFIRM); + + mac->mlme.pending_mlme_opts &= ~GNRC_LORAWAN_MLME_OPTS_LINK_CHECK_REQ; +} + +void gnrc_lorawan_process_fopts(gnrc_lorawan_t *mac, uint8_t *fopts, size_t size) +{ + if (!fopts || !size) { + return; + } + + uint8_t ret = 0; + void (*cb)(gnrc_lorawan_t*, uint8_t *p) = NULL; + + for(uint8_t pos = 0; pos < size; pos += ret) { + switch (fopts[pos]) { + case GNRC_LORAWAN_CID_LINK_CHECK_ANS: + ret += GNRC_LORAWAN_FOPT_LINK_CHECK_ANS_SIZE; + cb = _mlme_link_check_ans; + break; + default: + return; + } + + if(pos + ret > size) { + return; + } + + cb(mac, &fopts[pos]); + } +} + +uint8_t gnrc_lorawan_build_options(gnrc_lorawan_t *mac, lorawan_buffer_t *buf) +{ + size_t size = 0; + + if(mac->mlme.pending_mlme_opts & GNRC_LORAWAN_MLME_OPTS_LINK_CHECK_REQ) { + size += _fopts_mlme_link_check_req(buf); + } + + return size; +} + +void gnrc_lorawan_mlme_no_rx(gnrc_lorawan_t *mac) +{ + mlme_confirm_t *mlme_confirm = gnrc_lorawan_mlme_allocate(mac); + + mlme_confirm->status = -ETIMEDOUT; + + if (mac->mlme.activation == MLME_ACTIVATION_NONE) { + mlme_confirm->type = MLME_JOIN; + mac->netdev.event_callback(&mac->netdev, NETDEV_EVENT_MLME_CONFIRM); + } + else if (mac->mlme.pending_mlme_opts & GNRC_LORAWAN_MLME_OPTS_LINK_CHECK_REQ) { + mlme_confirm->type = MLME_LINK_CHECK; + mac->netdev.event_callback(&mac->netdev, NETDEV_EVENT_MLME_CONFIRM); + mac->mlme.pending_mlme_opts &= ~GNRC_LORAWAN_MLME_OPTS_LINK_CHECK_REQ; + } +} diff --git a/sys/net/gnrc/link_layer/lorawan/gnrc_lorawan_region.c b/sys/net/gnrc/link_layer/lorawan/gnrc_lorawan_region.c new file mode 100644 index 0000000000..b845626375 --- /dev/null +++ b/sys/net/gnrc/link_layer/lorawan/gnrc_lorawan_region.c @@ -0,0 +1,130 @@ +/* + * Copyright (C) 2019 HAW Hamburg + * + * This file is subject to the terms and conditions of the GNU Lesser + * General Public License v2.1. See the file LICENSE in the top level + * directory for more details. + */ + +/** + * @{ + * + * @file + * @author José Ignacio Alamos + */ +#include "net/gnrc/lorawan/region.h" + +#define GNRC_LORAWAN_DATARATES_NUMOF (6U) + +static uint8_t dr_sf[GNRC_LORAWAN_DATARATES_NUMOF] = +{ LORA_SF12, LORA_SF11, LORA_SF10, LORA_SF9, LORA_SF8, LORA_SF7 }; +static uint8_t dr_bw[GNRC_LORAWAN_DATARATES_NUMOF] = +{ LORA_BW_125_KHZ, LORA_BW_125_KHZ, LORA_BW_125_KHZ, LORA_BW_125_KHZ, + LORA_BW_125_KHZ, LORA_BW_125_KHZ }; + +int gnrc_lorawan_set_dr(gnrc_lorawan_t *mac, uint8_t datarate) +{ + netdev_t *dev = mac->netdev.lower; + + if (!gnrc_lorawan_validate_dr(datarate)) { + return -EINVAL; + } + uint8_t bw = dr_bw[datarate]; + uint8_t sf = dr_sf[datarate]; + + dev->driver->set(dev, NETOPT_BANDWIDTH, &bw, sizeof(bw)); + dev->driver->set(dev, NETOPT_SPREADING_FACTOR, &sf, sizeof(sf)); + + return 0; +} + +uint8_t gnrc_lorawan_rx1_get_dr_offset(uint8_t dr_up, uint8_t dr_offset) +{ + return (dr_up > dr_offset) ? (dr_up - dr_offset) : 0; +} + +static size_t _get_num_used_channels(gnrc_lorawan_t *mac) +{ + size_t count = 0; + + for (unsigned i = 0; i < GNRC_LORAWAN_MAX_CHANNELS; i++) { + if (mac->channel[i]) { + count++; + } + } + return count; +} + +static uint32_t _get_nth_channel(gnrc_lorawan_t *mac, size_t n) +{ + int i = 0; + uint32_t channel = 0; + + while (n) { + if (mac->channel[i]) { + n--; + channel = mac->channel[i]; + i++; + } + } + return channel; +} + +void gnrc_lorawan_channels_init(gnrc_lorawan_t *mac) +{ + for (unsigned i = 0; i < GNRC_LORAWAN_DEFAULT_CHANNELS_NUMOF; i++) { + mac->channel[i] = gnrc_lorawan_default_channels[i]; + } + + for (unsigned i = GNRC_LORAWAN_DEFAULT_CHANNELS_NUMOF; + i < GNRC_LORAWAN_MAX_CHANNELS; i++) { + mac->channel[i] = 0; + } +} + +uint32_t gnrc_lorawan_pick_channel(gnrc_lorawan_t *mac) +{ + netdev_t *netdev = mac->netdev.lower; + uint32_t random_number; + + netdev->driver->get(netdev, NETOPT_RANDOM, &random_number, + sizeof(random_number)); + + return _get_nth_channel(mac, + 1 + (random_number % _get_num_used_channels(mac))); +} + +void gnrc_lorawan_process_cflist(gnrc_lorawan_t *mac, uint8_t *cflist) +{ + /* TODO: Check CFListType to 0 */ + for (unsigned i = GNRC_LORAWAN_DEFAULT_CHANNELS_NUMOF; i < 8; i++) { + le_uint32_t cl; + cl.u32 = 0; + memcpy(&cl, cflist, GNRC_LORAWAN_CFLIST_ENTRY_SIZE); + mac->channel[i] = byteorder_ntohl(byteorder_ltobl(cl)) * 100; + cflist += GNRC_LORAWAN_CFLIST_ENTRY_SIZE; + } +} + +uint8_t gnrc_lorawan_region_mac_payload_max(uint8_t datarate) +{ + if (datarate < 3) { + return GNRC_LORAWAN_MAX_PAYLOAD_1; + } + else if (datarate == 3) { + return GNRC_LORAWAN_MAX_PAYLOAD_2; + } + else { + return GNRC_LORAWAN_MAX_PAYLOAD_3; + } +} + +bool gnrc_lorawan_validate_dr(uint8_t dr) +{ + if (dr < GNRC_LORAWAN_DATARATES_NUMOF) { + return true; + } + return false; +} + +/** @} */ diff --git a/sys/net/gnrc/link_layer/lorawan/include/gnrc_lorawan_internal.h b/sys/net/gnrc/link_layer/lorawan/include/gnrc_lorawan_internal.h new file mode 100644 index 0000000000..e9dedbe1bd --- /dev/null +++ b/sys/net/gnrc/link_layer/lorawan/include/gnrc_lorawan_internal.h @@ -0,0 +1,481 @@ +/* + * Copyright (C) 2019 HAW Hamburg + * + * This file is subject to the terms and conditions of the GNU Lesser + * General Public License v2.1. See the file LICENSE in the top level + * directory for more details. + */ + +/** + * @ingroup net_gnrc_lorawan + * @{ + * + * @file + * @brief GNRC LoRaWAN internal header + * + * @author Jose Ignacio Alamos + */ +#ifndef GNRC_LORAWAN_INTERNAL_H +#define GNRC_LORAWAN_INTERNAL_H + +#include +#include +#include "iolist.h" +#include "net/lora.h" +#include "net/lorawan/hdr.h" +#include "net/gnrc/pktbuf.h" +#include "xtimer.h" +#include "msg.h" +#include "net/netdev.h" +#include "net/netdev/layer.h" +#include "net/loramac.h" + +#ifdef __cplusplus +extern "C" { +#endif + +#define MSG_TYPE_TIMEOUT (0x3457) /**< Timeout message type */ +#define MSG_TYPE_MCPS_ACK_TIMEOUT (0x3458) /**< ACK timeout message type */ +#define MSG_TYPE_MLME_BACKOFF_EXPIRE (0x3459) /**< Backoff timer expiration message type */ + +#define MTYPE_MASK 0xE0 /**< MHDR mtype mask */ +#define MTYPE_JOIN_REQUEST 0x0 /**< Join Request type */ +#define MTYPE_JOIN_ACCEPT 0x1 /**< Join Accept type */ +#define MTYPE_UNCNF_UPLINK 0x2 /**< Unconfirmed uplink type */ +#define MTYPE_UNCNF_DOWNLINK 0x3 /**< Unconfirmed downlink type */ +#define MTYPE_CNF_UPLINK 0x4 /**< Confirmed uplink type */ +#define MTYPE_CNF_DOWNLINK 0x5 /**< Confirmed downlink type */ +#define MTYPE_REJOIN_REQ 0x6 /**< Re-join request type */ +#define MTYPE_PROPIETARY 0x7 /**< Propietary frame type */ + +#define MAJOR_MASK 0x3 /**< Major mtype mask */ +#define MAJOR_LRWAN_R1 0x0 /**< LoRaWAN R1 version type */ + +#define JOIN_REQUEST_SIZE (23U) /**< Join Request size in bytes */ +#define MIC_SIZE (4U) /**< MIC size in bytes */ +#define CFLIST_SIZE (16U) /**< Channel Frequency list size in bytes */ + +#define GNRC_LORAWAN_MAX_CHANNELS (16U) /**< Maximum number of channels */ + +#define LORAWAN_STATE_IDLE (0) /**< MAC state machine in idle */ +#define LORAWAN_STATE_RX_1 (1) /**< MAC state machine in RX1 */ +#define LORAWAN_STATE_RX_2 (2) /**< MAC state machine in RX2 */ +#define LORAWAN_STATE_TX (3) /**< MAC state machine in TX */ + +#define GNRC_LORAWAN_DIR_UPLINK (0U) /**< uplink frame direction */ +#define GNRC_LORAWAN_DIR_DOWNLINK (1U) /**< downlink frame direction */ + +#define GNRC_LORAWAN_BACKOFF_WINDOW_TICK (3600000000LL) /**< backoff expire tick in usecs (set to 1 second) */ + +#define GNRC_LORAWAN_BACKOFF_BUDGET_1 (36000000LL) /**< budget of time on air during the first hour */ +#define GNRC_LORAWAN_BACKOFF_BUDGET_2 (36000000LL) /**< budget of time on air between 1-10 hours after boot */ +#define GNRC_LORAWAN_BACKOFF_BUDGET_3 (8700000LL) /**< budget of time on air every 24 hours */ + +#define GNRC_LORAWAN_MLME_OPTS_LINK_CHECK_REQ (1 << 0) /**< Internal Link Check request flag */ + +#define GNRC_LORAWAN_CID_SIZE (1U) /**< size of Command ID in FOps */ +#define GNRC_LORAWAN_CID_LINK_CHECK_ANS (0x02) /**< Link Check CID */ + +#define GNRC_LORAWAN_FOPT_LINK_CHECK_ANS_SIZE (3U) /**< size of Link check answer */ + +#define GNRC_LORAWAN_JOIN_DELAY_U32_MASK (0x1FFFFF) /**< mask for detecting overflow in frame counter */ + +#define GNRC_LORAWAN_MAX_PAYLOAD_1 (59U) /**< max MAC payload in DR0, DR1 and DR2 */ +#define GNRC_LORAWAN_MAX_PAYLOAD_2 (123U) /**< max MAC payload in DR3 */ +#define GNRC_LORAWAN_MAX_PAYLOAD_3 (250U) /**< max MAC payload above DR3 */ + +#define GNRC_LORAWAN_CFLIST_ENTRY_SIZE (3U) /**< size of Channel Frequency list */ +#define GNRC_LORAWAN_JOIN_ACCEPT_MAX_SIZE (33U) /**< max size of Join Accept frame */ + +#define GNRC_LORAWAN_BACKOFF_STATE_1 (0U) /**< backoff state during the first hour after boot */ +#define GNRC_LORAWAN_BACKOFF_STATE_2 (1U) /**< backoff state between 1-10 hours after boot */ +#define GNRC_LORAWAN_BACKOFF_STATE_3 (2U) /**< backoff state past 11 hours after boot */ + +#define GNRC_LORAWAN_BACKOFF_TIME_1 (1U) /**< duration of first backoff state (in hours) */ +#define GNRC_LORAWAN_BACKOFF_TIME_2 (10U) /**< duration of second backoff state (in hours) */ +#define GNRC_LORAWAN_BACKOFF_TIME_3 (24U) /**< duration of third backoff state (in hours) */ + +#define GNRC_LORAWAN_APP_NONCE_SIZE (3U) /**< App Nonce size */ +#define GNRC_LORAWAN_NET_ID_SIZE (3U) /**< Net ID size */ +#define GNRC_LORAWAN_DEV_NONCE_SIZE (2U) /**< Dev Nonce size */ + +/** + * @brief buffer helper for parsing and constructing LoRaWAN packets. + */ +typedef struct { + uint8_t *data; /**< pointer to the beginning of the buffer holding data */ + uint8_t size; /**< size of the buffer */ + uint8_t index; /**< current inxed in the buffer */ +} lorawan_buffer_t; + +/** + * @brief MLME Join Request data + */ +typedef struct { + void *deveui; /**< pointer to the Device EUI */ + void *appeui; /**< pointer to the Application EUI */ + void *appkey; /**< pointer to the Application Key */ + uint8_t dr; /**< datarate for the Join Request */ +} mlme_lorawan_join_t; + +/** + * @brief MLME Link Check confirmation data + */ +typedef struct { + uint8_t margin; /**< demodulation margin (in dB) */ + uint8_t num_gateways; /**< number of gateways */ +} mlme_link_req_confirm_t; + +/** + * @brief MCPS data + */ +typedef struct { + gnrc_pktsnip_t *pkt; /**< packet of the request */ + uint8_t port; /**< port of the request */ + uint8_t dr; /**< datarate of the request */ +} mcps_data_t; + +/** + * @brief MCPS service access point descriptor + */ +typedef struct { + uint32_t fcnt; /**< uplink framecounter */ + uint32_t fcnt_down; /**< downlink frame counter */ + gnrc_pktsnip_t *outgoing_pkt; /**< holds the outgoing packet in case of retransmissions */ + int nb_trials; /**< holds the remaining number of retransmissions */ + int ack_requested; /**< wether the network server requested an ACK */ + int waiting_for_ack; /**< true if the MAC layer is waiting for an ACK */ +} gnrc_lorawan_mcps_t; + +/** + * @brief MLME service access point descriptor + */ +typedef struct { + xtimer_t backoff_timer; /**< timer used for backoff expiration */ + msg_t backoff_msg; /**< msg for backoff expiration */ + uint8_t activation; /**< Activation mechanism of the MAC layer */ + int pending_mlme_opts; /**< holds pending mlme opts */ + uint32_t nid; /**< current Network ID */ + int32_t backoff_budget; /**< remaining Time On Air budget */ + uint8_t dev_nonce[2]; /**< Device Nonce */ + uint8_t backoff_state; /**< state in the backoff state machine */ +} gnrc_lorawan_mlme_t; + +/** + * @brief GNRC LoRaWAN mac descriptor */ +typedef struct { + netdev_t netdev; /**< netdev for the MAC layer */ + xtimer_t rx; /**< RX timer */ + msg_t msg; /**< MAC layer message descriptor */ + gnrc_lorawan_mcps_t mcps; /**< MCPS descriptor */ + gnrc_lorawan_mlme_t mlme; /**< MLME descriptor */ + void *mlme_buf; /**< pointer to MLME buffer */ + void *mcps_buf; /**< pointer to MCPS buffer */ + uint8_t *nwkskey; /**< pointer to Network SKey buffer */ + uint8_t *appskey; /**< pointer to Application SKey buffer */ + uint32_t channel[GNRC_LORAWAN_MAX_CHANNELS]; /**< channel array */ + uint32_t toa; /**< Time on Air of the last transmission */ + int busy; /**< MAC busy */ + int shutdown_req; /**< MAC Shutdown request */ + le_uint32_t dev_addr; /**< Device address */ + int state; /**< state of MAC layer */ + uint8_t dl_settings; /**< downlink settings */ + uint8_t rx_delay; /**< Delay of first reception window */ + uint8_t dr_range[GNRC_LORAWAN_MAX_CHANNELS]; /**< Datarate Range for all channels */ + uint8_t last_dr; /**< datarate of the last transmission */ +} gnrc_lorawan_t; + +/** + * @brief Encrypts LoRaWAN payload + * + * @note This function is also used for decrypting a LoRaWAN packet. The LoRaWAN server encrypts the packet using decryption, so the end device only needs to implement encryption + * + * @param[in] iolist packet iolist representation + * @param[in] dev_addr device address + * @param[in] fcnt frame counter + * @param[in] dir direction of the packet (0 if uplink, 1 if downlink) + * @param[in] appskey pointer to the Application Session Key + */ +void gnrc_lorawan_encrypt_payload(iolist_t *iolist, const le_uint32_t *dev_addr, uint32_t fcnt, uint8_t dir, const uint8_t *appskey); + +/** + * @brief Decrypts join accept message + * + * @param[in] key key to be used in the decryption + * @param[in] pkt pointer to Join Accept MAC component (next byte after the MHDR) + * @param[in] has_clist true if the Join Accept frame has CFList + * @param[out] out buffer where the decryption is stored + */ +void gnrc_lorawan_decrypt_join_accept(const uint8_t *key, uint8_t *pkt, int has_clist, uint8_t *out); + +/** + * @brief Generate LoRaWAN session keys + * + * Intended to be called after a successfull Join Request in order to generate + * NwkSKey and AppSKey + * + * @param[in] app_nonce pointer to the app_nonce of the Join Accept message + * @param[in] dev_nonce pointer to the dev_nonce buffer + * @param[in] appkey pointer to eh AppKey + * @param[out] nwkskey pointer to the NwkSKey + * @param[out] appskey pointer to the AppSKey + */ +void gnrc_lorawan_generate_session_keys(const uint8_t *app_nonce, const uint8_t *dev_nonce, const uint8_t *appkey, uint8_t *nwkskey, uint8_t *appskey); + +/** + * @brief Set datarate for the next transmission + * + * @param[in] mac pointer to the MAC descriptor + * @param[in] datarate desired datarate + * + * @return 0 on success + * @return -EINVAL if datarate is not available in the current region + */ +int gnrc_lorawan_set_dr(gnrc_lorawan_t *mac, uint8_t datarate); + +/** + * @brief build uplink frame + * + * @param[in] mac pointer to MAC descriptor + * @param[in] payload packet containing payload + * @param[in] confirmed_data true if confirmed frame + * @param[in] port MAC port + * + * @return full LoRaWAN frame including payload + * @return NULL if packet buffer is full. `payload` is released + */ +gnrc_pktsnip_t *gnrc_lorawan_build_uplink(gnrc_lorawan_t *mac, gnrc_pktsnip_t *payload, int confirmed_data, uint8_t port); + +/** + * @brief pick a random available LoRaWAN channel + * + * @param[in] mac pointer to the MAC descriptor + * + * @return a free channel + */ +uint32_t gnrc_lorawan_pick_channel(gnrc_lorawan_t *mac); + +/** + * @brief Build fopts header + * + * @param[in] mac pointer to MAC descriptor + * @param[out] buf destination buffer of fopts. If NULL, this function just returns + * the size of the expected fopts frame. + * + * @return size of the fopts frame + */ +uint8_t gnrc_lorawan_build_options(gnrc_lorawan_t *mac, lorawan_buffer_t *buf); + +/** + * @brief Process an fopts frame + * + * @param[in] mac pointer to MAC descriptor + * @param[in] fopts pointer to fopts frame + * @param[in] size size of fopts frame + */ +void gnrc_lorawan_process_fopts(gnrc_lorawan_t *mac, uint8_t *fopts, size_t size); + +/** + * @brief calculate join Message Integrity Code + * + * @param[in] io iolist representation of the packet + * @param[in] key key used to calculate the MIC + * @param[out] out calculated MIC + */ +void gnrc_lorawan_calculate_join_mic(const iolist_t *io, const uint8_t *key, le_uint32_t *out); + +/** + * @brief Calculate Message Integrity Code for a MCPS message + * + * @param[in] dev_addr the Device Address + * @param[in] fcnt frame counter + * @param[in] dir direction of the packet (0 is uplink, 1 is downlink) + * @param[in] pkt the pkt + * @param[in] nwkskey pointer to the Network Session Key + * @param[out] out calculated MIC + */ +void gnrc_lorawan_calculate_mic(const le_uint32_t *dev_addr, uint32_t fcnt, + uint8_t dir, iolist_t *pkt, const uint8_t *nwkskey, le_uint32_t *out); + +/** + * @brief Build a MCPS LoRaWAN header + * + * @param[in] mtype the MType of the header + * @param[in] dev_addr the Device Address + * @param[in] fcnt frame counter + * @param[in] ack true if ACK bit is set + * @param[in] fopts_length the length of the FOpts field + * @param[out] buf destination buffer of the hdr + * + * @return the size of the header + */ +size_t gnrc_lorawan_build_hdr(uint8_t mtype, le_uint32_t *dev_addr, uint32_t fcnt, uint8_t ack, uint8_t fopts_length, lorawan_buffer_t *buf); + +/** + * @brief Process an MCPS downlink message (confirmable or non comfirmable) + * + * @param[in] mac pointer to the MAC descriptor + * @param[in] pkt pointer to the downlink message + */ +void gnrc_lorawan_mcps_process_downlink(gnrc_lorawan_t *mac, gnrc_pktsnip_t *pkt); + +/** + * @brief Init regional channel settings. + * + * Intended to be called upon initialization + * + * @param[in] mac pointer to the MAC descriptor + */ +void gnrc_lorawan_channels_init(gnrc_lorawan_t *mac); + +/** + * @brief Reset MAC parameters + * + * @note This doesn't affect backoff timers variables. + * + * @param[in] mac pointer to the MAC layer + */ +void gnrc_lorawan_reset(gnrc_lorawan_t *mac); + +/** + * @brief Send a LoRaWAN packet + * + * @param[in] mac pointer to the MAC descriptor + * @param[in] pkt the packet to be sent + * @param[in] dr the datarate used for the transmission + */ +void gnrc_lorawan_send_pkt(gnrc_lorawan_t *mac, gnrc_pktsnip_t *pkt, uint8_t dr); + +/** + * @brief Process join accept message + * + * @param[in] mac pointer to the MAC descriptor + * @param[in] pkt the Join Accept packet + */ +void gnrc_lorawan_mlme_process_join(gnrc_lorawan_t *mac, gnrc_pktsnip_t *pkt); + +/** + * @brief Inform the MAC layer that no packet was received during reception. + * + * To be called when the radio reports "NO RX" after the second reception + * window + * + * @param[in] mac pointer to the MAC descriptor + */ +void gnrc_lorawan_mlme_no_rx(gnrc_lorawan_t *mac); + +/** + * @brief Trigger a MCPS event + * + * @param[in] mac pointer to the MAC descriptor + * @param[in] event the event to be processed. + * @param[in] data set to true if the packet contains payload + */ +void gnrc_lorawan_mcps_event(gnrc_lorawan_t *mac, int event, int data); + +/** + * @brief Get the maximum MAC payload (M value) for a given datarate. + * + * @note This function is region specific + * + * @param[in] datarate datarate + * + * @return the maximum allowed size of the packet + */ +uint8_t gnrc_lorawan_region_mac_payload_max(uint8_t datarate); + +/** + * @brief MLME Backoff expiration tick + * + * Should be called every hour in order to maintain the Time On Air budget. + * + * @param[in] mac pointer to the MAC descriptor + */ +void gnrc_lorawan_mlme_backoff_expire(gnrc_lorawan_t *mac); + +/** + * @brief Process and dispatch a full LoRaWAN packet + * + * Intended to be called right after reception from the radio + * + * @param[in] mac pointer to the MAC descriptor + * @param[in] pkt the received packet + */ +void gnrc_lorawan_process_pkt(gnrc_lorawan_t *mac, gnrc_pktsnip_t *pkt); + +/** + * @brief Open a reception window + * + * This is called by the MAC layer on timeout event. + * + * @param[in] mac pointer to the MAC descriptor + */ +void gnrc_lorawan_open_rx_window(gnrc_lorawan_t *mac); + +/** + * @brief save internal MAC state in non-volatile storage and shutdown + * the MAC layer gracefully. + * + * @param mac + */ +void gnrc_lorawan_perform_save(gnrc_lorawan_t *mac); + +/** + * @brief Acquire the MAC layer + * + * @param[in] mac pointer to the MAC descriptor + * + * @return true on success + * @return false if MAC is already acquired + */ +static inline int gnrc_lorawan_mac_acquire(gnrc_lorawan_t *mac) +{ + int _c = mac->busy; + + mac->busy = true; + return !_c; +} + +/** + * @brief Release the MAC layer + * + * @param[in] mac pointer to the MAC descriptor + */ +static inline void gnrc_lorawan_mac_release(gnrc_lorawan_t *mac) +{ + mac->busy = false; +} + +/** + * @brief Allocate memory to hold a GNRC LoRaWAN MCPS request + * + * @param[in] mac pointer to the MAC descriptor + * + * @return pointer the allocated buffer + */ +static inline void *gnrc_lorawan_mcps_allocate(gnrc_lorawan_t *mac) +{ + mac->netdev.event_callback((netdev_t *) mac, NETDEV_EVENT_MCPS_GET_BUFFER); + return mac->mcps_buf; +} + +/** + * @brief Allocate memory to hold a GNRC LoRaWAN MLME request + * + * @param[in] mac pointer to the MAC descriptor + * + * @return pointer the allocated buffer + */ +static inline void *gnrc_lorawan_mlme_allocate(gnrc_lorawan_t *mac) +{ + mac->netdev.event_callback((netdev_t *) mac, NETDEV_EVENT_MLME_GET_BUFFER); + return mac->mlme_buf; +} + + +#ifdef __cplusplus +} +#endif + +#endif /* GNRC_LORAWAN_INTERNAL_H */ +/** @} */