diff --git a/CMakeLists.txt b/CMakeLists.txt index ecf33c6b..76b23b06 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -775,11 +775,13 @@ target_sources( ${CMAKE_CURRENT_LIST_DIR}/src/coap_block.c ${CMAKE_CURRENT_LIST_DIR}/src/coap_cache.c ${CMAKE_CURRENT_LIST_DIR}/src/coap_debug.c + ${CMAKE_CURRENT_LIST_DIR}/src/coap_dgrm_posix.c ${CMAKE_CURRENT_LIST_DIR}/src/coap_dtls.c ${CMAKE_CURRENT_LIST_DIR}/src/coap_encode.c ${CMAKE_CURRENT_LIST_DIR}/src/coap_event.c ${CMAKE_CURRENT_LIST_DIR}/src/coap_hashkey.c ${CMAKE_CURRENT_LIST_DIR}/src/coap_io.c + ${CMAKE_CURRENT_LIST_DIR}/src/coap_io_posix.c ${CMAKE_CURRENT_LIST_DIR}/src/coap_layers.c ${CMAKE_CURRENT_LIST_DIR}/src/coap_mem.c ${CMAKE_CURRENT_LIST_DIR}/src/coap_net.c @@ -794,8 +796,8 @@ target_sources( ${CMAKE_CURRENT_LIST_DIR}/src/coap_session.c ${CMAKE_CURRENT_LIST_DIR}/src/coap_sha1.c ${CMAKE_CURRENT_LIST_DIR}/src/coap_str.c + ${CMAKE_CURRENT_LIST_DIR}/src/coap_strm_posix.c ${CMAKE_CURRENT_LIST_DIR}/src/coap_subscribe.c - ${CMAKE_CURRENT_LIST_DIR}/src/coap_tcp.c ${CMAKE_CURRENT_LIST_DIR}/src/coap_threadsafe.c ${CMAKE_CURRENT_LIST_DIR}/src/coap_time.c ${CMAKE_CURRENT_LIST_DIR}/src/coap_uri.c diff --git a/Makefile.am b/Makefile.am index 9c918ea1..5d3c0641 100644 --- a/Makefile.am +++ b/Makefile.am @@ -133,6 +133,12 @@ EXTRA_DIST = \ src/coap_io_contiki.c \ src/coap_io_lwip.c \ src/coap_io_riot.c \ + src/coap_dgrm_contiki.c \ + src/coap_dgrm_lwip.c \ + src/coap_dgrm_riot.c \ + src/coap_strm_contiki.c \ + src/coap_strm_lwip.c \ + src/coap_strm_riot.c \ tests/test_common.h \ tests/test_error_response.h \ tests/test_encode.h \ @@ -193,12 +199,14 @@ libcoap_@LIBCOAP_NAME_SUFFIX@_la_SOURCES = \ src/coap_block.c \ src/coap_cache.c \ src/coap_debug.c \ + src/coap_dgrm_posix.c \ src/coap_dtls.c \ src/coap_encode.c \ src/coap_event.c \ src/coap_hashkey.c \ src/coap_gnutls.c \ src/coap_io.c \ + src/coap_io_posix.c \ src/coap_layers.c \ src/coap_mbedtls.c \ src/coap_mem.c \ @@ -215,8 +223,8 @@ libcoap_@LIBCOAP_NAME_SUFFIX@_la_SOURCES = \ src/coap_session.c \ src/coap_sha1.c \ src/coap_str.c \ + src/coap_strm_posix.c \ src/coap_subscribe.c \ - src/coap_tcp.c \ src/coap_threadsafe.c \ src/coap_time.c \ src/coap_tinydtls.c \ diff --git a/Makefile.libcoap b/Makefile.libcoap index c181ed2e..4fa431e4 100644 --- a/Makefile.libcoap +++ b/Makefile.libcoap @@ -2,4 +2,11 @@ LIBCOAP_DIR = os/net/app-layer/libcoap MODULES += $(LIBCOAP_DIR)/src MODULES += $(LIBCOAP_DIR)/include MODULES_SOURCES_EXCLUDES += coap_io_riot.c +MODULES_SOURCES_EXCLUDES += coap_strm_riot.c +MODULES_SOURCES_EXCLUDES += coap_dgrm_riot.c MODULES_SOURCES_EXCLUDES += coap_io_lwip.c +MODULES_SOURCES_EXCLUDES += coap_strm_lwip.c +MODULES_SOURCES_EXCLUDES += coap_dgrm_lwip.c +MODULES_SOURCES_EXCLUDES += coap_io_posix.c +MODULES_SOURCES_EXCLUDES += coap_strm_posix.c +MODULES_SOURCES_EXCLUDES += coap_dgrm_posix.c diff --git a/examples/lwip/Makefile b/examples/lwip/Makefile index 1fda4ba4..a631215f 100644 --- a/examples/lwip/Makefile +++ b/examples/lwip/Makefile @@ -150,6 +150,7 @@ COAP_SRC = coap_address.c \ coap_block.c \ coap_cache.c \ coap_debug.c \ + coap_dgrm_lwip.c \ coap_dtls.c \ coap_encode.c \ coap_hashkey.c \ @@ -168,8 +169,8 @@ COAP_SRC = coap_address.c \ coap_session.c \ coap_sha1.c \ coap_str.c \ + coap_strm_lwip.c \ coap_subscribe.c \ - coap_tcp.c \ coap_threadsafe.c \ coap_tinydtls.c \ coap_uri.c \ diff --git a/examples/riot/pkg_libcoap/Makefile.libcoap b/examples/riot/pkg_libcoap/Makefile.libcoap index ca00aa5b..08af89dd 100644 --- a/examples/riot/pkg_libcoap/Makefile.libcoap +++ b/examples/riot/pkg_libcoap/Makefile.libcoap @@ -6,6 +6,7 @@ SRC := coap_address.c \ coap_block.c \ coap_cache.c \ coap_debug.c \ + coap_dgrm_riot.c \ coap_dtls.c \ coap_encode.c \ coap_event.c \ @@ -29,8 +30,8 @@ SRC := coap_address.c \ coap_session.c \ coap_sha1.c \ coap_str.c \ + coap_strm_riot.c \ coap_subscribe.c \ - coap_tcp.c \ coap_threadsafe.c \ coap_tinydtls.c \ coap_uri.c \ diff --git a/include/coap3/coap_dgrm_internal.h b/include/coap3/coap_dgrm_internal.h index 4ee65abf..9ee446f2 100644 --- a/include/coap3/coap_dgrm_internal.h +++ b/include/coap3/coap_dgrm_internal.h @@ -113,14 +113,15 @@ ssize_t coap_socket_send(coap_socket_t *sock, coap_session_t *session, */ ssize_t coap_socket_recv(coap_socket_t *sock, coap_packet_t *packet); - /** - * Function interface to close off a socket (for both TCP and UDP). + * Function interface to close off a datagram socket. + * + * Internal function. * * @param sock Socket to close. * */ -void coap_socket_close(coap_socket_t *sock); +void coap_socket_dgrm_close(coap_socket_t *sock); /** @} */ diff --git a/include/coap3/coap_io_internal.h b/include/coap3/coap_io_internal.h index c7f90201..97aceb34 100644 --- a/include/coap3/coap_io_internal.h +++ b/include/coap3/coap_io_internal.h @@ -97,6 +97,10 @@ void coap_mfree_endpoint(coap_endpoint_t *ep); const char *coap_socket_format_errno(int error); +#ifdef _WIN32 +void coap_win_error_to_errno(void); +#endif /* _WIN32 */ + /** * Epoll specific function to add the state of events that epoll is to track * for the appropriate file descriptor. diff --git a/include/coap3/coap_netif_internal.h b/include/coap3/coap_netif_internal.h index bbeb27c6..9cf92aff 100644 --- a/include/coap3/coap_netif_internal.h +++ b/include/coap3/coap_netif_internal.h @@ -116,6 +116,13 @@ ssize_t coap_netif_dgrm_read_ep(coap_endpoint_t *endpoint, ssize_t coap_netif_dgrm_write(coap_session_t *session, const uint8_t *data, size_t datalen); +/** + * Layer function interface for netif datagram close for a session. + * + * @param session Session to do the netif datagram close on. + */ +void coap_netif_dgrm_close(coap_session_t *session); + /** * Layer function interface for Netif stream listem (tcp). * @@ -195,11 +202,11 @@ ssize_t coap_netif_strm_write(coap_session_t *session, const uint8_t *data, size_t datalen); /** - * Layer function interface for Netif close for a session. + * Layer function interface for netif stream close for a session. * - * @param session Session to do the netif close on. + * @param session Session to do the netif stream close on. */ -void coap_netif_close(coap_session_t *session); +void coap_netif_strm_close(coap_session_t *session); /** * Layer function interface for Netif close for a endpoint. diff --git a/include/coap3/coap_strm_internal.h b/include/coap3/coap_strm_internal.h index 528b4c91..2888e122 100644 --- a/include/coap3/coap_strm_internal.h +++ b/include/coap3/coap_strm_internal.h @@ -131,6 +131,16 @@ ssize_t coap_socket_write(coap_socket_t *sock, const uint8_t *data, size_t data_ */ ssize_t coap_socket_read(coap_socket_t *sock, uint8_t *data, size_t data_len); +/** + * Function interface to close off a stream socket. + * + * Internal function. + * + * @param sock Socket to close. + * + */ +void coap_socket_strm_close(coap_socket_t *sock); + #endif /* !COAP_DISABLE_TCP */ /** @} */ diff --git a/src/coap_dgrm_contiki.c b/src/coap_dgrm_contiki.c new file mode 100644 index 00000000..2d4edf2b --- /dev/null +++ b/src/coap_dgrm_contiki.c @@ -0,0 +1,154 @@ +/* coap_dgrm_contiki.c -- UDP Network I/O functions for libcoap on Contiki-NG + * + * Copyright (C) 2012,2014,2024-2025 Olaf Bergmann + * 2014 chrysn + * + * SPDX-License-Identifier: BSD-2-Clause + * + * This file is part of the CoAP library libcoap. Please see + * README for terms of use. + */ + +/** + * @file coap_dgrm_contiki.c + * @brief Contiki-NG-specific Datagram (UDP) functions + */ + +#include "coap3/coap_libcoap_build.h" +#include "contiki-net.h" + +extern struct process libcoap_io_process; + +int +coap_socket_bind_udp(coap_socket_t *sock, + const coap_address_t *listen_addr, + coap_address_t *bound_addr) { + uip_ds6_addr_t *addr; + + addr = uip_ds6_get_global(ADDR_PREFERRED); + if (!addr) { + coap_log_err("coap_socket_bind_udp: called before getting an IPv6 address\n"); + return 0; + } + PROCESS_CONTEXT_BEGIN(&libcoap_io_process); + sock->udp_conn = udp_new(NULL, 0, sock); + PROCESS_CONTEXT_END(&libcoap_io_process); + if (!sock->udp_conn) { + coap_log_err("coap_socket_bind_udp: udp_new returned NULL\n"); + return 0; + } + udp_bind(sock->udp_conn, listen_addr->port); + uip_ipaddr_copy(&bound_addr->addr, &addr->ipaddr); + bound_addr->port = sock->udp_conn->lport; + return 1; +} + +int +coap_socket_connect_udp(coap_socket_t *sock, + const coap_address_t *local_if, + const coap_address_t *server, + int default_port, + coap_address_t *local_addr, + coap_address_t *remote_addr) { + uip_ds6_addr_t *addr; + + if (local_if) { + coap_log_warn("coap_socket_connect_udp: ignoring local_if parameter\n"); + } + addr = uip_ds6_get_global(ADDR_PREFERRED); + if (!addr) { + coap_log_err("coap_socket_connect_udp: called before getting an IPv6 address\n"); + return 0; + } + PROCESS_CONTEXT_BEGIN(&libcoap_io_process); + sock->udp_conn = udp_new(&server->addr, server->port ? server->port : default_port, sock); + PROCESS_CONTEXT_END(&libcoap_io_process); + if (!sock->udp_conn) { + coap_log_err("coap_socket_connect_udp: udp_new returned NULL\n"); + return 0; + } + uip_ipaddr_copy(&local_addr->addr, &addr->ipaddr); + local_addr->port = sock->udp_conn->lport; + uip_ipaddr_copy(&remote_addr->addr, &server->addr); + remote_addr->port = sock->udp_conn->rport; + sock->flags |= COAP_SOCKET_CONNECTED; + return 1; +} + +ssize_t +coap_socket_write(coap_socket_t *sock, const uint8_t *data, size_t data_len) { + return -1; +} + +ssize_t +coap_socket_read(coap_socket_t *sock, uint8_t *data, size_t data_len) { + return -1; +} + +void +coap_socket_dgrm_close(coap_socket_t *sock) { + uip_udp_remove(sock->udp_conn); + sock->udp_conn = NULL; + sock->flags = COAP_SOCKET_EMPTY; +} + +/* + * dgram + * return +ve Number of bytes written. + * -1 Error error in errno). + */ +ssize_t +coap_socket_send(coap_socket_t *sock, coap_session_t *session, const uint8_t *data, + size_t datalen) { + ssize_t bytes_written = 0; + + if (!coap_debug_send_packet()) { + bytes_written = (ssize_t)datalen; + } else { + uip_udp_packet_sendto(sock->udp_conn, data, datalen, + &session->addr_info.remote.addr, session->addr_info.remote.port); + bytes_written = datalen; + } + + if (bytes_written < 0) { + coap_log_crit("coap_socket_send: %s\n", coap_socket_strerror()); + } + + return bytes_written; +} + +/* + * dgram + * return +ve Number of bytes written. + * -1 Error error in errno). + * -2 ICMP error response + */ +ssize_t +coap_socket_recv(coap_socket_t *sock, coap_packet_t *packet) { + ssize_t len; + + assert(sock); + assert(packet); + + if (!(sock->flags & COAP_SOCKET_CAN_READ)) { + return -1; + } + /* clear has-data flag */ + sock->flags &= ~COAP_SOCKET_CAN_READ; + + uip_ipaddr_copy(&packet->addr_info.remote.addr, &UIP_IP_BUF->srcipaddr); + packet->addr_info.remote.port = UIP_UDP_BUF->srcport; + uip_ipaddr_copy(&packet->addr_info.local.addr, &UIP_IP_BUF->destipaddr); + packet->addr_info.local.port = UIP_UDP_BUF->destport; + + len = uip_datalen(); + + if (len > COAP_RXBUFFER_SIZE) { + coap_log_warn("Received message does not fit within buffer\n"); + return -1; + } + packet->length = len; + packet->payload = uip_appdata; + + return len; +} diff --git a/src/coap_dgrm_lwip.c b/src/coap_dgrm_lwip.c new file mode 100644 index 00000000..1a4e0fef --- /dev/null +++ b/src/coap_dgrm_lwip.c @@ -0,0 +1,441 @@ +/* + * Copyright (C) 2012,2014 Olaf Bergmann + * 2014 chrysn + * 2022-2025 Jon Shallow + * + * SPDX-License-Identifier: BSD-2-Clause + * + * This file is part of the CoAP library libcoap. Please see + * README for terms of use. + */ + +/** + * @file coap_dgrm_lwip.c + * @brief LwIP Datagram (UDP) specific functions + */ + +#include "coap3/coap_libcoap_build.h" +#include +#include +#include + +#if ! COAP_DISABLE_TCP +#include +#endif /* !COAP_DISABLE_TCP */ + +#if NO_SYS == 0 +extern sys_sem_t coap_io_timeout_sem; +#endif /* NO_SYS == 0 */ + +/* + * Not used for LwIP (done with coap_recvc()), but need dummy function. + */ +ssize_t +coap_socket_recv(coap_socket_t *sock, coap_packet_t *packet) { + (void)sock; + (void)packet; + assert(0); + return -1; +} + +#if COAP_CLIENT_SUPPORT +/** Callback from lwIP when a package was received for a client. + * + * The current implementation deals this to coap_dispatch immediately, but + * other mechanisms (as storing the package in a queue and later fetching it + * when coap_io_do_io is called) can be envisioned. + * + * It handles everything coap_io_do_io does on other implementations. + */ +static void +coap_recvc(void *arg, struct udp_pcb *upcb, struct pbuf *p, + const ip_addr_t *addr, u16_t port) { + coap_pdu_t *pdu = NULL; + coap_session_t *session = (coap_session_t *)arg; + int result = -1; + (void)upcb; + + assert(session); + LWIP_ASSERT("Proto not supported for LWIP", COAP_PROTO_NOT_RELIABLE(session->proto)); + + if (p->len < 4) { + /* Minimum size of CoAP header - ignore runt */ + return; + } + coap_lock_lock(return); + memcpy(&session->addr_info.remote.addr, addr, sizeof(session->addr_info.remote.addr)); + coap_address_set_port(&session->addr_info.remote, port); + + coap_log_debug("* %s: lwip: recv %4d bytes\n", + coap_session_str(session), p->len); + if (session->proto == COAP_PROTO_DTLS) { + if (session->tls) { + result = coap_dtls_receive(session, p->payload, p->len); + if (result < 0) + goto error; + } + pbuf_free(p); + } else { + coap_opt_filter_t error_opts; + + pdu = coap_pdu_from_pbuf(p); + if (!pdu) + goto error; + + coap_option_filter_clear(&error_opts); + if (!coap_pdu_parse2(session->proto, p->payload, p->len, pdu, &error_opts)) { + coap_handle_event_lkd(session->context, COAP_EVENT_BAD_PACKET, session); + coap_log_warn("discard malformed PDU\n"); + if (error_opts.mask && COAP_PDU_IS_REQUEST(pdu)) { + coap_pdu_t *response = + coap_new_error_response(pdu, + COAP_RESPONSE_CODE(402), &error_opts); + if (!response) { + coap_log_warn("coap_handle_dgram: cannot create error response\n"); + } else { + if (coap_send_internal(session, response, NULL) == COAP_INVALID_MID) + coap_log_warn("coap_handle_dgram: error sending response\n"); + } + coap_delete_pdu_lkd(pdu); + coap_lock_unlock(); +#if NO_SYS == 0 + sys_sem_signal(&coap_io_timeout_sem); +#endif /* NO_SYS == 0 */ + return; + } else { + goto error; + } + } + coap_dispatch(session->context, session, pdu); + } +#if NO_SYS == 0 + sys_sem_signal(&coap_io_timeout_sem); +#endif /* NO_SYS == 0 */ + coap_delete_pdu_lkd(pdu); + coap_lock_unlock(); + return; + +error: + /* + * https://rfc-editor.org/rfc/rfc7252#section-4.2 MUST send RST + * https://rfc-editor.org/rfc/rfc7252#section-4.3 MAY send RST + */ + if (session) + coap_send_rst_lkd(session, pdu); + coap_delete_pdu_lkd(pdu); + coap_lock_unlock(); +#if NO_SYS == 0 + sys_sem_signal(&coap_io_timeout_sem); +#endif /* NO_SYS == 0 */ + return; +} +#endif /* ! COAP_CLIENT_SUPPORT */ + +#if COAP_SERVER_SUPPORT + +static void +coap_free_packet(coap_packet_t *packet) { + coap_free_type(COAP_PACKET, packet); +} + +/** Callback from lwIP when a UDP packet was received for a server. + * + * The current implementation deals this to coap_dispatch immediately, but + * other mechanisms (as storing the package in a queue and later fetching it + * when coap_io_do_io is called) can be envisioned. + * + * It handles everything coap_io_do_io does on other implementations. + */ +static void +coap_udp_recvs(void *arg, struct udp_pcb *upcb, struct pbuf *p, + const ip_addr_t *addr, u16_t port) { + coap_endpoint_t *ep = (coap_endpoint_t *)arg; + coap_pdu_t *pdu = NULL; + coap_session_t *session = NULL; + coap_tick_t now; + coap_packet_t *packet = NULL; + int result = -1; + + if (p->len < 4) { + /* Minimum size of CoAP header - ignore runt */ + goto error_free_pbuf; + } + + packet = coap_malloc_type(COAP_PACKET, sizeof(coap_packet_t)); + + /* this is fatal because due to the short life of the packet, never should + there be more than one coap_packet_t required */ + LWIP_ASSERT("Insufficient coap_packet_t resources.", packet != NULL); + /* Need to do this as there may be holes in addr_info */ + memset(&packet->addr_info, 0, sizeof(packet->addr_info)); + packet->length = p->len; + packet->payload = p->payload; + packet->addr_info.remote.port = port; + packet->addr_info.remote.addr = *addr; + packet->addr_info.local.port = upcb->local_port; + packet->addr_info.local.addr = *ip_current_dest_addr(); + packet->ifindex = netif_get_index(ip_current_netif()); + + coap_ticks(&now); + + coap_lock_lock(goto error_free_pbuf); + session = coap_endpoint_get_session(ep, packet, now); + if (!session) + goto error_free_pbuf; + LWIP_ASSERT("Proto not supported for LWIP", COAP_PROTO_NOT_RELIABLE(session->proto)); + + coap_log_debug("* %s: lwip: recv %4d bytes\n", + coap_session_str(session), p->len); + + if (session->proto == COAP_PROTO_DTLS) { + if (session->type == COAP_SESSION_TYPE_HELLO) + result = coap_dtls_hello(session, p->payload, p->len); + else if (session->tls) + result = coap_dtls_receive(session, p->payload, p->len); + if (session->type == COAP_SESSION_TYPE_HELLO && result == 1) + coap_session_new_dtls_session(session, now); + pbuf_free(p); + } else { + coap_opt_filter_t error_opts; + + pdu = coap_pdu_from_pbuf(p); + if (!pdu) + goto error; + + coap_option_filter_clear(&error_opts); + if (!coap_pdu_parse2(ep->proto, p->payload, p->len, pdu, &error_opts)) { + coap_handle_event_lkd(ep->context, COAP_EVENT_BAD_PACKET, session); + coap_log_warn("discard malformed PDU\n"); + if (error_opts.mask && COAP_PDU_IS_REQUEST(pdu)) { + coap_pdu_t *response = + coap_new_error_response(pdu, + COAP_RESPONSE_CODE(402), &error_opts); + if (!response) { + coap_log_warn("coap_handle_dgram: cannot create error response\n"); + } else { + if (coap_send_internal(session, response, NULL) == COAP_INVALID_MID) + coap_log_warn("coap_handle_dgram: error sending response\n"); + } + goto cleanup; + } else { + goto error; + } + } + coap_dispatch(ep->context, session, pdu); + } + + coap_delete_pdu_lkd(pdu); + coap_free_packet(packet); + coap_lock_unlock(); +#if NO_SYS == 0 + sys_sem_signal(&coap_io_timeout_sem); +#endif /* NO_SYS == 0 */ + return; + +error_free_pbuf: + pbuf_free(p); + +error: + /* + * https://rfc-editor.org/rfc/rfc7252#section-4.2 MUST send RST + * https://rfc-editor.org/rfc/rfc7252#section-4.3 MAY send RST + */ + if (session && pdu) + coap_send_rst_lkd(session, pdu); +cleanup: + coap_delete_pdu_lkd(pdu); + coap_free_packet(packet); + coap_lock_unlock(); +#if NO_SYS == 0 + sys_sem_signal(&coap_io_timeout_sem); +#endif /* NO_SYS == 0 */ + return; +} + +#endif /* ! COAP_SERVER_SUPPORT */ + +ssize_t +coap_socket_send_pdu(coap_socket_t *sock, coap_session_t *session, + coap_pdu_t *pdu) { + /* FIXME: we can't check this here with the existing infrastructure, but we + * should actually check that the pdu is not held by anyone but us. the + * respective pbuf is already exclusively owned by the pdu. */ + struct pbuf *pbuf; + int err; + + pbuf_realloc(pdu->pbuf, pdu->used_size + coap_pdu_parse_header_size(session->proto, + pdu->pbuf->payload)); + + if (coap_debug_send_packet()) { + /* Need to take a copy as we may be re-using the origin in a retransmit */ + pbuf = pbuf_clone(PBUF_TRANSPORT, PBUF_RAM, pdu->pbuf); + if (pbuf == NULL) + return -1; + err = udp_sendto(sock->udp_pcb, pbuf, &session->addr_info.remote.addr, + session->addr_info.remote.port); + pbuf_free(pbuf); + if (err < 0) + return -1; + } + return pdu->used_size; +} + +/* + * dgram + * return +ve Number of bytes written. + * -1 Error error in errno). + */ +ssize_t +coap_socket_send(coap_socket_t *sock, coap_session_t *session, + const uint8_t *data, size_t data_len) { + struct pbuf *pbuf; + int err; + + if (coap_debug_send_packet()) { + pbuf = pbuf_alloc(PBUF_TRANSPORT, data_len, PBUF_RAM); + if (pbuf == NULL) + return -1; + memcpy(pbuf->payload, data, data_len); + + coap_lock_invert(LOCK_TCPIP_CORE(), + UNLOCK_TCPIP_CORE(); return -1); + + err = udp_sendto(sock->udp_pcb, pbuf, &session->addr_info.remote.addr, + session->addr_info.remote.port); + + UNLOCK_TCPIP_CORE(); + + pbuf_free(pbuf); + if (err < 0) { + if (err == ERR_RTE) { + coap_log_warn("** %s: udp_send: Packet not routable\n", + coap_session_str(session)); + } else { + coap_log_warn("** %s: udp_send: error %d\n", + coap_session_str(session), err); + } + return -1; + } + } + return data_len; +} + +#if COAP_SERVER_SUPPORT +int +coap_socket_bind_udp(coap_socket_t *sock, + const coap_address_t *listen_addr, + coap_address_t *bound_addr) { + int err; + coap_address_t l_listen = *listen_addr; + + sock->udp_pcb = udp_new_ip_type(IPADDR_TYPE_ANY); + if (sock->udp_pcb == NULL) + return 0; + +#if LWIP_IPV6 && LWIP_IPV4 + if (l_listen.addr.type == IPADDR_TYPE_V6) + l_listen.addr.type = IPADDR_TYPE_ANY; +#endif /* LWIP_IPV6 && LWIP_IPV4 */ + udp_recv(sock->udp_pcb, coap_udp_recvs, (void *)sock->endpoint); + err = udp_bind(sock->udp_pcb, &l_listen.addr, l_listen.port); + if (err) { + udp_remove(sock->udp_pcb); + sock->udp_pcb = NULL; + } + *bound_addr = l_listen; + return err ? 0 : 1; +} +#endif /* COAP_SERVER_SUPPORT */ + +#if COAP_CLIENT_SUPPORT +int +coap_socket_connect_udp(coap_socket_t *sock, + const coap_address_t *local_if, + const coap_address_t *server, + int default_port, + coap_address_t *local_addr, + coap_address_t *remote_addr) { + err_t err; + struct udp_pcb *pcb; + int is_mcast = coap_is_mcast(server); + coap_address_t connect_addr; + + coap_address_copy(&connect_addr, server); + if (connect_addr.port == 0) + connect_addr.port = default_port; + + coap_lock_invert(LOCK_TCPIP_CORE(), + goto err_unlock); + + pcb = udp_new(); + + if (!pcb) { + goto err_unlock; + } + + if (local_if) { + pcb->local_ip = local_if->addr; + pcb->local_port = local_if->port; + } + err = udp_bind(pcb, &pcb->local_ip, pcb->local_port); + if (err) { + LWIP_DEBUGF(UDP_DEBUG | LWIP_DBG_TRACE | LWIP_DBG_LEVEL_SERIOUS, + ("coap_socket_connect_udp: port bind failed\n")); + goto err_udp_remove; + } + + if (local_addr) { + local_addr->addr = pcb->local_ip; + local_addr->port = pcb->local_port; + } + sock->session->addr_info.local.port = pcb->local_port; + + if (remote_addr) { + coap_address_copy(remote_addr, &connect_addr); + } + + if (is_mcast) { + coap_address_copy(&sock->mcast_addr, &connect_addr); + sock->flags |= COAP_SOCKET_MULTICAST; + } else { + err = udp_connect(pcb, &connect_addr.addr, connect_addr.port); + if (err) { + goto err_udp_unbind; + } + } + +#if LWIP_IPV6 && LWIP_IPV4 + pcb->local_ip.type = pcb->remote_ip.type; +#endif /* LWIP_IPV6 && LWIP_IPV4 */ + + sock->udp_pcb = pcb; + + udp_recv(sock->udp_pcb, coap_recvc, (void *)sock->session); + + UNLOCK_TCPIP_CORE(); + + return 1; + +err_udp_unbind: +err_udp_remove: + udp_remove(pcb); +err_unlock: + UNLOCK_TCPIP_CORE(); + return 0; +} +#endif /* ! COAP_CLIENT_SUPPORT */ +void +coap_socket_dgrm_close(coap_socket_t *sock) { + if (sock->udp_pcb) { + if (sock->session) { + coap_lock_invert(LOCK_TCPIP_CORE(), + UNLOCK_TCPIP_CORE(); return); + } else { + LOCK_TCPIP_CORE(); + } + udp_remove(sock->udp_pcb); + UNLOCK_TCPIP_CORE(); + sock->udp_pcb = NULL; + } + return; +} diff --git a/src/coap_dgrm_posix.c b/src/coap_dgrm_posix.c new file mode 100644 index 00000000..64e046f4 --- /dev/null +++ b/src/coap_dgrm_posix.c @@ -0,0 +1,944 @@ +/* + * coap_dgrm_posix.c -- Datagram (UDP) functions for libcoap + * + * Copyright (C) 2019-2025 Olaf Bergmann and others + * + * SPDX-License-Identifier: BSD-2-Clause + * + * This file is part of the CoAP library libcoap. Please see README for terms + * of use. + */ + +/** + * @file coap_dgrm_posix.c + * @brief Posix CoAP Datagram (UDP) handling functions + */ + +#include "coap3/coap_libcoap_build.h" + +#ifdef HAVE_STDIO_H +# include +#endif +#ifdef HAVE_UNISTD_H +# include +#endif + +#ifndef __ZEPHYR__ +#ifdef HAVE_SYS_SELECT_H +# include +#endif +#ifdef HAVE_SYS_SOCKET_H +# include +# define OPTVAL_T(t) (t) +# define OPTVAL_GT(t) (t) +#endif +#ifdef HAVE_SYS_IOCTL_H +#include +#endif +#ifdef HAVE_NETINET_IN_H +# include +#endif +#ifdef HAVE_WS2TCPIP_H +#include +# define OPTVAL_T(t) (const char*)(t) +# define OPTVAL_GT(t) (char*)(t) +# undef CMSG_DATA +# define CMSG_DATA WSA_CMSG_DATA +#endif +#ifdef HAVE_SYS_UIO_H +# include +#endif +#ifdef _WIN32 +#include +#endif /* _WIN32 */ +#ifdef COAP_EPOLL_SUPPORT +#include +#include +#ifdef HAVE_LIMITS_H +#include +#endif +#endif /* COAP_EPOLL_SUPPORT */ +#else /* __ZEPHYR__ */ +#include +#include +#define OPTVAL_T(t) (const void*)(t) +#define OPTVAL_GT(t) (void*)(t) + +#ifndef IPV6_PKTINFO +#ifdef IPV6_RECVPKTINFO +#define IPV6_PKTINFO IPV6_RECVPKTINFO +#else +#define IPV6_PKTINFO IP_PKTINFO +#endif +#ifndef IN6_IS_ADDR_V4MAPPED +#define IN6_IS_ADDR_V4MAPPED(a) \ + ((((a)->s6_addr32[0]) == 0) && (((a)->s6_addr32[1]) == 0) && \ + (((a)->s6_addr32[2]) == htonl(0xffff))) +#endif +#endif +#endif /* __ZEPHYR__ */ + +/* define generic PKTINFO for IPv4 */ +#if defined(IP_PKTINFO) +# define GEN_IP_PKTINFO IP_PKTINFO +#elif defined(IP_RECVDSTADDR) +# define GEN_IP_PKTINFO IP_RECVDSTADDR +#else +# error "Need IP_PKTINFO or IP_RECVDSTADDR to request ancillary data from OS." +#endif /* IP_PKTINFO */ + +/* define generic PKTINFO for IPv6 */ +#ifdef IPV6_RECVPKTINFO +# define GEN_IPV6_PKTINFO IPV6_RECVPKTINFO +#elif defined(IPV6_PKTINFO) +# define GEN_IPV6_PKTINFO IPV6_PKTINFO +#else +# error "Need IPV6_PKTINFO or IPV6_RECVPKTINFO to request ancillary data from OS." +#endif /* IPV6_RECVPKTINFO */ + +#if COAP_SERVER_SUPPORT +int +coap_socket_bind_udp(coap_socket_t *sock, + const coap_address_t *listen_addr, + coap_address_t *bound_addr) { + int on = 1; +#if COAP_IPV6_SUPPORT + int off = 0; +#endif /* COAP_IPV6_SUPPORT */ +#ifdef _WIN32 + u_long u_on = 1; +#endif + + sock->fd = socket(listen_addr->addr.sa.sa_family, SOCK_DGRAM, 0); + + if (sock->fd == COAP_INVALID_SOCKET) { + coap_log_warn("coap_socket_bind_udp: socket: %s\n", coap_socket_strerror()); + goto error; + } +#ifdef _WIN32 + if (ioctlsocket(sock->fd, FIONBIO, &u_on) == COAP_SOCKET_ERROR) +#else + if (ioctl(sock->fd, FIONBIO, &on) == COAP_SOCKET_ERROR) +#endif + { + coap_log_warn("coap_socket_bind_udp: ioctl FIONBIO: %s\n", coap_socket_strerror()); + } + + if (setsockopt(sock->fd, SOL_SOCKET, SO_REUSEADDR, OPTVAL_T(&on), sizeof(on)) == COAP_SOCKET_ERROR) + coap_log_warn("coap_socket_bind_udp: setsockopt SO_REUSEADDR: %s\n", + coap_socket_strerror()); + + switch (listen_addr->addr.sa.sa_family) { +#if COAP_IPV4_SUPPORT + case AF_INET: + if (setsockopt(sock->fd, IPPROTO_IP, GEN_IP_PKTINFO, OPTVAL_T(&on), + sizeof(on)) == COAP_SOCKET_ERROR) + coap_log_alert("coap_socket_bind_udp: setsockopt IP_PKTINFO: %s\n", + coap_socket_strerror()); + break; +#endif /* COAP_IPV4_SUPPORT */ +#if COAP_IPV6_SUPPORT + case AF_INET6: + /* Configure the socket as dual-stacked */ + if (setsockopt(sock->fd, IPPROTO_IPV6, IPV6_V6ONLY, OPTVAL_T(&off), + sizeof(off)) == COAP_SOCKET_ERROR) + coap_log_alert("coap_socket_bind_udp: setsockopt IPV6_V6ONLY: %s\n", + coap_socket_strerror()); +#if !defined(ESPIDF_VERSION) + if (setsockopt(sock->fd, IPPROTO_IPV6, GEN_IPV6_PKTINFO, OPTVAL_T(&on), + sizeof(on)) == COAP_SOCKET_ERROR) + coap_log_alert("coap_socket_bind_udp: setsockopt IPV6_PKTINFO: %s\n", + coap_socket_strerror()); +#endif /* !defined(ESPIDF_VERSION) */ +#endif /* COAP_IPV6_SUPPORT */ + setsockopt(sock->fd, IPPROTO_IP, GEN_IP_PKTINFO, OPTVAL_T(&on), sizeof(on)); + /* ignore error, because likely cause is that IPv4 is disabled at the os + level */ + break; +#if COAP_AF_UNIX_SUPPORT + case AF_UNIX: + break; +#endif /* COAP_AF_UNIX_SUPPORT */ + default: + coap_log_alert("coap_socket_bind_udp: unsupported sa_family\n"); + break; + } + + if (bind(sock->fd, &listen_addr->addr.sa, +#if COAP_IPV4_SUPPORT + listen_addr->addr.sa.sa_family == AF_INET ? + (socklen_t)sizeof(struct sockaddr_in) : +#endif /* COAP_IPV4_SUPPORT */ + (socklen_t)listen_addr->size) == COAP_SOCKET_ERROR) { + coap_log_warn("coap_socket_bind_udp: bind: %s\n", + coap_socket_strerror()); + goto error; + } + + bound_addr->size = (socklen_t)sizeof(*bound_addr); + if (getsockname(sock->fd, &bound_addr->addr.sa, &bound_addr->size) < 0) { + coap_log_warn("coap_socket_bind_udp: getsockname: %s\n", + coap_socket_strerror()); + goto error; + } + return 1; + +error: + coap_socket_dgrm_close(sock); + return 0; +} +#endif /* COAP_SERVER_SUPPORT */ + +#if COAP_CLIENT_SUPPORT +int +coap_socket_connect_udp(coap_socket_t *sock, + const coap_address_t *local_if, + const coap_address_t *server, + int default_port, + coap_address_t *local_addr, + coap_address_t *remote_addr) { + int on = 1; +#if COAP_IPV6_SUPPORT + int off = 0; +#endif /* COAP_IPV6_SUPPORT */ +#ifdef _WIN32 + u_long u_on = 1; +#endif + coap_address_t connect_addr; + int is_mcast = coap_is_mcast(server); + coap_address_copy(&connect_addr, server); + + sock->flags &= ~(COAP_SOCKET_CONNECTED | COAP_SOCKET_MULTICAST); + sock->fd = socket(connect_addr.addr.sa.sa_family, SOCK_DGRAM, 0); + + if (sock->fd == COAP_INVALID_SOCKET) { + coap_log_warn("coap_socket_connect_udp: socket: %s\n", + coap_socket_strerror()); + goto error; + } + +#ifdef _WIN32 + if (ioctlsocket(sock->fd, FIONBIO, &u_on) == COAP_SOCKET_ERROR) +#else + if (ioctl(sock->fd, FIONBIO, &on) == COAP_SOCKET_ERROR) +#endif + { + /* Ignore Zephyr unexpected Success response */ + if (errno != 0) { + int keep_errno = errno; + + coap_log_warn("coap_socket_connect_udp: ioctl FIONBIO: %s (%d)\n", + coap_socket_strerror(), keep_errno); + } + } + + switch (connect_addr.addr.sa.sa_family) { +#if COAP_IPV4_SUPPORT + case AF_INET: + if (connect_addr.addr.sin.sin_port == 0) + connect_addr.addr.sin.sin_port = htons(default_port); + break; +#endif /* COAP_IPV4_SUPPORT */ +#if COAP_IPV6_SUPPORT + case AF_INET6: + if (connect_addr.addr.sin6.sin6_port == 0) + connect_addr.addr.sin6.sin6_port = htons(default_port); + /* Configure the socket as dual-stacked */ + if (setsockopt(sock->fd, IPPROTO_IPV6, IPV6_V6ONLY, OPTVAL_T(&off), + sizeof(off)) == COAP_SOCKET_ERROR) + if (errno != ENOSYS) { + coap_log_warn("coap_socket_connect_udp: setsockopt IPV6_V6ONLY: %s\n", + coap_socket_strerror()); + } +#endif /* COAP_IPV6_SUPPORT */ + break; +#if COAP_AF_UNIX_SUPPORT + case AF_UNIX: + break; +#endif /* COAP_AF_UNIX_SUPPORT */ + default: + coap_log_alert("coap_socket_connect_udp: unsupported sa_family %d\n", + connect_addr.addr.sa.sa_family); + goto error;; + } + + if (local_if && local_if->addr.sa.sa_family) { + if (local_if->addr.sa.sa_family != connect_addr.addr.sa.sa_family) { + coap_log_warn("coap_socket_connect_udp: local address family != " + "remote address family\n"); + goto error; + } + if (setsockopt(sock->fd, SOL_SOCKET, SO_REUSEADDR, OPTVAL_T(&on), sizeof(on)) == COAP_SOCKET_ERROR) + coap_log_warn("coap_socket_connect_udp: setsockopt SO_REUSEADDR: %s\n", + coap_socket_strerror()); + if (bind(sock->fd, &local_if->addr.sa, +#if COAP_IPV4_SUPPORT + local_if->addr.sa.sa_family == AF_INET ? + (socklen_t)sizeof(struct sockaddr_in) : +#endif /* COAP_IPV4_SUPPORT */ + (socklen_t)local_if->size) == COAP_SOCKET_ERROR) { + coap_log_warn("coap_socket_connect_udp: bind: %s\n", + coap_socket_strerror()); + goto error; + } +#if COAP_AF_UNIX_SUPPORT + } else if (connect_addr.addr.sa.sa_family == AF_UNIX) { + /* Need to bind to a local address for clarity over endpoints */ + coap_log_warn("coap_socket_connect_udp: local address required\n"); + goto error; +#endif /* COAP_AF_UNIX_SUPPORT */ + } + + /* special treatment for sockets that are used for multicast communication */ + if (is_mcast) { + if (!(local_if && local_if->addr.sa.sa_family)) { + /* Bind to a (unused) port to simplify logging */ + coap_address_t bind_addr; + + coap_address_init(&bind_addr); + bind_addr.addr.sa.sa_family = connect_addr.addr.sa.sa_family; + if (bind(sock->fd, &bind_addr.addr.sa, +#if COAP_IPV4_SUPPORT + bind_addr.addr.sa.sa_family == AF_INET ? + (socklen_t)sizeof(struct sockaddr_in) : +#endif /* COAP_IPV4_SUPPORT */ + (socklen_t)bind_addr.size) == COAP_SOCKET_ERROR) { + coap_log_warn("coap_socket_connect_udp: bind: %s\n", + coap_socket_strerror()); + goto error; + } + } + if (getsockname(sock->fd, &local_addr->addr.sa, &local_addr->size) == COAP_SOCKET_ERROR) { + coap_log_warn("coap_socket_connect_udp: getsockname for multicast socket: %s\n", + coap_socket_strerror()); + } + coap_address_copy(remote_addr, &connect_addr); + coap_address_copy(&sock->mcast_addr, &connect_addr); + sock->flags |= COAP_SOCKET_MULTICAST; + if (coap_is_bcast(server) && + setsockopt(sock->fd, SOL_SOCKET, SO_BROADCAST, OPTVAL_T(&on), + sizeof(on)) == COAP_SOCKET_ERROR) + coap_log_warn("coap_socket_connect_udp: setsockopt SO_BROADCAST: %s\n", + coap_socket_strerror()); + return 1; + } + + if (connect(sock->fd, &connect_addr.addr.sa, connect_addr.size) == COAP_SOCKET_ERROR) { +#if COAP_AF_UNIX_SUPPORT + if (connect_addr.addr.sa.sa_family == AF_UNIX) { + coap_log_warn("coap_socket_connect_udp: connect: %s: %s\n", + connect_addr.addr.cun.sun_path, coap_socket_strerror()); + } else +#endif /* COAP_AF_UNIX_SUPPORT */ + { + coap_log_warn("coap_socket_connect_udp: connect: %s (%d)\n", + coap_socket_strerror(), connect_addr.addr.sa.sa_family); + } + goto error; + } + + if (getsockname(sock->fd, &local_addr->addr.sa, &local_addr->size) == COAP_SOCKET_ERROR) { + coap_log_warn("coap_socket_connect_udp: getsockname: %s\n", + coap_socket_strerror()); + } + + if (getpeername(sock->fd, &remote_addr->addr.sa, &remote_addr->size) == COAP_SOCKET_ERROR) { + coap_log_warn("coap_socket_connect_udp: getpeername: %s\n", + coap_socket_strerror()); + } + + sock->flags |= COAP_SOCKET_CONNECTED; + return 1; + +error: + coap_socket_dgrm_close(sock); + return 0; +} +#endif /* COAP_CLIENT_SUPPORT */ + +#if !defined(__ZEPHYR__) +#if 0 == ( defined(HAVE_NETINET_IN_H) || defined(HAVE_WS2TCPIP_H) ) +/* define struct in6_pktinfo and struct in_pktinfo if not available + FIXME: check with configure +*/ +#if !defined(__MINGW32__) +struct in6_pktinfo { + struct in6_addr ipi6_addr; /* src/dst IPv6 address */ + unsigned int ipi6_ifindex; /* send/recv interface index */ +}; + +struct in_pktinfo { + int ipi_ifindex; + struct in_addr ipi_spec_dst; + struct in_addr ipi_addr; +}; +#endif /* ! __MINGW32__ */ +#endif +#endif /* ! __ZEPHYR__ */ + +#if !defined(SOL_IP) +/* Solaris expects level IPPROTO_IP for ancillary data. */ +#define SOL_IP IPPROTO_IP +#endif +#ifdef _WIN32 +#define COAP_SOL_IP IPPROTO_IP +#else /* ! _WIN32 */ +#define COAP_SOL_IP SOL_IP +#endif /* ! _WIN32 */ + +#if defined(_WIN32) +#include +#if defined(__MINGW32__) +static __thread LPFN_WSARECVMSG lpWSARecvMsg = NULL; +#if(_WIN32_WINNT >= 0x0600) +#define CMSG_FIRSTHDR WSA_CMSG_FIRSTHDR +#define CMSG_NXTHDR WSA_CMSG_NXTHDR +#define CMSG_LEN WSA_CMSG_LEN +#define CMSG_SPACE WSA_CMSG_SPACE +#if(_WIN32_WINNT < 0x0603 || _WIN32_WINNT == 0x0a00) +#define cmsghdr _WSACMSGHDR +#endif /* (_WIN32_WINNT<0x0603 || _WIN32_WINNT == 0x0a00) */ +#endif /* (_WIN32_WINNT>=0x0600) */ +#else /* ! __MINGW32__ */ +static __declspec(thread) LPFN_WSARECVMSG lpWSARecvMsg = NULL; +#endif /* ! __MINGW32__ */ +/* Map struct WSABUF fields to their posix counterpart */ +#define msghdr _WSAMSG +#define msg_name name +#define msg_namelen namelen +#define msg_iov lpBuffers +#define msg_iovlen dwBufferCount +#define msg_control Control.buf +#define msg_controllen Control.len +#define iovec _WSABUF +#define iov_base buf +#define iov_len len +#define iov_len_t u_long +#undef CMSG_DATA +#define CMSG_DATA WSA_CMSG_DATA +#define ipi_spec_dst ipi_addr +#if !defined(__MINGW32__) +#pragma warning( disable : 4116 ) +#endif /* ! __MINGW32__ */ +#else +#define iov_len_t size_t +#endif + +#if defined(_CYGWIN_ENV) || defined(__QNXNTO__) +#define ipi_spec_dst ipi_addr +#endif + +#if COAP_CLIENT_SUPPORT +static uint32_t cid_track_counter; + +static void +coap_test_cid_tuple_change(coap_session_t *session) { + if (session->type == COAP_SESSION_TYPE_CLIENT && + session->negotiated_cid && + session->state == COAP_SESSION_STATE_ESTABLISHED && + session->proto == COAP_PROTO_DTLS && session->context->testing_cids) { + if ((++cid_track_counter) % session->context->testing_cids == 0) { + coap_address_t local_if = session->addr_info.local; + uint16_t port = coap_address_get_port(&local_if); + + port++; + coap_address_set_port(&local_if, port); + + coap_socket_dgrm_close(&session->sock); + session->sock.session = session; + if (!coap_socket_connect_udp(&session->sock, &local_if, &session->addr_info.remote, + port, + &session->addr_info.local, + &session->addr_info.remote)) { + coap_log_err("Tuple change for CID failed\n"); + return; +#ifdef COAP_EPOLL_SUPPORT + } else { + coap_epoll_ctl_add(&session->sock, + EPOLLIN | + ((session->sock.flags & COAP_SOCKET_WANT_CONNECT) ? + EPOLLOUT : 0), + __func__); +#endif /* COAP_EPOLL_SUPPORT */ + } + session->sock.flags |= COAP_SOCKET_NOT_EMPTY | COAP_SOCKET_WANT_READ | COAP_SOCKET_BOUND; + } + } +} +#endif /* COAP_CLIENT_SUPPORT */ + +/* + * dgram + * return +ve Number of bytes written. + * -1 Error error in errno). + */ +ssize_t +coap_socket_send(coap_socket_t *sock, coap_session_t *session, + const uint8_t *data, size_t datalen) { + ssize_t bytes_written = 0; + +#if COAP_CLIENT_SUPPORT + coap_test_cid_tuple_change(session); +#endif /* COAP_CLIENT_SUPPORT */ + + if (!coap_debug_send_packet()) { + bytes_written = (ssize_t)datalen; + } else if (sock->flags & COAP_SOCKET_CONNECTED) { +#ifdef _WIN32 + bytes_written = send(sock->fd, (const char *)data, (int)datalen, 0); +#else + bytes_written = send(sock->fd, data, datalen, 0); +#endif + } else { +#if defined(_WIN32) + DWORD dwNumberOfBytesSent = 0; + int r; +#endif /* _WIN32 */ +#ifdef HAVE_STRUCT_CMSGHDR + /* a buffer large enough to hold all packet info types, ipv6 is the largest */ + char buf[CMSG_SPACE(sizeof(struct in6_pktinfo))]; + struct msghdr mhdr; + struct iovec iov[1]; + const void *addr = &session->addr_info.remote.addr; + + assert(session); + + memcpy(&iov[0].iov_base, &data, sizeof(iov[0].iov_base)); + iov[0].iov_len = (iov_len_t)datalen; + + memset(buf, 0, sizeof(buf)); + + memset(&mhdr, 0, sizeof(struct msghdr)); + memcpy(&mhdr.msg_name, &addr, sizeof(mhdr.msg_name)); + mhdr.msg_namelen = session->addr_info.remote.addr.sa.sa_family == AF_INET ? + (socklen_t)sizeof(struct sockaddr_in) : + session->addr_info.remote.size; + + mhdr.msg_iov = iov; + mhdr.msg_iovlen = 1; + + if (!coap_address_isany(&session->addr_info.local) && + !coap_is_mcast(&session->addr_info.local)) { + switch (session->addr_info.local.addr.sa.sa_family) { +#if COAP_IPV6_SUPPORT + case AF_INET6: { + struct cmsghdr *cmsg; + +#if COAP_IPV4_SUPPORT + if (IN6_IS_ADDR_V4MAPPED(&session->addr_info.local.addr.sin6.sin6_addr)) { +#if defined(IP_PKTINFO) + struct in_pktinfo *pktinfo; + mhdr.msg_control = buf; + mhdr.msg_controllen = CMSG_SPACE(sizeof(struct in_pktinfo)); + + cmsg = CMSG_FIRSTHDR(&mhdr); + cmsg->cmsg_level = COAP_SOL_IP; + cmsg->cmsg_type = IP_PKTINFO; + cmsg->cmsg_len = CMSG_LEN(sizeof(struct in_pktinfo)); + + pktinfo = (struct in_pktinfo *)CMSG_DATA(cmsg); + + pktinfo->ipi_ifindex = session->ifindex; + memcpy(&pktinfo->ipi_spec_dst, + session->addr_info.local.addr.sin6.sin6_addr.s6_addr + 12, + sizeof(pktinfo->ipi_spec_dst)); +#elif defined(IP_SENDSRCADDR) + mhdr.msg_control = buf; + mhdr.msg_controllen = CMSG_SPACE(sizeof(struct in_addr)); + + cmsg = CMSG_FIRSTHDR(&mhdr); + cmsg->cmsg_level = IPPROTO_IP; + cmsg->cmsg_type = IP_SENDSRCADDR; + cmsg->cmsg_len = CMSG_LEN(sizeof(struct in_addr)); + + memcpy(CMSG_DATA(cmsg), + session->addr_info.local.addr.sin6.sin6_addr.s6_addr + 12, + sizeof(struct in_addr)); +#endif /* IP_PKTINFO */ + } else { +#endif /* COAP_IPV4_SUPPORT */ + struct in6_pktinfo *pktinfo; + mhdr.msg_control = buf; + mhdr.msg_controllen = CMSG_SPACE(sizeof(struct in6_pktinfo)); + + cmsg = CMSG_FIRSTHDR(&mhdr); + cmsg->cmsg_level = IPPROTO_IPV6; + cmsg->cmsg_type = IPV6_PKTINFO; + cmsg->cmsg_len = CMSG_LEN(sizeof(struct in6_pktinfo)); + + pktinfo = (struct in6_pktinfo *)CMSG_DATA(cmsg); + + if (coap_is_mcast(&session->addr_info.remote)) { + pktinfo->ipi6_ifindex = session->addr_info.remote.addr.sin6.sin6_scope_id; + } else { + pktinfo->ipi6_ifindex = session->ifindex; + } + memcpy(&pktinfo->ipi6_addr, + &session->addr_info.local.addr.sin6.sin6_addr, + sizeof(pktinfo->ipi6_addr)); +#if COAP_IPV4_SUPPORT + } +#endif /* COAP_IPV4_SUPPORT */ + break; + } +#endif /* COAP_IPV6_SUPPORT */ +#if COAP_IPV4_SUPPORT + case AF_INET: { +#if defined(IP_PKTINFO) + struct cmsghdr *cmsg; + struct in_pktinfo *pktinfo; + + mhdr.msg_control = buf; + mhdr.msg_controllen = CMSG_SPACE(sizeof(struct in_pktinfo)); + + cmsg = CMSG_FIRSTHDR(&mhdr); + cmsg->cmsg_level = COAP_SOL_IP; + cmsg->cmsg_type = IP_PKTINFO; + cmsg->cmsg_len = CMSG_LEN(sizeof(struct in_pktinfo)); + + pktinfo = (struct in_pktinfo *)CMSG_DATA(cmsg); + + pktinfo->ipi_ifindex = session->ifindex; + memcpy(&pktinfo->ipi_spec_dst, + &session->addr_info.local.addr.sin.sin_addr, + sizeof(pktinfo->ipi_spec_dst)); +#elif defined(IP_SENDSRCADDR) + struct cmsghdr *cmsg; + mhdr.msg_control = buf; + mhdr.msg_controllen = CMSG_SPACE(sizeof(struct in_addr)); + + cmsg = CMSG_FIRSTHDR(&mhdr); + cmsg->cmsg_level = IPPROTO_IP; + cmsg->cmsg_type = IP_SENDSRCADDR; + cmsg->cmsg_len = CMSG_LEN(sizeof(struct in_addr)); + + memcpy(CMSG_DATA(cmsg), + &session->addr_info.local.addr.sin.sin_addr, + sizeof(struct in_addr)); +#endif /* IP_PKTINFO */ + break; + } +#endif /* COAP_IPV4_SUPPORT */ +#if COAP_AF_UNIX_SUPPORT + case AF_UNIX: + break; +#endif /* COAP_AF_UNIX_SUPPORT */ + default: + /* error */ + coap_log_warn("protocol not supported\n"); + return -1; + } + } +#endif /* HAVE_STRUCT_CMSGHDR */ + +#if defined(_WIN32) + r = WSASendMsg(sock->fd, &mhdr, 0 /*dwFlags*/, &dwNumberOfBytesSent, NULL /*lpOverlapped*/, + NULL /*lpCompletionRoutine*/); + if (r == 0) + bytes_written = (ssize_t)dwNumberOfBytesSent; + else { + bytes_written = -1; + coap_win_error_to_errno(); + } +#else /* !_WIN32 */ +#ifdef HAVE_STRUCT_CMSGHDR + bytes_written = sendmsg(sock->fd, &mhdr, 0); +#else /* ! HAVE_STRUCT_CMSGHDR */ + bytes_written = sendto(sock->fd, (const void *)data, datalen, 0, + &session->addr_info.remote.addr.sa, + session->addr_info.remote.size); +#endif /* ! HAVE_STRUCT_CMSGHDR */ +#endif /* !_WIN32 */ + } + + if (bytes_written < 0) + coap_log_crit("coap_socket_send: %s\n", coap_socket_strerror()); + + return bytes_written; +} + +#define SIN6(A) ((struct sockaddr_in6 *)(A)) + +/* + * dgram + * return +ve Number of bytes written. + * -1 Error error in errno). + * -2 ICMP error response + */ +ssize_t +coap_socket_recv(coap_socket_t *sock, coap_packet_t *packet) { + ssize_t len = -1; + + assert(sock); + assert(packet); + + if ((sock->flags & COAP_SOCKET_CAN_READ) == 0) { + return -1; + } else { + /* clear has-data flag */ + sock->flags &= ~COAP_SOCKET_CAN_READ; + } + + if (sock->flags & COAP_SOCKET_CONNECTED) { +#ifdef _WIN32 + len = recv(sock->fd, (char *)packet->payload, COAP_RXBUFFER_SIZE, 0); +#else + len = recv(sock->fd, packet->payload, COAP_RXBUFFER_SIZE, 0); +#endif + if (len < 0) { +#ifdef _WIN32 + coap_win_error_to_errno(); +#endif /* _WIN32 */ + if (errno == ECONNREFUSED || errno == EHOSTUNREACH || errno == ECONNRESET) { + /* client-side ICMP destination unreachable, ignore it */ + coap_log_warn("** %s: coap_socket_recv: ICMP: %s\n", + sock->session ? + coap_session_str(sock->session) : "", + coap_socket_strerror()); + return -2; + } + if (errno != EAGAIN) { + coap_log_warn("** %s: coap_socket_recv: %s\n", + sock->session ? + coap_session_str(sock->session) : "", + coap_socket_strerror()); + } + goto error; + } else if (len > 0) { + packet->length = (size_t)len; + } + } else { +#if defined(_WIN32) + DWORD dwNumberOfBytesRecvd = 0; + int r; +#endif /* _WIN32 */ +#ifdef HAVE_STRUCT_CMSGHDR + /* a buffer large enough to hold all packet info types, ipv6 is the largest */ + char buf[CMSG_SPACE(sizeof(struct in6_pktinfo))]; + struct cmsghdr *cmsg; + struct msghdr mhdr; + struct iovec iov[1]; + +#if defined(__MINGW32__) + iov[0].iov_base = (char *) packet->payload; +#else /* ! __MINGW32__ */ + iov[0].iov_base = packet->payload; +#endif /* defined(__MINGW32__) */ + iov[0].iov_len = (iov_len_t)COAP_RXBUFFER_SIZE; + + memset(&mhdr, 0, sizeof(struct msghdr)); + + mhdr.msg_name = (struct sockaddr *)&packet->addr_info.remote.addr; + mhdr.msg_namelen = sizeof(packet->addr_info.remote.addr); + + mhdr.msg_iov = iov; + mhdr.msg_iovlen = 1; + + mhdr.msg_control = buf; + mhdr.msg_controllen = sizeof(buf); + /* set a big first length incase recvmsg() does not implement updating + msg_control as well as preset the first cmsg with bad data */ + cmsg = (struct cmsghdr *)buf; + cmsg->cmsg_len = CMSG_LEN(sizeof(buf)); + cmsg->cmsg_level = -1; + cmsg->cmsg_type = -1; + +#if defined(_WIN32) + if (!lpWSARecvMsg) { + GUID wsaid = WSAID_WSARECVMSG; + DWORD cbBytesReturned = 0; + if (WSAIoctl(sock->fd, SIO_GET_EXTENSION_FUNCTION_POINTER, &wsaid, sizeof(wsaid), &lpWSARecvMsg, + sizeof(lpWSARecvMsg), &cbBytesReturned, NULL, NULL) != 0) { + coap_log_warn("coap_socket_recv: no WSARecvMsg\n"); + return -1; + } + } + r = lpWSARecvMsg(sock->fd, &mhdr, &dwNumberOfBytesRecvd, NULL /* LPWSAOVERLAPPED */, + NULL /* LPWSAOVERLAPPED_COMPLETION_ROUTINE */); + if (r == 0) + len = (ssize_t)dwNumberOfBytesRecvd; + else if (r == COAP_SOCKET_ERROR) + coap_win_error_to_errno(); +#else + len = recvmsg(sock->fd, &mhdr, 0); +#endif + +#else /* ! HAVE_STRUCT_CMSGHDR */ + len = recvfrom(sock->fd, (void *)packet->payload, COAP_RXBUFFER_SIZE, 0, + &packet->addr_info.remote.addr.sa, + &packet->addr_info.remote.size); +#endif /* ! HAVE_STRUCT_CMSGHDR */ + + if (len < 0) { +#ifdef _WIN32 + coap_win_error_to_errno(); +#endif /* _WIN32 */ + if (errno == ECONNREFUSED || errno == EHOSTUNREACH || errno == ECONNRESET) { + /* server-side ICMP destination unreachable, ignore it. The destination address is in msg_name. */ + coap_log_warn("** %s: coap_socket_recv: ICMP: %s\n", + sock->session ? + coap_session_str(sock->session) : "", + coap_socket_strerror()); + return 0; + } + if (errno != EAGAIN) { + coap_log_warn("coap_socket_recv: %s\n", coap_socket_strerror()); + } + goto error; + } else { +#ifdef HAVE_STRUCT_CMSGHDR + int dst_found = 0; + + packet->addr_info.remote.size = mhdr.msg_namelen; + packet->length = (size_t)len; + + /* Walk through ancillary data records until the local interface + * is found where the data was received. */ + for (cmsg = CMSG_FIRSTHDR(&mhdr); cmsg; cmsg = CMSG_NXTHDR(&mhdr, cmsg)) { + +#if COAP_IPV6_SUPPORT + /* get the local interface for IPv6 */ + if (cmsg->cmsg_level == IPPROTO_IPV6 && cmsg->cmsg_type == IPV6_PKTINFO) { + union { + uint8_t *c; + struct in6_pktinfo *p; + } u; + u.c = CMSG_DATA(cmsg); + packet->ifindex = (int)(u.p->ipi6_ifindex); + memcpy(&packet->addr_info.local.addr.sin6.sin6_addr, + &u.p->ipi6_addr, sizeof(struct in6_addr)); + dst_found = 1; + break; + } +#endif /* COAP_IPV6_SUPPORT */ + +#if COAP_IPV4_SUPPORT + /* local interface for IPv4 */ +#if defined(IP_PKTINFO) + if (cmsg->cmsg_level == COAP_SOL_IP && cmsg->cmsg_type == IP_PKTINFO) { + union { + uint8_t *c; + struct in_pktinfo *p; + } u; + u.c = CMSG_DATA(cmsg); + packet->ifindex = u.p->ipi_ifindex; +#if COAP_IPV6_SUPPORT + if (packet->addr_info.local.addr.sa.sa_family == AF_INET6) { + memset(packet->addr_info.local.addr.sin6.sin6_addr.s6_addr, 0, 10); + packet->addr_info.local.addr.sin6.sin6_addr.s6_addr[10] = 0xff; + packet->addr_info.local.addr.sin6.sin6_addr.s6_addr[11] = 0xff; + memcpy(packet->addr_info.local.addr.sin6.sin6_addr.s6_addr + 12, + &u.p->ipi_addr, sizeof(struct in_addr)); + } else +#endif /* COAP_IPV6_SUPPORT */ + { + memcpy(&packet->addr_info.local.addr.sin.sin_addr, + &u.p->ipi_addr, sizeof(struct in_addr)); + } + dst_found = 1; + break; + } +#endif /* IP_PKTINFO */ +#if defined(IP_RECVDSTADDR) + if (cmsg->cmsg_level == IPPROTO_IP && cmsg->cmsg_type == IP_RECVDSTADDR) { + packet->ifindex = (int)sock->fd; + memcpy(&packet->addr_info.local.addr.sin.sin_addr, + CMSG_DATA(cmsg), sizeof(struct in_addr)); + dst_found = 1; + break; + } +#endif /* IP_RECVDSTADDR */ +#endif /* COAP_IPV4_SUPPORT */ + if (!dst_found) { + /* cmsg_level / cmsg_type combination we do not understand + (ignore preset case for bad recvmsg() not updating cmsg) */ + if (cmsg->cmsg_level != -1 && cmsg->cmsg_type != -1) { + coap_log_debug("cmsg_level = %d and cmsg_type = %d not supported - fix\n", + cmsg->cmsg_level, cmsg->cmsg_type); + } + } + } + if (!dst_found) { + /* Not expected, but cmsg_level and cmsg_type don't match above and + may need a new case */ + packet->ifindex = (int)sock->fd; + if (getsockname(sock->fd, &packet->addr_info.local.addr.sa, + &packet->addr_info.local.size) < 0) { + coap_log_debug("Cannot determine local port\n"); + } + } +#else /* ! HAVE_STRUCT_CMSGHDR */ + packet->length = (size_t)len; + packet->ifindex = 0; + if (getsockname(sock->fd, &packet->addr_info.local.addr.sa, + &packet->addr_info.local.size) < 0) { + coap_log_debug("Cannot determine local port\n"); + goto error; + } +#endif /* ! HAVE_STRUCT_CMSGHDR */ + } + } + + if (len >= 0) + return len; +error: + return -1; +} + +void +coap_socket_dgrm_close(coap_socket_t *sock) { + if (sock->fd != COAP_INVALID_SOCKET && !(sock->flags & COAP_SOCKET_SLAVE)) { +#ifdef COAP_EPOLL_SUPPORT +#if COAP_SERVER_SUPPORT + coap_context_t *context = sock->session ? sock->session->context : + sock->endpoint ? sock->endpoint->context : NULL; +#else /* COAP_SERVER_SUPPORT */ + coap_context_t *context = sock->session ? sock->session->context : NULL; +#endif /* COAP_SERVER_SUPPORT */ + if (context != NULL) { + int ret; + struct epoll_event event; + + /* Kernels prior to 2.6.9 expect non NULL event parameter */ + ret = epoll_ctl(context->epfd, EPOLL_CTL_DEL, sock->fd, &event); + if (ret == -1 && errno != ENOENT) { + coap_log_err("%s: epoll_ctl DEL failed: %d: %s (%d)\n", + "coap_socket_close", + sock->fd, + coap_socket_strerror(), errno); + } + } +#endif /* COAP_EPOLL_SUPPORT */ +#if COAP_SERVER_SUPPORT +#if COAP_AF_UNIX_SUPPORT + if (sock->endpoint && + sock->endpoint->bind_addr.addr.sa.sa_family == AF_UNIX) { + /* Clean up Unix endpoint */ +#ifdef _WIN32 + _unlink(sock->endpoint->bind_addr.addr.cun.sun_path); +#else /* ! _WIN32 */ + unlink(sock->endpoint->bind_addr.addr.cun.sun_path); +#endif /* ! _WIN32 */ + } +#endif /* COAP_AF_UNIX_SUPPORT */ + sock->endpoint = NULL; +#endif /* COAP_SERVER_SUPPORT */ +#if COAP_CLIENT_SUPPORT +#if COAP_AF_UNIX_SUPPORT + if (sock->session && sock->session->type == COAP_SESSION_TYPE_CLIENT && + sock->session->addr_info.local.addr.sa.sa_family == AF_UNIX) { + /* Clean up Unix endpoint */ +#ifdef _WIN32 + _unlink(sock->session->addr_info.local.addr.cun.sun_path); +#else /* ! _WIN32 */ + unlink(sock->session->addr_info.local.addr.cun.sun_path); +#endif /* ! _WIN32 */ + } +#endif /* COAP_AF_UNIX_SUPPORT */ +#endif /* COAP_CLIENT_SUPPORT */ + sock->session = NULL; + coap_closesocket(sock->fd); + sock->fd = COAP_INVALID_SOCKET; + } + sock->flags = COAP_SOCKET_EMPTY; +} diff --git a/src/coap_dgrm_riot.c b/src/coap_dgrm_riot.c new file mode 100644 index 00000000..d866e25d --- /dev/null +++ b/src/coap_dgrm_riot.c @@ -0,0 +1,327 @@ +/* coap_dgrm_riot.c -- Default Datagram (UDP) network I/O functions for libcoap on RIOT + * + * Copyright (C) 2019-2025 Olaf Bergmann + * + * SPDX-License-Identifier: BSD-2-Clause + * + * This file is part of the CoAP library libcoap. Please see + * README for terms of use. + */ + +/** + * @file coap_dgrm_riot.c + * @brief RIOT Datagran (UDP) specific I/O functions + */ + +#include "coap3/coap_libcoap_build.h" + +#include "net/gnrc.h" +#include "net/gnrc/ipv6.h" +#include "net/gnrc/netreg.h" +#include "net/udp.h" +#if COAP_DISABLE_TCP +#include "net/tcp.h" +#endif /* ! COAP_DISABLE_TCP */ +#include "net/sock/async.h" + +#include "coap3/coap_riot.h" + +#define COAP_SELECT_THREAD_FLAG (1U << 4) + +/* + * dgram + * return +ve Number of bytes written. + * -1 Error error in errno). + */ +ssize_t +coap_socket_send(coap_socket_t *sock, + coap_session_t *session, + const uint8_t *data, + size_t datalen) { + ssize_t bytes_written = 0; + + if (!coap_debug_send_packet()) { + bytes_written = (ssize_t)datalen; + } else if (sock->flags & COAP_SOCKET_CONNECTED) { + bytes_written = sock_udp_send(&sock->udp, data, datalen, NULL); + } else { + bytes_written = sock_udp_send(&sock->udp, data, datalen, &session->addr_info.remote.riot); + } + + if (bytes_written < 0) { + errno = -bytes_written; + bytes_written = -1; + coap_log_crit("coap_socket_send: %s\n", coap_socket_strerror()); + } + + return bytes_written; +} + +/* + * dgram + * return +ve Number of bytes written. + * -1 Error error in errno). + * -2 ICMP error response + */ +ssize_t +coap_socket_recv(coap_socket_t *sock, coap_packet_t *packet) { + ssize_t len = -1; + + assert(sock); + assert(packet); + + if ((sock->flags & COAP_SOCKET_CAN_READ) == 0) { + return -1; + } else { + /* clear has-data flag */ + sock->flags &= ~COAP_SOCKET_CAN_READ; + } + + if (sock->flags & COAP_SOCKET_CONNECTED) { + len = sock_udp_recv(&sock->udp, (char *)packet->payload, COAP_RXBUFFER_SIZE, 0, NULL); + if (len < 0) { + errno = -len; + len = -1; + if (errno == ECONNREFUSED || errno == EHOSTUNREACH || errno == ECONNRESET) { + /* client-side ICMP destination unreachable, ignore it */ + coap_log_warn("** %s: coap_socket_recv: ICMP: %s\n", + sock->session ? + coap_session_str(sock->session) : "", + coap_socket_strerror()); + return -2; + } + if (errno != EAGAIN) { + coap_log_warn("** %s: coap_socket_recv: %s\n", + sock->session ? + coap_session_str(sock->session) : "", + coap_socket_strerror()); + } + goto error; + } else if (len > 0) { + packet->length = (size_t)len; + } + } else { + sock_udp_aux_rx_t aux; + sock_udp_ep_t remote; + + aux.flags = SOCK_AUX_GET_LOCAL; + len = sock_udp_recv_aux(&sock->udp, (char *)packet->payload, COAP_RXBUFFER_SIZE, 0, + &remote, &aux); + if (len < 0) { + errno = -len; + len = -1; + if (errno == ECONNREFUSED || errno == EHOSTUNREACH || errno == ECONNRESET) { + /* client-side ICMP destination unreachable, ignore it */ + coap_log_warn("** %s: coap_socket_recv: ICMP: %s\n", + sock->session ? + coap_session_str(sock->session) : "", + coap_socket_strerror()); + return -2; + } + if (errno != EAGAIN) { + coap_log_warn("** %s: coap_socket_recv: %s\n", + sock->session ? + coap_session_str(sock->session) : "", + coap_socket_strerror()); + } + goto error; + } else if (len > 0) { + packet->length = (size_t)len; + memcpy(&packet->addr_info.local.riot, &aux.local, sizeof(packet->addr_info.local.riot)); + memcpy(&packet->addr_info.remote.riot, &remote, sizeof(packet->addr_info.remote.riot)); + } + } + + if (len >= 0) + return len; +error: + return -1; +} + +#if COAP_SERVER_SUPPORT + +static void +udp_recv_endpoint_cb(sock_udp_t *sock, sock_async_flags_t flags, void *arg) { + coap_endpoint_t *endpoint = (coap_endpoint_t *)arg; + + (void)sock; + if (!(flags & (SOCK_ASYNC_MSG_RECV | SOCK_ASYNC_MSG_SENT))) + return; + + if (flags & SOCK_ASYNC_MSG_RECV) + endpoint->sock.flags |= COAP_SOCKET_CAN_READ; + if (endpoint->context->selecting_thread) { + thread_flags_set(endpoint->context->selecting_thread, + COAP_SELECT_THREAD_FLAG); + } +} + +int +coap_socket_bind_udp(coap_socket_t *sock, + const coap_address_t *listen_addr, + coap_address_t *bound_addr) { + int ret; + + ret = sock_udp_create(&sock->udp, &listen_addr->riot, NULL, SOCK_FLAGS_REUSE_EP); + if (ret < 0) { + errno = -ret; + ret = -1; + coap_log_warn("coap_socket_bind_udp: sock_udp_create: %s (%d)\n", + coap_socket_strerror(), listen_addr->riot.family); + goto error; + } + ret = sock_udp_get_local(&sock->udp, &bound_addr->riot); + if (ret != 0) { + errno = -ret; + ret = -1; + coap_log_warn("coap_socket_bind_udp: sock_udp_get_local: %s\n", + coap_socket_strerror()); + } + sock_udp_set_cb(&sock->udp, udp_recv_endpoint_cb, sock->endpoint); + + return 1; + +error: + coap_socket_dgrm_close(sock); + return 0; +} +#endif /* COAP_SERVER_SUPPORT */ + +#if COAP_CLIENT_SUPPORT + +static void +udp_recv_session_cb(sock_udp_t *sock, sock_async_flags_t flags, void *arg) { + coap_session_t *session = (coap_session_t *)arg; + + (void)sock; + if (!(flags & (SOCK_ASYNC_MSG_RECV | SOCK_ASYNC_MSG_SENT))) + return; + + if (flags & SOCK_ASYNC_MSG_RECV) + session->sock.flags |= COAP_SOCKET_CAN_READ; + if (session->context->selecting_thread) { + thread_flags_set(session->context->selecting_thread, + COAP_SELECT_THREAD_FLAG); + } +} + +int +coap_socket_connect_udp(coap_socket_t *sock, + const coap_address_t *local_if, + const coap_address_t *server, + int default_port, + coap_address_t *local_addr, + coap_address_t *remote_addr) { + sock_udp_ep_t local; + sock_udp_ep_t remote; + coap_address_t connect_addr; + int is_mcast = coap_is_mcast(server); + int ret; + + coap_address_copy(&connect_addr, server); + + sock->flags &= ~(COAP_SOCKET_CONNECTED | COAP_SOCKET_MULTICAST); + + if (local_if && local_if->riot.family) { + if (local_if->riot.family != connect_addr.riot.family) { + coap_log_warn("coap_socket_connect_udp: local address family != " + "remote address family\n"); + goto error; + } + } + + local.netif = SOCK_ADDR_ANY_NETIF; + remote.netif = SOCK_ADDR_ANY_NETIF; + switch (connect_addr.riot.family) { +#if COAP_IPV4_SUPPORT + case AF_INET: + local.family = AF_INET; + local.port = 0; + if (local_if) { + memcpy(local.addr.ipv4, &local_if->riot.addr.ipv4, sizeof(local.addr.ipv4)); + local.port = local_if->riot.port; + } else { + memset(local.addr.ipv4, 0, sizeof(local.addr.ipv4)); + } + remote.family = AF_INET; + memcpy(remote.addr.ipv4, &server->riot.addr.ipv4, sizeof(remote.addr.ipv4)); + if (connect_addr.riot.port == 0) + connect_addr.riot.port = default_port; + remote.port = connect_addr.riot.port; + break; +#endif /* COAP_IPV4_SUPPORT */ +#if COAP_IPV6_SUPPORT + case AF_INET6: + local.family = AF_INET6; + local.port = 0; + if (local_if) { + memcpy(local.addr.ipv6, &local_if->riot.addr.ipv6, sizeof(local.addr.ipv6)); + local.port = local_if->riot.port; + } else { + memset(local.addr.ipv6, 0, sizeof(local.addr.ipv6)); + } + remote.family = AF_INET6; + memcpy(remote.addr.ipv6, &server->riot.addr.ipv6, sizeof(remote.addr.ipv6)); + if (connect_addr.riot.port == 0) + connect_addr.riot.port = htons(default_port); + remote.port = connect_addr.riot.port; + break; +#endif /* COAP_IPV6_SUPPORT */ + default: + coap_log_alert("coap_socket_connect_udp: unsupported sa_family %d\n", + connect_addr.riot.family); + goto error; + } + + ret = sock_udp_create(&sock->udp, &local, &remote, is_mcast ? 0 : SOCK_FLAGS_CONNECT_REMOTE); + if (ret < 0) { + errno = -ret; + ret = -1; + coap_log_warn("coap_socket_connect_udp: sock_udp_create: %s (%d)\n", + coap_socket_strerror(), connect_addr.riot.family); + goto error; + } + ret = sock_udp_get_local(&sock->udp, &local); + if (ret != 0) { + errno = -ret; + ret = -1; + coap_log_warn("coap_socket_connect_udp: sock_udp_get_local: %s\n", + coap_socket_strerror()); + } + memcpy(&local_addr->riot, &local, sizeof(local_addr->riot)); + + ret = sock_udp_get_remote(&sock->udp, &remote); + if (ret != 0) { + errno = -ret; + ret = -1; + coap_log_warn("coap_socket_connect_udp: sock_udp_get_remote: %s\n", + coap_socket_strerror()); + } + memcpy(&remote_addr->riot, &remote, sizeof(remote_addr->riot)); + + sock_udp_set_cb(&sock->udp, udp_recv_session_cb, sock->session); + + /* special treatment for sockets that are used for multicast communication */ + if (is_mcast) { + coap_address_copy(remote_addr, &connect_addr); + coap_address_copy(&sock->mcast_addr, &connect_addr); + sock->flags |= COAP_SOCKET_MULTICAST; + return 1; + } + + sock->flags |= COAP_SOCKET_CONNECTED; + return 1; + +error: + coap_socket_dgrm_close(sock); + return 0; +} +#endif /* COAP_CLIENT_SUPPORT */ + +void +coap_socket_dgrm_close(coap_socket_t *sock) { + if (sock->flags != COAP_SOCKET_EMPTY) { + sock_udp_close(&sock->udp); + } + sock->flags = COAP_SOCKET_EMPTY; +} diff --git a/src/coap_io.c b/src/coap_io.c index b9a2c1c5..05ec214d 100644 --- a/src/coap_io.c +++ b/src/coap_io.c @@ -28,8 +28,6 @@ #endif #ifdef HAVE_SYS_SOCKET_H # include -# define OPTVAL_T(t) (t) -# define OPTVAL_GT(t) (t) #endif #ifdef HAVE_SYS_IOCTL_H #include @@ -37,13 +35,6 @@ #ifdef HAVE_NETINET_IN_H # include #endif -#ifdef HAVE_WS2TCPIP_H -#include -# define OPTVAL_T(t) (const char*)(t) -# define OPTVAL_GT(t) (char*)(t) -# undef CMSG_DATA -# define CMSG_DATA WSA_CMSG_DATA -#endif #ifdef HAVE_SYS_UIO_H # include #endif @@ -60,43 +51,8 @@ #else /* __ZEPHYR__ */ #include #include -#define OPTVAL_T(t) (const void*)(t) -#define OPTVAL_GT(t) (void*)(t) - -#ifndef IPV6_PKTINFO -#ifdef IPV6_RECVPKTINFO -#define IPV6_PKTINFO IPV6_RECVPKTINFO -#else -#define IPV6_PKTINFO IP_PKTINFO -#endif -#ifndef IN6_IS_ADDR_V4MAPPED -#define IN6_IS_ADDR_V4MAPPED(a) \ - ((((a)->s6_addr32[0]) == 0) && (((a)->s6_addr32[1]) == 0) && \ - (((a)->s6_addr32[2]) == htonl(0xffff))) -#endif -#endif #endif /* __ZEPHYR__ */ -#if !defined(WITH_CONTIKI) && !defined(RIOT_VERSION) && !defined(WITH_LWIP) -/* define generic PKTINFO for IPv4 */ -#if defined(IP_PKTINFO) -# define GEN_IP_PKTINFO IP_PKTINFO -#elif defined(IP_RECVDSTADDR) -# define GEN_IP_PKTINFO IP_RECVDSTADDR -#else -# error "Need IP_PKTINFO or IP_RECVDSTADDR to request ancillary data from OS." -#endif /* IP_PKTINFO */ - -/* define generic PKTINFO for IPv6 */ -#ifdef IPV6_RECVPKTINFO -# define GEN_IPV6_PKTINFO IPV6_RECVPKTINFO -#elif defined(IPV6_PKTINFO) -# define GEN_IPV6_PKTINFO IPV6_PKTINFO -#else -# error "Need IPV6_PKTINFO or IPV6_RECVPKTINFO to request ancillary data from OS." -#endif /* IPV6_RECVPKTINFO */ -#endif /* ! WITH_CONTIKI && ! RIOT_VERSION && ! WITH_LWIP */ - #if COAP_SERVER_SUPPORT coap_endpoint_t * coap_malloc_endpoint(void) { @@ -109,425 +65,6 @@ coap_mfree_endpoint(coap_endpoint_t *ep) { } #endif /* COAP_SERVER_SUPPORT */ -#if !defined(WITH_CONTIKI) && !defined(WITH_LWIP) && !defined(RIOT_VERSION) - -#if COAP_SERVER_SUPPORT -int -coap_socket_bind_udp(coap_socket_t *sock, - const coap_address_t *listen_addr, - coap_address_t *bound_addr) { -#ifndef RIOT_VERSION - int on = 1; -#if COAP_IPV6_SUPPORT - int off = 0; -#endif /* COAP_IPV6_SUPPORT */ -#else /* ! RIOT_VERSION */ - struct timeval timeout = {0, 0}; -#endif /* ! RIOT_VERSION */ -#ifdef _WIN32 - u_long u_on = 1; -#endif - - sock->fd = socket(listen_addr->addr.sa.sa_family, SOCK_DGRAM, 0); - - if (sock->fd == COAP_INVALID_SOCKET) { - coap_log_warn("coap_socket_bind_udp: socket: %s\n", coap_socket_strerror()); - goto error; - } -#ifndef RIOT_VERSION -#ifdef _WIN32 - if (ioctlsocket(sock->fd, FIONBIO, &u_on) == COAP_SOCKET_ERROR) -#else - if (ioctl(sock->fd, FIONBIO, &on) == COAP_SOCKET_ERROR) -#endif - { - coap_log_warn("coap_socket_bind_udp: ioctl FIONBIO: %s\n", coap_socket_strerror()); - } - - if (setsockopt(sock->fd, SOL_SOCKET, SO_REUSEADDR, OPTVAL_T(&on), sizeof(on)) == COAP_SOCKET_ERROR) - coap_log_warn("coap_socket_bind_udp: setsockopt SO_REUSEADDR: %s\n", - coap_socket_strerror()); - - switch (listen_addr->addr.sa.sa_family) { -#if COAP_IPV4_SUPPORT - case AF_INET: - if (setsockopt(sock->fd, IPPROTO_IP, GEN_IP_PKTINFO, OPTVAL_T(&on), - sizeof(on)) == COAP_SOCKET_ERROR) - coap_log_alert("coap_socket_bind_udp: setsockopt IP_PKTINFO: %s\n", - coap_socket_strerror()); - break; -#endif /* COAP_IPV4_SUPPORT */ -#if COAP_IPV6_SUPPORT - case AF_INET6: - /* Configure the socket as dual-stacked */ - if (setsockopt(sock->fd, IPPROTO_IPV6, IPV6_V6ONLY, OPTVAL_T(&off), - sizeof(off)) == COAP_SOCKET_ERROR) - coap_log_alert("coap_socket_bind_udp: setsockopt IPV6_V6ONLY: %s\n", - coap_socket_strerror()); -#if !defined(ESPIDF_VERSION) - if (setsockopt(sock->fd, IPPROTO_IPV6, GEN_IPV6_PKTINFO, OPTVAL_T(&on), - sizeof(on)) == COAP_SOCKET_ERROR) - coap_log_alert("coap_socket_bind_udp: setsockopt IPV6_PKTINFO: %s\n", - coap_socket_strerror()); -#endif /* !defined(ESPIDF_VERSION) */ -#endif /* COAP_IPV6_SUPPORT */ - setsockopt(sock->fd, IPPROTO_IP, GEN_IP_PKTINFO, OPTVAL_T(&on), sizeof(on)); - /* ignore error, because likely cause is that IPv4 is disabled at the os - level */ - break; -#if COAP_AF_UNIX_SUPPORT - case AF_UNIX: - break; -#endif /* COAP_AF_UNIX_SUPPORT */ - default: - coap_log_alert("coap_socket_bind_udp: unsupported sa_family\n"); - break; - } -#else /* RIOT_VERSION */ - if (setsockopt(sock->fd, SOL_SOCKET, SO_RCVTIMEO, OPTVAL_T(&timeout), - (socklen_t)sizeof(timeout)) == COAP_SOCKET_ERROR) - coap_log_alert("coap_socket_bind_udp: setsockopt SO_RCVTIMEO: %s\n", - coap_socket_strerror()); -#endif /* RIOT_VERSION */ - - if (bind(sock->fd, &listen_addr->addr.sa, -#if COAP_IPV4_SUPPORT - listen_addr->addr.sa.sa_family == AF_INET ? - (socklen_t)sizeof(struct sockaddr_in) : -#endif /* COAP_IPV4_SUPPORT */ - (socklen_t)listen_addr->size) == COAP_SOCKET_ERROR) { - coap_log_warn("coap_socket_bind_udp: bind: %s\n", - coap_socket_strerror()); - goto error; - } - - bound_addr->size = (socklen_t)sizeof(*bound_addr); - if (getsockname(sock->fd, &bound_addr->addr.sa, &bound_addr->size) < 0) { - coap_log_warn("coap_socket_bind_udp: getsockname: %s\n", - coap_socket_strerror()); - goto error; - } -#if defined(RIOT_VERSION) && defined(COAP_SERVER_SUPPORT) - if (sock->endpoint && - bound_addr->addr.sa.sa_family == AF_INET6) { - bound_addr->addr.sin6.sin6_scope_id = - listen_addr->addr.sin6.sin6_scope_id; - bound_addr->addr.sin6.sin6_flowinfo = 0; - } -#endif /* RIOT_VERSION && COAP_SERVER_SUPPORT */ - - return 1; - -error: - coap_socket_close(sock); - return 0; -} -#endif /* COAP_SERVER_SUPPORT */ - -#if COAP_CLIENT_SUPPORT -int -coap_socket_connect_udp(coap_socket_t *sock, - const coap_address_t *local_if, - const coap_address_t *server, - int default_port, - coap_address_t *local_addr, - coap_address_t *remote_addr) { - int on = 1; -#if COAP_IPV6_SUPPORT - int off = 0; -#endif /* COAP_IPV6_SUPPORT */ -#ifdef _WIN32 - u_long u_on = 1; -#endif - coap_address_t connect_addr; - int is_mcast = coap_is_mcast(server); - coap_address_copy(&connect_addr, server); - - sock->flags &= ~(COAP_SOCKET_CONNECTED | COAP_SOCKET_MULTICAST); - sock->fd = socket(connect_addr.addr.sa.sa_family, SOCK_DGRAM, 0); - - if (sock->fd == COAP_INVALID_SOCKET) { - coap_log_warn("coap_socket_connect_udp: socket: %s\n", - coap_socket_strerror()); - goto error; - } - -#ifdef _WIN32 - if (ioctlsocket(sock->fd, FIONBIO, &u_on) == COAP_SOCKET_ERROR) -#else - if (ioctl(sock->fd, FIONBIO, &on) == COAP_SOCKET_ERROR) -#endif - { - /* Ignore Zephyr unexpected Success response */ - if (errno != 0) { - int keep_errno = errno; - - coap_log_warn("coap_socket_connect_udp: ioctl FIONBIO: %s (%d)\n", - coap_socket_strerror(), keep_errno); - } - } - - switch (connect_addr.addr.sa.sa_family) { -#if COAP_IPV4_SUPPORT - case AF_INET: - if (connect_addr.addr.sin.sin_port == 0) - connect_addr.addr.sin.sin_port = htons(default_port); - break; -#endif /* COAP_IPV4_SUPPORT */ -#if COAP_IPV6_SUPPORT - case AF_INET6: - if (connect_addr.addr.sin6.sin6_port == 0) - connect_addr.addr.sin6.sin6_port = htons(default_port); - /* Configure the socket as dual-stacked */ - if (setsockopt(sock->fd, IPPROTO_IPV6, IPV6_V6ONLY, OPTVAL_T(&off), - sizeof(off)) == COAP_SOCKET_ERROR) - if (errno != ENOSYS) { - coap_log_warn("coap_socket_connect_udp: setsockopt IPV6_V6ONLY: %s\n", - coap_socket_strerror()); - } -#endif /* COAP_IPV6_SUPPORT */ - break; -#if COAP_AF_UNIX_SUPPORT - case AF_UNIX: - break; -#endif /* COAP_AF_UNIX_SUPPORT */ - default: - coap_log_alert("coap_socket_connect_udp: unsupported sa_family %d\n", - connect_addr.addr.sa.sa_family); - goto error;; - } - - if (local_if && local_if->addr.sa.sa_family) { - if (local_if->addr.sa.sa_family != connect_addr.addr.sa.sa_family) { - coap_log_warn("coap_socket_connect_udp: local address family != " - "remote address family\n"); - goto error; - } - if (setsockopt(sock->fd, SOL_SOCKET, SO_REUSEADDR, OPTVAL_T(&on), sizeof(on)) == COAP_SOCKET_ERROR) - coap_log_warn("coap_socket_connect_udp: setsockopt SO_REUSEADDR: %s\n", - coap_socket_strerror()); - if (bind(sock->fd, &local_if->addr.sa, -#if COAP_IPV4_SUPPORT - local_if->addr.sa.sa_family == AF_INET ? - (socklen_t)sizeof(struct sockaddr_in) : -#endif /* COAP_IPV4_SUPPORT */ - (socklen_t)local_if->size) == COAP_SOCKET_ERROR) { - coap_log_warn("coap_socket_connect_udp: bind: %s\n", - coap_socket_strerror()); - goto error; - } -#if COAP_AF_UNIX_SUPPORT - } else if (connect_addr.addr.sa.sa_family == AF_UNIX) { - /* Need to bind to a local address for clarity over endpoints */ - coap_log_warn("coap_socket_connect_udp: local address required\n"); - goto error; -#endif /* COAP_AF_UNIX_SUPPORT */ - } - - /* special treatment for sockets that are used for multicast communication */ - if (is_mcast) { - if (!(local_if && local_if->addr.sa.sa_family)) { - /* Bind to a (unused) port to simplify logging */ - coap_address_t bind_addr; - - coap_address_init(&bind_addr); - bind_addr.addr.sa.sa_family = connect_addr.addr.sa.sa_family; - if (bind(sock->fd, &bind_addr.addr.sa, -#if COAP_IPV4_SUPPORT - bind_addr.addr.sa.sa_family == AF_INET ? - (socklen_t)sizeof(struct sockaddr_in) : -#endif /* COAP_IPV4_SUPPORT */ - (socklen_t)bind_addr.size) == COAP_SOCKET_ERROR) { - coap_log_warn("coap_socket_connect_udp: bind: %s\n", - coap_socket_strerror()); - goto error; - } - } - if (getsockname(sock->fd, &local_addr->addr.sa, &local_addr->size) == COAP_SOCKET_ERROR) { - coap_log_warn("coap_socket_connect_udp: getsockname for multicast socket: %s\n", - coap_socket_strerror()); - } - coap_address_copy(remote_addr, &connect_addr); - coap_address_copy(&sock->mcast_addr, &connect_addr); - sock->flags |= COAP_SOCKET_MULTICAST; - if (coap_is_bcast(server) && - setsockopt(sock->fd, SOL_SOCKET, SO_BROADCAST, OPTVAL_T(&on), - sizeof(on)) == COAP_SOCKET_ERROR) - coap_log_warn("coap_socket_connect_udp: setsockopt SO_BROADCAST: %s\n", - coap_socket_strerror()); - return 1; - } - - if (connect(sock->fd, &connect_addr.addr.sa, connect_addr.size) == COAP_SOCKET_ERROR) { -#if COAP_AF_UNIX_SUPPORT - if (connect_addr.addr.sa.sa_family == AF_UNIX) { - coap_log_warn("coap_socket_connect_udp: connect: %s: %s\n", - connect_addr.addr.cun.sun_path, coap_socket_strerror()); - } else -#endif /* COAP_AF_UNIX_SUPPORT */ - { - coap_log_warn("coap_socket_connect_udp: connect: %s (%d)\n", - coap_socket_strerror(), connect_addr.addr.sa.sa_family); - } - goto error; - } - - if (getsockname(sock->fd, &local_addr->addr.sa, &local_addr->size) == COAP_SOCKET_ERROR) { - coap_log_warn("coap_socket_connect_udp: getsockname: %s\n", - coap_socket_strerror()); - } - - if (getpeername(sock->fd, &remote_addr->addr.sa, &remote_addr->size) == COAP_SOCKET_ERROR) { - coap_log_warn("coap_socket_connect_udp: getpeername: %s\n", - coap_socket_strerror()); - } - - sock->flags |= COAP_SOCKET_CONNECTED; - return 1; - -error: - coap_socket_close(sock); - return 0; -} -#endif /* COAP_CLIENT_SUPPORT */ - -void -coap_socket_close(coap_socket_t *sock) { - if (sock->fd != COAP_INVALID_SOCKET && !(sock->flags & COAP_SOCKET_SLAVE)) { -#ifdef COAP_EPOLL_SUPPORT -#if COAP_SERVER_SUPPORT - coap_context_t *context = sock->session ? sock->session->context : - sock->endpoint ? sock->endpoint->context : NULL; -#else /* COAP_SERVER_SUPPORT */ - coap_context_t *context = sock->session ? sock->session->context : NULL; -#endif /* COAP_SERVER_SUPPORT */ - if (context != NULL) { - int ret; - struct epoll_event event; - - /* Kernels prior to 2.6.9 expect non NULL event parameter */ - ret = epoll_ctl(context->epfd, EPOLL_CTL_DEL, sock->fd, &event); - if (ret == -1 && errno != ENOENT) { - coap_log_err("%s: epoll_ctl DEL failed: %d: %s (%d)\n", - "coap_socket_close", - sock->fd, - coap_socket_strerror(), errno); - } - } -#endif /* COAP_EPOLL_SUPPORT */ -#if COAP_SERVER_SUPPORT -#if COAP_AF_UNIX_SUPPORT - if (sock->endpoint && - sock->endpoint->bind_addr.addr.sa.sa_family == AF_UNIX) { - /* Clean up Unix endpoint */ -#ifdef _WIN32 - _unlink(sock->endpoint->bind_addr.addr.cun.sun_path); -#else /* ! _WIN32 */ - unlink(sock->endpoint->bind_addr.addr.cun.sun_path); -#endif /* ! _WIN32 */ - } -#endif /* COAP_AF_UNIX_SUPPORT */ - sock->endpoint = NULL; -#endif /* COAP_SERVER_SUPPORT */ -#if COAP_CLIENT_SUPPORT -#if COAP_AF_UNIX_SUPPORT - if (sock->session && sock->session->type == COAP_SESSION_TYPE_CLIENT && - sock->session->addr_info.local.addr.sa.sa_family == AF_UNIX) { - /* Clean up Unix endpoint */ -#ifdef _WIN32 - _unlink(sock->session->addr_info.local.addr.cun.sun_path); -#else /* ! _WIN32 */ - unlink(sock->session->addr_info.local.addr.cun.sun_path); -#endif /* ! _WIN32 */ - } -#endif /* COAP_AF_UNIX_SUPPORT */ -#endif /* COAP_CLIENT_SUPPORT */ - sock->session = NULL; - coap_closesocket(sock->fd); - sock->fd = COAP_INVALID_SOCKET; - } - sock->flags = COAP_SOCKET_EMPTY; -} - -#ifdef COAP_EPOLL_SUPPORT -void -coap_epoll_ctl_add(coap_socket_t *sock, - uint32_t events, - const char *func) { - int ret; - struct epoll_event event; - coap_context_t *context; - -#if COAP_MAX_LOGGING_LEVEL < _COAP_LOG_ERR - (void)func; -#endif - - if (sock == NULL) - return; - -#if COAP_SERVER_SUPPORT - context = sock->session ? sock->session->context : - sock->endpoint ? sock->endpoint->context : NULL; -#else /* ! COAP_SERVER_SUPPORT */ - context = sock->session ? sock->session->context : NULL; -#endif /* ! COAP_SERVER_SUPPORT */ - if (context == NULL) - return; - - /* Needed if running 32bit as ptr is only 32bit */ - memset(&event, 0, sizeof(event)); - event.events = events; - event.data.ptr = sock; - - ret = epoll_ctl(context->epfd, EPOLL_CTL_ADD, sock->fd, &event); - if (ret == -1) { - coap_log_err("%s: epoll_ctl ADD failed: %s (%d)\n", - func, - coap_socket_strerror(), errno); - } -} - -void -coap_epoll_ctl_mod(coap_socket_t *sock, - uint32_t events, - const char *func) { - int ret; - struct epoll_event event; - coap_context_t *context; - -#if COAP_MAX_LOGGING_LEVEL < _COAP_LOG_ERR - (void)func; -#endif - - if (sock == NULL) - return; - -#if COAP_SERVER_SUPPORT - context = sock->session ? sock->session->context : - sock->endpoint ? sock->endpoint->context : NULL; -#else /* COAP_SERVER_SUPPORT */ - context = sock->session ? sock->session->context : NULL; -#endif /* COAP_SERVER_SUPPORT */ - if (context == NULL) - return; - - event.events = events; - event.data.ptr = sock; - - ret = epoll_ctl(context->epfd, EPOLL_CTL_MOD, sock->fd, &event); - if (ret == -1) { -#if (COAP_MAX_LOGGING_LEVEL < COAP_LOG_ERR) - (void)func; -#endif - coap_log_err("%s: epoll_ctl MOD failed: %s (%d)\n", - func, - coap_socket_strerror(), errno); - } -} -#endif /* COAP_EPOLL_SUPPORT */ - -#endif /* ! WITH_CONTIKI && ! WITH_LWIP && ! RIOT_VERSION*/ - #ifndef WITH_CONTIKI void coap_update_io_timer(coap_context_t *context, coap_tick_t delay) { @@ -574,10 +111,8 @@ coap_update_io_timer(coap_context_t *context, coap_tick_t delay) { } #endif /* ! WITH_CONTIKI */ -#if !defined(WITH_CONTIKI) && !defined(WITH_LWIP) && !defined(RIOT_VERSION) - #ifdef _WIN32 -static void +void coap_win_error_to_errno(void) { int w_error = WSAGetLastError(); switch (w_error) { @@ -644,110 +179,6 @@ coap_win_error_to_errno(void) { } #endif /* _WIN32 */ -/* - * strm - * return +ve Number of bytes written. - * 0 No data written. - * -1 Error (error in errno). - */ -ssize_t -coap_socket_write(coap_socket_t *sock, const uint8_t *data, size_t data_len) { - ssize_t r; - - sock->flags &= ~(COAP_SOCKET_WANT_WRITE | COAP_SOCKET_CAN_WRITE); -#ifdef _WIN32 - r = send(sock->fd, (const char *)data, (int)data_len, 0); -#else -#ifndef MSG_NOSIGNAL -#define MSG_NOSIGNAL 0 -#endif /* MSG_NOSIGNAL */ - r = send(sock->fd, data, data_len, MSG_NOSIGNAL); -#endif - if (r == COAP_SOCKET_ERROR) { -#ifdef _WIN32 - coap_win_error_to_errno(); -#endif /* _WIN32 */ - if (errno==EAGAIN || -#if EAGAIN != EWOULDBLOCK - errno == EWOULDBLOCK || -#endif - errno == EINTR) { - sock->flags |= COAP_SOCKET_WANT_WRITE; -#ifdef COAP_EPOLL_SUPPORT - coap_epoll_ctl_mod(sock, - EPOLLOUT | - ((sock->flags & COAP_SOCKET_WANT_READ) ? - EPOLLIN : 0), - __func__); -#endif /* COAP_EPOLL_SUPPORT */ - return 0; - } - if (errno == EPIPE || errno == ECONNRESET) { - coap_log_info("coap_socket_write: send: %s\n", - coap_socket_strerror()); - } else { - coap_log_warn("coap_socket_write: send: %s\n", - coap_socket_strerror()); - } - return -1; - } - if (r < (ssize_t)data_len) { - sock->flags |= COAP_SOCKET_WANT_WRITE; -#ifdef COAP_EPOLL_SUPPORT - coap_epoll_ctl_mod(sock, - EPOLLOUT | - ((sock->flags & COAP_SOCKET_WANT_READ) ? - EPOLLIN : 0), - __func__); -#endif /* COAP_EPOLL_SUPPORT */ - } - return r; -} - -/* - * strm - * return >=0 Number of bytes read. - * -1 Error (error in errno). - */ -ssize_t -coap_socket_read(coap_socket_t *sock, uint8_t *data, size_t data_len) { - ssize_t r; - -#ifdef _WIN32 - r = recv(sock->fd, (char *)data, (int)data_len, 0); -#else - r = recv(sock->fd, data, data_len, 0); -#endif - if (r == 0) { - /* graceful shutdown */ - sock->flags &= ~COAP_SOCKET_CAN_READ; - errno = ECONNRESET; - return -1; - } else if (r == COAP_SOCKET_ERROR) { - sock->flags &= ~COAP_SOCKET_CAN_READ; -#ifdef _WIN32 - coap_win_error_to_errno(); -#endif /* _WIN32 */ - if (errno==EAGAIN || -#if EAGAIN != EWOULDBLOCK - errno == EWOULDBLOCK || -#endif - errno == EINTR) { - return 0; - } - if (errno != ECONNRESET) { - coap_log_warn("coap_socket_read: recv: %s\n", - coap_socket_strerror()); - } - return -1; - } - if (r < (ssize_t)data_len) - sock->flags &= ~COAP_SOCKET_CAN_READ; - return r; -} - -#endif /* ! WITH_CONTIKI && ! WITH_LWIP && ! RIOT_VERSION */ - #if !defined(WITH_LWIP) && !defined(__ZEPHYR__) #if (!defined(WITH_CONTIKI)) != ( defined(HAVE_NETINET_IN_H) || defined(HAVE_WS2TCPIP_H) ) /* define struct in6_pktinfo and struct in_pktinfo if not available @@ -768,525 +199,12 @@ struct in_pktinfo { #endif #endif /* ! WITH_LWIP && ! __ZEPHYR__ */ -#if !defined(WITH_CONTIKI) && !defined(SOL_IP) -/* Solaris expects level IPPROTO_IP for ancillary data. */ -#define SOL_IP IPPROTO_IP -#endif -#ifdef _WIN32 -#define COAP_SOL_IP IPPROTO_IP -#else /* ! _WIN32 */ -#define COAP_SOL_IP SOL_IP -#endif /* ! _WIN32 */ - -#if defined(_WIN32) -#include -#if defined(__MINGW32__) -static __thread LPFN_WSARECVMSG lpWSARecvMsg = NULL; -#if(_WIN32_WINNT >= 0x0600) -#define CMSG_FIRSTHDR WSA_CMSG_FIRSTHDR -#define CMSG_NXTHDR WSA_CMSG_NXTHDR -#define CMSG_LEN WSA_CMSG_LEN -#define CMSG_SPACE WSA_CMSG_SPACE -#if(_WIN32_WINNT < 0x0603 || _WIN32_WINNT == 0x0a00) -#define cmsghdr _WSACMSGHDR -#endif /* (_WIN32_WINNT<0x0603 || _WIN32_WINNT == 0x0a00) */ -#endif /* (_WIN32_WINNT>=0x0600) */ -#else /* ! __MINGW32__ */ -static __declspec(thread) LPFN_WSARECVMSG lpWSARecvMsg = NULL; -#endif /* ! __MINGW32__ */ -/* Map struct WSABUF fields to their posix counterpart */ -#define msghdr _WSAMSG -#define msg_name name -#define msg_namelen namelen -#define msg_iov lpBuffers -#define msg_iovlen dwBufferCount -#define msg_control Control.buf -#define msg_controllen Control.len -#define iovec _WSABUF -#define iov_base buf -#define iov_len len -#define iov_len_t u_long -#undef CMSG_DATA -#define CMSG_DATA WSA_CMSG_DATA -#define ipi_spec_dst ipi_addr -#if !defined(__MINGW32__) -#pragma warning( disable : 4116 ) -#endif /* ! __MINGW32__ */ -#else -#define iov_len_t size_t -#endif - -#if defined(_CYGWIN_ENV) || defined(__QNXNTO__) -#define ipi_spec_dst ipi_addr -#endif - -#if !defined(RIOT_VERSION) && !defined(WITH_LWIP) && !defined(WITH_CONTIKI) -#if COAP_CLIENT_SUPPORT -static uint32_t cid_track_counter; - -static void -coap_test_cid_tuple_change(coap_session_t *session) { - if (session->type == COAP_SESSION_TYPE_CLIENT && - session->negotiated_cid && - session->state == COAP_SESSION_STATE_ESTABLISHED && - session->proto == COAP_PROTO_DTLS && session->context->testing_cids) { - if ((++cid_track_counter) % session->context->testing_cids == 0) { - coap_address_t local_if = session->addr_info.local; - uint16_t port = coap_address_get_port(&local_if); - - port++; - coap_address_set_port(&local_if, port); - - coap_socket_close(&session->sock); - session->sock.session = session; - if (!coap_socket_connect_udp(&session->sock, &local_if, &session->addr_info.remote, - port, - &session->addr_info.local, - &session->addr_info.remote)) { - coap_log_err("Tuple change for CID failed\n"); - return; -#ifdef COAP_EPOLL_SUPPORT - } else { - coap_epoll_ctl_add(&session->sock, - EPOLLIN | - ((session->sock.flags & COAP_SOCKET_WANT_CONNECT) ? - EPOLLOUT : 0), - __func__); -#endif /* COAP_EPOLL_SUPPORT */ - } - session->sock.flags |= COAP_SOCKET_NOT_EMPTY | COAP_SOCKET_WANT_READ | COAP_SOCKET_BOUND; - } - } -} -#endif /* COAP_CLIENT_SUPPORT */ - -/* - * dgram - * return +ve Number of bytes written. - * -1 Error error in errno). - */ -ssize_t -coap_socket_send(coap_socket_t *sock, coap_session_t *session, - const uint8_t *data, size_t datalen) { - ssize_t bytes_written = 0; - -#if COAP_CLIENT_SUPPORT - coap_test_cid_tuple_change(session); -#endif /* COAP_CLIENT_SUPPORT */ - - if (!coap_debug_send_packet()) { - bytes_written = (ssize_t)datalen; - } else if (sock->flags & COAP_SOCKET_CONNECTED) { -#ifdef _WIN32 - bytes_written = send(sock->fd, (const char *)data, (int)datalen, 0); -#else - bytes_written = send(sock->fd, data, datalen, 0); -#endif - } else { -#if defined(_WIN32) - DWORD dwNumberOfBytesSent = 0; - int r; -#endif /* _WIN32 */ -#ifdef HAVE_STRUCT_CMSGHDR - /* a buffer large enough to hold all packet info types, ipv6 is the largest */ - char buf[CMSG_SPACE(sizeof(struct in6_pktinfo))]; - struct msghdr mhdr; - struct iovec iov[1]; - const void *addr = &session->addr_info.remote.addr; - - assert(session); - - memcpy(&iov[0].iov_base, &data, sizeof(iov[0].iov_base)); - iov[0].iov_len = (iov_len_t)datalen; - - memset(buf, 0, sizeof(buf)); - - memset(&mhdr, 0, sizeof(struct msghdr)); - memcpy(&mhdr.msg_name, &addr, sizeof(mhdr.msg_name)); - mhdr.msg_namelen = session->addr_info.remote.addr.sa.sa_family == AF_INET ? - (socklen_t)sizeof(struct sockaddr_in) : - session->addr_info.remote.size; - - mhdr.msg_iov = iov; - mhdr.msg_iovlen = 1; - - if (!coap_address_isany(&session->addr_info.local) && - !coap_is_mcast(&session->addr_info.local)) { - switch (session->addr_info.local.addr.sa.sa_family) { -#if COAP_IPV6_SUPPORT - case AF_INET6: { - struct cmsghdr *cmsg; - -#if COAP_IPV4_SUPPORT - if (IN6_IS_ADDR_V4MAPPED(&session->addr_info.local.addr.sin6.sin6_addr)) { -#if defined(IP_PKTINFO) - struct in_pktinfo *pktinfo; - mhdr.msg_control = buf; - mhdr.msg_controllen = CMSG_SPACE(sizeof(struct in_pktinfo)); - - cmsg = CMSG_FIRSTHDR(&mhdr); - cmsg->cmsg_level = COAP_SOL_IP; - cmsg->cmsg_type = IP_PKTINFO; - cmsg->cmsg_len = CMSG_LEN(sizeof(struct in_pktinfo)); - - pktinfo = (struct in_pktinfo *)CMSG_DATA(cmsg); - - pktinfo->ipi_ifindex = session->ifindex; - memcpy(&pktinfo->ipi_spec_dst, - session->addr_info.local.addr.sin6.sin6_addr.s6_addr + 12, - sizeof(pktinfo->ipi_spec_dst)); -#elif defined(IP_SENDSRCADDR) - mhdr.msg_control = buf; - mhdr.msg_controllen = CMSG_SPACE(sizeof(struct in_addr)); - - cmsg = CMSG_FIRSTHDR(&mhdr); - cmsg->cmsg_level = IPPROTO_IP; - cmsg->cmsg_type = IP_SENDSRCADDR; - cmsg->cmsg_len = CMSG_LEN(sizeof(struct in_addr)); - - memcpy(CMSG_DATA(cmsg), - session->addr_info.local.addr.sin6.sin6_addr.s6_addr + 12, - sizeof(struct in_addr)); -#endif /* IP_PKTINFO */ - } else { -#endif /* COAP_IPV4_SUPPORT */ - struct in6_pktinfo *pktinfo; - mhdr.msg_control = buf; - mhdr.msg_controllen = CMSG_SPACE(sizeof(struct in6_pktinfo)); - - cmsg = CMSG_FIRSTHDR(&mhdr); - cmsg->cmsg_level = IPPROTO_IPV6; - cmsg->cmsg_type = IPV6_PKTINFO; - cmsg->cmsg_len = CMSG_LEN(sizeof(struct in6_pktinfo)); - - pktinfo = (struct in6_pktinfo *)CMSG_DATA(cmsg); - - if (coap_is_mcast(&session->addr_info.remote)) { - pktinfo->ipi6_ifindex = session->addr_info.remote.addr.sin6.sin6_scope_id; - } else { - pktinfo->ipi6_ifindex = session->ifindex; - } - memcpy(&pktinfo->ipi6_addr, - &session->addr_info.local.addr.sin6.sin6_addr, - sizeof(pktinfo->ipi6_addr)); -#if COAP_IPV4_SUPPORT - } -#endif /* COAP_IPV4_SUPPORT */ - break; - } -#endif /* COAP_IPV6_SUPPORT */ -#if COAP_IPV4_SUPPORT - case AF_INET: { -#if defined(IP_PKTINFO) - struct cmsghdr *cmsg; - struct in_pktinfo *pktinfo; - - mhdr.msg_control = buf; - mhdr.msg_controllen = CMSG_SPACE(sizeof(struct in_pktinfo)); - - cmsg = CMSG_FIRSTHDR(&mhdr); - cmsg->cmsg_level = COAP_SOL_IP; - cmsg->cmsg_type = IP_PKTINFO; - cmsg->cmsg_len = CMSG_LEN(sizeof(struct in_pktinfo)); - - pktinfo = (struct in_pktinfo *)CMSG_DATA(cmsg); - - pktinfo->ipi_ifindex = session->ifindex; - memcpy(&pktinfo->ipi_spec_dst, - &session->addr_info.local.addr.sin.sin_addr, - sizeof(pktinfo->ipi_spec_dst)); -#elif defined(IP_SENDSRCADDR) - struct cmsghdr *cmsg; - mhdr.msg_control = buf; - mhdr.msg_controllen = CMSG_SPACE(sizeof(struct in_addr)); - - cmsg = CMSG_FIRSTHDR(&mhdr); - cmsg->cmsg_level = IPPROTO_IP; - cmsg->cmsg_type = IP_SENDSRCADDR; - cmsg->cmsg_len = CMSG_LEN(sizeof(struct in_addr)); - - memcpy(CMSG_DATA(cmsg), - &session->addr_info.local.addr.sin.sin_addr, - sizeof(struct in_addr)); -#endif /* IP_PKTINFO */ - break; - } -#endif /* COAP_IPV4_SUPPORT */ -#if COAP_AF_UNIX_SUPPORT - case AF_UNIX: - break; -#endif /* COAP_AF_UNIX_SUPPORT */ - default: - /* error */ - coap_log_warn("protocol not supported\n"); - return -1; - } - } -#endif /* HAVE_STRUCT_CMSGHDR */ - -#if defined(_WIN32) - r = WSASendMsg(sock->fd, &mhdr, 0 /*dwFlags*/, &dwNumberOfBytesSent, NULL /*lpOverlapped*/, - NULL /*lpCompletionRoutine*/); - if (r == 0) - bytes_written = (ssize_t)dwNumberOfBytesSent; - else { - bytes_written = -1; - coap_win_error_to_errno(); - } -#else /* !_WIN32 */ -#ifdef HAVE_STRUCT_CMSGHDR - bytes_written = sendmsg(sock->fd, &mhdr, 0); -#else /* ! HAVE_STRUCT_CMSGHDR */ - bytes_written = sendto(sock->fd, (const void *)data, datalen, 0, - &session->addr_info.remote.addr.sa, - session->addr_info.remote.size); -#endif /* ! HAVE_STRUCT_CMSGHDR */ -#endif /* !_WIN32 */ - } - - if (bytes_written < 0) - coap_log_crit("coap_socket_send: %s\n", coap_socket_strerror()); - - return bytes_written; -} -#endif /* ! RIOT_VERSION && ! WITH_LWIP && ! WITH_CONTIKI */ - -#define SIN6(A) ((struct sockaddr_in6 *)(A)) - void coap_packet_get_memmapped(coap_packet_t *packet, unsigned char **address, size_t *length) { *address = packet->payload; *length = packet->length; } -#if !defined(WITH_LWIP) && !defined(WITH_CONTIKI) && !defined(RIOT_VERSION) -/* - * dgram - * return +ve Number of bytes written. - * -1 Error error in errno). - * -2 ICMP error response - */ -ssize_t -coap_socket_recv(coap_socket_t *sock, coap_packet_t *packet) { - ssize_t len = -1; - - assert(sock); - assert(packet); - - if ((sock->flags & COAP_SOCKET_CAN_READ) == 0) { - return -1; - } else { - /* clear has-data flag */ - sock->flags &= ~COAP_SOCKET_CAN_READ; - } - - if (sock->flags & COAP_SOCKET_CONNECTED) { -#ifdef _WIN32 - len = recv(sock->fd, (char *)packet->payload, COAP_RXBUFFER_SIZE, 0); -#else - len = recv(sock->fd, packet->payload, COAP_RXBUFFER_SIZE, 0); -#endif - if (len < 0) { -#ifdef _WIN32 - coap_win_error_to_errno(); -#endif /* _WIN32 */ - if (errno == ECONNREFUSED || errno == EHOSTUNREACH || errno == ECONNRESET) { - /* client-side ICMP destination unreachable, ignore it */ - coap_log_warn("** %s: coap_socket_recv: ICMP: %s\n", - sock->session ? - coap_session_str(sock->session) : "", - coap_socket_strerror()); - return -2; - } - if (errno != EAGAIN) { - coap_log_warn("** %s: coap_socket_recv: %s\n", - sock->session ? - coap_session_str(sock->session) : "", - coap_socket_strerror()); - } - goto error; - } else if (len > 0) { - packet->length = (size_t)len; - } - } else { -#if defined(_WIN32) - DWORD dwNumberOfBytesRecvd = 0; - int r; -#endif /* _WIN32 */ -#ifdef HAVE_STRUCT_CMSGHDR - /* a buffer large enough to hold all packet info types, ipv6 is the largest */ - char buf[CMSG_SPACE(sizeof(struct in6_pktinfo))]; - struct cmsghdr *cmsg; - struct msghdr mhdr; - struct iovec iov[1]; - -#if defined(__MINGW32__) - iov[0].iov_base = (char *) packet->payload; -#else /* ! __MINGW32__ */ - iov[0].iov_base = packet->payload; -#endif /* defined(__MINGW32__) */ - iov[0].iov_len = (iov_len_t)COAP_RXBUFFER_SIZE; - - memset(&mhdr, 0, sizeof(struct msghdr)); - - mhdr.msg_name = (struct sockaddr *)&packet->addr_info.remote.addr; - mhdr.msg_namelen = sizeof(packet->addr_info.remote.addr); - - mhdr.msg_iov = iov; - mhdr.msg_iovlen = 1; - - mhdr.msg_control = buf; - mhdr.msg_controllen = sizeof(buf); - /* set a big first length incase recvmsg() does not implement updating - msg_control as well as preset the first cmsg with bad data */ - cmsg = (struct cmsghdr *)buf; - cmsg->cmsg_len = CMSG_LEN(sizeof(buf)); - cmsg->cmsg_level = -1; - cmsg->cmsg_type = -1; - -#if defined(_WIN32) - if (!lpWSARecvMsg) { - GUID wsaid = WSAID_WSARECVMSG; - DWORD cbBytesReturned = 0; - if (WSAIoctl(sock->fd, SIO_GET_EXTENSION_FUNCTION_POINTER, &wsaid, sizeof(wsaid), &lpWSARecvMsg, - sizeof(lpWSARecvMsg), &cbBytesReturned, NULL, NULL) != 0) { - coap_log_warn("coap_socket_recv: no WSARecvMsg\n"); - return -1; - } - } - r = lpWSARecvMsg(sock->fd, &mhdr, &dwNumberOfBytesRecvd, NULL /* LPWSAOVERLAPPED */, - NULL /* LPWSAOVERLAPPED_COMPLETION_ROUTINE */); - if (r == 0) - len = (ssize_t)dwNumberOfBytesRecvd; - else if (r == COAP_SOCKET_ERROR) - coap_win_error_to_errno(); -#else - len = recvmsg(sock->fd, &mhdr, 0); -#endif - -#else /* ! HAVE_STRUCT_CMSGHDR */ - len = recvfrom(sock->fd, (void *)packet->payload, COAP_RXBUFFER_SIZE, 0, - &packet->addr_info.remote.addr.sa, - &packet->addr_info.remote.size); -#endif /* ! HAVE_STRUCT_CMSGHDR */ - - if (len < 0) { -#ifdef _WIN32 - coap_win_error_to_errno(); -#endif /* _WIN32 */ - if (errno == ECONNREFUSED || errno == EHOSTUNREACH || errno == ECONNRESET) { - /* server-side ICMP destination unreachable, ignore it. The destination address is in msg_name. */ - coap_log_warn("** %s: coap_socket_recv: ICMP: %s\n", - sock->session ? - coap_session_str(sock->session) : "", - coap_socket_strerror()); - return 0; - } - if (errno != EAGAIN) { - coap_log_warn("coap_socket_recv: %s\n", coap_socket_strerror()); - } - goto error; - } else { -#ifdef HAVE_STRUCT_CMSGHDR - int dst_found = 0; - - packet->addr_info.remote.size = mhdr.msg_namelen; - packet->length = (size_t)len; - - /* Walk through ancillary data records until the local interface - * is found where the data was received. */ - for (cmsg = CMSG_FIRSTHDR(&mhdr); cmsg; cmsg = CMSG_NXTHDR(&mhdr, cmsg)) { - -#if COAP_IPV6_SUPPORT - /* get the local interface for IPv6 */ - if (cmsg->cmsg_level == IPPROTO_IPV6 && cmsg->cmsg_type == IPV6_PKTINFO) { - union { - uint8_t *c; - struct in6_pktinfo *p; - } u; - u.c = CMSG_DATA(cmsg); - packet->ifindex = (int)(u.p->ipi6_ifindex); - memcpy(&packet->addr_info.local.addr.sin6.sin6_addr, - &u.p->ipi6_addr, sizeof(struct in6_addr)); - dst_found = 1; - break; - } -#endif /* COAP_IPV6_SUPPORT */ - -#if COAP_IPV4_SUPPORT - /* local interface for IPv4 */ -#if defined(IP_PKTINFO) - if (cmsg->cmsg_level == COAP_SOL_IP && cmsg->cmsg_type == IP_PKTINFO) { - union { - uint8_t *c; - struct in_pktinfo *p; - } u; - u.c = CMSG_DATA(cmsg); - packet->ifindex = u.p->ipi_ifindex; -#if COAP_IPV6_SUPPORT - if (packet->addr_info.local.addr.sa.sa_family == AF_INET6) { - memset(packet->addr_info.local.addr.sin6.sin6_addr.s6_addr, 0, 10); - packet->addr_info.local.addr.sin6.sin6_addr.s6_addr[10] = 0xff; - packet->addr_info.local.addr.sin6.sin6_addr.s6_addr[11] = 0xff; - memcpy(packet->addr_info.local.addr.sin6.sin6_addr.s6_addr + 12, - &u.p->ipi_addr, sizeof(struct in_addr)); - } else -#endif /* COAP_IPV6_SUPPORT */ - { - memcpy(&packet->addr_info.local.addr.sin.sin_addr, - &u.p->ipi_addr, sizeof(struct in_addr)); - } - dst_found = 1; - break; - } -#endif /* IP_PKTINFO */ -#if defined(IP_RECVDSTADDR) - if (cmsg->cmsg_level == IPPROTO_IP && cmsg->cmsg_type == IP_RECVDSTADDR) { - packet->ifindex = (int)sock->fd; - memcpy(&packet->addr_info.local.addr.sin.sin_addr, - CMSG_DATA(cmsg), sizeof(struct in_addr)); - dst_found = 1; - break; - } -#endif /* IP_RECVDSTADDR */ -#endif /* COAP_IPV4_SUPPORT */ - if (!dst_found) { - /* cmsg_level / cmsg_type combination we do not understand - (ignore preset case for bad recvmsg() not updating cmsg) */ - if (cmsg->cmsg_level != -1 && cmsg->cmsg_type != -1) { - coap_log_debug("cmsg_level = %d and cmsg_type = %d not supported - fix\n", - cmsg->cmsg_level, cmsg->cmsg_type); - } - } - } - if (!dst_found) { - /* Not expected, but cmsg_level and cmsg_type don't match above and - may need a new case */ - packet->ifindex = (int)sock->fd; - if (getsockname(sock->fd, &packet->addr_info.local.addr.sa, - &packet->addr_info.local.size) < 0) { - coap_log_debug("Cannot determine local port\n"); - } - } -#else /* ! HAVE_STRUCT_CMSGHDR */ - packet->length = (size_t)len; - packet->ifindex = 0; - if (getsockname(sock->fd, &packet->addr_info.local.addr.sa, - &packet->addr_info.local.size) < 0) { - coap_log_debug("Cannot determine local port\n"); - goto error; - } -#endif /* ! HAVE_STRUCT_CMSGHDR */ - } - } - - if (len >= 0) - return len; -error: - return -1; -} -#endif /* ! WITH_LWIP && ! WITH_CONTIKI && ! RIOT_VERSION */ - COAP_API unsigned int coap_io_prepare_epoll(coap_context_t *ctx, coap_tick_t now) { unsigned int ret; @@ -1827,474 +745,6 @@ coap_io_get_fds_lkd(coap_context_t *ctx, } #endif /* WITH_LWIP || WITH_CONTIKI */ -#if !defined(WITH_LWIP) && !defined(CONTIKI) && !defined(RIOT_VERSION) -COAP_API int -coap_io_process(coap_context_t *ctx, uint32_t timeout_ms) { - int ret; - - coap_lock_lock(return 0); - ret = coap_io_process_lkd(ctx, timeout_ms); - coap_lock_unlock(); - return ret; -} - -int -coap_io_process_lkd(coap_context_t *ctx, uint32_t timeout_ms) { - return coap_io_process_with_fds_lkd(ctx, timeout_ms, 0, NULL, NULL, NULL); -} - -COAP_API int -coap_io_process_with_fds(coap_context_t *ctx, uint32_t timeout_ms, - int enfds, fd_set *ereadfds, fd_set *ewritefds, - fd_set *eexceptfds) { - int ret; - - coap_lock_lock(return 0); - ret = coap_io_process_with_fds_lkd(ctx, timeout_ms, enfds, ereadfds, ewritefds, - eexceptfds); - coap_lock_unlock(); - return ret; -} - -#if !defined(COAP_EPOLL_SUPPORT) && COAP_THREAD_SAFE -static unsigned int -coap_io_prepare_fds(coap_context_t *ctx, - int enfds, fd_set *ereadfds, fd_set *ewritefds, - fd_set *eexceptfds) { - coap_session_t *s, *stmp; - unsigned int max_sockets = sizeof(ctx->sockets) / sizeof(ctx->sockets[0]); - coap_fd_t nfds = 0; - unsigned int i; - - ctx->num_sockets = 0; -#if COAP_SERVER_SUPPORT - coap_endpoint_t *ep; - - LL_FOREACH(ctx->endpoint, ep) { - if (ep->sock.flags & (COAP_SOCKET_WANT_READ | COAP_SOCKET_WANT_WRITE | COAP_SOCKET_WANT_ACCEPT)) { - if (ctx->num_sockets < max_sockets) - ctx->sockets[ctx->num_sockets++] = &ep->sock; - } - SESSIONS_ITER(ep->sessions, s, stmp) { - if (s->sock.flags & (COAP_SOCKET_WANT_READ|COAP_SOCKET_WANT_WRITE)) { - if (ctx->num_sockets < max_sockets) - ctx->sockets[ctx->num_sockets++] = &s->sock; - } - } - } -#endif /* COAP_SERVER_SUPPORT */ -#if COAP_CLIENT_SUPPORT - SESSIONS_ITER(ctx->sessions, s, stmp) { - if (s->sock.flags & (COAP_SOCKET_WANT_READ | - COAP_SOCKET_WANT_WRITE | - COAP_SOCKET_WANT_CONNECT)) { - if (ctx->num_sockets < max_sockets) - ctx->sockets[ctx->num_sockets++] = &s->sock; - } - } -#endif /* COAP_CLIENT_SUPPORT */ - if (ereadfds) { - ctx->readfds = *ereadfds; - nfds = enfds; - } else { - FD_ZERO(&ctx->readfds); - } - if (ewritefds) { - ctx->writefds = *ewritefds; - nfds = enfds; - } else { - FD_ZERO(&ctx->writefds); - } - if (eexceptfds) { - ctx->exceptfds = *eexceptfds; - nfds = enfds; - } else { - FD_ZERO(&ctx->exceptfds); - } - for (i = 0; i < ctx->num_sockets; i++) { - if (ctx->sockets[i]->fd + 1 > nfds) - nfds = ctx->sockets[i]->fd + 1; - if (ctx->sockets[i]->flags & COAP_SOCKET_WANT_READ) - FD_SET(ctx->sockets[i]->fd, &ctx->readfds); - if (ctx->sockets[i]->flags & COAP_SOCKET_WANT_WRITE) - FD_SET(ctx->sockets[i]->fd, &ctx->writefds); -#if !COAP_DISABLE_TCP - if (ctx->sockets[i]->flags & COAP_SOCKET_WANT_ACCEPT) - FD_SET(ctx->sockets[i]->fd, &ctx->readfds); - if (ctx->sockets[i]->flags & COAP_SOCKET_WANT_CONNECT) { - FD_SET(ctx->sockets[i]->fd, &ctx->writefds); - FD_SET(ctx->sockets[i]->fd, &ctx->exceptfds); - } -#endif /* !COAP_DISABLE_TCP */ - } - return nfds; -} -#endif /* ! COAP_EPOLL_SUPPORT && COAP_THREAD_SAFE */ - -int -coap_io_process_with_fds_lkd(coap_context_t *ctx, uint32_t timeout_ms, - int enfds, fd_set *ereadfds, fd_set *ewritefds, - fd_set *eexceptfds) { - coap_fd_t nfds = 0; - coap_tick_t before, now; - unsigned int timeout; -#ifndef COAP_EPOLL_SUPPORT - struct timeval tv; - int result; - unsigned int i; -#endif /* ! COAP_EPOLL_SUPPORT */ - - coap_lock_check_locked(); - coap_ticks(&before); - -#ifndef COAP_EPOLL_SUPPORT - - timeout = coap_io_prepare_io_lkd(ctx, ctx->sockets, - (sizeof(ctx->sockets) / sizeof(ctx->sockets[0])), - &ctx->num_sockets, before); - ctx->next_timeout = timeout ? timeout + before : 0; - - if (ereadfds) { - ctx->readfds = *ereadfds; - nfds = enfds; - } else { - FD_ZERO(&ctx->readfds); - } - if (ewritefds) { - ctx->writefds = *ewritefds; - nfds = enfds; - } else { - FD_ZERO(&ctx->writefds); - } - if (eexceptfds) { - ctx->exceptfds = *eexceptfds; - nfds = enfds; - } else { - FD_ZERO(&ctx->exceptfds); - } - for (i = 0; i < ctx->num_sockets; i++) { - if (ctx->sockets[i]->fd + 1 > nfds) - nfds = ctx->sockets[i]->fd + 1; - if (ctx->sockets[i]->flags & COAP_SOCKET_WANT_READ) - FD_SET(ctx->sockets[i]->fd, &ctx->readfds); - if (ctx->sockets[i]->flags & COAP_SOCKET_WANT_WRITE) - FD_SET(ctx->sockets[i]->fd, &ctx->writefds); -#if !COAP_DISABLE_TCP - if (ctx->sockets[i]->flags & COAP_SOCKET_WANT_ACCEPT) - FD_SET(ctx->sockets[i]->fd, &ctx->readfds); - if (ctx->sockets[i]->flags & COAP_SOCKET_WANT_CONNECT) { - FD_SET(ctx->sockets[i]->fd, &ctx->writefds); - FD_SET(ctx->sockets[i]->fd, &ctx->exceptfds); - } -#endif /* !COAP_DISABLE_TCP */ - } - - if (timeout_ms == COAP_IO_NO_WAIT) { - tv.tv_usec = 0; - tv.tv_sec = 0; - timeout = 1; - } else if (timeout == 0 && timeout_ms == COAP_IO_WAIT) { - ; - } else { - if (timeout == 0 || (timeout_ms != COAP_IO_WAIT && timeout_ms < timeout)) - timeout = timeout_ms; - tv.tv_usec = (timeout % 1000) * 1000; - tv.tv_sec = (long)(timeout / 1000); - } - - /* on Windows select will return an error if called without FDs */ - if (nfds > 0) { - /* Unlock so that other threads can lock/update ctx */ - coap_lock_unlock(); - - result = select((int)nfds, &ctx->readfds, &ctx->writefds, &ctx->exceptfds, - timeout > 0 ? &tv : NULL); - - coap_lock_lock(return -1); - } else { - goto all_over; - } - - if (result < 0) { /* error */ -#ifdef _WIN32 - coap_win_error_to_errno(); -#endif - if (errno != EINTR) { -#if COAP_THREAD_SAFE - if (errno == EBADF) { - coap_log_debug("select: %s\n", coap_socket_strerror()); - goto all_over; - } -#endif /* COAP_THREAD_SAFE */ - coap_log_err("select: %s\n", coap_socket_strerror()); - return -1; - } - goto all_over; - } -#if COAP_THREAD_SAFE - /* Need to refresh what is available to read / write etc. */ - nfds = coap_io_prepare_fds(ctx, enfds, ereadfds, ewritefds, eexceptfds); - tv.tv_usec = 0; - tv.tv_sec = 0; - result = select((int)nfds, &ctx->readfds, &ctx->writefds, &ctx->exceptfds, &tv); - if (result < 0) { /* error */ -#ifdef _WIN32 - coap_win_error_to_errno(); -#endif - if (errno != EINTR) { - if (errno == EBADF) { - coap_log_debug("select: %s\n", coap_socket_strerror()); - goto all_over; - } - coap_log_err("select: %s\n", coap_socket_strerror()); - return -1; - } - goto all_over; - } -#endif /* COAP_THREAD_SAFE */ - if (ereadfds) { - *ereadfds = ctx->readfds; - } - if (ewritefds) { - *ewritefds = ctx->writefds; - } - if (eexceptfds) { - *eexceptfds = ctx->exceptfds; - } - - if (result > 0) { - for (i = 0; i < ctx->num_sockets; i++) { - if ((ctx->sockets[i]->flags & COAP_SOCKET_WANT_READ) && - FD_ISSET(ctx->sockets[i]->fd, &ctx->readfds)) - ctx->sockets[i]->flags |= COAP_SOCKET_CAN_READ; -#if !COAP_DISABLE_TCP - if ((ctx->sockets[i]->flags & COAP_SOCKET_WANT_ACCEPT) && - FD_ISSET(ctx->sockets[i]->fd, &ctx->readfds)) - ctx->sockets[i]->flags |= COAP_SOCKET_CAN_ACCEPT; - if ((ctx->sockets[i]->flags & COAP_SOCKET_WANT_WRITE) && - FD_ISSET(ctx->sockets[i]->fd, &ctx->writefds)) - ctx->sockets[i]->flags |= COAP_SOCKET_CAN_WRITE; - if ((ctx->sockets[i]->flags & COAP_SOCKET_WANT_CONNECT) && - (FD_ISSET(ctx->sockets[i]->fd, &ctx->writefds) || - FD_ISSET(ctx->sockets[i]->fd, &ctx->exceptfds))) - ctx->sockets[i]->flags |= COAP_SOCKET_CAN_CONNECT; -#endif /* !COAP_DISABLE_TCP */ - } - } - - coap_ticks(&now); - coap_io_do_io_lkd(ctx, now); - coap_ticks(&now); - timeout = coap_io_prepare_io_lkd(ctx, ctx->sockets, - (sizeof(ctx->sockets) / sizeof(ctx->sockets[0])), - &ctx->num_sockets, now); - ctx->next_timeout = timeout ? timeout + now : 0; - -#else /* COAP_EPOLL_SUPPORT */ - (void)ereadfds; - (void)ewritefds; - (void)eexceptfds; - (void)enfds; - - timeout = coap_io_prepare_epoll_lkd(ctx, before); - - do { - struct epoll_event events[COAP_MAX_EPOLL_EVENTS]; - int etimeout; - - /* Potentially adjust based on what the caller wants */ - if (timeout_ms == COAP_IO_NO_WAIT) { - /* Need to return immediately from epoll_wait() */ - etimeout = 0; - } else if (timeout == 0 && timeout_ms == COAP_IO_WAIT) { - /* - * Nothing found in coap_io_prepare_epoll_lkd() and COAP_IO_WAIT set, - * so wait forever in epoll_wait(). - */ - etimeout = -1; - } else { - etimeout = timeout; - if (timeout == 0 || (timeout_ms != COAP_IO_WAIT && timeout_ms < timeout)) - etimeout = timeout_ms; - if (etimeout < 0) { - /* - * If timeout > INT_MAX, epoll_wait() cannot wait longer than this as - * it has int timeout parameter - */ - etimeout = INT_MAX; - } - } - - /* Unlock so that other threads can lock/update ctx */ - coap_lock_unlock(); - - nfds = epoll_wait(ctx->epfd, events, COAP_MAX_EPOLL_EVENTS, etimeout); - if (nfds < 0) { - if (errno != EINTR) { - coap_log_err("epoll_wait: unexpected error: %s (%d)\n", - coap_socket_strerror(), nfds); - } - coap_lock_lock(return -1); - break; - } - - coap_lock_lock(return -1); -#if COAP_THREAD_SAFE - /* Need to refresh what is available to read / write etc. */ - nfds = epoll_wait(ctx->epfd, events, COAP_MAX_EPOLL_EVENTS, 0); - if (nfds < 0) { - if (errno != EINTR) { - coap_log_err("epoll_wait: unexpected error: %s (%d)\n", - coap_socket_strerror(), nfds); - } - break; - } -#endif /* COAP_THREAD_SAFE */ - - coap_io_do_epoll_lkd(ctx, events, nfds); - - /* - * reset to COAP_IO_NO_WAIT (which causes etimeout to become 0) - * incase we have to do another iteration - * (COAP_MAX_EPOLL_EVENTS insufficient) - */ - timeout_ms = COAP_IO_NO_WAIT; - - /* Keep retrying until less than COAP_MAX_EPOLL_EVENTS are returned */ - } while (nfds == COAP_MAX_EPOLL_EVENTS); - -#endif /* COAP_EPOLL_SUPPORT */ -#if COAP_SERVER_SUPPORT - coap_expire_cache_entries(ctx); -#endif /* COAP_SERVER_SUPPORT */ -#if COAP_ASYNC_SUPPORT - /* Check to see if we need to send off any Async requests as delay might - have been updated */ - coap_ticks(&now); - coap_check_async(ctx, now, NULL); -#endif /* COAP_ASYNC_SUPPORT */ - -#ifndef COAP_EPOLL_SUPPORT -all_over: -#endif /* COAP_EPOLL_SUPPORT */ - coap_ticks(&now); - return (int)(((now - before) * 1000) / COAP_TICKS_PER_SECOND); -} - -volatile int coap_thread_quit = 0; - -void -coap_io_process_terminate_loop(void) { - coap_send_recv_terminate(); - coap_thread_quit = 1; -} - -COAP_API int -coap_io_process_loop(coap_context_t *context, - coap_io_process_thread_t main_loop_code, - void *main_loop_code_arg, uint32_t timeout_ms, - uint32_t thread_count) { - int ret; - - if (!context) - return 0; - coap_lock_lock(return 0); - ret = coap_io_process_loop_lkd(context, main_loop_code, - main_loop_code_arg, timeout_ms, - thread_count); - coap_lock_unlock(); - return ret; -} - -int -coap_io_process_loop_lkd(coap_context_t *context, - coap_io_process_thread_t main_loop_code, - void *main_loop_code_arg, uint32_t timeout_ms, - uint32_t thread_count) { - int ret = 0;; - -#if COAP_THREAD_SAFE - if (thread_count > 1) { - if (!coap_io_process_configure_threads(context, thread_count - 1)) - return 0; - } -#else /* COAP_THREAD_SAFE */ - thread_count = 1; -#endif /* COAP_THREAD_SAFE */ - while (!coap_thread_quit) { - if (main_loop_code) { - coap_tick_t begin, end; - uint32_t used_ms; - - coap_ticks(&begin); - /* - * main_loop_codecode should not be blocking for any time, and not calling - * coap_io_process(). - */ - coap_lock_callback_release(main_loop_code(main_loop_code_arg), - /* On re-lock failure */ - ret = 0; break); - /* - * Need to delay for the remainder of timeout_ms. In case main_loop_code() - * is time sensitive (e.g Observe subscription to /time), delay to the - * start of the a second boundary - */ - coap_ticks(&end); - used_ms = (uint32_t)(end - begin) * 1000 / COAP_TICKS_PER_SECOND; - if (timeout_ms == COAP_IO_NO_WAIT || timeout_ms == COAP_IO_WAIT) { - ret = coap_io_process_lkd(context, timeout_ms); - } else if (timeout_ms > used_ms) { - /* Wait for remaining time rounded up to next second start */ - coap_tick_t next_time = end + (timeout_ms - used_ms) * COAP_TICKS_PER_SECOND / 1000; - unsigned int next_sec_us; - unsigned int next_sec_ms; - - next_sec_us = (timeout_ms - used_ms) * 1000000 / COAP_TICKS_PER_SECOND + 1000000 - - (coap_ticks_to_rt_us(next_time) % 1000000); - next_sec_ms = (next_sec_us + 999) / 1000; - if (next_sec_ms > timeout_ms && next_sec_ms > 1000) - next_sec_ms -= 1000; - ret = coap_io_process_lkd(context, next_sec_ms ? next_sec_ms : 1); - } else { - /* timeout_ms has expired */ - ret = coap_io_process_lkd(context, COAP_IO_NO_WAIT); - } - - if (thread_count == 1) { - /* - * Need to delay if only one thread until the remainder of - * timeout_ms is used up. Otherwise, another thread will be - * waiting on coap_io_process() to do any input / timeout work. - */ - coap_ticks(&end); - used_ms = (uint32_t)(end - begin) * 1000 / COAP_TICKS_PER_SECOND; - if (timeout_ms > 0 && timeout_ms < used_ms) { - ret = coap_io_process_lkd(context, used_ms - timeout_ms); - } else { - ret = coap_io_process_lkd(context, COAP_IO_NO_WAIT); - } - } - } else { - ret = coap_io_process_lkd(context, timeout_ms); - } - /* coap_io_process_lkd() can return 0 */ - if (ret >= 0) - ret = 1; - - if (ret < 0) { - ret = 0; - break; - } - } -#if COAP_THREAD_SAFE - coap_io_process_remove_threads(context); -#endif /* COAP_THREAD_SAFE */ - coap_thread_quit = 0; - return ret; -} - -#endif /* ! WITH_LWIP && ! WITH_CONTIKI && ! RIOT_VERSION*/ - COAP_API int coap_io_pending(coap_context_t *context) { int ret; @@ -2385,5 +835,3 @@ COAP_API void coap_socket_set_flags(coap_socket_t *sock, coap_socket_flags_t flags) { sock->flags = flags; } - -#undef SIN6 diff --git a/src/coap_io_contiki.c b/src/coap_io_contiki.c index 1bf2de92..efb3eedd 100644 --- a/src/coap_io_contiki.c +++ b/src/coap_io_contiki.c @@ -11,7 +11,7 @@ /** * @file coap_io_contiki.c - * @brief Contiki-NG-specific functions + * @brief Contiki-NG Netowrk specific functions */ #include "coap3/coap_libcoap_build.h" @@ -107,140 +107,6 @@ exit: PROCESS_END(); } -int -coap_socket_bind_udp(coap_socket_t *sock, - const coap_address_t *listen_addr, - coap_address_t *bound_addr) { - uip_ds6_addr_t *addr; - - addr = uip_ds6_get_global(ADDR_PREFERRED); - if (!addr) { - coap_log_err("coap_socket_bind_udp: called before getting an IPv6 address\n"); - return 0; - } - PROCESS_CONTEXT_BEGIN(&libcoap_io_process); - sock->udp_conn = udp_new(NULL, 0, sock); - PROCESS_CONTEXT_END(); - if (!sock->udp_conn) { - coap_log_err("coap_socket_bind_udp: udp_new returned NULL\n"); - return 0; - } - udp_bind(sock->udp_conn, listen_addr->port); - uip_ipaddr_copy(&bound_addr->addr, &addr->ipaddr); - bound_addr->port = sock->udp_conn->lport; - return 1; -} - -int -coap_socket_connect_udp(coap_socket_t *sock, - const coap_address_t *local_if, - const coap_address_t *server, - int default_port, - coap_address_t *local_addr, - coap_address_t *remote_addr) { - uip_ds6_addr_t *addr; - - if (local_if) { - coap_log_warn("coap_socket_connect_udp: ignoring local_if parameter\n"); - } - addr = uip_ds6_get_global(ADDR_PREFERRED); - if (!addr) { - coap_log_err("coap_socket_connect_udp: called before getting an IPv6 address\n"); - return 0; - } - PROCESS_CONTEXT_BEGIN(&libcoap_io_process); - sock->udp_conn = udp_new(&server->addr, server->port ? server->port : default_port, sock); - PROCESS_CONTEXT_END(); - if (!sock->udp_conn) { - coap_log_err("coap_socket_connect_udp: udp_new returned NULL\n"); - return 0; - } - uip_ipaddr_copy(&local_addr->addr, &addr->ipaddr); - local_addr->port = sock->udp_conn->lport; - uip_ipaddr_copy(&remote_addr->addr, &server->addr); - remote_addr->port = sock->udp_conn->rport; - sock->flags |= COAP_SOCKET_CONNECTED; - return 1; -} - -ssize_t -coap_socket_write(coap_socket_t *sock, const uint8_t *data, size_t data_len) { - return -1; -} - -ssize_t -coap_socket_read(coap_socket_t *sock, uint8_t *data, size_t data_len) { - return -1; -} - -void -coap_socket_close(coap_socket_t *sock) { - uip_udp_remove(sock->udp_conn); - sock->udp_conn = NULL; - sock->flags = COAP_SOCKET_EMPTY; -} - -/* - * dgram - * return +ve Number of bytes written. - * -1 Error error in errno). - */ -ssize_t -coap_socket_send(coap_socket_t *sock, coap_session_t *session, const uint8_t *data, - size_t datalen) { - ssize_t bytes_written = 0; - - if (!coap_debug_send_packet()) { - bytes_written = (ssize_t)datalen; - } else { - uip_udp_packet_sendto(sock->udp_conn, data, datalen, - &session->addr_info.remote.addr, session->addr_info.remote.port); - bytes_written = datalen; - } - - if (bytes_written < 0) { - coap_log_crit("coap_socket_send: %s\n", coap_socket_strerror()); - } - - return bytes_written; -} - -/* - * dgram - * return +ve Number of bytes written. - * -1 Error error in errno). - * -2 ICMP error response - */ -ssize_t -coap_socket_recv(coap_socket_t *sock, coap_packet_t *packet) { - ssize_t len; - - assert(sock); - assert(packet); - - if (!(sock->flags & COAP_SOCKET_CAN_READ)) { - return -1; - } - /* clear has-data flag */ - sock->flags &= ~COAP_SOCKET_CAN_READ; - - uip_ipaddr_copy(&packet->addr_info.remote.addr, &UIP_IP_BUF->srcipaddr); - packet->addr_info.remote.port = UIP_UDP_BUF->srcport; - uip_ipaddr_copy(&packet->addr_info.local.addr, &UIP_IP_BUF->destipaddr); - packet->addr_info.local.port = UIP_UDP_BUF->destport; - - len = uip_datalen(); - - if (len > COAP_RXBUFFER_SIZE) { - coap_log_warn("Received message does not fit within buffer\n"); - return -1; - } - packet->length = len; - packet->payload = uip_appdata; - - return len; -} - int coap_io_process_lkd(coap_context_t *ctx, uint32_t timeout_ms) { coap_tick_t before, now; @@ -259,66 +125,3 @@ coap_io_process_lkd(coap_context_t *ctx, uint32_t timeout_ms) { coap_ticks(&now); return (int)(((now - before) * 1000) / COAP_TICKS_PER_SECOND); } - -#if ! COAP_DISABLE_TCP - -#if COAP_CLIENT_SUPPORT -int -coap_socket_connect_tcp1(coap_socket_t *sock, - const coap_address_t *local_if, - const coap_address_t *server, - int default_port, - coap_address_t *local_addr, - coap_address_t *remote_addr) { - (void)sock; - (void)local_if; - (void)server; - (void)default_port; - (void)local_addr; - (void)remote_addr; - - return -1; -} - -int -coap_socket_connect_tcp2(coap_socket_t *sock, - coap_address_t *local_addr, - coap_address_t *remote_addr) { - (void)sock; - (void)local_addr; - (void)remote_addr; - - return -1; -} -#endif /* COAP_CLIENT_SUPPORT */ - -#if COAP_SERVER_SUPPORT - -int -coap_socket_bind_tcp(coap_socket_t *sock, - const coap_address_t *listen_addr, - coap_address_t *bound_addr) { - (void)sock; - (void)listen_addr; - (void)bound_addr; - - return -1; -} - -int -coap_socket_accept_tcp(coap_socket_t *server, - coap_socket_t *new_client, - coap_address_t *local_addr, - coap_address_t *remote_addr, - void *extra) { - (void)server; - (void)new_client; - (void)local_addr; - (void)remote_addr; - (void)extra; - - return -1; -} -#endif /* COAP_SERVER_SUPPORT */ - -#endif /* ! COAP_DISABLE_TCP */ diff --git a/src/coap_io_lwip.c b/src/coap_io_lwip.c index 8c1d07d2..15f73f12 100644 --- a/src/coap_io_lwip.c +++ b/src/coap_io_lwip.c @@ -1,4 +1,5 @@ -/* +/* coap_io_lwip.c -- Network I/O functions for libcoap using LwIP + * * Copyright (C) 2012,2014 Olaf Bergmann * 2014 chrysn * 2022-2025 Jon Shallow @@ -11,7 +12,7 @@ /** * @file coap_io_lwip.c - * @brief LwIP specific functions + * @brief LwIP specific Network I/O functions */ #include "coap3/coap_libcoap_build.h" @@ -143,726 +144,6 @@ coap_io_process_lkd(coap_context_t *context, uint32_t timeout_ms) { return (int)(((now - before) * 1000) / COAP_TICKS_PER_SECOND); } -/* - * Not used for LwIP (done with coap_recvc()), but need dummy function. - */ -ssize_t -coap_socket_recv(coap_socket_t *sock, coap_packet_t *packet) { - (void)sock; - (void)packet; - assert(0); - return -1; -} - -#if COAP_CLIENT_SUPPORT -/** Callback from lwIP when a package was received for a client. - * - * The current implementation deals this to coap_dispatch immediately, but - * other mechanisms (as storing the package in a queue and later fetching it - * when coap_io_do_io is called) can be envisioned. - * - * It handles everything coap_io_do_io does on other implementations. - */ -static void -coap_recvc(void *arg, struct udp_pcb *upcb, struct pbuf *p, - const ip_addr_t *addr, u16_t port) { - coap_pdu_t *pdu = NULL; - coap_session_t *session = (coap_session_t *)arg; - int result = -1; - (void)upcb; - - assert(session); - LWIP_ASSERT("Proto not supported for LWIP", COAP_PROTO_NOT_RELIABLE(session->proto)); - - if (p->len < 4) { - /* Minimum size of CoAP header - ignore runt */ - return; - } - coap_lock_lock(return); - memcpy(&session->addr_info.remote.addr, addr, sizeof(session->addr_info.remote.addr)); - coap_address_set_port(&session->addr_info.remote, port); - - coap_log_debug("* %s: lwip: recv %4d bytes\n", - coap_session_str(session), p->len); - if (session->proto == COAP_PROTO_DTLS) { - if (session->tls) { - result = coap_dtls_receive(session, p->payload, p->len); - if (result < 0) - goto error; - } - pbuf_free(p); - } else { - coap_opt_filter_t error_opts; - - pdu = coap_pdu_from_pbuf(p); - if (!pdu) - goto error; - - coap_option_filter_clear(&error_opts); - if (!coap_pdu_parse2(session->proto, p->payload, p->len, pdu, &error_opts)) { - coap_handle_event_lkd(session->context, COAP_EVENT_BAD_PACKET, session); - coap_log_warn("discard malformed PDU\n"); - if (error_opts.mask && COAP_PDU_IS_REQUEST(pdu)) { - coap_pdu_t *response = - coap_new_error_response(pdu, - COAP_RESPONSE_CODE(402), &error_opts); - if (!response) { - coap_log_warn("coap_handle_dgram: cannot create error response\n"); - } else { - if (coap_send_internal(session, response, NULL) == COAP_INVALID_MID) - coap_log_warn("coap_handle_dgram: error sending response\n"); - } - coap_delete_pdu_lkd(pdu); - coap_lock_unlock(); -#if NO_SYS == 0 - sys_sem_signal(&coap_io_timeout_sem); -#endif /* NO_SYS == 0 */ - return; - } else { - goto error; - } - } - coap_dispatch(session->context, session, pdu); - } -#if NO_SYS == 0 - sys_sem_signal(&coap_io_timeout_sem); -#endif /* NO_SYS == 0 */ - coap_delete_pdu_lkd(pdu); - coap_lock_unlock(); - return; - -error: - /* - * https://rfc-editor.org/rfc/rfc7252#section-4.2 MUST send RST - * https://rfc-editor.org/rfc/rfc7252#section-4.3 MAY send RST - */ - if (session) - coap_send_rst_lkd(session, pdu); - coap_delete_pdu_lkd(pdu); - coap_lock_unlock(); -#if NO_SYS == 0 - sys_sem_signal(&coap_io_timeout_sem); -#endif /* NO_SYS == 0 */ - return; -} -#endif /* ! COAP_CLIENT_SUPPORT */ - -#if COAP_SERVER_SUPPORT - -static void -coap_free_packet(coap_packet_t *packet) { - coap_free_type(COAP_PACKET, packet); -} - -/** Callback from lwIP when a UDP packet was received for a server. - * - * The current implementation deals this to coap_dispatch immediately, but - * other mechanisms (as storing the package in a queue and later fetching it - * when coap_io_do_io is called) can be envisioned. - * - * It handles everything coap_io_do_io does on other implementations. - */ -static void -coap_udp_recvs(void *arg, struct udp_pcb *upcb, struct pbuf *p, - const ip_addr_t *addr, u16_t port) { - coap_endpoint_t *ep = (coap_endpoint_t *)arg; - coap_pdu_t *pdu = NULL; - coap_session_t *session = NULL; - coap_tick_t now; - coap_packet_t *packet = NULL; - int result = -1; - - if (p->len < 4) { - /* Minimum size of CoAP header - ignore runt */ - goto error_free_pbuf; - } - - packet = coap_malloc_type(COAP_PACKET, sizeof(coap_packet_t)); - - /* this is fatal because due to the short life of the packet, never should - there be more than one coap_packet_t required */ - LWIP_ASSERT("Insufficient coap_packet_t resources.", packet != NULL); - /* Need to do this as there may be holes in addr_info */ - memset(&packet->addr_info, 0, sizeof(packet->addr_info)); - packet->length = p->len; - packet->payload = p->payload; - packet->addr_info.remote.port = port; - packet->addr_info.remote.addr = *addr; - packet->addr_info.local.port = upcb->local_port; - packet->addr_info.local.addr = *ip_current_dest_addr(); - packet->ifindex = netif_get_index(ip_current_netif()); - - coap_ticks(&now); - - coap_lock_lock(goto error_free_pbuf); - session = coap_endpoint_get_session(ep, packet, now); - if (!session) - goto error_free_pbuf; - LWIP_ASSERT("Proto not supported for LWIP", COAP_PROTO_NOT_RELIABLE(session->proto)); - - coap_log_debug("* %s: lwip: recv %4d bytes\n", - coap_session_str(session), p->len); - - if (session->proto == COAP_PROTO_DTLS) { - if (session->type == COAP_SESSION_TYPE_HELLO) - result = coap_dtls_hello(session, p->payload, p->len); - else if (session->tls) - result = coap_dtls_receive(session, p->payload, p->len); - if (session->type == COAP_SESSION_TYPE_HELLO && result == 1) - coap_session_new_dtls_session(session, now); - pbuf_free(p); - } else { - coap_opt_filter_t error_opts; - - pdu = coap_pdu_from_pbuf(p); - if (!pdu) - goto error; - - coap_option_filter_clear(&error_opts); - if (!coap_pdu_parse2(ep->proto, p->payload, p->len, pdu, &error_opts)) { - coap_handle_event_lkd(ep->context, COAP_EVENT_BAD_PACKET, session); - coap_log_warn("discard malformed PDU\n"); - if (error_opts.mask && COAP_PDU_IS_REQUEST(pdu)) { - coap_pdu_t *response = - coap_new_error_response(pdu, - COAP_RESPONSE_CODE(402), &error_opts); - if (!response) { - coap_log_warn("coap_handle_dgram: cannot create error response\n"); - } else { - if (coap_send_internal(session, response, NULL) == COAP_INVALID_MID) - coap_log_warn("coap_handle_dgram: error sending response\n"); - } - goto cleanup; - } else { - goto error; - } - } - coap_dispatch(ep->context, session, pdu); - } - - coap_delete_pdu_lkd(pdu); - coap_free_packet(packet); - coap_lock_unlock(); -#if NO_SYS == 0 - sys_sem_signal(&coap_io_timeout_sem); -#endif /* NO_SYS == 0 */ - return; - -error_free_pbuf: - pbuf_free(p); - -error: - /* - * https://rfc-editor.org/rfc/rfc7252#section-4.2 MUST send RST - * https://rfc-editor.org/rfc/rfc7252#section-4.3 MAY send RST - */ - if (session && pdu) - coap_send_rst_lkd(session, pdu); -cleanup: - coap_delete_pdu_lkd(pdu); - coap_free_packet(packet); - coap_lock_unlock(); -#if NO_SYS == 0 - sys_sem_signal(&coap_io_timeout_sem); -#endif /* NO_SYS == 0 */ - return; -} - -#endif /* ! COAP_SERVER_SUPPORT */ - -ssize_t -coap_socket_send_pdu(coap_socket_t *sock, coap_session_t *session, - coap_pdu_t *pdu) { - /* FIXME: we can't check this here with the existing infrastructure, but we - * should actually check that the pdu is not held by anyone but us. the - * respective pbuf is already exclusively owned by the pdu. */ - struct pbuf *pbuf; - int err; - - pbuf_realloc(pdu->pbuf, pdu->used_size + coap_pdu_parse_header_size(session->proto, - pdu->pbuf->payload)); - - if (coap_debug_send_packet()) { - /* Need to take a copy as we may be re-using the origin in a retransmit */ - pbuf = pbuf_clone(PBUF_TRANSPORT, PBUF_RAM, pdu->pbuf); - if (pbuf == NULL) - return -1; - err = udp_sendto(sock->udp_pcb, pbuf, &session->addr_info.remote.addr, - session->addr_info.remote.port); - pbuf_free(pbuf); - if (err < 0) - return -1; - } - return pdu->used_size; -} - -/* - * dgram - * return +ve Number of bytes written. - * -1 Error error in errno). - */ -ssize_t -coap_socket_send(coap_socket_t *sock, coap_session_t *session, - const uint8_t *data, size_t data_len) { - struct pbuf *pbuf; - int err; - - if (coap_debug_send_packet()) { - pbuf = pbuf_alloc(PBUF_TRANSPORT, data_len, PBUF_RAM); - if (pbuf == NULL) - return -1; - memcpy(pbuf->payload, data, data_len); - - coap_lock_invert(LOCK_TCPIP_CORE(), - UNLOCK_TCPIP_CORE(); return -1); - - err = udp_sendto(sock->udp_pcb, pbuf, &session->addr_info.remote.addr, - session->addr_info.remote.port); - - UNLOCK_TCPIP_CORE(); - - pbuf_free(pbuf); - if (err < 0) { - if (err == ERR_RTE) { - coap_log_warn("** %s: udp_send: Packet not routable\n", - coap_session_str(session)); - } else { - coap_log_warn("** %s: udp_send: error %d\n", - coap_session_str(session), err); - } - return -1; - } - } - return data_len; -} - -#if COAP_SERVER_SUPPORT -int -coap_socket_bind_udp(coap_socket_t *sock, - const coap_address_t *listen_addr, - coap_address_t *bound_addr) { - int err; - coap_address_t l_listen = *listen_addr; - - sock->udp_pcb = udp_new_ip_type(IPADDR_TYPE_ANY); - if (sock->udp_pcb == NULL) - return 0; - -#if LWIP_IPV6 && LWIP_IPV4 - if (l_listen.addr.type == IPADDR_TYPE_V6) - l_listen.addr.type = IPADDR_TYPE_ANY; -#endif /* LWIP_IPV6 && LWIP_IPV4 */ - udp_recv(sock->udp_pcb, coap_udp_recvs, (void *)sock->endpoint); - err = udp_bind(sock->udp_pcb, &l_listen.addr, l_listen.port); - if (err) { - udp_remove(sock->udp_pcb); - sock->udp_pcb = NULL; - } - *bound_addr = l_listen; - return err ? 0 : 1; -} -#endif /* COAP_SERVER_SUPPORT */ - -#if COAP_CLIENT_SUPPORT -int -coap_socket_connect_udp(coap_socket_t *sock, - const coap_address_t *local_if, - const coap_address_t *server, - int default_port, - coap_address_t *local_addr, - coap_address_t *remote_addr) { - err_t err; - struct udp_pcb *pcb; - int is_mcast = coap_is_mcast(server); - coap_address_t connect_addr; - - coap_address_copy(&connect_addr, server); - if (connect_addr.port == 0) - connect_addr.port = default_port; - - coap_lock_invert(LOCK_TCPIP_CORE(), - goto err_unlock); - - pcb = udp_new(); - - if (!pcb) { - goto err_unlock; - } - - if (local_if) { - pcb->local_ip = local_if->addr; - pcb->local_port = local_if->port; - } - err = udp_bind(pcb, &pcb->local_ip, pcb->local_port); - if (err) { - LWIP_DEBUGF(UDP_DEBUG | LWIP_DBG_TRACE | LWIP_DBG_LEVEL_SERIOUS, - ("coap_socket_connect_udp: port bind failed\n")); - goto err_udp_remove; - } - - if (local_addr) { - local_addr->addr = pcb->local_ip; - local_addr->port = pcb->local_port; - } - sock->session->addr_info.local.port = pcb->local_port; - - if (remote_addr) { - coap_address_copy(remote_addr, &connect_addr); - } - - if (is_mcast) { - coap_address_copy(&sock->mcast_addr, &connect_addr); - sock->flags |= COAP_SOCKET_MULTICAST; - } else { - err = udp_connect(pcb, &connect_addr.addr, connect_addr.port); - if (err) { - goto err_udp_unbind; - } - } - -#if LWIP_IPV6 && LWIP_IPV4 - pcb->local_ip.type = pcb->remote_ip.type; -#endif /* LWIP_IPV6 && LWIP_IPV4 */ - - sock->udp_pcb = pcb; - - udp_recv(sock->udp_pcb, coap_recvc, (void *)sock->session); - - UNLOCK_TCPIP_CORE(); - - return 1; - -err_udp_unbind: -err_udp_remove: - udp_remove(pcb); -err_unlock: - UNLOCK_TCPIP_CORE(); - return 0; -} -#endif /* ! COAP_CLIENT_SUPPORT */ - -#if ! COAP_DISABLE_TCP - -#include - -static void -do_tcp_err(void *arg, err_t err) { - coap_session_t *session = (coap_session_t *)arg; - - (void)err; - - coap_lock_lock(return); - coap_handle_event_lkd(session->context, COAP_EVENT_TCP_FAILED, session); - /* - * as per tcp_err() documentation, the corresponding pcb is already freed - * when this callback is called. So, stop a double free when - * coap_session_disconnected_lkd() eventually coap_socket_close() is called. - */ - session->sock.tcp_pcb = NULL; - coap_session_disconnected_lkd(session, COAP_NACK_NOT_DELIVERABLE); - coap_lock_unlock(); -} - -/** Callback from lwIP when a TCP packet is received. - * - * The current implementation invokes coap_read_session() to do the bulk of the - * work. - */ -static err_t -coap_tcp_recv(void *arg, struct tcp_pcb *tpcb, struct pbuf *p, err_t err) { - coap_session_t *session = (coap_session_t *)arg; - coap_socket_t *sock = &session->sock; - coap_tick_t now; - - (void)tpcb; - if (p == NULL) { - /* remote host closed connection */ - tcp_arg(sock->tcp_pcb, NULL); - tcp_recv(sock->tcp_pcb, NULL); - tcp_close(sock->tcp_pcb); - sock->tcp_pcb = NULL; - coap_lock_lock(return ERR_ARG); - coap_session_disconnected_lkd(session, COAP_NACK_NOT_DELIVERABLE); - coap_lock_unlock(); - return ERR_OK; - } else if (err != ERR_OK) { - /* cleanup, for unknown reason */ - if (p != NULL) { - pbuf_free(p); - } - return err; - } - - sock->p = p; - coap_lock_lock(return ERR_ARG); - coap_ticks(&now); - coap_read_session(session->context, session, now); - coap_lock_unlock(); - return ERR_OK; -} - -#if COAP_CLIENT_SUPPORT - -static err_t -do_tcp_connected(void *arg, struct tcp_pcb *tpcb, err_t err) { - coap_session_t *session = (coap_session_t *)arg; - coap_tick_t now; - - if (err) - return err; - coap_lock_lock(return ERR_ARG); - session->sock.flags |= COAP_SOCKET_CONNECTED; - session->addr_info.local.addr = tpcb->local_ip; - session->addr_info.local.port = tpcb->local_port; - tcp_recv(tpcb, coap_tcp_recv); - coap_ticks(&now); - coap_connect_session(session, now); - coap_lock_unlock(); - return ERR_OK; -} - -int -coap_socket_connect_tcp1(coap_socket_t *sock, - const coap_address_t *local_if, - const coap_address_t *server, - int default_port, - coap_address_t *local_addr, - coap_address_t *remote_addr) { - coap_address_t connect_addr; - err_t err; - - (void)local_addr; - (void)remote_addr; - - sock->flags &= ~(COAP_SOCKET_WANT_CONNECT | COAP_SOCKET_CONNECTED); - - sock->tcp_pcb = tcp_new_ip_type(IPADDR_TYPE_ANY); - if (sock->tcp_pcb == NULL) - return 0; - - tcp_arg(sock->tcp_pcb, sock->session); - tcp_recv(sock->tcp_pcb, coap_tcp_recv); - tcp_err(sock->tcp_pcb, do_tcp_err); - if (local_if) { - coap_address_t l_local_if = *local_if; -#if LWIP_IPV6 && LWIP_IPV4 - if (l_local_if.addr.type == IPADDR_TYPE_V6) - l_local_if.addr.type = IPADDR_TYPE_ANY; -#endif /* LWIP_IPV6 && LWIP_IPV4 */ - err = tcp_bind(sock->tcp_pcb, &l_local_if.addr, l_local_if.port); - if (err != ERR_OK) { - tcp_arg(sock->tcp_pcb, NULL); - tcp_recv(sock->tcp_pcb, NULL); - tcp_close(sock->tcp_pcb); - sock->tcp_pcb = NULL; - return 0; - } - } - coap_address_copy(&connect_addr, server); - if (connect_addr.port == 0) - connect_addr.port = htons(default_port); - - err = tcp_connect(sock->tcp_pcb, &connect_addr.addr, connect_addr.port, - do_tcp_connected); - if (err == ERR_OK) - sock->flags |= COAP_SOCKET_WANT_CONNECT | COAP_SOCKET_CONNECTED; - return err ? 0 : 1; -} - -int -coap_socket_connect_tcp2(coap_socket_t *sock, - coap_address_t *local_addr, - coap_address_t *remote_addr) { - (void)sock; - (void)local_addr; - (void)remote_addr; - - sock->flags &= ~(COAP_SOCKET_WANT_CONNECT | COAP_SOCKET_CAN_CONNECT); - return 1; -} -#endif /* COAP_CLIENT_SUPPORT */ - -#if COAP_SERVER_SUPPORT - -static err_t -do_tcp_accept(void *arg, struct tcp_pcb *newpcb, err_t err) { - coap_endpoint_t *endpoint = arg; - coap_session_t *session; - coap_tick_t now; - err_t ret_err = ERR_OK; - - if ((err != ERR_OK) || (newpcb == NULL)) { - return ERR_VAL; - } - coap_ticks(&now); - - coap_lock_lock(return ERR_MEM); - session = coap_new_server_session(endpoint->context, endpoint, newpcb); - - if (session) { - session->sock.tcp_pcb = newpcb; - session->last_rx_tx = now; - tcp_arg(newpcb, session); - tcp_setprio(newpcb, TCP_PRIO_MIN); - tcp_recv(newpcb, coap_tcp_recv); - tcp_err(newpcb, do_tcp_err); - } else { - ret_err = ERR_MEM; - } - coap_lock_unlock(); - return ret_err; -} - -int -coap_socket_bind_tcp(coap_socket_t *sock, - const coap_address_t *listen_addr, - coap_address_t *bound_addr) { - int err; - coap_address_t l_listen = *listen_addr; - struct tcp_pcb *tcp_pcb; - - sock->tcp_pcb = tcp_new_ip_type(IPADDR_TYPE_ANY); - if (sock->tcp_pcb == NULL) - return 0; - -#if LWIP_IPV6 && LWIP_IPV4 - if (l_listen.addr.type == IPADDR_TYPE_V6) - l_listen.addr.type = IPADDR_TYPE_ANY; -#endif /* LWIP_IPV6 && LWIP_IPV4 */ - tcp_arg(sock->tcp_pcb, sock->endpoint); - err = tcp_bind(sock->tcp_pcb, &l_listen.addr, l_listen.port); - if (err != ERR_OK) { - tcp_arg(sock->tcp_pcb, NULL); - tcp_recv(sock->tcp_pcb, NULL); - tcp_close(sock->tcp_pcb); - sock->tcp_pcb = NULL; - return 0; - } else { - tcp_pcb = tcp_listen(sock->tcp_pcb); - if (tcp_pcb) { - sock->tcp_pcb = tcp_pcb; - tcp_accept(sock->tcp_pcb, do_tcp_accept); - } else { - tcp_arg(sock->tcp_pcb, NULL); - tcp_recv(sock->tcp_pcb, NULL); - tcp_close(sock->tcp_pcb); - sock->tcp_pcb = NULL; - return 0; - } - } - *bound_addr = l_listen; - return err ? 0 : 1; -} - -int -coap_socket_accept_tcp(coap_socket_t *server, - coap_socket_t *new_client, - coap_address_t *local_addr, - coap_address_t *remote_addr, - void *extra) { - struct tcp_pcb *tcp_pcb = (struct tcp_pcb *)extra; - - (void)server; - - new_client->tcp_pcb = tcp_pcb; - local_addr->addr = tcp_pcb->local_ip; - local_addr->port = tcp_pcb->local_port; - remote_addr->addr = tcp_pcb->remote_ip; - remote_addr->port = tcp_pcb->remote_port; - return 1; -} -#endif /* COAP_SERVER_SUPPORT */ - -/* - * strm - * return +ve Number of bytes written. - * -1 Error error in errno). - */ -ssize_t -coap_socket_write(coap_socket_t *sock, const uint8_t *data, size_t data_len) { - struct pbuf *pbuf; - int err; - - pbuf = pbuf_alloc(PBUF_TRANSPORT, data_len, PBUF_RAM); - if (pbuf == NULL) - return -1; - memcpy(pbuf->payload, data, data_len); - - coap_lock_invert(LOCK_TCPIP_CORE(), - UNLOCK_TCPIP_CORE(); return 0); - - err = tcp_write(sock->tcp_pcb, pbuf->payload, pbuf->len, 1); - - UNLOCK_TCPIP_CORE(); - - pbuf_free(pbuf); - if (err < 0) - return -1; - return data_len; -} - -/* - * strm - * return >=0 Number of bytes read. - * -1 Error error in errno). - */ -ssize_t -coap_socket_read(coap_socket_t *sock, uint8_t *data, size_t data_len) { - if (sock->p) { - if (data_len < sock->p->len) { - uint8_t *ptr = (uint8_t *)sock->p->payload; - - /* Handle partial read of data request */ - memcpy(data, sock->p->payload, data_len); - sock->p->payload = &ptr[data_len]; - sock->p->len -= data_len; - return data_len; - } else { - data_len = sock->p->len; - memcpy(data, sock->p->payload, sock->p->len); - pbuf_free(sock->p); - sock->p = NULL; - return data_len; - } - } - return 0; -} -#endif /* !COAP_DISABLE_TCP */ - -void -coap_socket_close(coap_socket_t *sock) { - if (sock->udp_pcb) { - if (sock->session) { - coap_lock_invert(LOCK_TCPIP_CORE(), - UNLOCK_TCPIP_CORE(); return); - } else { - LOCK_TCPIP_CORE(); - } - udp_remove(sock->udp_pcb); - UNLOCK_TCPIP_CORE(); - sock->udp_pcb = NULL; - } -#if ! COAP_DISABLE_TCP - if (sock->tcp_pcb) { - tcp_arg(sock->tcp_pcb, NULL); -#if COAP_SERVER_SUPPORT - if (!sock->endpoint) -#endif /* COAP_SERVER_SUPPORT */ - tcp_recv(sock->tcp_pcb, NULL); - if (sock->session) { - coap_lock_invert(LOCK_TCPIP_CORE(), - UNLOCK_TCPIP_CORE(); return); - } else { - LOCK_TCPIP_CORE(); - } - tcp_close(sock->tcp_pcb); - UNLOCK_TCPIP_CORE(); - sock->tcp_pcb = NULL; - } -#endif /* !COAP_DISABLE_TCP */ - return; -} - int coap_is_mcast(const coap_address_t *a) { if (!a) diff --git a/src/coap_io_posix.c b/src/coap_io_posix.c new file mode 100644 index 00000000..9cb598f1 --- /dev/null +++ b/src/coap_io_posix.c @@ -0,0 +1,596 @@ +/* coap_io_posix.c -- Network I/O functions for libcoap using Posix + * + * Copyright (C) 2012,2014,2016-2025 Olaf Bergmann and others + * + * SPDX-License-Identifier: BSD-2-Clause + * + * This file is part of the CoAP library libcoap. Please see + * README for terms of use. + */ + +/** + * @file coap_io_posix.c + * @brief Posix specific Network I/O functions + */ + +#include "coap3/coap_libcoap_build.h" + +#ifdef HAVE_STDIO_H +# include +#endif +#ifdef HAVE_UNISTD_H +# include +#endif + +#ifndef __ZEPHYR__ +#ifdef HAVE_SYS_SELECT_H +# include +#endif +#ifdef HAVE_SYS_SOCKET_H +# include +#endif +#ifdef HAVE_SYS_IOCTL_H +#include +#endif +#ifdef HAVE_NETINET_IN_H +# include +#endif +#ifdef HAVE_SYS_UIO_H +# include +#endif +#ifdef _WIN32 +#include +#endif /* _WIN32 */ +#ifdef COAP_EPOLL_SUPPORT +#include +#include +#ifdef HAVE_LIMITS_H +#include +#endif +#endif /* COAP_EPOLL_SUPPORT */ +#else /* __ZEPHYR__ */ +#include +#include +#endif /* __ZEPHYR__ */ + +#ifdef COAP_EPOLL_SUPPORT +void +coap_epoll_ctl_add(coap_socket_t *sock, + uint32_t events, + const char *func) { + int ret; + struct epoll_event event; + coap_context_t *context; + +#if COAP_MAX_LOGGING_LEVEL < _COAP_LOG_ERR + (void)func; +#endif + + if (sock == NULL) + return; + +#if COAP_SERVER_SUPPORT + context = sock->session ? sock->session->context : + sock->endpoint ? sock->endpoint->context : NULL; +#else /* ! COAP_SERVER_SUPPORT */ + context = sock->session ? sock->session->context : NULL; +#endif /* ! COAP_SERVER_SUPPORT */ + if (context == NULL) + return; + + /* Needed if running 32bit as ptr is only 32bit */ + memset(&event, 0, sizeof(event)); + event.events = events; + event.data.ptr = sock; + + ret = epoll_ctl(context->epfd, EPOLL_CTL_ADD, sock->fd, &event); + if (ret == -1) { + coap_log_err("%s: epoll_ctl ADD failed: %s (%d)\n", + func, + coap_socket_strerror(), errno); + } +} + +void +coap_epoll_ctl_mod(coap_socket_t *sock, + uint32_t events, + const char *func) { + int ret; + struct epoll_event event; + coap_context_t *context; + +#if COAP_MAX_LOGGING_LEVEL < _COAP_LOG_ERR + (void)func; +#endif + + if (sock == NULL) + return; + +#if COAP_SERVER_SUPPORT + context = sock->session ? sock->session->context : + sock->endpoint ? sock->endpoint->context : NULL; +#else /* COAP_SERVER_SUPPORT */ + context = sock->session ? sock->session->context : NULL; +#endif /* COAP_SERVER_SUPPORT */ + if (context == NULL) + return; + + event.events = events; + event.data.ptr = sock; + + ret = epoll_ctl(context->epfd, EPOLL_CTL_MOD, sock->fd, &event); + if (ret == -1) { +#if (COAP_MAX_LOGGING_LEVEL < COAP_LOG_ERR) + (void)func; +#endif + coap_log_err("%s: epoll_ctl MOD failed: %s (%d)\n", + func, + coap_socket_strerror(), errno); + } +} +#endif /* COAP_EPOLL_SUPPORT */ + +COAP_API int +coap_io_process(coap_context_t *ctx, uint32_t timeout_ms) { + int ret; + + coap_lock_lock(return 0); + ret = coap_io_process_lkd(ctx, timeout_ms); + coap_lock_unlock(); + return ret; +} + +int +coap_io_process_lkd(coap_context_t *ctx, uint32_t timeout_ms) { + return coap_io_process_with_fds_lkd(ctx, timeout_ms, 0, NULL, NULL, NULL); +} + +COAP_API int +coap_io_process_with_fds(coap_context_t *ctx, uint32_t timeout_ms, + int enfds, fd_set *ereadfds, fd_set *ewritefds, + fd_set *eexceptfds) { + int ret; + + coap_lock_lock(return 0); + ret = coap_io_process_with_fds_lkd(ctx, timeout_ms, enfds, ereadfds, ewritefds, + eexceptfds); + coap_lock_unlock(); + return ret; +} + +#if !defined(COAP_EPOLL_SUPPORT) && COAP_THREAD_SAFE +static unsigned int +coap_io_prepare_fds(coap_context_t *ctx, + int enfds, fd_set *ereadfds, fd_set *ewritefds, + fd_set *eexceptfds) { + coap_session_t *s, *stmp; + unsigned int max_sockets = sizeof(ctx->sockets) / sizeof(ctx->sockets[0]); + coap_fd_t nfds = 0; + unsigned int i; + + ctx->num_sockets = 0; +#if COAP_SERVER_SUPPORT + coap_endpoint_t *ep; + + LL_FOREACH(ctx->endpoint, ep) { + if (ep->sock.flags & (COAP_SOCKET_WANT_READ | COAP_SOCKET_WANT_WRITE | COAP_SOCKET_WANT_ACCEPT)) { + if (ctx->num_sockets < max_sockets) + ctx->sockets[ctx->num_sockets++] = &ep->sock; + } + SESSIONS_ITER(ep->sessions, s, stmp) { + if (s->sock.flags & (COAP_SOCKET_WANT_READ|COAP_SOCKET_WANT_WRITE)) { + if (ctx->num_sockets < max_sockets) + ctx->sockets[ctx->num_sockets++] = &s->sock; + } + } + } +#endif /* COAP_SERVER_SUPPORT */ +#if COAP_CLIENT_SUPPORT + SESSIONS_ITER(ctx->sessions, s, stmp) { + if (s->sock.flags & (COAP_SOCKET_WANT_READ | + COAP_SOCKET_WANT_WRITE | + COAP_SOCKET_WANT_CONNECT)) { + if (ctx->num_sockets < max_sockets) + ctx->sockets[ctx->num_sockets++] = &s->sock; + } + } +#endif /* COAP_CLIENT_SUPPORT */ + if (ereadfds) { + ctx->readfds = *ereadfds; + nfds = enfds; + } else { + FD_ZERO(&ctx->readfds); + } + if (ewritefds) { + ctx->writefds = *ewritefds; + nfds = enfds; + } else { + FD_ZERO(&ctx->writefds); + } + if (eexceptfds) { + ctx->exceptfds = *eexceptfds; + nfds = enfds; + } else { + FD_ZERO(&ctx->exceptfds); + } + for (i = 0; i < ctx->num_sockets; i++) { + if (ctx->sockets[i]->fd + 1 > nfds) + nfds = ctx->sockets[i]->fd + 1; + if (ctx->sockets[i]->flags & COAP_SOCKET_WANT_READ) + FD_SET(ctx->sockets[i]->fd, &ctx->readfds); + if (ctx->sockets[i]->flags & COAP_SOCKET_WANT_WRITE) + FD_SET(ctx->sockets[i]->fd, &ctx->writefds); +#if !COAP_DISABLE_TCP + if (ctx->sockets[i]->flags & COAP_SOCKET_WANT_ACCEPT) + FD_SET(ctx->sockets[i]->fd, &ctx->readfds); + if (ctx->sockets[i]->flags & COAP_SOCKET_WANT_CONNECT) { + FD_SET(ctx->sockets[i]->fd, &ctx->writefds); + FD_SET(ctx->sockets[i]->fd, &ctx->exceptfds); + } +#endif /* !COAP_DISABLE_TCP */ + } + return nfds; +} +#endif /* ! COAP_EPOLL_SUPPORT && COAP_THREAD_SAFE */ + +int +coap_io_process_with_fds_lkd(coap_context_t *ctx, uint32_t timeout_ms, + int enfds, fd_set *ereadfds, fd_set *ewritefds, + fd_set *eexceptfds) { + coap_fd_t nfds = 0; + coap_tick_t before, now; + unsigned int timeout; +#ifndef COAP_EPOLL_SUPPORT + struct timeval tv; + int result; + unsigned int i; +#endif /* ! COAP_EPOLL_SUPPORT */ + + coap_lock_check_locked(); + coap_ticks(&before); + +#ifndef COAP_EPOLL_SUPPORT + + timeout = coap_io_prepare_io_lkd(ctx, ctx->sockets, + (sizeof(ctx->sockets) / sizeof(ctx->sockets[0])), + &ctx->num_sockets, before); + ctx->next_timeout = timeout ? timeout + before : 0; + + if (ereadfds) { + ctx->readfds = *ereadfds; + nfds = enfds; + } else { + FD_ZERO(&ctx->readfds); + } + if (ewritefds) { + ctx->writefds = *ewritefds; + nfds = enfds; + } else { + FD_ZERO(&ctx->writefds); + } + if (eexceptfds) { + ctx->exceptfds = *eexceptfds; + nfds = enfds; + } else { + FD_ZERO(&ctx->exceptfds); + } + for (i = 0; i < ctx->num_sockets; i++) { + if (ctx->sockets[i]->fd + 1 > nfds) + nfds = ctx->sockets[i]->fd + 1; + if (ctx->sockets[i]->flags & COAP_SOCKET_WANT_READ) + FD_SET(ctx->sockets[i]->fd, &ctx->readfds); + if (ctx->sockets[i]->flags & COAP_SOCKET_WANT_WRITE) + FD_SET(ctx->sockets[i]->fd, &ctx->writefds); +#if !COAP_DISABLE_TCP + if (ctx->sockets[i]->flags & COAP_SOCKET_WANT_ACCEPT) + FD_SET(ctx->sockets[i]->fd, &ctx->readfds); + if (ctx->sockets[i]->flags & COAP_SOCKET_WANT_CONNECT) { + FD_SET(ctx->sockets[i]->fd, &ctx->writefds); + FD_SET(ctx->sockets[i]->fd, &ctx->exceptfds); + } +#endif /* !COAP_DISABLE_TCP */ + } + + if (timeout_ms == COAP_IO_NO_WAIT) { + tv.tv_usec = 0; + tv.tv_sec = 0; + timeout = 1; + } else if (timeout == 0 && timeout_ms == COAP_IO_WAIT) { + ; + } else { + if (timeout == 0 || (timeout_ms != COAP_IO_WAIT && timeout_ms < timeout)) + timeout = timeout_ms; + tv.tv_usec = (timeout % 1000) * 1000; + tv.tv_sec = (long)(timeout / 1000); + } + + /* on Windows select will return an error if called without FDs */ + if (nfds > 0) { + /* Unlock so that other threads can lock/update ctx */ + coap_lock_unlock(); + + result = select((int)nfds, &ctx->readfds, &ctx->writefds, &ctx->exceptfds, + timeout > 0 ? &tv : NULL); + + coap_lock_lock(return -1); + } else { + goto all_over; + } + + if (result < 0) { /* error */ +#ifdef _WIN32 + coap_win_error_to_errno(); +#endif + if (errno != EINTR) { +#if COAP_THREAD_SAFE + if (errno == EBADF) { + coap_log_debug("select: %s\n", coap_socket_strerror()); + goto all_over; + } +#endif /* COAP_THREAD_SAFE */ + coap_log_err("select: %s\n", coap_socket_strerror()); + return -1; + } + goto all_over; + } +#if COAP_THREAD_SAFE + /* Need to refresh what is available to read / write etc. */ + nfds = coap_io_prepare_fds(ctx, enfds, ereadfds, ewritefds, eexceptfds); + tv.tv_usec = 0; + tv.tv_sec = 0; + result = select((int)nfds, &ctx->readfds, &ctx->writefds, &ctx->exceptfds, &tv); + if (result < 0) { /* error */ +#ifdef _WIN32 + coap_win_error_to_errno(); +#endif + if (errno != EINTR) { + if (errno == EBADF) { + coap_log_debug("select: %s\n", coap_socket_strerror()); + goto all_over; + } + coap_log_err("select: %s\n", coap_socket_strerror()); + return -1; + } + goto all_over; + } +#endif /* COAP_THREAD_SAFE */ + if (ereadfds) { + *ereadfds = ctx->readfds; + } + if (ewritefds) { + *ewritefds = ctx->writefds; + } + if (eexceptfds) { + *eexceptfds = ctx->exceptfds; + } + + if (result > 0) { + for (i = 0; i < ctx->num_sockets; i++) { + if ((ctx->sockets[i]->flags & COAP_SOCKET_WANT_READ) && + FD_ISSET(ctx->sockets[i]->fd, &ctx->readfds)) + ctx->sockets[i]->flags |= COAP_SOCKET_CAN_READ; +#if !COAP_DISABLE_TCP + if ((ctx->sockets[i]->flags & COAP_SOCKET_WANT_ACCEPT) && + FD_ISSET(ctx->sockets[i]->fd, &ctx->readfds)) + ctx->sockets[i]->flags |= COAP_SOCKET_CAN_ACCEPT; + if ((ctx->sockets[i]->flags & COAP_SOCKET_WANT_WRITE) && + FD_ISSET(ctx->sockets[i]->fd, &ctx->writefds)) + ctx->sockets[i]->flags |= COAP_SOCKET_CAN_WRITE; + if ((ctx->sockets[i]->flags & COAP_SOCKET_WANT_CONNECT) && + (FD_ISSET(ctx->sockets[i]->fd, &ctx->writefds) || + FD_ISSET(ctx->sockets[i]->fd, &ctx->exceptfds))) + ctx->sockets[i]->flags |= COAP_SOCKET_CAN_CONNECT; +#endif /* !COAP_DISABLE_TCP */ + } + } + + coap_ticks(&now); + coap_io_do_io_lkd(ctx, now); + coap_ticks(&now); + timeout = coap_io_prepare_io_lkd(ctx, ctx->sockets, + (sizeof(ctx->sockets) / sizeof(ctx->sockets[0])), + &ctx->num_sockets, now); + ctx->next_timeout = timeout ? timeout + now : 0; + +#else /* COAP_EPOLL_SUPPORT */ + (void)ereadfds; + (void)ewritefds; + (void)eexceptfds; + (void)enfds; + + timeout = coap_io_prepare_epoll_lkd(ctx, before); + + do { + struct epoll_event events[COAP_MAX_EPOLL_EVENTS]; + int etimeout; + + /* Potentially adjust based on what the caller wants */ + if (timeout_ms == COAP_IO_NO_WAIT) { + /* Need to return immediately from epoll_wait() */ + etimeout = 0; + } else if (timeout == 0 && timeout_ms == COAP_IO_WAIT) { + /* + * Nothing found in coap_io_prepare_epoll_lkd() and COAP_IO_WAIT set, + * so wait forever in epoll_wait(). + */ + etimeout = -1; + } else { + etimeout = timeout; + if (timeout == 0 || (timeout_ms != COAP_IO_WAIT && timeout_ms < timeout)) + etimeout = timeout_ms; + if (etimeout < 0) { + /* + * If timeout > INT_MAX, epoll_wait() cannot wait longer than this as + * it has int timeout parameter + */ + etimeout = INT_MAX; + } + } + + /* Unlock so that other threads can lock/update ctx */ + coap_lock_unlock(); + + nfds = epoll_wait(ctx->epfd, events, COAP_MAX_EPOLL_EVENTS, etimeout); + if (nfds < 0) { + if (errno != EINTR) { + coap_log_err("epoll_wait: unexpected error: %s (%d)\n", + coap_socket_strerror(), nfds); + } + coap_lock_lock(return -1); + break; + } + + coap_lock_lock(return -1); +#if COAP_THREAD_SAFE + /* Need to refresh what is available to read / write etc. */ + nfds = epoll_wait(ctx->epfd, events, COAP_MAX_EPOLL_EVENTS, 0); + if (nfds < 0) { + if (errno != EINTR) { + coap_log_err("epoll_wait: unexpected error: %s (%d)\n", + coap_socket_strerror(), nfds); + } + break; + } +#endif /* COAP_THREAD_SAFE */ + + coap_io_do_epoll_lkd(ctx, events, nfds); + + /* + * reset to COAP_IO_NO_WAIT (which causes etimeout to become 0) + * incase we have to do another iteration + * (COAP_MAX_EPOLL_EVENTS insufficient) + */ + timeout_ms = COAP_IO_NO_WAIT; + + /* Keep retrying until less than COAP_MAX_EPOLL_EVENTS are returned */ + } while (nfds == COAP_MAX_EPOLL_EVENTS); + +#endif /* COAP_EPOLL_SUPPORT */ +#if COAP_SERVER_SUPPORT + coap_expire_cache_entries(ctx); +#endif /* COAP_SERVER_SUPPORT */ +#if COAP_ASYNC_SUPPORT + /* Check to see if we need to send off any Async requests as delay might + have been updated */ + coap_ticks(&now); + coap_check_async(ctx, now, NULL); +#endif /* COAP_ASYNC_SUPPORT */ + +#ifndef COAP_EPOLL_SUPPORT +all_over: +#endif /* COAP_EPOLL_SUPPORT */ + coap_ticks(&now); + return (int)(((now - before) * 1000) / COAP_TICKS_PER_SECOND); +} + +volatile int coap_thread_quit = 0; + +void +coap_io_process_terminate_loop(void) { + coap_send_recv_terminate(); + coap_thread_quit = 1; +} + +COAP_API int +coap_io_process_loop(coap_context_t *context, + coap_io_process_thread_t main_loop_code, + void *main_loop_code_arg, uint32_t timeout_ms, + uint32_t thread_count) { + int ret; + + if (!context) + return 0; + coap_lock_lock(return 0); + ret = coap_io_process_loop_lkd(context, main_loop_code, + main_loop_code_arg, timeout_ms, + thread_count); + coap_lock_unlock(); + return ret; +} + +int +coap_io_process_loop_lkd(coap_context_t *context, + coap_io_process_thread_t main_loop_code, + void *main_loop_code_arg, uint32_t timeout_ms, + uint32_t thread_count) { + int ret = 0;; + +#if COAP_THREAD_SAFE + if (thread_count > 1) { + if (!coap_io_process_configure_threads(context, thread_count - 1)) + return 0; + } +#else /* COAP_THREAD_SAFE */ + thread_count = 1; +#endif /* COAP_THREAD_SAFE */ + while (!coap_thread_quit) { + if (main_loop_code) { + coap_tick_t begin, end; + uint32_t used_ms; + + coap_ticks(&begin); + /* + * main_loop_codecode should not be blocking for any time, and not calling + * coap_io_process(). + */ + coap_lock_callback_release(main_loop_code(main_loop_code_arg), + /* On re-lock failure */ + ret = 0; break); + /* + * Need to delay for the remainder of timeout_ms. In case main_loop_code() + * is time sensitive (e.g Observe subscription to /time), delay to the + * start of the a second boundary + */ + coap_ticks(&end); + used_ms = (uint32_t)(end - begin) * 1000 / COAP_TICKS_PER_SECOND; + if (timeout_ms == COAP_IO_NO_WAIT || timeout_ms == COAP_IO_WAIT) { + ret = coap_io_process_lkd(context, timeout_ms); + } else if (timeout_ms > used_ms) { + /* Wait for remaining time rounded up to next second start */ + coap_tick_t next_time = end + (timeout_ms - used_ms) * COAP_TICKS_PER_SECOND / 1000; + unsigned int next_sec_us; + unsigned int next_sec_ms; + + next_sec_us = (timeout_ms - used_ms) * 1000000 / COAP_TICKS_PER_SECOND + 1000000 - + (coap_ticks_to_rt_us(next_time) % 1000000); + next_sec_ms = (next_sec_us + 999) / 1000; + if (next_sec_ms > timeout_ms && next_sec_ms > 1000) + next_sec_ms -= 1000; + ret = coap_io_process_lkd(context, next_sec_ms ? next_sec_ms : 1); + } else { + /* timeout_ms has expired */ + ret = coap_io_process_lkd(context, COAP_IO_NO_WAIT); + } + + if (thread_count == 1) { + /* + * Need to delay if only one thread until the remainder of + * timeout_ms is used up. Otherwise, another thread will be + * waiting on coap_io_process() to do any input / timeout work. + */ + coap_ticks(&end); + used_ms = (uint32_t)(end - begin) * 1000 / COAP_TICKS_PER_SECOND; + if (timeout_ms > 0 && timeout_ms < used_ms) { + ret = coap_io_process_lkd(context, used_ms - timeout_ms); + } else { + ret = coap_io_process_lkd(context, COAP_IO_NO_WAIT); + } + } + } else { + ret = coap_io_process_lkd(context, timeout_ms); + } + /* coap_io_process_lkd() can return 0 */ + if (ret >= 0) + ret = 1; + + if (ret < 0) { + ret = 0; + break; + } + } +#if COAP_THREAD_SAFE + coap_io_process_remove_threads(context); +#endif /* COAP_THREAD_SAFE */ + coap_thread_quit = 0; + return ret; +} diff --git a/src/coap_io_riot.c b/src/coap_io_riot.c index c6a172ee..fdfda18d 100644 --- a/src/coap_io_riot.c +++ b/src/coap_io_riot.c @@ -10,7 +10,7 @@ /** * @file coap_io_riot.c - * @brief RIOT specific I/O functions + * @brief RIOT specific Network I/O functions */ #include "coap3/coap_libcoap_build.h" @@ -19,9 +19,6 @@ #include "net/gnrc/ipv6.h" #include "net/gnrc/netreg.h" #include "net/udp.h" -#if COAP_DISABLE_TCP -#include "net/tcp.h" -#endif /* ! COAP_DISABLE_TCP */ #include "net/sock/async.h" #include "coap3/coap_riot.h" @@ -99,595 +96,6 @@ coap_io_process_lkd(coap_context_t *ctx, uint32_t timeout_ms) { return (int)(((now - before) * 1000) / COAP_TICKS_PER_SECOND); } -/* - * dgram - * return +ve Number of bytes written. - * -1 Error error in errno). - */ -ssize_t -coap_socket_send(coap_socket_t *sock, - coap_session_t *session, - const uint8_t *data, - size_t datalen) { - ssize_t bytes_written = 0; - - if (!coap_debug_send_packet()) { - bytes_written = (ssize_t)datalen; - } else if (sock->flags & COAP_SOCKET_CONNECTED) { - bytes_written = sock_udp_send(&sock->udp, data, datalen, NULL); - } else { - bytes_written = sock_udp_send(&sock->udp, data, datalen, &session->addr_info.remote.riot); - } - - if (bytes_written < 0) { - errno = -bytes_written; - bytes_written = -1; - coap_log_crit("coap_socket_send: %s\n", coap_socket_strerror()); - } - - return bytes_written; -} - -/* - * dgram - * return +ve Number of bytes written. - * -1 Error error in errno). - * -2 ICMP error response - */ -ssize_t -coap_socket_recv(coap_socket_t *sock, coap_packet_t *packet) { - ssize_t len = -1; - - assert(sock); - assert(packet); - - if ((sock->flags & COAP_SOCKET_CAN_READ) == 0) { - return -1; - } else { - /* clear has-data flag */ - sock->flags &= ~COAP_SOCKET_CAN_READ; - } - - if (sock->flags & COAP_SOCKET_CONNECTED) { - len = sock_udp_recv(&sock->udp, (char *)packet->payload, COAP_RXBUFFER_SIZE, 0, NULL); - if (len < 0) { - errno = -len; - len = -1; - if (errno == ECONNREFUSED || errno == EHOSTUNREACH || errno == ECONNRESET) { - /* client-side ICMP destination unreachable, ignore it */ - coap_log_warn("** %s: coap_socket_recv: ICMP: %s\n", - sock->session ? - coap_session_str(sock->session) : "", - coap_socket_strerror()); - return -2; - } - if (errno != EAGAIN) { - coap_log_warn("** %s: coap_socket_recv: %s\n", - sock->session ? - coap_session_str(sock->session) : "", - coap_socket_strerror()); - } - goto error; - } else if (len > 0) { - packet->length = (size_t)len; - } - } else { - sock_udp_aux_rx_t aux; - sock_udp_ep_t remote; - - aux.flags = SOCK_AUX_GET_LOCAL; - len = sock_udp_recv_aux(&sock->udp, (char *)packet->payload, COAP_RXBUFFER_SIZE, 0, - &remote, &aux); - if (len < 0) { - errno = -len; - len = -1; - if (errno == ECONNREFUSED || errno == EHOSTUNREACH || errno == ECONNRESET) { - /* client-side ICMP destination unreachable, ignore it */ - coap_log_warn("** %s: coap_socket_recv: ICMP: %s\n", - sock->session ? - coap_session_str(sock->session) : "", - coap_socket_strerror()); - return -2; - } - if (errno != EAGAIN) { - coap_log_warn("** %s: coap_socket_recv: %s\n", - sock->session ? - coap_session_str(sock->session) : "", - coap_socket_strerror()); - } - goto error; - } else if (len > 0) { - packet->length = (size_t)len; - memcpy(&packet->addr_info.local.riot, &aux.local, sizeof(packet->addr_info.local.riot)); - memcpy(&packet->addr_info.remote.riot, &remote, sizeof(packet->addr_info.remote.riot)); - } - } - - if (len >= 0) - return len; -error: - return -1; -} - -#if COAP_SERVER_SUPPORT - -static void -udp_recv_endpoint_cb(sock_udp_t *sock, sock_async_flags_t flags, void *arg) { - coap_endpoint_t *endpoint = (coap_endpoint_t *)arg; - - (void)sock; - if (!(flags & (SOCK_ASYNC_MSG_RECV | SOCK_ASYNC_MSG_SENT))) - return; - - if (flags & SOCK_ASYNC_MSG_RECV) - endpoint->sock.flags |= COAP_SOCKET_CAN_READ; - if (endpoint->context->selecting_thread) { - thread_flags_set(endpoint->context->selecting_thread, - COAP_SELECT_THREAD_FLAG); - } -} - -int -coap_socket_bind_udp(coap_socket_t *sock, - const coap_address_t *listen_addr, - coap_address_t *bound_addr) { - int ret; - - ret = sock_udp_create(&sock->udp, &listen_addr->riot, NULL, SOCK_FLAGS_REUSE_EP); - if (ret < 0) { - errno = -ret; - ret = -1; - coap_log_warn("coap_socket_bind_udp: sock_udp_create: %s (%d)\n", - coap_socket_strerror(), listen_addr->riot.family); - goto error; - } - ret = sock_udp_get_local(&sock->udp, &bound_addr->riot); - if (ret != 0) { - errno = -ret; - ret = -1; - coap_log_warn("coap_socket_bind_udp: sock_udp_get_local: %s\n", - coap_socket_strerror()); - } - sock_udp_set_cb(&sock->udp, udp_recv_endpoint_cb, sock->endpoint); - - return 1; - -error: - coap_socket_close(sock); - return 0; -} -#endif /* COAP_SERVER_SUPPORT */ - -#if COAP_CLIENT_SUPPORT - -static void -udp_recv_session_cb(sock_udp_t *sock, sock_async_flags_t flags, void *arg) { - coap_session_t *session = (coap_session_t *)arg; - - (void)sock; - if (!(flags & (SOCK_ASYNC_MSG_RECV | SOCK_ASYNC_MSG_SENT))) - return; - - if (flags & SOCK_ASYNC_MSG_RECV) - session->sock.flags |= COAP_SOCKET_CAN_READ; - if (session->context->selecting_thread) { - thread_flags_set(session->context->selecting_thread, - COAP_SELECT_THREAD_FLAG); - } -} - -int -coap_socket_connect_udp(coap_socket_t *sock, - const coap_address_t *local_if, - const coap_address_t *server, - int default_port, - coap_address_t *local_addr, - coap_address_t *remote_addr) { - sock_udp_ep_t local; - sock_udp_ep_t remote; - coap_address_t connect_addr; - int is_mcast = coap_is_mcast(server); - int ret; - - coap_address_copy(&connect_addr, server); - - sock->flags &= ~(COAP_SOCKET_CONNECTED | COAP_SOCKET_MULTICAST); - - if (local_if && local_if->riot.family) { - if (local_if->riot.family != connect_addr.riot.family) { - coap_log_warn("coap_socket_connect_udp: local address family != " - "remote address family\n"); - goto error; - } - } - - local.netif = SOCK_ADDR_ANY_NETIF; - remote.netif = SOCK_ADDR_ANY_NETIF; - switch (connect_addr.riot.family) { -#if COAP_IPV4_SUPPORT - case AF_INET: - local.family = AF_INET; - local.port = 0; - if (local_if) { - memcpy(local.addr.ipv4, &local_if->riot.addr.ipv4, sizeof(local.addr.ipv4)); - local.port = local_if->riot.port; - } else { - memset(local.addr.ipv4, 0, sizeof(local.addr.ipv4)); - } - remote.family = AF_INET; - memcpy(remote.addr.ipv4, &server->riot.addr.ipv4, sizeof(remote.addr.ipv4)); - if (connect_addr.riot.port == 0) - connect_addr.riot.port = default_port; - remote.port = connect_addr.riot.port; - break; -#endif /* COAP_IPV4_SUPPORT */ -#if COAP_IPV6_SUPPORT - case AF_INET6: - local.family = AF_INET6; - local.port = 0; - if (local_if) { - memcpy(local.addr.ipv6, &local_if->riot.addr.ipv6, sizeof(local.addr.ipv6)); - local.port = local_if->riot.port; - } else { - memset(local.addr.ipv6, 0, sizeof(local.addr.ipv6)); - } - remote.family = AF_INET6; - memcpy(remote.addr.ipv6, &server->riot.addr.ipv6, sizeof(remote.addr.ipv6)); - if (connect_addr.riot.port == 0) - connect_addr.riot.port = htons(default_port); - remote.port = connect_addr.riot.port; - break; -#endif /* COAP_IPV6_SUPPORT */ - default: - coap_log_alert("coap_socket_connect_udp: unsupported sa_family %d\n", - connect_addr.riot.family); - goto error; - } - - ret = sock_udp_create(&sock->udp, &local, &remote, is_mcast ? 0 : SOCK_FLAGS_CONNECT_REMOTE); - if (ret < 0) { - errno = -ret; - ret = -1; - coap_log_warn("coap_socket_connect_udp: sock_udp_create: %s (%d)\n", - coap_socket_strerror(), connect_addr.riot.family); - goto error; - } - ret = sock_udp_get_local(&sock->udp, &local); - if (ret != 0) { - errno = -ret; - ret = -1; - coap_log_warn("coap_socket_connect_udp: sock_udp_get_local: %s\n", - coap_socket_strerror()); - } - memcpy(&local_addr->riot, &local, sizeof(local_addr->riot)); - - ret = sock_udp_get_remote(&sock->udp, &remote); - if (ret != 0) { - errno = -ret; - ret = -1; - coap_log_warn("coap_socket_connect_udp: sock_udp_get_remote: %s\n", - coap_socket_strerror()); - } - memcpy(&remote_addr->riot, &remote, sizeof(remote_addr->riot)); - - sock_udp_set_cb(&sock->udp, udp_recv_session_cb, sock->session); - - /* special treatment for sockets that are used for multicast communication */ - if (is_mcast) { - coap_address_copy(remote_addr, &connect_addr); - coap_address_copy(&sock->mcast_addr, &connect_addr); - sock->flags |= COAP_SOCKET_MULTICAST; - return 1; - } - - sock->flags |= COAP_SOCKET_CONNECTED; - return 1; - -error: - coap_socket_close(sock); - return 0; -} -#endif /* COAP_CLIENT_SUPPORT */ - -void -coap_socket_close(coap_socket_t *sock) { - if (sock->flags != COAP_SOCKET_EMPTY) { - sock_udp_close(&sock->udp); - } -#if !COAP_DISABLE_TCP - if (sock->flags != COAP_SOCKET_EMPTY) { - sock_tcp_disconnect(&sock->tcp); - } -#endif /* !COAP_DISABLE_TCP */ - sock->flags = COAP_SOCKET_EMPTY; -} - -#if ! COAP_DISABLE_TCP - -/* - * strm - * return +ve Number of bytes written. - * 0 No data written. - * -1 Error (error in errno). - */ -ssize_t -coap_socket_write(coap_socket_t *sock, const uint8_t *data, size_t data_len) { - ssize_t ret; - - sock->flags &= ~(COAP_SOCKET_WANT_WRITE | COAP_SOCKET_CAN_WRITE); - ret = sock_tcp_write(&sock->tcp, data, data_len); - if (ret < 0) { - errno = -ret; - ret = -1; - if (errno==EAGAIN || -#if EAGAIN != EWOULDBLOCK - errno == EWOULDBLOCK || -#endif - errno == EINTR) { - sock->flags |= COAP_SOCKET_WANT_WRITE; - return 0; - } - if (errno == EPIPE || errno == ECONNRESET) { - coap_log_info("coap_socket_write: send: %s\n", - coap_socket_strerror()); - } else { - coap_log_warn("coap_socket_write: send: %s\n", - coap_socket_strerror()); - } - return -1; - } - if (ret < (ssize_t)data_len) { - sock->flags |= COAP_SOCKET_WANT_WRITE; - } - return ret; -} - -/* - * strm - * return >=0 Number of bytes read. - * -1 Error (error in errno). - */ -ssize_t -coap_socket_read(coap_socket_t *sock, uint8_t *data, size_t data_len) { - ssize_t ret; - - ret = sock_tcp_read(&sock->tcp, data, data_len, SOCK_NO_TIMEOUT); - if (ret == 0) { - /* graceful shutdown */ - sock->flags &= ~COAP_SOCKET_CAN_READ; - errno = ECONNRESET; - return -1; - } else if (ret < 0) { - errno = -ret; - ret = -1; - sock->flags &= ~COAP_SOCKET_CAN_READ; - if (errno==EAGAIN || -#if EAGAIN != EWOULDBLOCK - errno == EWOULDBLOCK || -#endif - errno == EINTR) { - return 0; - } - if (errno != ECONNRESET) { - coap_log_warn("coap_socket_read: recv: %s\n", - coap_socket_strerror()); - } - return -1; - } - if (ret < (ssize_t)data_len) - sock->flags &= ~COAP_SOCKET_CAN_READ; - return ret; -} - -#ifdef MODULE_LWIP_TCP -static void -tcp_recv_session_cb(sock_tcp_t *sock, sock_async_flags_t flags, void *arg) { - coap_session_t *session = (coap_session_t *)arg; - - (void)sock; - if (!(flags & (SOCK_ASYNC_MSG_RECV | SOCK_ASYNC_MSG_SENT))) - return; - - if (flags & SOCK_ASYNC_MSG_RECV) - session->sock.flags |= COAP_SOCKET_CAN_READ; - if (session->context->selecting_thread) { - thread_flags_set(session->context->selecting_thread, - COAP_SELECT_THREAD_FLAG); - } -} -#endif /* MODULE_LWIP_TCP */ - -#if COAP_CLIENT_SUPPORT - -int -coap_socket_connect_tcp1(coap_socket_t *sock, - const coap_address_t *local_if, - const coap_address_t *server, - int default_port, - coap_address_t *local_addr, - coap_address_t *remote_addr) { - sock_tcp_ep_t local; - sock_tcp_ep_t remote; - coap_address_t connect_addr; - int ret; - - coap_address_copy(&connect_addr, server); - - sock->flags &= ~(COAP_SOCKET_CONNECTED | COAP_SOCKET_MULTICAST); - - if (local_if && local_if->riot.family) { - if (local_if->riot.family != connect_addr.riot.family) { - coap_log_warn("coap_socket_connect_tcp1: local address family != " - "remote address family\n"); - goto error; - } - } - - local.netif = SOCK_ADDR_ANY_NETIF; - remote.netif = SOCK_ADDR_ANY_NETIF; - switch (connect_addr.riot.family) { -#if COAP_IPV4_SUPPORT - case AF_INET: - local.family = AF_INET; - local.port = 0; - if (local_if) { - memcpy(local.addr.ipv4, &local_if->riot.addr.ipv4, sizeof(local.addr.ipv4)); - local.port = local_if->riot.port; - } else { - memset(local.addr.ipv4, 0, sizeof(local.addr.ipv4)); - } - remote.family = AF_INET; - memcpy(remote.addr.ipv4, &server->riot.addr.ipv4, sizeof(remote.addr.ipv4)); - if (connect_addr.riot.port == 0) - connect_addr.riot.port = default_port; - remote.port = connect_addr.riot.port; - break; -#endif /* COAP_IPV4_SUPPORT */ -#if COAP_IPV6_SUPPORT - case AF_INET6: - local.family = AF_INET6; - local.port = 0; - if (local_if) { - memcpy(local.addr.ipv6, &local_if->riot.addr.ipv6, sizeof(local.addr.ipv6)); - local.port = local_if->riot.port; - } else { - memset(local.addr.ipv6, 0, sizeof(local.addr.ipv6)); - } - remote.family = AF_INET6; - memcpy(remote.addr.ipv6, &server->riot.addr.ipv6, sizeof(remote.addr.ipv6)); - if (connect_addr.riot.port == 0) - connect_addr.riot.port = default_port; - remote.port = connect_addr.riot.port; - break; -#endif /* COAP_IPV6_SUPPORT */ - default: - coap_log_alert("coap_socket_connect_tcp1: unsupported sa_family %d\n", - connect_addr.riot.family); - goto error; - } - - ret = sock_tcp_connect(&sock->tcp, &remote, 0, 0); - if (ret < 0) { - errno = -ret; - ret = -1; - coap_log_warn("coap_socket_connect_tcp1: sock_tcp_create: %s (%d)\n", - coap_socket_strerror(), connect_addr.riot.family); - goto error; - } - ret = sock_tcp_get_local(&sock->tcp, &local); - if (ret != 0) { - errno = -ret; - ret = -1; - coap_log_warn("coap_socket_connect_tcp1: sock_tcp_get_local: %s\n", - coap_socket_strerror()); - } - memcpy(&local_addr->riot, &local, sizeof(local_addr->riot)); - - ret = sock_tcp_get_remote(&sock->tcp, &remote); - if (ret != 0) { - errno = -ret; - ret = -1; - coap_log_warn("coap_socket_connect_tcp: sock_tcp_get_remote: %s\n", - coap_socket_strerror()); - } - memcpy(&remote_addr->riot, &remote, sizeof(remote_addr->riot)); - -#ifdef MODULE_LWIP_TCP - sock_tcp_set_cb(&sock->tcp, tcp_recv_session_cb, sock->session); -#endif /* MODULE_LWIP_TCP */ - - sock->flags |= COAP_SOCKET_CONNECTED; - return 1; - -error: - coap_socket_close(sock); - return 0; -} - -int -coap_socket_connect_tcp2(coap_socket_t *sock, - coap_address_t *local_addr, - coap_address_t *remote_addr) { - (void)sock; - (void)local_addr; - (void)remote_addr; - - return -1; -} -#endif /* COAP_CLIENT_SUPPORT */ - -#if COAP_SERVER_SUPPORT - -#define SOCK_QUEUE_LEN (1U) - -static sock_tcp_t sock_queue[SOCK_QUEUE_LEN]; -static sock_tcp_queue_t queue; - -int -coap_socket_bind_tcp(coap_socket_t *sock, - const coap_address_t *listen_addr, - coap_address_t *bound_addr) { - ssize_t ret; - - (void)sock; - - ret = sock_tcp_listen(&queue, &listen_addr->riot, sock_queue, SOCK_QUEUE_LEN, 0); - if (ret < 0) { - errno = -ret; - return 0; - } - - coap_address_copy(bound_addr, listen_addr); - - return 1; -} - -int -coap_socket_accept_tcp(coap_socket_t *server, - coap_socket_t *new_client, - coap_address_t *local_addr, - coap_address_t *remote_addr, - void *extra) { - sock_tcp_t *sock = NULL; - ssize_t ret; - sock_tcp_ep_t scratch; - - (void)extra; - server->flags &= ~COAP_SOCKET_CAN_ACCEPT; - ret = sock_tcp_accept(&queue, &sock, SOCK_NO_TIMEOUT); - if (ret < 0) { - errno = -ret; - return 0; - } - if (sock == NULL || ret < 0) { - coap_log_warn("coap_socket_accept_tcp: accept: %s\n", - coap_socket_strerror()); - return 0; - } - new_client->tcp = *sock; - - ret = sock_tcp_get_remote(&new_client->tcp, &scratch); - if (ret < 0) { - errno = -ret; - return 0; - } - memcpy(&remote_addr->riot, &scratch, sizeof(remote_addr->riot)); - ret = sock_tcp_get_local(&new_client->tcp, &scratch); - if (ret < 0) { - errno = -ret; - return 0; - } - memcpy(&local_addr->riot, &scratch, sizeof(local_addr->riot)); - -#ifdef MODULE_LWIP_TCP - sock_tcp_set_cb(&new_client->tcp, tcp_recv_session_cb, new_client->session); -#endif /* MODULE_LWIP_TCP */ - return 1; -} -#endif /* COAP_SERVER_SUPPORT */ - -#endif /* ! COAP_DISABLE_TCP */ - static msg_t _msg_q[LIBCOAP_MSG_QUEUE_SIZE]; void diff --git a/src/coap_layers.c b/src/coap_layers.c index 8ea9be4f..ae1a348d 100644 --- a/src/coap_layers.c +++ b/src/coap_layers.c @@ -45,41 +45,41 @@ coap_layer_func_t coap_layers_coap[COAP_PROTO_LAST][COAP_LAYER_LAST] = { }, { /* COAP_PROTO_UDP */ - { NULL, coap_netif_dgrm_write, coap_session_establish, coap_netif_close }, /* SESSION */ - { NULL, NULL, NULL, NULL }, /* WS */ - { NULL, NULL, NULL, NULL } /* TLS */ + { NULL, coap_netif_dgrm_write, coap_session_establish, coap_netif_dgrm_close }, /* SESSION */ + { NULL, NULL, NULL, NULL }, /* WS */ + { NULL, NULL, NULL, NULL } /* TLS */ }, { /* COAP_PROTO_DTLS */ - { NULL, coap_dtls_send, coap_dtls_establish, coap_dtls_close }, /* SESSION */ - { NULL, NULL, NULL, NULL }, /* WS */ - { NULL, coap_netif_dgrm_write, coap_session_establish, coap_netif_close } /* TLS */ + { NULL, coap_dtls_send, coap_dtls_establish, coap_dtls_close }, /* SESSION */ + { NULL, NULL, NULL, NULL }, /* WS */ + { NULL, coap_netif_dgrm_write, coap_session_establish, coap_netif_dgrm_close } /* TLS */ }, #if !COAP_DISABLE_TCP { /* COAP_PROTO_TCP */ - { coap_netif_strm_read, coap_netif_strm_write, coap_session_establish, coap_netif_close }, /* SESSION */ - { NULL, NULL, NULL, NULL }, /* WS */ - { NULL, NULL, NULL, NULL } /* TLS */ + { coap_netif_strm_read, coap_netif_strm_write, coap_session_establish, coap_netif_strm_close }, /* SESSION */ + { NULL, NULL, NULL, NULL }, /* WS */ + { NULL, NULL, NULL, NULL } /* TLS */ }, { /* COAP_PROTO_TLS */ - { coap_tls_read, coap_tls_write, coap_tls_establish, coap_tls_close }, /* SESSION */ - { NULL, NULL, NULL, NULL }, /* WS */ - { coap_netif_strm_read, coap_netif_strm_write, coap_session_establish, coap_netif_close } /* TLS */ + { coap_tls_read, coap_tls_write, coap_tls_establish, coap_tls_close }, /* SESSION */ + { NULL, NULL, NULL, NULL }, /* WS */ + { coap_netif_strm_read, coap_netif_strm_write, coap_session_establish, coap_netif_strm_close } /* TLS */ }, #if COAP_WS_SUPPORT { /* COAP_PROTO_WS */ - { coap_ws_read, coap_ws_write, coap_ws_establish, coap_ws_close }, /* SESSION */ - { coap_netif_strm_read, coap_netif_strm_write, coap_session_establish, coap_netif_close }, /* WS */ - { NULL, NULL, NULL, NULL } /* TLS */ + { coap_ws_read, coap_ws_write, coap_ws_establish, coap_ws_close }, /* SESSION */ + { coap_netif_strm_read, coap_netif_strm_write, coap_session_establish, coap_netif_strm_close }, /* WS */ + { NULL, NULL, NULL, NULL } /* TLS */ }, { /* COAP_PROTO_WSS */ - { coap_ws_read, coap_ws_write, coap_tls_establish, coap_ws_close }, /* SESSION */ - { coap_tls_read, coap_tls_write, coap_session_establish, coap_tls_close }, /* WS */ - { coap_netif_strm_read, coap_netif_strm_write, coap_ws_establish, coap_netif_close } /* TLS */ + { coap_ws_read, coap_ws_write, coap_tls_establish, coap_ws_close }, /* SESSION */ + { coap_tls_read, coap_tls_write, coap_session_establish, coap_tls_close }, /* WS */ + { coap_netif_strm_read, coap_netif_strm_write, coap_ws_establish, coap_netif_strm_close } /* TLS */ } #else /* !COAP_WS_SUPPORT */ { diff --git a/src/coap_netif.c b/src/coap_netif.c index 226cbba5..da37dfba 100644 --- a/src/coap_netif.c +++ b/src/coap_netif.c @@ -156,6 +156,12 @@ coap_netif_dgrm_write(coap_session_t *session, const uint8_t *data, return bytes_written; } +void +coap_netif_dgrm_close(coap_session_t *session) { + if (coap_netif_available(session)) + coap_socket_dgrm_close(&session->sock); +} + #if !COAP_DISABLE_TCP #if COAP_SERVER_SUPPORT int @@ -256,17 +262,23 @@ coap_netif_strm_write(coap_session_t *session, const uint8_t *data, } return bytes_written; } -#endif /* COAP_DISABLE_TCP */ void -coap_netif_close(coap_session_t *session) { +coap_netif_strm_close(coap_session_t *session) { if (coap_netif_available(session)) - coap_socket_close(&session->sock); + coap_socket_strm_close(&session->sock); } +#endif /* COAP_DISABLE_TCP */ #if COAP_SERVER_SUPPORT void coap_netif_close_ep(coap_endpoint_t *endpoint) { - coap_socket_close(&endpoint->sock); + if (COAP_PROTO_NOT_RELIABLE(endpoint->proto)) { + coap_socket_dgrm_close(&endpoint->sock); +#if ! COAP_DISABLE_TCP + } else { + coap_socket_strm_close(&endpoint->sock); +#endif /* ! COAP_DISABLE_TCP */ + } } #endif /* COAP_SERVER_SUPPORT */ diff --git a/src/coap_strm_contiki.c b/src/coap_strm_contiki.c new file mode 100644 index 00000000..5206ff21 --- /dev/null +++ b/src/coap_strm_contiki.c @@ -0,0 +1,107 @@ +/* coap_strm_contiki.c -- TCP Network I/O functions for libcoap on Contiki-NG + * + * Copyright (C) 2012,2014,2024-2025 Olaf Bergmann + * 2014 chrysn + * + * SPDX-License-Identifier: BSD-2-Clause + * + * This file is part of the CoAP library libcoap. Please see + * README for terms of use. + */ + +/** + * @file coap_strm_contiki.c + * @brief Contiki-NG-specific Stream (TCP) functions + */ + +#include "coap3/coap_libcoap_build.h" +#include "contiki-net.h" + +int +coap_tcp_is_supported(void) { + return 0; +} + +#if ! COAP_DISABLE_TCP + +#if COAP_CLIENT_SUPPORT +int +coap_socket_connect_tcp1(coap_socket_t *sock, + const coap_address_t *local_if, + const coap_address_t *server, + int default_port, + coap_address_t *local_addr, + coap_address_t *remote_addr) { + (void)sock; + (void)local_if; + (void)server; + (void)default_port; + (void)local_addr; + (void)remote_addr; + + return -1; +} + +int +coap_socket_connect_tcp2(coap_socket_t *sock, + coap_address_t *local_addr, + coap_address_t *remote_addr) { + (void)sock; + (void)local_addr; + (void)remote_addr; + + return -1; +} +#endif /* COAP_CLIENT_SUPPORT */ + +#if COAP_SERVER_SUPPORT + +int +coap_socket_bind_tcp(coap_socket_t *sock, + const coap_address_t *listen_addr, + coap_address_t *bound_addr) { + (void)sock; + (void)listen_addr; + (void)bound_addr; + + return -1; +} + +int +coap_socket_accept_tcp(coap_socket_t *server, + coap_socket_t *new_client, + coap_address_t *local_addr, + coap_address_t *remote_addr, + void *extra) { + (void)server; + (void)new_client; + (void)local_addr; + (void)remote_addr; + (void)extra; + + return -1; +} +#endif /* COAP_SERVER_SUPPORT */ + +ssize_t +coap_socket_write(coap_socket_t *sock, const uint8_t *data, size_t data_len) { + (void)sock; + (void)data; + (void)data_len; + return -1; +} + +ssize_t +coap_socket_read(coap_socket_t *sock, uint8_t *data, size_t data_len) { + (void)sock; + (void)data; + (void)data_len; + return -1; +} + +void +coap_socket_strm_close(coap_socket_t *sock) { + (void)sock; +} + +#endif /* ! COAP_DISABLE_TCP */ diff --git a/src/coap_strm_lwip.c b/src/coap_strm_lwip.c new file mode 100644 index 00000000..d2e37bbf --- /dev/null +++ b/src/coap_strm_lwip.c @@ -0,0 +1,333 @@ +/* + * Copyright (C) 2012,2014 Olaf Bergmann + * 2014 chrysn + * 2022-2025 Jon Shallow + * + * SPDX-License-Identifier: BSD-2-Clause + * + * This file is part of the CoAP library libcoap. Please see + * README for terms of use. + */ + +/** + * @file coap_strm_lwip.c + * @brief LwIP Stream (TCP) specific functions + */ + +#include "coap3/coap_libcoap_build.h" +#include +#include + +int +coap_tcp_is_supported(void) { + return !COAP_DISABLE_TCP; +} + +#if ! COAP_DISABLE_TCP + +#include + +static void +do_tcp_err(void *arg, err_t err) { + coap_session_t *session = (coap_session_t *)arg; + + (void)err; + + coap_lock_lock(return); + coap_handle_event_lkd(session->context, COAP_EVENT_TCP_FAILED, session); + /* + * as per tcp_err() documentation, the corresponding pcb is already freed + * when this callback is called. So, stop a double free when + * coap_session_disconnected_lkd() eventually coap_socket_close() is called. + */ + session->sock.tcp_pcb = NULL; + coap_session_disconnected_lkd(session, COAP_NACK_NOT_DELIVERABLE); + coap_lock_unlock(); +} + +/** Callback from lwIP when a TCP packet is received. + * + * The current implementation invokes coap_read_session() to do the bulk of the + * work. + */ +static err_t +coap_tcp_recv(void *arg, struct tcp_pcb *tpcb, struct pbuf *p, err_t err) { + coap_session_t *session = (coap_session_t *)arg; + coap_socket_t *sock = &session->sock; + coap_tick_t now; + + (void)tpcb; + if (p == NULL) { + /* remote host closed connection */ + tcp_arg(sock->tcp_pcb, NULL); + tcp_recv(sock->tcp_pcb, NULL); + tcp_close(sock->tcp_pcb); + sock->tcp_pcb = NULL; + coap_lock_lock(return ERR_ARG); + coap_session_disconnected_lkd(session, COAP_NACK_NOT_DELIVERABLE); + coap_lock_unlock(); + return ERR_OK; + } else if (err != ERR_OK) { + /* cleanup, for unknown reason */ + if (p != NULL) { + pbuf_free(p); + } + return err; + } + + sock->p = p; + coap_lock_lock(return ERR_ARG); + coap_ticks(&now); + coap_read_session(session->context, session, now); + coap_lock_unlock(); + return ERR_OK; +} + +#if COAP_CLIENT_SUPPORT + +static err_t +do_tcp_connected(void *arg, struct tcp_pcb *tpcb, err_t err) { + coap_session_t *session = (coap_session_t *)arg; + coap_tick_t now; + + if (err) + return err; + coap_lock_lock(return ERR_ARG); + session->sock.flags |= COAP_SOCKET_CONNECTED; + session->addr_info.local.addr = tpcb->local_ip; + session->addr_info.local.port = tpcb->local_port; + tcp_recv(tpcb, coap_tcp_recv); + coap_ticks(&now); + coap_connect_session(session, now); + coap_lock_unlock(); + return ERR_OK; +} + +int +coap_socket_connect_tcp1(coap_socket_t *sock, + const coap_address_t *local_if, + const coap_address_t *server, + int default_port, + coap_address_t *local_addr, + coap_address_t *remote_addr) { + coap_address_t connect_addr; + err_t err; + + (void)local_addr; + (void)remote_addr; + + sock->flags &= ~(COAP_SOCKET_WANT_CONNECT | COAP_SOCKET_CONNECTED); + + sock->tcp_pcb = tcp_new_ip_type(IPADDR_TYPE_ANY); + if (sock->tcp_pcb == NULL) + return 0; + + tcp_arg(sock->tcp_pcb, sock->session); + tcp_recv(sock->tcp_pcb, coap_tcp_recv); + tcp_err(sock->tcp_pcb, do_tcp_err); + if (local_if) { + coap_address_t l_local_if = *local_if; +#if LWIP_IPV6 && LWIP_IPV4 + if (l_local_if.addr.type == IPADDR_TYPE_V6) + l_local_if.addr.type = IPADDR_TYPE_ANY; +#endif /* LWIP_IPV6 && LWIP_IPV4 */ + err = tcp_bind(sock->tcp_pcb, &l_local_if.addr, l_local_if.port); + if (err != ERR_OK) { + tcp_arg(sock->tcp_pcb, NULL); + tcp_recv(sock->tcp_pcb, NULL); + tcp_close(sock->tcp_pcb); + sock->tcp_pcb = NULL; + return 0; + } + } + coap_address_copy(&connect_addr, server); + if (connect_addr.port == 0) + connect_addr.port = htons(default_port); + + err = tcp_connect(sock->tcp_pcb, &connect_addr.addr, connect_addr.port, + do_tcp_connected); + if (err == ERR_OK) + sock->flags |= COAP_SOCKET_WANT_CONNECT | COAP_SOCKET_CONNECTED; + return err ? 0 : 1; +} + +int +coap_socket_connect_tcp2(coap_socket_t *sock, + coap_address_t *local_addr, + coap_address_t *remote_addr) { + (void)sock; + (void)local_addr; + (void)remote_addr; + + sock->flags &= ~(COAP_SOCKET_WANT_CONNECT | COAP_SOCKET_CAN_CONNECT); + return 1; +} +#endif /* COAP_CLIENT_SUPPORT */ + +#if COAP_SERVER_SUPPORT + +static err_t +do_tcp_accept(void *arg, struct tcp_pcb *newpcb, err_t err) { + coap_endpoint_t *endpoint = arg; + coap_session_t *session; + coap_tick_t now; + err_t ret_err = ERR_OK; + + if ((err != ERR_OK) || (newpcb == NULL)) { + return ERR_VAL; + } + coap_ticks(&now); + + coap_lock_lock(return ERR_MEM); + session = coap_new_server_session(endpoint->context, endpoint, newpcb); + + if (session) { + session->sock.tcp_pcb = newpcb; + session->last_rx_tx = now; + tcp_arg(newpcb, session); + tcp_setprio(newpcb, TCP_PRIO_MIN); + tcp_recv(newpcb, coap_tcp_recv); + tcp_err(newpcb, do_tcp_err); + } else { + ret_err = ERR_MEM; + } + coap_lock_unlock(); + return ret_err; +} + +int +coap_socket_bind_tcp(coap_socket_t *sock, + const coap_address_t *listen_addr, + coap_address_t *bound_addr) { + int err; + coap_address_t l_listen = *listen_addr; + struct tcp_pcb *tcp_pcb; + + sock->tcp_pcb = tcp_new_ip_type(IPADDR_TYPE_ANY); + if (sock->tcp_pcb == NULL) + return 0; + +#if LWIP_IPV6 && LWIP_IPV4 + if (l_listen.addr.type == IPADDR_TYPE_V6) + l_listen.addr.type = IPADDR_TYPE_ANY; +#endif /* LWIP_IPV6 && LWIP_IPV4 */ + tcp_arg(sock->tcp_pcb, sock->endpoint); + err = tcp_bind(sock->tcp_pcb, &l_listen.addr, l_listen.port); + if (err != ERR_OK) { + tcp_arg(sock->tcp_pcb, NULL); + tcp_recv(sock->tcp_pcb, NULL); + tcp_close(sock->tcp_pcb); + sock->tcp_pcb = NULL; + return 0; + } else { + tcp_pcb = tcp_listen(sock->tcp_pcb); + if (tcp_pcb) { + sock->tcp_pcb = tcp_pcb; + tcp_accept(sock->tcp_pcb, do_tcp_accept); + } else { + tcp_arg(sock->tcp_pcb, NULL); + tcp_recv(sock->tcp_pcb, NULL); + tcp_close(sock->tcp_pcb); + sock->tcp_pcb = NULL; + return 0; + } + } + *bound_addr = l_listen; + return err ? 0 : 1; +} + +int +coap_socket_accept_tcp(coap_socket_t *server, + coap_socket_t *new_client, + coap_address_t *local_addr, + coap_address_t *remote_addr, + void *extra) { + struct tcp_pcb *tcp_pcb = (struct tcp_pcb *)extra; + + (void)server; + + new_client->tcp_pcb = tcp_pcb; + local_addr->addr = tcp_pcb->local_ip; + local_addr->port = tcp_pcb->local_port; + remote_addr->addr = tcp_pcb->remote_ip; + remote_addr->port = tcp_pcb->remote_port; + return 1; +} +#endif /* COAP_SERVER_SUPPORT */ + +/* + * strm + * return +ve Number of bytes written. + * -1 Error error in errno). + */ +ssize_t +coap_socket_write(coap_socket_t *sock, const uint8_t *data, size_t data_len) { + struct pbuf *pbuf; + int err; + + pbuf = pbuf_alloc(PBUF_TRANSPORT, data_len, PBUF_RAM); + if (pbuf == NULL) + return -1; + memcpy(pbuf->payload, data, data_len); + + coap_lock_invert(LOCK_TCPIP_CORE(), + UNLOCK_TCPIP_CORE(); return 0); + + err = tcp_write(sock->tcp_pcb, pbuf->payload, pbuf->len, 1); + + UNLOCK_TCPIP_CORE(); + + pbuf_free(pbuf); + if (err < 0) + return -1; + return data_len; +} + +/* + * strm + * return >=0 Number of bytes read. + * -1 Error error in errno). + */ +ssize_t +coap_socket_read(coap_socket_t *sock, uint8_t *data, size_t data_len) { + if (sock->p) { + if (data_len < sock->p->len) { + uint8_t *ptr = (uint8_t *)sock->p->payload; + + /* Handle partial read of data request */ + memcpy(data, sock->p->payload, data_len); + sock->p->payload = &ptr[data_len]; + sock->p->len -= data_len; + return data_len; + } else { + data_len = sock->p->len; + memcpy(data, sock->p->payload, sock->p->len); + pbuf_free(sock->p); + sock->p = NULL; + return data_len; + } + } + return 0; +} + +void +coap_socket_strm_close(coap_socket_t *sock) { + if (sock->tcp_pcb) { + tcp_arg(sock->tcp_pcb, NULL); +#if COAP_SERVER_SUPPORT + if (!sock->endpoint) +#endif /* COAP_SERVER_SUPPORT */ + tcp_recv(sock->tcp_pcb, NULL); + if (sock->session) { + coap_lock_invert(LOCK_TCPIP_CORE(), + UNLOCK_TCPIP_CORE(); return); + } else { + LOCK_TCPIP_CORE(); + } + tcp_close(sock->tcp_pcb); + UNLOCK_TCPIP_CORE(); + sock->tcp_pcb = NULL; + } + return; +} +#endif /* !COAP_DISABLE_TCP */ diff --git a/src/coap_tcp.c b/src/coap_strm_posix.c similarity index 76% rename from src/coap_tcp.c rename to src/coap_strm_posix.c index a76abd3b..407df77c 100644 --- a/src/coap_tcp.c +++ b/src/coap_strm_posix.c @@ -1,5 +1,5 @@ /* - * coap_tcp.c -- TCP functions for libcoap + * coap_strm_posix.c -- Stream (TCP) functions for libcoap * * Copyright (C) 2019-2025 Olaf Bergmann and others * @@ -10,8 +10,8 @@ */ /** - * @file coap_tcp.c - * @brief CoAP TCP handling functions + * @file coap_strm_posix.c + * @brief Posix CoAP Stream (TCP) handling functions */ #include "coap3/coap_libcoap_build.h" @@ -24,13 +24,17 @@ #include #endif /* _WIN32 */ #endif /* COAP_AF_UNIX_SUPPORT */ +#ifdef COAP_EPOLL_SUPPORT +#include +#include +#endif /* COAP_EPOLL_SUPPORT */ int coap_tcp_is_supported(void) { return !COAP_DISABLE_TCP; } -#if !COAP_DISABLE_TCP && !defined(WITH_LWIP) && !defined(WITH_CONTIKI) && !defined(RIOT_VERSION) +#if !COAP_DISABLE_TCP #include #ifdef HAVE_SYS_SOCKET_H # include @@ -184,7 +188,7 @@ error: #endif /* ! _WIN32 */ } #endif /* COAP_AF_UNIX_SUPPORT */ - coap_socket_close(sock); + coap_socket_strm_close(sock); return 0; } @@ -210,7 +214,7 @@ coap_socket_connect_tcp2(coap_socket_t *sock, if (error) { coap_log_warn("coap_socket_connect_tcp2: connect failed: %s\n", coap_socket_format_errno(error)); - coap_socket_close(sock); + coap_socket_strm_close(sock); return 0; } @@ -314,7 +318,7 @@ coap_socket_bind_tcp(coap_socket_t *sock, return 1; error: - coap_socket_close(sock); + coap_socket_strm_close(sock); return 0; } @@ -357,4 +361,113 @@ coap_socket_accept_tcp(coap_socket_t *server, } return 1; } + +/* + * strm + * return +ve Number of bytes written. + * 0 No data written. + * -1 Error (error in errno). + */ +ssize_t +coap_socket_write(coap_socket_t *sock, const uint8_t *data, size_t data_len) { + ssize_t r; + + sock->flags &= ~(COAP_SOCKET_WANT_WRITE | COAP_SOCKET_CAN_WRITE); +#ifdef _WIN32 + r = send(sock->fd, (const char *)data, (int)data_len, 0); +#else +#ifndef MSG_NOSIGNAL +#define MSG_NOSIGNAL 0 +#endif /* MSG_NOSIGNAL */ + r = send(sock->fd, data, data_len, MSG_NOSIGNAL); +#endif + if (r == COAP_SOCKET_ERROR) { +#ifdef _WIN32 + coap_win_error_to_errno(); +#endif /* _WIN32 */ + if (errno==EAGAIN || +#if EAGAIN != EWOULDBLOCK + errno == EWOULDBLOCK || +#endif + errno == EINTR) { + sock->flags |= COAP_SOCKET_WANT_WRITE; +#ifdef COAP_EPOLL_SUPPORT + coap_epoll_ctl_mod(sock, + EPOLLOUT | + ((sock->flags & COAP_SOCKET_WANT_READ) ? + EPOLLIN : 0), + __func__); +#endif /* COAP_EPOLL_SUPPORT */ + return 0; + } + if (errno == EPIPE || errno == ECONNRESET) { + coap_log_info("coap_socket_write: send: %s\n", + coap_socket_strerror()); + } else { + coap_log_warn("coap_socket_write: send: %s\n", + coap_socket_strerror()); + } + return -1; + } + if (r < (ssize_t)data_len) { + sock->flags |= COAP_SOCKET_WANT_WRITE; +#ifdef COAP_EPOLL_SUPPORT + coap_epoll_ctl_mod(sock, + EPOLLOUT | + ((sock->flags & COAP_SOCKET_WANT_READ) ? + EPOLLIN : 0), + __func__); +#endif /* COAP_EPOLL_SUPPORT */ + } + return r; +} + +/* + * strm + * return >=0 Number of bytes read. + * -1 Error (error in errno). + */ +ssize_t +coap_socket_read(coap_socket_t *sock, uint8_t *data, size_t data_len) { + ssize_t r; + +#ifdef _WIN32 + r = recv(sock->fd, (char *)data, (int)data_len, 0); +#else + r = recv(sock->fd, data, data_len, 0); +#endif + if (r == 0) { + /* graceful shutdown */ + sock->flags &= ~COAP_SOCKET_CAN_READ; + errno = ECONNRESET; + return -1; + } else if (r == COAP_SOCKET_ERROR) { + sock->flags &= ~COAP_SOCKET_CAN_READ; +#ifdef _WIN32 + coap_win_error_to_errno(); +#endif /* _WIN32 */ + if (errno==EAGAIN || +#if EAGAIN != EWOULDBLOCK + errno == EWOULDBLOCK || +#endif + errno == EINTR) { + return 0; + } + if (errno != ECONNRESET) { + coap_log_warn("coap_socket_read: recv: %s\n", + coap_socket_strerror()); + } + return -1; + } + if (r < (ssize_t)data_len) + sock->flags &= ~COAP_SOCKET_CAN_READ; + return r; +} + +void +coap_socket_strm_close(coap_socket_t *sock) { + /* For POSIX, this is the same as the datagram version */ + coap_socket_dgrm_close(sock); +} + #endif /* !COAP_DISABLE_TCP */ diff --git a/src/coap_strm_riot.c b/src/coap_strm_riot.c new file mode 100644 index 00000000..8af9f3b7 --- /dev/null +++ b/src/coap_strm_riot.c @@ -0,0 +1,328 @@ +/* coap_strm_riot.c -- Default Stream (TCP) network I/O functions for libcoap on RIOT + * + * Copyright (C) 2019-2025 Olaf Bergmann + * + * SPDX-License-Identifier: BSD-2-Clause + * + * This file is part of the CoAP library libcoap. Please see + * README for terms of use. + */ + +/** + * @file coap_strm_riot.c + * @brief RIOT specific Stream (TCP) I/O functions + */ + +#include "coap3/coap_libcoap_build.h" + +#include "net/gnrc.h" +#include "net/gnrc/ipv6.h" +#include "net/gnrc/netreg.h" +#include "net/udp.h" +#if COAP_DISABLE_TCP +#include "net/tcp.h" +#endif /* ! COAP_DISABLE_TCP */ +#include "net/sock/async.h" + +#include "coap3/coap_riot.h" + +#define COAP_SELECT_THREAD_FLAG (1U << 4) + +int +coap_tcp_is_supported(void) { + return !COAP_DISABLE_TCP; +} + +#if ! COAP_DISABLE_TCP + +/* + * strm + * return +ve Number of bytes written. + * 0 No data written. + * -1 Error (error in errno). + */ +ssize_t +coap_socket_write(coap_socket_t *sock, const uint8_t *data, size_t data_len) { + ssize_t ret; + + sock->flags &= ~(COAP_SOCKET_WANT_WRITE | COAP_SOCKET_CAN_WRITE); + ret = sock_tcp_write(&sock->tcp, data, data_len); + if (ret < 0) { + errno = -ret; + ret = -1; + if (errno==EAGAIN || +#if EAGAIN != EWOULDBLOCK + errno == EWOULDBLOCK || +#endif + errno == EINTR) { + sock->flags |= COAP_SOCKET_WANT_WRITE; + return 0; + } + if (errno == EPIPE || errno == ECONNRESET) { + coap_log_info("coap_socket_write: send: %s\n", + coap_socket_strerror()); + } else { + coap_log_warn("coap_socket_write: send: %s\n", + coap_socket_strerror()); + } + return -1; + } + if (ret < (ssize_t)data_len) { + sock->flags |= COAP_SOCKET_WANT_WRITE; + } + return ret; +} + +/* + * strm + * return >=0 Number of bytes read. + * -1 Error (error in errno). + */ +ssize_t +coap_socket_read(coap_socket_t *sock, uint8_t *data, size_t data_len) { + ssize_t ret; + + ret = sock_tcp_read(&sock->tcp, data, data_len, SOCK_NO_TIMEOUT); + if (ret == 0) { + /* graceful shutdown */ + sock->flags &= ~COAP_SOCKET_CAN_READ; + errno = ECONNRESET; + return -1; + } else if (ret < 0) { + errno = -ret; + ret = -1; + sock->flags &= ~COAP_SOCKET_CAN_READ; + if (errno==EAGAIN || +#if EAGAIN != EWOULDBLOCK + errno == EWOULDBLOCK || +#endif + errno == EINTR) { + return 0; + } + if (errno != ECONNRESET) { + coap_log_warn("coap_socket_read: recv: %s\n", + coap_socket_strerror()); + } + return -1; + } + if (ret < (ssize_t)data_len) + sock->flags &= ~COAP_SOCKET_CAN_READ; + return ret; +} + +#ifdef MODULE_LWIP_TCP +static void +tcp_recv_session_cb(sock_tcp_t *sock, sock_async_flags_t flags, void *arg) { + coap_session_t *session = (coap_session_t *)arg; + + (void)sock; + if (!(flags & (SOCK_ASYNC_MSG_RECV | SOCK_ASYNC_MSG_SENT))) + return; + + if (flags & SOCK_ASYNC_MSG_RECV) + session->sock.flags |= COAP_SOCKET_CAN_READ; + if (session->context->selecting_thread) { + thread_flags_set(session->context->selecting_thread, + COAP_SELECT_THREAD_FLAG); + } +} +#endif /* MODULE_LWIP_TCP */ + +#if COAP_CLIENT_SUPPORT + +int +coap_socket_connect_tcp1(coap_socket_t *sock, + const coap_address_t *local_if, + const coap_address_t *server, + int default_port, + coap_address_t *local_addr, + coap_address_t *remote_addr) { + sock_tcp_ep_t local; + sock_tcp_ep_t remote; + coap_address_t connect_addr; + int ret; + + coap_address_copy(&connect_addr, server); + + sock->flags &= ~(COAP_SOCKET_CONNECTED | COAP_SOCKET_MULTICAST); + + if (local_if && local_if->riot.family) { + if (local_if->riot.family != connect_addr.riot.family) { + coap_log_warn("coap_socket_connect_tcp1: local address family != " + "remote address family\n"); + goto error; + } + } + + local.netif = SOCK_ADDR_ANY_NETIF; + remote.netif = SOCK_ADDR_ANY_NETIF; + switch (connect_addr.riot.family) { +#if COAP_IPV4_SUPPORT + case AF_INET: + local.family = AF_INET; + local.port = 0; + if (local_if) { + memcpy(local.addr.ipv4, &local_if->riot.addr.ipv4, sizeof(local.addr.ipv4)); + local.port = local_if->riot.port; + } else { + memset(local.addr.ipv4, 0, sizeof(local.addr.ipv4)); + } + remote.family = AF_INET; + memcpy(remote.addr.ipv4, &server->riot.addr.ipv4, sizeof(remote.addr.ipv4)); + if (connect_addr.riot.port == 0) + connect_addr.riot.port = default_port; + remote.port = connect_addr.riot.port; + break; +#endif /* COAP_IPV4_SUPPORT */ +#if COAP_IPV6_SUPPORT + case AF_INET6: + local.family = AF_INET6; + local.port = 0; + if (local_if) { + memcpy(local.addr.ipv6, &local_if->riot.addr.ipv6, sizeof(local.addr.ipv6)); + local.port = local_if->riot.port; + } else { + memset(local.addr.ipv6, 0, sizeof(local.addr.ipv6)); + } + remote.family = AF_INET6; + memcpy(remote.addr.ipv6, &server->riot.addr.ipv6, sizeof(remote.addr.ipv6)); + if (connect_addr.riot.port == 0) + connect_addr.riot.port = default_port; + remote.port = connect_addr.riot.port; + break; +#endif /* COAP_IPV6_SUPPORT */ + default: + coap_log_alert("coap_socket_connect_tcp1: unsupported sa_family %d\n", + connect_addr.riot.family); + goto error; + } + + ret = sock_tcp_connect(&sock->tcp, &remote, 0, 0); + if (ret < 0) { + errno = -ret; + ret = -1; + coap_log_warn("coap_socket_connect_tcp1: sock_tcp_create: %s (%d)\n", + coap_socket_strerror(), connect_addr.riot.family); + goto error; + } + ret = sock_tcp_get_local(&sock->tcp, &local); + if (ret != 0) { + errno = -ret; + ret = -1; + coap_log_warn("coap_socket_connect_tcp1: sock_tcp_get_local: %s\n", + coap_socket_strerror()); + } + memcpy(&local_addr->riot, &local, sizeof(local_addr->riot)); + + ret = sock_tcp_get_remote(&sock->tcp, &remote); + if (ret != 0) { + errno = -ret; + ret = -1; + coap_log_warn("coap_socket_connect_tcp: sock_tcp_get_remote: %s\n", + coap_socket_strerror()); + } + memcpy(&remote_addr->riot, &remote, sizeof(remote_addr->riot)); + +#ifdef MODULE_LWIP_TCP + sock_tcp_set_cb(&sock->tcp, tcp_recv_session_cb, sock->session); +#endif /* MODULE_LWIP_TCP */ + + sock->flags |= COAP_SOCKET_CONNECTED; + return 1; + +error: + coap_socket_close(sock); + return 0; +} + +int +coap_socket_connect_tcp2(coap_socket_t *sock, + coap_address_t *local_addr, + coap_address_t *remote_addr) { + (void)sock; + (void)local_addr; + (void)remote_addr; + + return -1; +} +#endif /* COAP_CLIENT_SUPPORT */ + +#if COAP_SERVER_SUPPORT + +#define SOCK_QUEUE_LEN (1U) + +static sock_tcp_t sock_queue[SOCK_QUEUE_LEN]; +static sock_tcp_queue_t queue; + +int +coap_socket_bind_tcp(coap_socket_t *sock, + const coap_address_t *listen_addr, + coap_address_t *bound_addr) { + ssize_t ret; + + (void)sock; + + ret = sock_tcp_listen(&queue, &listen_addr->riot, sock_queue, SOCK_QUEUE_LEN, 0); + if (ret < 0) { + errno = -ret; + return 0; + } + + coap_address_copy(bound_addr, listen_addr); + + return 1; +} + +int +coap_socket_accept_tcp(coap_socket_t *server, + coap_socket_t *new_client, + coap_address_t *local_addr, + coap_address_t *remote_addr, + void *extra) { + sock_tcp_t *sock = NULL; + ssize_t ret; + sock_tcp_ep_t scratch; + + (void)extra; + server->flags &= ~COAP_SOCKET_CAN_ACCEPT; + ret = sock_tcp_accept(&queue, &sock, SOCK_NO_TIMEOUT); + if (ret < 0) { + errno = -ret; + return 0; + } + if (sock == NULL || ret < 0) { + coap_log_warn("coap_socket_accept_tcp: accept: %s\n", + coap_socket_strerror()); + return 0; + } + new_client->tcp = *sock; + + ret = sock_tcp_get_remote(&new_client->tcp, &scratch); + if (ret < 0) { + errno = -ret; + return 0; + } + memcpy(&remote_addr->riot, &scratch, sizeof(remote_addr->riot)); + ret = sock_tcp_get_local(&new_client->tcp, &scratch); + if (ret < 0) { + errno = -ret; + return 0; + } + memcpy(&local_addr->riot, &scratch, sizeof(local_addr->riot)); + +#ifdef MODULE_LWIP_TCP + sock_tcp_set_cb(&new_client->tcp, tcp_recv_session_cb, new_client->session); +#endif /* MODULE_LWIP_TCP */ + return 1; +} +#endif /* COAP_SERVER_SUPPORT */ + +void +coap_socket_strm_close(coap_socket_t *sock) { + if (sock->flags != COAP_SOCKET_EMPTY) { + sock_tcp_disconnect(&sock->tcp); + } + sock->flags = COAP_SOCKET_EMPTY; +} + +#endif /* ! COAP_DISABLE_TCP */ diff --git a/win32/libcoap.vcxproj b/win32/libcoap.vcxproj index 2b515dde..ec4ea437 100644 --- a/win32/libcoap.vcxproj +++ b/win32/libcoap.vcxproj @@ -44,12 +44,14 @@ + + @@ -66,9 +68,9 @@ + - diff --git a/win32/libcoap.vcxproj.filters b/win32/libcoap.vcxproj.filters index 54149e6e..7895969f 100644 --- a/win32/libcoap.vcxproj.filters +++ b/win32/libcoap.vcxproj.filters @@ -30,8 +30,12 @@ Source Files + + Source Files + Source Files + Source Files @@ -47,6 +51,9 @@ Source Files + + Source Files + Source Files @@ -92,10 +99,10 @@ Source Files - + Source Files - + Source Files