libcoap 4.3.5-develop-4fa3dfa
Loading...
Searching...
No Matches
coap_io.c
Go to the documentation of this file.
1/* coap_io.c -- Default network I/O functions for libcoap
2 *
3 * Copyright (C) 2012,2014,2016-2025 Olaf Bergmann <bergmann@tzi.org> and others
4 *
5 * SPDX-License-Identifier: BSD-2-Clause
6 *
7 * This file is part of the CoAP library libcoap. Please see
8 * README for terms of use.
9 */
10
17
18#ifdef HAVE_STDIO_H
19# include <stdio.h>
20#endif
21
22#ifndef __ZEPHYR__
23#ifdef HAVE_SYS_SELECT_H
24# include <sys/select.h>
25#endif
26#ifdef HAVE_SYS_SOCKET_H
27# include <sys/socket.h>
28# define OPTVAL_T(t) (t)
29# define OPTVAL_GT(t) (t)
30#endif
31#ifdef HAVE_SYS_IOCTL_H
32#include <sys/ioctl.h>
33#endif
34#ifdef HAVE_NETINET_IN_H
35# include <netinet/in.h>
36#endif
37#ifdef HAVE_WS2TCPIP_H
38#include <ws2tcpip.h>
39# define OPTVAL_T(t) (const char*)(t)
40# define OPTVAL_GT(t) (char*)(t)
41# undef CMSG_DATA
42# define CMSG_DATA WSA_CMSG_DATA
43#endif
44#ifdef HAVE_SYS_UIO_H
45# include <sys/uio.h>
46#endif
47#ifdef HAVE_UNISTD_H
48# include <unistd.h>
49#endif
50#ifdef _WIN32
51#include <stdio.h>
52#endif /* _WIN32 */
53#ifdef COAP_EPOLL_SUPPORT
54#include <sys/epoll.h>
55#include <sys/timerfd.h>
56#ifdef HAVE_LIMITS_H
57#include <limits.h>
58#endif
59#endif /* COAP_EPOLL_SUPPORT */
60#else /* __ZEPHYR__ */
61#include <zephyr/posix/sys/ioctl.h>
62#include <zephyr/posix/sys/select.h>
63#define OPTVAL_T(t) (const void*)(t)
64#define OPTVAL_GT(t) (void*)(t)
65
66#ifndef IPV6_PKTINFO
67#ifdef IPV6_RECVPKTINFO
68#define IPV6_PKTINFO IPV6_RECVPKTINFO
69#else
70#define IPV6_PKTINFO IP_PKTINFO
71#endif
72#ifndef IN6_IS_ADDR_V4MAPPED
73#define IN6_IS_ADDR_V4MAPPED(a) \
74 ((((a)->s6_addr32[0]) == 0) && (((a)->s6_addr32[1]) == 0) && \
75 (((a)->s6_addr32[2]) == htonl(0xffff)))
76#endif
77#endif
78#endif /* __ZEPHYR__ */
79
80#if !defined(WITH_CONTIKI) && !defined(RIOT_VERSION) && !defined(WITH_LWIP)
81/* define generic PKTINFO for IPv4 */
82#if defined(IP_PKTINFO)
83# define GEN_IP_PKTINFO IP_PKTINFO
84#elif defined(IP_RECVDSTADDR)
85# define GEN_IP_PKTINFO IP_RECVDSTADDR
86#else
87# error "Need IP_PKTINFO or IP_RECVDSTADDR to request ancillary data from OS."
88#endif /* IP_PKTINFO */
89
90/* define generic PKTINFO for IPv6 */
91#ifdef IPV6_RECVPKTINFO
92# define GEN_IPV6_PKTINFO IPV6_RECVPKTINFO
93#elif defined(IPV6_PKTINFO)
94# define GEN_IPV6_PKTINFO IPV6_PKTINFO
95#else
96# error "Need IPV6_PKTINFO or IPV6_RECVPKTINFO to request ancillary data from OS."
97#endif /* IPV6_RECVPKTINFO */
98#endif /* ! WITH_CONTIKI && ! RIOT_VERSION && ! WITH_LWIP */
99
100#if COAP_SERVER_SUPPORT
104}
105
106void
109}
110#endif /* COAP_SERVER_SUPPORT */
111
112#if !defined(WITH_CONTIKI) && !defined(WITH_LWIP) && !defined(RIOT_VERSION)
113
114#if COAP_SERVER_SUPPORT
115int
117 const coap_address_t *listen_addr,
118 coap_address_t *bound_addr) {
119#ifndef RIOT_VERSION
120 int on = 1;
121#if COAP_IPV6_SUPPORT
122 int off = 0;
123#endif /* COAP_IPV6_SUPPORT */
124#else /* ! RIOT_VERSION */
125 struct timeval timeout = {0, 0};
126#endif /* ! RIOT_VERSION */
127#ifdef _WIN32
128 u_long u_on = 1;
129#endif
130
131 sock->fd = socket(listen_addr->addr.sa.sa_family, SOCK_DGRAM, 0);
132
133 if (sock->fd == COAP_INVALID_SOCKET) {
134 coap_log_warn("coap_socket_bind_udp: socket: %s\n", coap_socket_strerror());
135 goto error;
136 }
137#ifndef RIOT_VERSION
138#ifdef _WIN32
139 if (ioctlsocket(sock->fd, FIONBIO, &u_on) == COAP_SOCKET_ERROR)
140#else
141 if (ioctl(sock->fd, FIONBIO, &on) == COAP_SOCKET_ERROR)
142#endif
143 {
144 coap_log_warn("coap_socket_bind_udp: ioctl FIONBIO: %s\n", coap_socket_strerror());
145 }
146
147 if (setsockopt(sock->fd, SOL_SOCKET, SO_REUSEADDR, OPTVAL_T(&on), sizeof(on)) == COAP_SOCKET_ERROR)
148 coap_log_warn("coap_socket_bind_udp: setsockopt SO_REUSEADDR: %s\n",
150
151 switch (listen_addr->addr.sa.sa_family) {
152#if COAP_IPV4_SUPPORT
153 case AF_INET:
154 if (setsockopt(sock->fd, IPPROTO_IP, GEN_IP_PKTINFO, OPTVAL_T(&on),
155 sizeof(on)) == COAP_SOCKET_ERROR)
156 coap_log_alert("coap_socket_bind_udp: setsockopt IP_PKTINFO: %s\n",
158 break;
159#endif /* COAP_IPV4_SUPPORT */
160#if COAP_IPV6_SUPPORT
161 case AF_INET6:
162 /* Configure the socket as dual-stacked */
163 if (setsockopt(sock->fd, IPPROTO_IPV6, IPV6_V6ONLY, OPTVAL_T(&off),
164 sizeof(off)) == COAP_SOCKET_ERROR)
165 coap_log_alert("coap_socket_bind_udp: setsockopt IPV6_V6ONLY: %s\n",
167#if !defined(ESPIDF_VERSION)
168 if (setsockopt(sock->fd, IPPROTO_IPV6, GEN_IPV6_PKTINFO, OPTVAL_T(&on),
169 sizeof(on)) == COAP_SOCKET_ERROR)
170 coap_log_alert("coap_socket_bind_udp: setsockopt IPV6_PKTINFO: %s\n",
172#endif /* !defined(ESPIDF_VERSION) */
173#endif /* COAP_IPV6_SUPPORT */
174 setsockopt(sock->fd, IPPROTO_IP, GEN_IP_PKTINFO, OPTVAL_T(&on), sizeof(on));
175 /* ignore error, because likely cause is that IPv4 is disabled at the os
176 level */
177 break;
178#if COAP_AF_UNIX_SUPPORT
179 case AF_UNIX:
180 break;
181#endif /* COAP_AF_UNIX_SUPPORT */
182 default:
183 coap_log_alert("coap_socket_bind_udp: unsupported sa_family\n");
184 break;
185 }
186#else /* RIOT_VERSION */
187 if (setsockopt(sock->fd, SOL_SOCKET, SO_RCVTIMEO, OPTVAL_T(&timeout),
188 (socklen_t)sizeof(timeout)) == COAP_SOCKET_ERROR)
189 coap_log_alert("coap_socket_bind_udp: setsockopt SO_RCVTIMEO: %s\n",
191#endif /* RIOT_VERSION */
192
193 if (bind(sock->fd, &listen_addr->addr.sa,
195 listen_addr->addr.sa.sa_family == AF_INET ?
196 (socklen_t)sizeof(struct sockaddr_in) :
197#endif /* COAP_IPV4_SUPPORT */
198 (socklen_t)listen_addr->size) == COAP_SOCKET_ERROR) {
199 coap_log_warn("coap_socket_bind_udp: bind: %s\n",
201 goto error;
202 }
203
204 bound_addr->size = (socklen_t)sizeof(*bound_addr);
205 if (getsockname(sock->fd, &bound_addr->addr.sa, &bound_addr->size) < 0) {
206 coap_log_warn("coap_socket_bind_udp: getsockname: %s\n",
208 goto error;
209 }
210#if defined(RIOT_VERSION) && defined(COAP_SERVER_SUPPORT)
211 if (sock->endpoint &&
212 bound_addr->addr.sa.sa_family == AF_INET6) {
213 bound_addr->addr.sin6.sin6_scope_id =
214 listen_addr->addr.sin6.sin6_scope_id;
215 bound_addr->addr.sin6.sin6_flowinfo = 0;
216 }
217#endif /* RIOT_VERSION && COAP_SERVER_SUPPORT */
218
219 return 1;
220
221error:
222 coap_socket_close(sock);
223 return 0;
224}
225#endif /* COAP_SERVER_SUPPORT */
226
227#if COAP_CLIENT_SUPPORT
228int
230 const coap_address_t *local_if,
231 const coap_address_t *server,
232 int default_port,
233 coap_address_t *local_addr,
234 coap_address_t *remote_addr) {
235 int on = 1;
236#if COAP_IPV6_SUPPORT
237 int off = 0;
238#endif /* COAP_IPV6_SUPPORT */
239#ifdef _WIN32
240 u_long u_on = 1;
241#endif
242 coap_address_t connect_addr;
243 int is_mcast = coap_is_mcast(server);
244 coap_address_copy(&connect_addr, server);
245
247 sock->fd = socket(connect_addr.addr.sa.sa_family, SOCK_DGRAM, 0);
248
249 if (sock->fd == COAP_INVALID_SOCKET) {
250 coap_log_warn("coap_socket_connect_udp: socket: %s\n",
252 goto error;
253 }
254
255#ifdef _WIN32
256 if (ioctlsocket(sock->fd, FIONBIO, &u_on) == COAP_SOCKET_ERROR)
257#else
258 if (ioctl(sock->fd, FIONBIO, &on) == COAP_SOCKET_ERROR)
259#endif
260 {
261 coap_log_warn("coap_socket_connect_udp: ioctl FIONBIO: %s\n",
263 }
264
265 switch (connect_addr.addr.sa.sa_family) {
266#if COAP_IPV4_SUPPORT
267 case AF_INET:
268 if (connect_addr.addr.sin.sin_port == 0)
269 connect_addr.addr.sin.sin_port = htons(default_port);
270 break;
271#endif /* COAP_IPV4_SUPPORT */
272#if COAP_IPV6_SUPPORT
273 case AF_INET6:
274 if (connect_addr.addr.sin6.sin6_port == 0)
275 connect_addr.addr.sin6.sin6_port = htons(default_port);
276 /* Configure the socket as dual-stacked */
277 if (setsockopt(sock->fd, IPPROTO_IPV6, IPV6_V6ONLY, OPTVAL_T(&off),
278 sizeof(off)) == COAP_SOCKET_ERROR)
279 if (errno != ENOSYS) {
280 coap_log_warn("coap_socket_connect_udp: setsockopt IPV6_V6ONLY: %s\n",
282 }
283#endif /* COAP_IPV6_SUPPORT */
284 break;
285#if COAP_AF_UNIX_SUPPORT
286 case AF_UNIX:
287 break;
288#endif /* COAP_AF_UNIX_SUPPORT */
289 default:
290 coap_log_alert("coap_socket_connect_udp: unsupported sa_family %d\n",
291 connect_addr.addr.sa.sa_family);
292 goto error;;
293 }
294
295 if (local_if && local_if->addr.sa.sa_family) {
296 if (local_if->addr.sa.sa_family != connect_addr.addr.sa.sa_family) {
297 coap_log_warn("coap_socket_connect_udp: local address family != "
298 "remote address family\n");
299 goto error;
300 }
301 if (setsockopt(sock->fd, SOL_SOCKET, SO_REUSEADDR, OPTVAL_T(&on), sizeof(on)) == COAP_SOCKET_ERROR)
302 coap_log_warn("coap_socket_connect_udp: setsockopt SO_REUSEADDR: %s\n",
304 if (bind(sock->fd, &local_if->addr.sa,
306 local_if->addr.sa.sa_family == AF_INET ?
307 (socklen_t)sizeof(struct sockaddr_in) :
308#endif /* COAP_IPV4_SUPPORT */
309 (socklen_t)local_if->size) == COAP_SOCKET_ERROR) {
310 coap_log_warn("coap_socket_connect_udp: bind: %s\n",
312 goto error;
313 }
314#if COAP_AF_UNIX_SUPPORT
315 } else if (connect_addr.addr.sa.sa_family == AF_UNIX) {
316 /* Need to bind to a local address for clarity over endpoints */
317 coap_log_warn("coap_socket_connect_udp: local address required\n");
318 goto error;
319#endif /* COAP_AF_UNIX_SUPPORT */
320 }
321
322 /* special treatment for sockets that are used for multicast communication */
323 if (is_mcast) {
324 if (!(local_if && local_if->addr.sa.sa_family)) {
325 /* Bind to a (unused) port to simplify logging */
326 coap_address_t bind_addr;
327
328 coap_address_init(&bind_addr);
329 bind_addr.addr.sa.sa_family = connect_addr.addr.sa.sa_family;
330 if (bind(sock->fd, &bind_addr.addr.sa,
332 bind_addr.addr.sa.sa_family == AF_INET ?
333 (socklen_t)sizeof(struct sockaddr_in) :
334#endif /* COAP_IPV4_SUPPORT */
335 (socklen_t)bind_addr.size) == COAP_SOCKET_ERROR) {
336 coap_log_warn("coap_socket_connect_udp: bind: %s\n",
338 goto error;
339 }
340 }
341 if (getsockname(sock->fd, &local_addr->addr.sa, &local_addr->size) == COAP_SOCKET_ERROR) {
342 coap_log_warn("coap_socket_connect_udp: getsockname for multicast socket: %s\n",
344 }
345 coap_address_copy(remote_addr, &connect_addr);
346 coap_address_copy(&sock->mcast_addr, &connect_addr);
348 if (coap_is_bcast(server) &&
349 setsockopt(sock->fd, SOL_SOCKET, SO_BROADCAST, OPTVAL_T(&on),
350 sizeof(on)) == COAP_SOCKET_ERROR)
351 coap_log_warn("coap_socket_connect_udp: setsockopt SO_BROADCAST: %s\n",
353 return 1;
354 }
355
356 if (connect(sock->fd, &connect_addr.addr.sa, connect_addr.size) == COAP_SOCKET_ERROR) {
357#if COAP_AF_UNIX_SUPPORT
358 if (connect_addr.addr.sa.sa_family == AF_UNIX) {
359 coap_log_warn("coap_socket_connect_udp: connect: %s: %s\n",
360 connect_addr.addr.cun.sun_path, coap_socket_strerror());
361 } else
362#endif /* COAP_AF_UNIX_SUPPORT */
363 {
364 coap_log_warn("coap_socket_connect_udp: connect: %s (%d)\n",
365 coap_socket_strerror(), connect_addr.addr.sa.sa_family);
366 }
367 goto error;
368 }
369
370 if (getsockname(sock->fd, &local_addr->addr.sa, &local_addr->size) == COAP_SOCKET_ERROR) {
371 coap_log_warn("coap_socket_connect_udp: getsockname: %s\n",
373 }
374
375 if (getpeername(sock->fd, &remote_addr->addr.sa, &remote_addr->size) == COAP_SOCKET_ERROR) {
376 coap_log_warn("coap_socket_connect_udp: getpeername: %s\n",
378 }
379
381 return 1;
382
383error:
384 coap_socket_close(sock);
385 return 0;
386}
387#endif /* COAP_CLIENT_SUPPORT */
388
389void
391 if (sock->fd != COAP_INVALID_SOCKET) {
392#ifdef COAP_EPOLL_SUPPORT
393#if COAP_SERVER_SUPPORT
394 coap_context_t *context = sock->session ? sock->session->context :
395 sock->endpoint ? sock->endpoint->context : NULL;
396#else /* COAP_SERVER_SUPPORT */
397 coap_context_t *context = sock->session ? sock->session->context : NULL;
398#endif /* COAP_SERVER_SUPPORT */
399 if (context != NULL) {
400 int ret;
401 struct epoll_event event;
402
403 /* Kernels prior to 2.6.9 expect non NULL event parameter */
404 ret = epoll_ctl(context->epfd, EPOLL_CTL_DEL, sock->fd, &event);
405 if (ret == -1 && errno != ENOENT) {
406 coap_log_err("%s: epoll_ctl DEL failed: %s (%d)\n",
407 "coap_socket_close",
408 coap_socket_strerror(), errno);
409 }
410 }
411#endif /* COAP_EPOLL_SUPPORT */
412#if COAP_SERVER_SUPPORT
413#if COAP_AF_UNIX_SUPPORT
414 if (sock->endpoint &&
415 sock->endpoint->bind_addr.addr.sa.sa_family == AF_UNIX) {
416 /* Clean up Unix endpoint */
417#ifdef _WIN32
418 _unlink(sock->endpoint->bind_addr.addr.cun.sun_path);
419#else /* ! _WIN32 */
420 unlink(sock->endpoint->bind_addr.addr.cun.sun_path);
421#endif /* ! _WIN32 */
422 }
423#endif /* COAP_AF_UNIX_SUPPORT */
424 sock->endpoint = NULL;
425#endif /* COAP_SERVER_SUPPORT */
426#if COAP_CLIENT_SUPPORT
427#if COAP_AF_UNIX_SUPPORT
428 if (sock->session && sock->session->type == COAP_SESSION_TYPE_CLIENT &&
429 sock->session->addr_info.local.addr.sa.sa_family == AF_UNIX) {
430 /* Clean up Unix endpoint */
431#ifdef _WIN32
432 _unlink(sock->session->addr_info.local.addr.cun.sun_path);
433#else /* ! _WIN32 */
434 unlink(sock->session->addr_info.local.addr.cun.sun_path);
435#endif /* ! _WIN32 */
436 }
437#endif /* COAP_AF_UNIX_SUPPORT */
438#endif /* COAP_CLIENT_SUPPORT */
439 sock->session = NULL;
440 coap_closesocket(sock->fd);
441 sock->fd = COAP_INVALID_SOCKET;
442 }
443 sock->flags = COAP_SOCKET_EMPTY;
444}
445
446#ifdef COAP_EPOLL_SUPPORT
447void
449 uint32_t events,
450 const char *func) {
451 int ret;
452 struct epoll_event event;
453 coap_context_t *context;
454
455#if COAP_MAX_LOGGING_LEVEL < _COAP_LOG_ERR
456 (void)func;
457#endif
458
459 if (sock == NULL)
460 return;
461
462#if COAP_SERVER_SUPPORT
463 context = sock->session ? sock->session->context :
464 sock->endpoint ? sock->endpoint->context : NULL;
465#else /* ! COAP_SERVER_SUPPORT */
466 context = sock->session ? sock->session->context : NULL;
467#endif /* ! COAP_SERVER_SUPPORT */
468 if (context == NULL)
469 return;
470
471 /* Needed if running 32bit as ptr is only 32bit */
472 memset(&event, 0, sizeof(event));
473 event.events = events;
474 event.data.ptr = sock;
475
476 ret = epoll_ctl(context->epfd, EPOLL_CTL_ADD, sock->fd, &event);
477 if (ret == -1) {
478 coap_log_err("%s: epoll_ctl ADD failed: %s (%d)\n",
479 func,
480 coap_socket_strerror(), errno);
481 }
482}
483
484void
486 uint32_t events,
487 const char *func) {
488 int ret;
489 struct epoll_event event;
490 coap_context_t *context;
491
492#if COAP_MAX_LOGGING_LEVEL < _COAP_LOG_ERR
493 (void)func;
494#endif
495
496 if (sock == NULL)
497 return;
498
499#if COAP_SERVER_SUPPORT
500 context = sock->session ? sock->session->context :
501 sock->endpoint ? sock->endpoint->context : NULL;
502#else /* COAP_SERVER_SUPPORT */
503 context = sock->session ? sock->session->context : NULL;
504#endif /* COAP_SERVER_SUPPORT */
505 if (context == NULL)
506 return;
507
508 event.events = events;
509 event.data.ptr = sock;
510
511 ret = epoll_ctl(context->epfd, EPOLL_CTL_MOD, sock->fd, &event);
512 if (ret == -1) {
513#if (COAP_MAX_LOGGING_LEVEL < COAP_LOG_ERR)
514 (void)func;
515#endif
516 coap_log_err("%s: epoll_ctl MOD failed: %s (%d)\n",
517 func,
518 coap_socket_strerror(), errno);
519 }
520}
521#endif /* COAP_EPOLL_SUPPORT */
522
523#endif /* ! WITH_CONTIKI && ! WITH_LWIP && ! RIOT_VERSION*/
524
525#ifndef WITH_CONTIKI
526void
528#if COAP_EPOLL_SUPPORT
529 if (context->eptimerfd != -1) {
530 coap_tick_t now;
531
532 coap_ticks(&now);
533 if (context->next_timeout == 0 || context->next_timeout > now + delay) {
534 struct itimerspec new_value;
535 int ret;
536
537 context->next_timeout = now + delay;
538 memset(&new_value, 0, sizeof(new_value));
539 if (delay == 0) {
540 new_value.it_value.tv_nsec = 1; /* small but not zero */
541 } else {
542 new_value.it_value.tv_sec = delay / COAP_TICKS_PER_SECOND;
543 new_value.it_value.tv_nsec = (delay % COAP_TICKS_PER_SECOND) *
544 1000000;
545 }
546 ret = timerfd_settime(context->eptimerfd, 0, &new_value, NULL);
547 if (ret == -1) {
548 coap_log_err("%s: timerfd_settime failed: %s (%d)\n",
549 "coap_update_io_timer",
550 coap_socket_strerror(), errno);
551 }
552#ifdef COAP_DEBUG_WAKEUP_TIMES
553 else {
554 coap_log_debug("****** Next wakeup time %3ld.%09ld\n",
555 new_value.it_value.tv_sec, new_value.it_value.tv_nsec);
556 }
557#endif /* COAP_DEBUG_WAKEUP_TIMES */
558 }
559 }
560#else /* ! COAP_EPOLL_SUPPORT */
561 coap_tick_t now;
562
563 coap_ticks(&now);
564 if (context->next_timeout == 0 || context->next_timeout > now + delay) {
565 context->next_timeout = now + delay;
566 }
567#endif /* ! COAP_EPOLL_SUPPORT */
568}
569#endif /* ! WITH_CONTIKI */
570
571#if !defined(WITH_CONTIKI) && !defined(WITH_LWIP) && !defined(RIOT_VERSION)
572
573#ifdef _WIN32
574static void
575coap_win_error_to_errno(void) {
576 int w_error = WSAGetLastError();
577 switch (w_error) {
578 case WSA_NOT_ENOUGH_MEMORY:
579 errno = ENOMEM;
580 break;
581 case WSA_INVALID_PARAMETER:
582 errno = EINVAL;
583 break;
584 case WSAEINTR:
585 errno = EINTR;
586 break;
587 case WSAEBADF:
588 errno = EBADF;
589 break;
590 case WSAEACCES:
591 errno = EACCES;
592 break;
593 case WSAEFAULT:
594 errno = EFAULT;
595 break;
596 case WSAEINVAL:
597 errno = EINVAL;
598 break;
599 case WSAEMFILE:
600 errno = EMFILE;
601 break;
602 case WSAEWOULDBLOCK:
603 errno = EWOULDBLOCK;
604 break;
605 case WSAENETDOWN:
606 errno = ENETDOWN;
607 break;
608 case WSAENETUNREACH:
609 errno = ENETUNREACH;
610 break;
611 case WSAENETRESET:
612 errno = ENETRESET;
613 break;
614 case WSAECONNABORTED:
615 errno = ECONNABORTED;
616 break;
617 case WSAECONNRESET:
618 errno = ECONNRESET;
619 break;
620 case WSAENOBUFS:
621 errno = ENOBUFS;
622 break;
623 case WSAETIMEDOUT:
624 errno = ETIMEDOUT;
625 break;
626 case WSAECONNREFUSED:
627 errno = ECONNREFUSED;
628 break;
629 default:
630 coap_log_err("WSAGetLastError: %d mapping to errno failed - please fix\n",
631 w_error);
632 errno = EPERM;
633 break;
634 }
635}
636#endif /* _WIN32 */
637
638/*
639 * strm
640 * return +ve Number of bytes written.
641 * 0 No data written.
642 * -1 Error (error in errno).
643 */
644ssize_t
645coap_socket_write(coap_socket_t *sock, const uint8_t *data, size_t data_len) {
646 ssize_t r;
647
649#ifdef _WIN32
650 r = send(sock->fd, (const char *)data, (int)data_len, 0);
651#else
652#ifndef MSG_NOSIGNAL
653#define MSG_NOSIGNAL 0
654#endif /* MSG_NOSIGNAL */
655 r = send(sock->fd, data, data_len, MSG_NOSIGNAL);
656#endif
657 if (r == COAP_SOCKET_ERROR) {
658#ifdef _WIN32
659 coap_win_error_to_errno();
660#endif /* _WIN32 */
661 if (errno==EAGAIN ||
662#if EAGAIN != EWOULDBLOCK
663 errno == EWOULDBLOCK ||
664#endif
665 errno == EINTR) {
667#ifdef COAP_EPOLL_SUPPORT
669 EPOLLOUT |
670 ((sock->flags & COAP_SOCKET_WANT_READ) ?
671 EPOLLIN : 0),
672 __func__);
673#endif /* COAP_EPOLL_SUPPORT */
674 return 0;
675 }
676 if (errno == EPIPE || errno == ECONNRESET) {
677 coap_log_info("coap_socket_write: send: %s\n",
679 } else {
680 coap_log_warn("coap_socket_write: send: %s\n",
682 }
683 return -1;
684 }
685 if (r < (ssize_t)data_len) {
687#ifdef COAP_EPOLL_SUPPORT
689 EPOLLOUT |
690 ((sock->flags & COAP_SOCKET_WANT_READ) ?
691 EPOLLIN : 0),
692 __func__);
693#endif /* COAP_EPOLL_SUPPORT */
694 }
695 return r;
696}
697
698/*
699 * strm
700 * return >=0 Number of bytes read.
701 * -1 Error (error in errno).
702 */
703ssize_t
704coap_socket_read(coap_socket_t *sock, uint8_t *data, size_t data_len) {
705 ssize_t r;
706
707#ifdef _WIN32
708 r = recv(sock->fd, (char *)data, (int)data_len, 0);
709#else
710 r = recv(sock->fd, data, data_len, 0);
711#endif
712 if (r == 0) {
713 /* graceful shutdown */
714 sock->flags &= ~COAP_SOCKET_CAN_READ;
715 errno = ECONNRESET;
716 return -1;
717 } else if (r == COAP_SOCKET_ERROR) {
718 sock->flags &= ~COAP_SOCKET_CAN_READ;
719#ifdef _WIN32
720 coap_win_error_to_errno();
721#endif /* _WIN32 */
722 if (errno==EAGAIN ||
723#if EAGAIN != EWOULDBLOCK
724 errno == EWOULDBLOCK ||
725#endif
726 errno == EINTR) {
727 return 0;
728 }
729 if (errno != ECONNRESET) {
730 coap_log_warn("coap_socket_read: recv: %s\n",
732 }
733 return -1;
734 }
735 if (r < (ssize_t)data_len)
736 sock->flags &= ~COAP_SOCKET_CAN_READ;
737 return r;
738}
739
740#endif /* ! WITH_CONTIKI && ! WITH_LWIP && ! RIOT_VERSION */
741
742#if !defined(WITH_LWIP) && !defined(__ZEPHYR__)
743#if (!defined(WITH_CONTIKI)) != ( defined(HAVE_NETINET_IN_H) || defined(HAVE_WS2TCPIP_H) )
744/* define struct in6_pktinfo and struct in_pktinfo if not available
745 FIXME: check with configure
746*/
747#if !defined(__MINGW32__) && !defined(RIOT_VERSION)
749 struct in6_addr ipi6_addr; /* src/dst IPv6 address */
750 unsigned int ipi6_ifindex; /* send/recv interface index */
751};
752
755 struct in_addr ipi_spec_dst;
756 struct in_addr ipi_addr;
757};
758#endif /* ! __MINGW32__ && ! RIOT_VERSION */
759#endif
760#endif /* ! WITH_LWIP && ! __ZEPHYR__ */
761
762#if !defined(WITH_CONTIKI) && !defined(SOL_IP)
763/* Solaris expects level IPPROTO_IP for ancillary data. */
764#define SOL_IP IPPROTO_IP
765#endif
766#ifdef _WIN32
767#define COAP_SOL_IP IPPROTO_IP
768#else /* ! _WIN32 */
769#define COAP_SOL_IP SOL_IP
770#endif /* ! _WIN32 */
771
772#if defined(_WIN32)
773#include <mswsock.h>
774#if defined(__MINGW32__)
775static __thread LPFN_WSARECVMSG lpWSARecvMsg = NULL;
776#if(_WIN32_WINNT >= 0x0600)
777#define CMSG_FIRSTHDR WSA_CMSG_FIRSTHDR
778#define CMSG_NXTHDR WSA_CMSG_NXTHDR
779#define CMSG_LEN WSA_CMSG_LEN
780#define CMSG_SPACE WSA_CMSG_SPACE
781#if(_WIN32_WINNT < 0x0603 || _WIN32_WINNT == 0x0a00)
782#define cmsghdr _WSACMSGHDR
783#endif /* (_WIN32_WINNT<0x0603 || _WIN32_WINNT == 0x0a00) */
784#endif /* (_WIN32_WINNT>=0x0600) */
785#else /* ! __MINGW32__ */
786static __declspec(thread) LPFN_WSARECVMSG lpWSARecvMsg = NULL;
787#endif /* ! __MINGW32__ */
788/* Map struct WSABUF fields to their posix counterpart */
789#define msghdr _WSAMSG
790#define msg_name name
791#define msg_namelen namelen
792#define msg_iov lpBuffers
793#define msg_iovlen dwBufferCount
794#define msg_control Control.buf
795#define msg_controllen Control.len
796#define iovec _WSABUF
797#define iov_base buf
798#define iov_len len
799#define iov_len_t u_long
800#undef CMSG_DATA
801#define CMSG_DATA WSA_CMSG_DATA
802#define ipi_spec_dst ipi_addr
803#if !defined(__MINGW32__)
804#pragma warning( disable : 4116 )
805#endif /* ! __MINGW32__ */
806#else
807#define iov_len_t size_t
808#endif
809
810#if defined(_CYGWIN_ENV) || defined(__QNXNTO__)
811#define ipi_spec_dst ipi_addr
812#endif
813
814#if !defined(RIOT_VERSION) && !defined(WITH_LWIP) && !defined(WITH_CONTIKI)
815#if COAP_CLIENT_SUPPORT
816static uint32_t cid_track_counter;
817
818static void
819coap_test_cid_tuple_change(coap_session_t *session) {
820 if (session->type == COAP_SESSION_TYPE_CLIENT &&
821 session->negotiated_cid &&
823 session->proto == COAP_PROTO_DTLS && session->context->testing_cids) {
824 if ((++cid_track_counter) % session->context->testing_cids == 0) {
825 coap_address_t local_if = session->addr_info.local;
826 uint16_t port = coap_address_get_port(&local_if);
827
828 port++;
829 coap_address_set_port(&local_if, port);
830
831 coap_socket_close(&session->sock);
832 session->sock.session = session;
833 if (!coap_socket_connect_udp(&session->sock, &local_if, &session->addr_info.remote,
834 port,
835 &session->addr_info.local,
836 &session->addr_info.remote)) {
837 coap_log_err("Tuple change for CID failed\n");
838 return;
839#ifdef COAP_EPOLL_SUPPORT
840 } else {
841 coap_epoll_ctl_add(&session->sock,
842 EPOLLIN |
843 ((session->sock.flags & COAP_SOCKET_WANT_CONNECT) ?
844 EPOLLOUT : 0),
845 __func__);
846#endif /* COAP_EPOLL_SUPPORT */
847 }
849 }
850 }
851}
852#endif /* COAP_CLIENT_SUPPORT */
853
854/*
855 * dgram
856 * return +ve Number of bytes written.
857 * -1 Error error in errno).
858 */
859ssize_t
861 const uint8_t *data, size_t datalen) {
862 ssize_t bytes_written = 0;
863
864#if COAP_CLIENT_SUPPORT
865 coap_test_cid_tuple_change(session);
866#endif /* COAP_CLIENT_SUPPORT */
867
868 if (!coap_debug_send_packet()) {
869 bytes_written = (ssize_t)datalen;
870 } else if (sock->flags & COAP_SOCKET_CONNECTED) {
871#ifdef _WIN32
872 bytes_written = send(sock->fd, (const char *)data, (int)datalen, 0);
873#else
874 bytes_written = send(sock->fd, data, datalen, 0);
875#endif
876 } else {
877#if defined(_WIN32)
878 DWORD dwNumberOfBytesSent = 0;
879 int r;
880#endif /* _WIN32 */
881#ifdef HAVE_STRUCT_CMSGHDR
882 /* a buffer large enough to hold all packet info types, ipv6 is the largest */
883 char buf[CMSG_SPACE(sizeof(struct in6_pktinfo))];
884 struct msghdr mhdr;
885 struct iovec iov[1];
886 const void *addr = &session->addr_info.remote.addr;
887
888 assert(session);
889
890 memcpy(&iov[0].iov_base, &data, sizeof(iov[0].iov_base));
891 iov[0].iov_len = (iov_len_t)datalen;
892
893 memset(buf, 0, sizeof(buf));
894
895 memset(&mhdr, 0, sizeof(struct msghdr));
896 memcpy(&mhdr.msg_name, &addr, sizeof(mhdr.msg_name));
897 mhdr.msg_namelen = session->addr_info.remote.addr.sa.sa_family == AF_INET ?
898 (socklen_t)sizeof(struct sockaddr_in) :
899 session->addr_info.remote.size;
900
901 mhdr.msg_iov = iov;
902 mhdr.msg_iovlen = 1;
903
904 if (!coap_address_isany(&session->addr_info.local) &&
905 !coap_is_mcast(&session->addr_info.local)) {
906 switch (session->addr_info.local.addr.sa.sa_family) {
907#if COAP_IPV6_SUPPORT
908 case AF_INET6: {
909 struct cmsghdr *cmsg;
910
911#if COAP_IPV4_SUPPORT
912 if (IN6_IS_ADDR_V4MAPPED(&session->addr_info.local.addr.sin6.sin6_addr)) {
913#if defined(IP_PKTINFO)
914 struct in_pktinfo *pktinfo;
915 mhdr.msg_control = buf;
916 mhdr.msg_controllen = CMSG_SPACE(sizeof(struct in_pktinfo));
917
918 cmsg = CMSG_FIRSTHDR(&mhdr);
919 cmsg->cmsg_level = COAP_SOL_IP;
920 cmsg->cmsg_type = IP_PKTINFO;
921 cmsg->cmsg_len = CMSG_LEN(sizeof(struct in_pktinfo));
922
923 pktinfo = (struct in_pktinfo *)CMSG_DATA(cmsg);
924
925 pktinfo->ipi_ifindex = session->ifindex;
926 memcpy(&pktinfo->ipi_spec_dst,
927 session->addr_info.local.addr.sin6.sin6_addr.s6_addr + 12,
928 sizeof(pktinfo->ipi_spec_dst));
929#elif defined(IP_SENDSRCADDR)
930 mhdr.msg_control = buf;
931 mhdr.msg_controllen = CMSG_SPACE(sizeof(struct in_addr));
932
933 cmsg = CMSG_FIRSTHDR(&mhdr);
934 cmsg->cmsg_level = IPPROTO_IP;
935 cmsg->cmsg_type = IP_SENDSRCADDR;
936 cmsg->cmsg_len = CMSG_LEN(sizeof(struct in_addr));
937
938 memcpy(CMSG_DATA(cmsg),
939 session->addr_info.local.addr.sin6.sin6_addr.s6_addr + 12,
940 sizeof(struct in_addr));
941#endif /* IP_PKTINFO */
942 } else {
943#endif /* COAP_IPV4_SUPPORT */
944 struct in6_pktinfo *pktinfo;
945 mhdr.msg_control = buf;
946 mhdr.msg_controllen = CMSG_SPACE(sizeof(struct in6_pktinfo));
947
948 cmsg = CMSG_FIRSTHDR(&mhdr);
949 cmsg->cmsg_level = IPPROTO_IPV6;
950 cmsg->cmsg_type = IPV6_PKTINFO;
951 cmsg->cmsg_len = CMSG_LEN(sizeof(struct in6_pktinfo));
952
953 pktinfo = (struct in6_pktinfo *)CMSG_DATA(cmsg);
954
955 if (coap_is_mcast(&session->addr_info.remote)) {
956 pktinfo->ipi6_ifindex = session->addr_info.remote.addr.sin6.sin6_scope_id;
957 } else {
958 pktinfo->ipi6_ifindex = session->ifindex;
959 }
960 memcpy(&pktinfo->ipi6_addr,
961 &session->addr_info.local.addr.sin6.sin6_addr,
962 sizeof(pktinfo->ipi6_addr));
963#if COAP_IPV4_SUPPORT
964 }
965#endif /* COAP_IPV4_SUPPORT */
966 break;
967 }
968#endif /* COAP_IPV6_SUPPORT */
969#if COAP_IPV4_SUPPORT
970 case AF_INET: {
971#if defined(IP_PKTINFO)
972 struct cmsghdr *cmsg;
973 struct in_pktinfo *pktinfo;
974
975 mhdr.msg_control = buf;
976 mhdr.msg_controllen = CMSG_SPACE(sizeof(struct in_pktinfo));
977
978 cmsg = CMSG_FIRSTHDR(&mhdr);
979 cmsg->cmsg_level = COAP_SOL_IP;
980 cmsg->cmsg_type = IP_PKTINFO;
981 cmsg->cmsg_len = CMSG_LEN(sizeof(struct in_pktinfo));
982
983 pktinfo = (struct in_pktinfo *)CMSG_DATA(cmsg);
984
985 pktinfo->ipi_ifindex = session->ifindex;
986 memcpy(&pktinfo->ipi_spec_dst,
987 &session->addr_info.local.addr.sin.sin_addr,
988 sizeof(pktinfo->ipi_spec_dst));
989#elif defined(IP_SENDSRCADDR)
990 struct cmsghdr *cmsg;
991 mhdr.msg_control = buf;
992 mhdr.msg_controllen = CMSG_SPACE(sizeof(struct in_addr));
993
994 cmsg = CMSG_FIRSTHDR(&mhdr);
995 cmsg->cmsg_level = IPPROTO_IP;
996 cmsg->cmsg_type = IP_SENDSRCADDR;
997 cmsg->cmsg_len = CMSG_LEN(sizeof(struct in_addr));
998
999 memcpy(CMSG_DATA(cmsg),
1000 &session->addr_info.local.addr.sin.sin_addr,
1001 sizeof(struct in_addr));
1002#endif /* IP_PKTINFO */
1003 break;
1004 }
1005#endif /* COAP_IPV4_SUPPORT */
1006#if COAP_AF_UNIX_SUPPORT
1007 case AF_UNIX:
1008 break;
1009#endif /* COAP_AF_UNIX_SUPPORT */
1010 default:
1011 /* error */
1012 coap_log_warn("protocol not supported\n");
1013 return -1;
1014 }
1015 }
1016#endif /* HAVE_STRUCT_CMSGHDR */
1017
1018#if defined(_WIN32)
1019 r = WSASendMsg(sock->fd, &mhdr, 0 /*dwFlags*/, &dwNumberOfBytesSent, NULL /*lpOverlapped*/,
1020 NULL /*lpCompletionRoutine*/);
1021 if (r == 0)
1022 bytes_written = (ssize_t)dwNumberOfBytesSent;
1023 else {
1024 bytes_written = -1;
1025 coap_win_error_to_errno();
1026 }
1027#else /* !_WIN32 */
1028#ifdef HAVE_STRUCT_CMSGHDR
1029 bytes_written = sendmsg(sock->fd, &mhdr, 0);
1030#else /* ! HAVE_STRUCT_CMSGHDR */
1031 bytes_written = sendto(sock->fd, (const void *)data, datalen, 0,
1032 &session->addr_info.remote.addr.sa,
1033 session->addr_info.remote.size);
1034#endif /* ! HAVE_STRUCT_CMSGHDR */
1035#endif /* !_WIN32 */
1036 }
1037
1038 if (bytes_written < 0)
1039 coap_log_crit("coap_socket_send: %s\n", coap_socket_strerror());
1040
1041 return bytes_written;
1042}
1043#endif /* ! RIOT_VERSION && ! WITH_LWIP && ! WITH_CONTIKI */
1044
1045#define SIN6(A) ((struct sockaddr_in6 *)(A))
1046
1047void
1048coap_packet_get_memmapped(coap_packet_t *packet, unsigned char **address, size_t *length) {
1049 *address = packet->payload;
1050 *length = packet->length;
1051}
1052
1053#if !defined(WITH_LWIP) && !defined(WITH_CONTIKI) && !defined(RIOT_VERSION)
1054/*
1055 * dgram
1056 * return +ve Number of bytes written.
1057 * -1 Error error in errno).
1058 * -2 ICMP error response
1059 */
1060ssize_t
1062 ssize_t len = -1;
1063
1064 assert(sock);
1065 assert(packet);
1066
1067 if ((sock->flags & COAP_SOCKET_CAN_READ) == 0) {
1068 return -1;
1069 } else {
1070 /* clear has-data flag */
1071 sock->flags &= ~COAP_SOCKET_CAN_READ;
1072 }
1073
1074 if (sock->flags & COAP_SOCKET_CONNECTED) {
1075#ifdef _WIN32
1076 len = recv(sock->fd, (char *)packet->payload, COAP_RXBUFFER_SIZE, 0);
1077#else
1078 len = recv(sock->fd, packet->payload, COAP_RXBUFFER_SIZE, 0);
1079#endif
1080 if (len < 0) {
1081#ifdef _WIN32
1082 coap_win_error_to_errno();
1083#endif /* _WIN32 */
1084 if (errno == ECONNREFUSED || errno == EHOSTUNREACH || errno == ECONNRESET) {
1085 /* client-side ICMP destination unreachable, ignore it */
1086 coap_log_warn("** %s: coap_socket_recv: ICMP: %s\n",
1087 sock->session ?
1088 coap_session_str(sock->session) : "",
1090 return -2;
1091 }
1092 if (errno != EAGAIN) {
1093 coap_log_warn("** %s: coap_socket_recv: %s\n",
1094 sock->session ?
1095 coap_session_str(sock->session) : "",
1097 }
1098 goto error;
1099 } else if (len > 0) {
1100 packet->length = (size_t)len;
1101 }
1102 } else {
1103#if defined(_WIN32)
1104 DWORD dwNumberOfBytesRecvd = 0;
1105 int r;
1106#endif /* _WIN32 */
1107#ifdef HAVE_STRUCT_CMSGHDR
1108 /* a buffer large enough to hold all packet info types, ipv6 is the largest */
1109 char buf[CMSG_SPACE(sizeof(struct in6_pktinfo))];
1110 struct cmsghdr *cmsg;
1111 struct msghdr mhdr;
1112 struct iovec iov[1];
1113
1114#if defined(__MINGW32__)
1115 iov[0].iov_base = (char *) packet->payload;
1116#else /* ! __MINGW32__ */
1117 iov[0].iov_base = packet->payload;
1118#endif /* defined(__MINGW32__) */
1119 iov[0].iov_len = (iov_len_t)COAP_RXBUFFER_SIZE;
1120
1121 memset(&mhdr, 0, sizeof(struct msghdr));
1122
1123 mhdr.msg_name = (struct sockaddr *)&packet->addr_info.remote.addr;
1124 mhdr.msg_namelen = sizeof(packet->addr_info.remote.addr);
1125
1126 mhdr.msg_iov = iov;
1127 mhdr.msg_iovlen = 1;
1128
1129 mhdr.msg_control = buf;
1130 mhdr.msg_controllen = sizeof(buf);
1131 /* set a big first length incase recvmsg() does not implement updating
1132 msg_control as well as preset the first cmsg with bad data */
1133 cmsg = (struct cmsghdr *)buf;
1134 cmsg->cmsg_len = CMSG_LEN(sizeof(buf));
1135 cmsg->cmsg_level = -1;
1136 cmsg->cmsg_type = -1;
1137
1138#if defined(_WIN32)
1139 if (!lpWSARecvMsg) {
1140 GUID wsaid = WSAID_WSARECVMSG;
1141 DWORD cbBytesReturned = 0;
1142 if (WSAIoctl(sock->fd, SIO_GET_EXTENSION_FUNCTION_POINTER, &wsaid, sizeof(wsaid), &lpWSARecvMsg,
1143 sizeof(lpWSARecvMsg), &cbBytesReturned, NULL, NULL) != 0) {
1144 coap_log_warn("coap_socket_recv: no WSARecvMsg\n");
1145 return -1;
1146 }
1147 }
1148 r = lpWSARecvMsg(sock->fd, &mhdr, &dwNumberOfBytesRecvd, NULL /* LPWSAOVERLAPPED */,
1149 NULL /* LPWSAOVERLAPPED_COMPLETION_ROUTINE */);
1150 if (r == 0)
1151 len = (ssize_t)dwNumberOfBytesRecvd;
1152 else if (r == COAP_SOCKET_ERROR)
1153 coap_win_error_to_errno();
1154#else
1155 len = recvmsg(sock->fd, &mhdr, 0);
1156#endif
1157
1158#else /* ! HAVE_STRUCT_CMSGHDR */
1159 len = recvfrom(sock->fd, (void *)packet->payload, COAP_RXBUFFER_SIZE, 0,
1160 &packet->addr_info.remote.addr.sa,
1161 &packet->addr_info.remote.size);
1162#endif /* ! HAVE_STRUCT_CMSGHDR */
1163
1164 if (len < 0) {
1165#ifdef _WIN32
1166 coap_win_error_to_errno();
1167#endif /* _WIN32 */
1168 if (errno == ECONNREFUSED || errno == EHOSTUNREACH || errno == ECONNRESET) {
1169 /* server-side ICMP destination unreachable, ignore it. The destination address is in msg_name. */
1170 coap_log_warn("** %s: coap_socket_recv: ICMP: %s\n",
1171 sock->session ?
1172 coap_session_str(sock->session) : "",
1174 return 0;
1175 }
1176 if (errno != EAGAIN) {
1177 coap_log_warn("coap_socket_recv: %s\n", coap_socket_strerror());
1178 }
1179 goto error;
1180 } else {
1181#ifdef HAVE_STRUCT_CMSGHDR
1182 int dst_found = 0;
1183
1184 packet->addr_info.remote.size = mhdr.msg_namelen;
1185 packet->length = (size_t)len;
1186
1187 /* Walk through ancillary data records until the local interface
1188 * is found where the data was received. */
1189 for (cmsg = CMSG_FIRSTHDR(&mhdr); cmsg; cmsg = CMSG_NXTHDR(&mhdr, cmsg)) {
1190
1191#if COAP_IPV6_SUPPORT
1192 /* get the local interface for IPv6 */
1193 if (cmsg->cmsg_level == IPPROTO_IPV6 && cmsg->cmsg_type == IPV6_PKTINFO) {
1194 union {
1195 uint8_t *c;
1196 struct in6_pktinfo *p;
1197 } u;
1198 u.c = CMSG_DATA(cmsg);
1199 packet->ifindex = (int)(u.p->ipi6_ifindex);
1200 memcpy(&packet->addr_info.local.addr.sin6.sin6_addr,
1201 &u.p->ipi6_addr, sizeof(struct in6_addr));
1202 dst_found = 1;
1203 break;
1204 }
1205#endif /* COAP_IPV6_SUPPORT */
1206
1207#if COAP_IPV4_SUPPORT
1208 /* local interface for IPv4 */
1209#if defined(IP_PKTINFO)
1210 if (cmsg->cmsg_level == COAP_SOL_IP && cmsg->cmsg_type == IP_PKTINFO) {
1211 union {
1212 uint8_t *c;
1213 struct in_pktinfo *p;
1214 } u;
1215 u.c = CMSG_DATA(cmsg);
1216 packet->ifindex = u.p->ipi_ifindex;
1217#if COAP_IPV6_SUPPORT
1218 if (packet->addr_info.local.addr.sa.sa_family == AF_INET6) {
1219 memset(packet->addr_info.local.addr.sin6.sin6_addr.s6_addr, 0, 10);
1220 packet->addr_info.local.addr.sin6.sin6_addr.s6_addr[10] = 0xff;
1221 packet->addr_info.local.addr.sin6.sin6_addr.s6_addr[11] = 0xff;
1222 memcpy(packet->addr_info.local.addr.sin6.sin6_addr.s6_addr + 12,
1223 &u.p->ipi_addr, sizeof(struct in_addr));
1224 } else
1225#endif /* COAP_IPV6_SUPPORT */
1226 {
1227 memcpy(&packet->addr_info.local.addr.sin.sin_addr,
1228 &u.p->ipi_addr, sizeof(struct in_addr));
1229 }
1230 dst_found = 1;
1231 break;
1232 }
1233#endif /* IP_PKTINFO */
1234#if defined(IP_RECVDSTADDR)
1235 if (cmsg->cmsg_level == IPPROTO_IP && cmsg->cmsg_type == IP_RECVDSTADDR) {
1236 packet->ifindex = (int)sock->fd;
1237 memcpy(&packet->addr_info.local.addr.sin.sin_addr,
1238 CMSG_DATA(cmsg), sizeof(struct in_addr));
1239 dst_found = 1;
1240 break;
1241 }
1242#endif /* IP_RECVDSTADDR */
1243#endif /* COAP_IPV4_SUPPORT */
1244 if (!dst_found) {
1245 /* cmsg_level / cmsg_type combination we do not understand
1246 (ignore preset case for bad recvmsg() not updating cmsg) */
1247 if (cmsg->cmsg_level != -1 && cmsg->cmsg_type != -1) {
1248 coap_log_debug("cmsg_level = %d and cmsg_type = %d not supported - fix\n",
1249 cmsg->cmsg_level, cmsg->cmsg_type);
1250 }
1251 }
1252 }
1253 if (!dst_found) {
1254 /* Not expected, but cmsg_level and cmsg_type don't match above and
1255 may need a new case */
1256 packet->ifindex = (int)sock->fd;
1257 if (getsockname(sock->fd, &packet->addr_info.local.addr.sa,
1258 &packet->addr_info.local.size) < 0) {
1259 coap_log_debug("Cannot determine local port\n");
1260 }
1261 }
1262#else /* ! HAVE_STRUCT_CMSGHDR */
1263 packet->length = (size_t)len;
1264 packet->ifindex = 0;
1265 if (getsockname(sock->fd, &packet->addr_info.local.addr.sa,
1266 &packet->addr_info.local.size) < 0) {
1267 coap_log_debug("Cannot determine local port\n");
1268 goto error;
1269 }
1270#endif /* ! HAVE_STRUCT_CMSGHDR */
1271 }
1272 }
1273
1274 if (len >= 0)
1275 return len;
1276error:
1277 return -1;
1278}
1279#endif /* ! WITH_LWIP && ! WITH_CONTIKI && ! RIOT_VERSION */
1280
1281COAP_API unsigned int
1283 unsigned int ret;
1284
1285 coap_lock_lock(return 0);
1286 ret = coap_io_prepare_epoll_lkd(ctx, now);
1288 return ret;
1289}
1290
1291unsigned int
1293#ifndef COAP_EPOLL_SUPPORT
1294 (void)ctx;
1295 (void)now;
1296 coap_log_emerg("coap_io_prepare_epoll() requires libcoap compiled for using epoll\n");
1297 return 0;
1298#else /* COAP_EPOLL_SUPPORT */
1299 coap_socket_t *sockets[1];
1300 unsigned int max_sockets = sizeof(sockets)/sizeof(sockets[0]);
1301 unsigned int num_sockets;
1302 unsigned int timeout;
1303
1305 /* Use the common logic */
1306 timeout = coap_io_prepare_io_lkd(ctx, sockets, max_sockets, &num_sockets, now);
1307 /* Save when the next expected I/O is to take place */
1308 ctx->next_timeout = timeout ? now + timeout : 0;
1309 if (ctx->eptimerfd != -1) {
1310 struct itimerspec new_value;
1311 int ret;
1312
1313 memset(&new_value, 0, sizeof(new_value));
1314 coap_ticks(&now);
1315 if (ctx->next_timeout != 0 && ctx->next_timeout > now) {
1316 coap_tick_t rem_timeout = ctx->next_timeout - now;
1317 /* Need to trigger an event on ctx->eptimerfd in the future */
1318 new_value.it_value.tv_sec = rem_timeout / COAP_TICKS_PER_SECOND;
1319 new_value.it_value.tv_nsec = (rem_timeout % COAP_TICKS_PER_SECOND) *
1320 1000000;
1321 }
1322#ifdef COAP_DEBUG_WAKEUP_TIMES
1323 coap_log_debug("****** Next wakeup time %3ld.%09ld\n",
1324 new_value.it_value.tv_sec, new_value.it_value.tv_nsec);
1325#endif /* COAP_DEBUG_WAKEUP_TIMES */
1326 /* reset, or specify a future time for eptimerfd to trigger */
1327 ret = timerfd_settime(ctx->eptimerfd, 0, &new_value, NULL);
1328 if (ret == -1) {
1329 coap_log_err("%s: timerfd_settime failed: %s (%d)\n",
1330 "coap_io_prepare_epoll",
1331 coap_socket_strerror(), errno);
1332 }
1333 }
1334 return timeout;
1335#endif /* COAP_EPOLL_SUPPORT */
1336}
1337
1338/*
1339 * return 0 No i/o pending
1340 * +ve millisecs to next i/o activity
1341 */
1342COAP_API unsigned int
1344 coap_socket_t *sockets[],
1345 unsigned int max_sockets,
1346 unsigned int *num_sockets,
1347 coap_tick_t now) {
1348 unsigned int ret;
1349
1350 coap_lock_lock(return 0);
1351 ret = coap_io_prepare_io_lkd(ctx, sockets, max_sockets, num_sockets, now);
1353 return ret;
1354}
1355
1356/*
1357 * return 0 No i/o pending
1358 * +ve millisecs to next i/o activity
1359 */
1360unsigned int
1362 coap_socket_t *sockets[],
1363 unsigned int max_sockets,
1364 unsigned int *num_sockets,
1365 coap_tick_t now) {
1366 coap_queue_t *nextpdu;
1367 coap_session_t *s, *stmp;
1369 coap_tick_t s_timeout;
1370#if COAP_SERVER_SUPPORT
1371 int check_dtls_timeouts = 0;
1372#endif /* COAP_SERVER_SUPPORT */
1373#if defined(COAP_EPOLL_SUPPORT) || defined(WITH_LWIP) || defined(RIOT_VERSION)
1374 (void)sockets;
1375 (void)max_sockets;
1376#endif /* COAP_EPOLL_SUPPORT || WITH_LWIP || RIOT_VERSION*/
1377
1379 *num_sockets = 0;
1380
1381#if COAP_SERVER_SUPPORT
1382 /* Check to see if we need to send off any Observe requests */
1384
1385#if COAP_ASYNC_SUPPORT
1386 /* Check to see if we need to send off any Async requests */
1387 if (coap_check_async(ctx, now, &s_timeout)) {
1388 if (s_timeout < timeout)
1389 timeout = s_timeout;
1390 }
1391#endif /* COAP_ASYNC_SUPPORT */
1392#endif /* COAP_SERVER_SUPPORT */
1393
1394 /* Check to see if we need to send off any retransmit request */
1395 nextpdu = coap_peek_next(ctx);
1396 while (nextpdu && now >= ctx->sendqueue_basetime &&
1397 nextpdu->t <= now - ctx->sendqueue_basetime) {
1398 coap_retransmit(ctx, coap_pop_next(ctx));
1399 nextpdu = coap_peek_next(ctx);
1400 }
1401 if (nextpdu && now >= ctx->sendqueue_basetime &&
1402 (nextpdu->t - (now - ctx->sendqueue_basetime) < timeout))
1403 timeout = nextpdu->t - (now - ctx->sendqueue_basetime);
1404
1405 /* Check for DTLS timeouts */
1406 if (ctx->dtls_context) {
1409 if (tls_timeout > 0) {
1410 if (tls_timeout < now + COAP_TICKS_PER_SECOND / 10)
1411 tls_timeout = now + COAP_TICKS_PER_SECOND / 10;
1412 coap_log_debug("** DTLS global timeout set to %dms\n",
1413 (int)((tls_timeout - now) * 1000 / COAP_TICKS_PER_SECOND));
1414 if (tls_timeout - now < timeout)
1415 timeout = tls_timeout - now;
1416 }
1417#if COAP_SERVER_SUPPORT
1418 } else {
1419 check_dtls_timeouts = 1;
1420#endif /* COAP_SERVER_SUPPORT */
1421 }
1422 }
1423#if COAP_PROXY_SUPPORT
1424 if (coap_proxy_check_timeouts(ctx, now, &s_timeout)) {
1425 if (s_timeout < timeout)
1426 timeout = s_timeout;
1427 }
1428#endif /* COAP_PROXY_SUPPORT */
1429#if COAP_SERVER_SUPPORT
1430 coap_endpoint_t *ep;
1431 coap_tick_t session_timeout;
1432
1433 if (ctx->session_timeout > 0)
1434 session_timeout = ctx->session_timeout * COAP_TICKS_PER_SECOND;
1435 else
1437
1438 LL_FOREACH(ctx->endpoint, ep) {
1439#if !defined(COAP_EPOLL_SUPPORT) && !defined(WITH_LWIP) && !defined(RIOT_VERSION)
1441 if (*num_sockets < max_sockets)
1442 sockets[(*num_sockets)++] = &ep->sock;
1443 }
1444#endif /* ! COAP_EPOLL_SUPPORT && ! WITH_LWIP && ! RIOT_VERSION */
1445 SESSIONS_ITER_SAFE(ep->sessions, s, stmp) {
1446 /* Check whether any idle server sessions should be released */
1447 if (s->type == COAP_SESSION_TYPE_SERVER && s->ref == 0 &&
1448 s->delayqueue == NULL &&
1449 (s->last_rx_tx + session_timeout <= now ||
1453 continue;
1454 } else {
1455 if (s->type == COAP_SESSION_TYPE_SERVER && s->ref == 0 &&
1456 s->delayqueue == NULL) {
1457 /* Has to be positive based on if() above */
1458 s_timeout = (s->last_rx_tx + session_timeout) - now;
1459 if (s_timeout < timeout)
1460 timeout = s_timeout;
1461 }
1462 /* Make sure the session object is not deleted in any callbacks */
1464 /* Check any DTLS timeouts and expire if appropriate */
1465 if (check_dtls_timeouts && s->state == COAP_SESSION_STATE_HANDSHAKE &&
1466 s->proto == COAP_PROTO_DTLS && s->tls) {
1467 coap_tick_t tls_timeout = coap_dtls_get_timeout(s, now);
1468 while (tls_timeout > 0 && tls_timeout <= now) {
1469 coap_log_debug("** %s: DTLS retransmit timeout\n",
1470 coap_session_str(s));
1472 goto release_1;
1473
1474 if (s->tls)
1475 tls_timeout = coap_dtls_get_timeout(s, now);
1476 else {
1477 tls_timeout = 0;
1478 timeout = 1;
1479 }
1480 }
1481 if (tls_timeout > 0 && tls_timeout - now < timeout)
1482 timeout = tls_timeout - now;
1483 }
1484 /* Check if any server large receives are missing blocks */
1485 if (s->lg_srcv) {
1486 if (coap_block_check_lg_srcv_timeouts(s, now, &s_timeout)) {
1487 if (s_timeout < timeout)
1488 timeout = s_timeout;
1489 }
1490 }
1491 /* Check if any server large sending have timed out */
1492 if (s->lg_xmit) {
1493 if (coap_block_check_lg_xmit_timeouts(s, now, &s_timeout)) {
1494 if (s_timeout < timeout)
1495 timeout = s_timeout;
1496 }
1497 }
1498#if !defined(COAP_EPOLL_SUPPORT) && !defined(WITH_LWIP) && !defined(RIOT_VERSION)
1500 if (*num_sockets < max_sockets)
1501 sockets[(*num_sockets)++] = &s->sock;
1502 }
1503#endif /* ! COAP_EPOLL_SUPPORT && ! WITH_LWIP && ! RIOT_VERSION */
1504#if COAP_Q_BLOCK_SUPPORT
1505 /*
1506 * Check if any server large transmits have hit MAX_PAYLOAD and need
1507 * restarting
1508 */
1509 if (s->lg_xmit) {
1510 if (coap_block_check_q_block2_xmit(s, now, &s_timeout)) {
1511 if (s_timeout < timeout)
1512 timeout = s_timeout;
1513 }
1514 }
1515#endif /* COAP_Q_BLOCK_SUPPORT */
1516release_1:
1518 }
1519 if (s->type == COAP_SESSION_TYPE_SERVER &&
1521 (s->ref_subscriptions || s->ref_proxy_subs) && !s->con_active &&
1522 ctx->ping_timeout > 0) {
1523 /* Only do this if this session is observing */
1524 if (s->last_rx_tx + ctx->ping_timeout * COAP_TICKS_PER_SECOND <= now) {
1525 /* Time to send a ping */
1526 coap_mid_t mid;
1527
1528 if ((mid = coap_session_send_ping_lkd(s)) == COAP_INVALID_MID) {
1529 /* Some issue - not safe to continue processing */
1530 s->last_rx_tx = now;
1531 continue;
1532 }
1533 s->last_ping_mid = mid;
1534 if (s->last_ping > 0 && s->last_pong < s->last_ping) {
1536 /* check the next session */
1537 continue;
1538 }
1539 s->last_rx_tx = now;
1540 s->last_ping = now;
1541 } else {
1542 /* Always positive due to if() above */
1543 s_timeout = (s->last_rx_tx + ctx->ping_timeout * COAP_TICKS_PER_SECOND) - now;
1544 if (s_timeout < timeout)
1545 timeout = s_timeout;
1546 }
1547 }
1548 }
1549 }
1550#endif /* COAP_SERVER_SUPPORT */
1551#if COAP_CLIENT_SUPPORT
1552 SESSIONS_ITER_SAFE(ctx->sessions, s, stmp) {
1553 if (s->type == COAP_SESSION_TYPE_CLIENT &&
1555 ctx->ping_timeout > 0) {
1556 if (s->last_rx_tx + ctx->ping_timeout * COAP_TICKS_PER_SECOND <= now) {
1557 /* Time to send a ping */
1558 coap_mid_t mid;
1559
1560 if ((mid = coap_session_send_ping_lkd(s)) == COAP_INVALID_MID) {
1561 /* Some issue - not safe to continue processing */
1562 s->last_rx_tx = now;
1564 continue;
1565 }
1566 s->last_ping_mid = mid;
1567 if (s->last_ping > 0 && s->last_pong < s->last_ping) {
1569 }
1570 s->last_rx_tx = now;
1571 s->last_ping = now;
1572 } else {
1573 /* Always positive due to if() above */
1574 s_timeout = (s->last_rx_tx + ctx->ping_timeout * COAP_TICKS_PER_SECOND) - now;
1575 if (s_timeout < timeout)
1576 timeout = s_timeout;
1577 }
1578 }
1579 if (s->type == COAP_SESSION_TYPE_CLIENT &&
1580 s->session_failed && ctx->reconnect_time) {
1581 if (s->last_rx_tx + ctx->reconnect_time * COAP_TICKS_PER_SECOND <= now) {
1582 if (!coap_session_reconnect(s)) {
1583 /* server is not back up yet - delay retry a while */
1584 s->last_rx_tx = now;
1585 s_timeout = ctx->reconnect_time * COAP_TICKS_PER_SECOND;
1586 if (timeout == 0 || s_timeout < timeout)
1587 timeout = s_timeout;
1588 }
1589 } else {
1590 /* Always positive due to if() above */
1591 s_timeout = (s->last_rx_tx + ctx->reconnect_time * COAP_TICKS_PER_SECOND) - now;
1592 if (s_timeout < timeout)
1593 timeout = s_timeout;
1594 }
1595 }
1596
1597#if !COAP_DISABLE_TCP
1599 s->state == COAP_SESSION_STATE_CSM && ctx->csm_timeout_ms > 0) {
1600 if (s->csm_tx == 0) {
1601 s->csm_tx = now;
1602 s_timeout = (ctx->csm_timeout_ms * COAP_TICKS_PER_SECOND) / 1000;
1603 } else if (s->csm_tx + (ctx->csm_timeout_ms * COAP_TICKS_PER_SECOND) / 1000 <= now) {
1604 /* timed out - cannot handle 0, so has to be just +ve */
1605 s_timeout = 1;
1606 } else {
1607 s_timeout = (s->csm_tx + (ctx->csm_timeout_ms * COAP_TICKS_PER_SECOND) / 1000) - now;
1608 }
1609 if (s_timeout < timeout)
1610 timeout = s_timeout;
1611 }
1612#endif /* !COAP_DISABLE_TCP */
1613
1614 /* Make sure the session object is not deleted in any callbacks */
1616 /* Check any DTLS timeouts and expire if appropriate */
1618 s->proto == COAP_PROTO_DTLS && s->tls) {
1619 coap_tick_t tls_timeout = coap_dtls_get_timeout(s, now);
1620 while (tls_timeout > 0 && tls_timeout <= now) {
1621 coap_log_debug("** %s: DTLS retransmit timeout\n", coap_session_str(s));
1623 goto release_2;
1624
1625 if (s->tls)
1626 tls_timeout = coap_dtls_get_timeout(s, now);
1627 else {
1628 tls_timeout = 0;
1629 timeout = 1;
1630 }
1631 }
1632 if (tls_timeout > 0 && tls_timeout - now < timeout)
1633 timeout = tls_timeout - now;
1634 }
1635
1636 /* Check if any client large receives are missing blocks */
1637 if (s->lg_crcv) {
1638 if (coap_block_check_lg_crcv_timeouts(s, now, &s_timeout)) {
1639 if (s_timeout < timeout)
1640 timeout = s_timeout;
1641 }
1642 }
1643 /* Check if any client large sending have timed out */
1644 if (s->lg_xmit) {
1645 if (coap_block_check_lg_xmit_timeouts(s, now, &s_timeout)) {
1646 if (s_timeout < timeout)
1647 timeout = s_timeout;
1648 }
1649 }
1650#if COAP_Q_BLOCK_SUPPORT
1651 /*
1652 * Check if any client large transmits have hit MAX_PAYLOAD and need
1653 * restarting
1654 */
1655 if (s->lg_xmit) {
1656 if (coap_block_check_q_block1_xmit(s, now, &s_timeout)) {
1657 if (s_timeout < timeout)
1658 timeout = s_timeout;
1659 }
1660 }
1661#endif /* COAP_Q_BLOCK_SUPPORT */
1662
1663#if !defined(COAP_EPOLL_SUPPORT) && !defined(WITH_LWIP) && !defined(RIOT_VERSION)
1664 assert(s->ref > 1);
1665 if (s->sock.flags & (COAP_SOCKET_WANT_READ |
1668 if (*num_sockets < max_sockets)
1669 sockets[(*num_sockets)++] = &s->sock;
1670 }
1671#endif /* ! COAP_EPOLL_SUPPORT && ! WITH_LWIP && ! RIOT_VERSION */
1672release_2:
1674 }
1675#endif /* COAP_CLIENT_SUPPORT */
1676
1677 return (unsigned int)((timeout * 1000 + COAP_TICKS_PER_SECOND - 1) / COAP_TICKS_PER_SECOND);
1678}
1679
1680/*
1681 * return 0 Insufficient space to hold fds, or fds not supported
1682 * 1 All fds found
1683 */
1684COAP_API unsigned int
1686 coap_fd_t read_fds[],
1687 unsigned int *have_read_fds,
1688 unsigned int max_read_fds,
1689 coap_fd_t write_fds[],
1690 unsigned int *have_write_fds,
1691 unsigned int max_write_fds,
1692 unsigned int *rem_timeout_ms) {
1693 unsigned int ret;
1694
1695 coap_lock_lock(return 0);
1696 ret = coap_io_get_fds_lkd(ctx, read_fds, have_read_fds, max_read_fds, write_fds,
1697 have_write_fds, max_write_fds, rem_timeout_ms);
1699 return ret;
1700}
1701
1702#if !defined(WITH_LWIP) && !defined(WITH_CONTIKI)
1703static int
1704coap_add_fd(coap_fd_t fd, coap_fd_t this_fds[], unsigned int *have_this_fds,
1705 unsigned int max_this_fds) {
1706 if (*have_this_fds < max_this_fds) {
1707 this_fds[(*have_this_fds)++] = fd;
1708 return 1;
1709 }
1710 coap_log_warn("coap_io_get_fds: Insufficient space for new fd (%u >= %u)\n", *have_this_fds,
1711 max_this_fds);
1712 return 0;
1713}
1714
1715/*
1716 * return 0 Insufficient space to hold fds, or fds not supported
1717 * 1 All fds found
1718 */
1719unsigned int
1721 coap_fd_t read_fds[],
1722 unsigned int *have_read_fds,
1723 unsigned int max_read_fds,
1724 coap_fd_t write_fds[],
1725 unsigned int *have_write_fds,
1726 unsigned int max_write_fds,
1727 unsigned int *rem_timeout_ms) {
1728 *have_read_fds = 0;
1729 *have_write_fds = 0;
1730
1731#ifdef COAP_EPOLL_SUPPORT
1732 (void)write_fds;
1733 (void)max_write_fds;;
1734
1735 if (!coap_add_fd(ctx->epfd, read_fds, have_read_fds, max_read_fds))
1736 return 0;
1737 /* epoll is making use of timerfd, so no need to return any timeout */
1738 *rem_timeout_ms = 0;
1739 return 1;
1740#else /* ! COAP_EPOLL_SUPPORT */
1741 coap_session_t *s, *rtmp;
1742 coap_tick_t now;
1743 unsigned int timeout_ms;
1744#if COAP_SERVER_SUPPORT
1745 coap_endpoint_t *ep;
1746
1747 LL_FOREACH(ctx->endpoint, ep) {
1749 if (!coap_add_fd(ep->sock.fd, read_fds, have_read_fds, max_read_fds))
1750 return 0;
1751 }
1753 if (!coap_add_fd(ep->sock.fd, write_fds, have_write_fds, max_write_fds))
1754 return 0;
1755 }
1756 SESSIONS_ITER_SAFE(ep->sessions, s, rtmp) {
1758 if (!coap_add_fd(s->sock.fd, read_fds, have_read_fds, max_read_fds))
1759 return 0;
1760 }
1762 if (!coap_add_fd(s->sock.fd, write_fds, have_write_fds, max_write_fds))
1763 return 0;
1764 }
1765 }
1766 }
1767#endif /* COAP_SERVER_SUPPORT */
1768
1769#if COAP_CLIENT_SUPPORT
1770 SESSIONS_ITER_SAFE(ctx->sessions, s, rtmp) {
1772 if (!coap_add_fd(s->sock.fd, read_fds, have_read_fds, max_read_fds))
1773 return 0;
1774 }
1776 if (!coap_add_fd(s->sock.fd, write_fds, have_write_fds, max_write_fds))
1777 return 0;
1778 }
1779 }
1780#endif /* COAP_CLIENT_SUPPORT */
1781
1782 coap_ticks(&now);
1783 timeout_ms = (unsigned int)(ctx->next_timeout ? ctx->next_timeout > now ?
1784 ctx->next_timeout - now : 0 : 0) *
1785 1000 / COAP_TICKS_PER_SECOND;
1786 *rem_timeout_ms = timeout_ms;
1787 return 1;
1788#endif /* ! COAP_EPOLL_SUPPORT */
1789}
1790
1791#else /* WITH_LWIP || WITH_CONTIKI */
1792
1793/*
1794 * return 0 Insufficient space to hold fds, or fds not supported
1795 * 1 All fds found
1796 */
1797unsigned int
1799 coap_fd_t read_fds[],
1800 unsigned int *have_read_fds,
1801 unsigned int max_read_fds,
1802 coap_fd_t write_fds[],
1803 unsigned int *have_write_fds,
1804 unsigned int max_write_fds,
1805 unsigned int *rem_timeout_ms) {
1806 (void)ctx;
1807 (void)read_fds;
1808 (void)max_read_fds;
1809 (void)write_fds;
1810 (void)max_write_fds;
1811
1812 *have_read_fds = 0;
1813 *have_write_fds = 0;
1814 *rem_timeout_ms = 0;
1815
1816 coap_log_warn("coap_io_get_fds: Not supported\n");
1817 return 0;
1818}
1819#endif /* WITH_LWIP || WITH_CONTIKI */
1820
1821#if !defined(WITH_LWIP) && !defined(CONTIKI) && !defined(RIOT_VERSION)
1822COAP_API int
1823coap_io_process(coap_context_t *ctx, uint32_t timeout_ms) {
1824 int ret;
1825
1826 coap_lock_lock(return 0);
1827 ret = coap_io_process_lkd(ctx, timeout_ms);
1829 return ret;
1830}
1831
1832int
1833coap_io_process_lkd(coap_context_t *ctx, uint32_t timeout_ms) {
1834 return coap_io_process_with_fds_lkd(ctx, timeout_ms, 0, NULL, NULL, NULL);
1835}
1836
1837COAP_API int
1839 int enfds, fd_set *ereadfds, fd_set *ewritefds,
1840 fd_set *eexceptfds) {
1841 int ret;
1842
1843 coap_lock_lock(return 0);
1844 ret = coap_io_process_with_fds_lkd(ctx, timeout_ms, enfds, ereadfds, ewritefds,
1845 eexceptfds);
1847 return ret;
1848}
1849
1850#if !defined(COAP_EPOLL_SUPPORT) && COAP_THREAD_SAFE
1851static unsigned int
1852coap_io_prepare_fds(coap_context_t *ctx,
1853 int enfds, fd_set *ereadfds, fd_set *ewritefds,
1854 fd_set *eexceptfds) {
1855 coap_session_t *s, *stmp;
1856 unsigned int max_sockets = sizeof(ctx->sockets) / sizeof(ctx->sockets[0]);
1857 coap_fd_t nfds = 0;
1858 unsigned int i;
1859
1860 ctx->num_sockets = 0;
1861#if COAP_SERVER_SUPPORT
1862 coap_endpoint_t *ep;
1863
1864 LL_FOREACH(ctx->endpoint, ep) {
1866 if (ctx->num_sockets < max_sockets)
1867 ctx->sockets[ctx->num_sockets++] = &ep->sock;
1868 }
1869 SESSIONS_ITER(ep->sessions, s, stmp) {
1871 if (ctx->num_sockets < max_sockets)
1872 ctx->sockets[ctx->num_sockets++] = &s->sock;
1873 }
1874 }
1875 }
1876#endif /* COAP_SERVER_SUPPORT */
1877#if COAP_CLIENT_SUPPORT
1878 SESSIONS_ITER(ctx->sessions, s, stmp) {
1879 if (s->sock.flags & (COAP_SOCKET_WANT_READ |
1882 if (ctx->num_sockets < max_sockets)
1883 ctx->sockets[ctx->num_sockets++] = &s->sock;
1884 }
1885 }
1886#endif /* COAP_CLIENT_SUPPORT */
1887 if (ereadfds) {
1888 ctx->readfds = *ereadfds;
1889 nfds = enfds;
1890 } else {
1891 FD_ZERO(&ctx->readfds);
1892 }
1893 if (ewritefds) {
1894 ctx->writefds = *ewritefds;
1895 nfds = enfds;
1896 } else {
1897 FD_ZERO(&ctx->writefds);
1898 }
1899 if (eexceptfds) {
1900 ctx->exceptfds = *eexceptfds;
1901 nfds = enfds;
1902 } else {
1903 FD_ZERO(&ctx->exceptfds);
1904 }
1905 for (i = 0; i < ctx->num_sockets; i++) {
1906 if (ctx->sockets[i]->fd + 1 > nfds)
1907 nfds = ctx->sockets[i]->fd + 1;
1908 if (ctx->sockets[i]->flags & COAP_SOCKET_WANT_READ)
1909 FD_SET(ctx->sockets[i]->fd, &ctx->readfds);
1910 if (ctx->sockets[i]->flags & COAP_SOCKET_WANT_WRITE)
1911 FD_SET(ctx->sockets[i]->fd, &ctx->writefds);
1912#if !COAP_DISABLE_TCP
1913 if (ctx->sockets[i]->flags & COAP_SOCKET_WANT_ACCEPT)
1914 FD_SET(ctx->sockets[i]->fd, &ctx->readfds);
1915 if (ctx->sockets[i]->flags & COAP_SOCKET_WANT_CONNECT) {
1916 FD_SET(ctx->sockets[i]->fd, &ctx->writefds);
1917 FD_SET(ctx->sockets[i]->fd, &ctx->exceptfds);
1918 }
1919#endif /* !COAP_DISABLE_TCP */
1920 }
1921 return nfds;
1922}
1923#endif /* ! COAP_EPOLL_SUPPORT && COAP_THREAD_SAFE */
1924
1925int
1927 int enfds, fd_set *ereadfds, fd_set *ewritefds,
1928 fd_set *eexceptfds) {
1929 coap_fd_t nfds = 0;
1930 coap_tick_t before, now;
1931 unsigned int timeout;
1932#ifndef COAP_EPOLL_SUPPORT
1933 struct timeval tv;
1934 int result;
1935 unsigned int i;
1936#endif /* ! COAP_EPOLL_SUPPORT */
1937
1939 coap_ticks(&before);
1940
1941#ifndef COAP_EPOLL_SUPPORT
1942
1943 timeout = coap_io_prepare_io_lkd(ctx, ctx->sockets,
1944 (sizeof(ctx->sockets) / sizeof(ctx->sockets[0])),
1945 &ctx->num_sockets, before);
1946 ctx->next_timeout = timeout ? timeout + before : 0;
1947
1948 if (ereadfds) {
1949 ctx->readfds = *ereadfds;
1950 nfds = enfds;
1951 } else {
1952 FD_ZERO(&ctx->readfds);
1953 }
1954 if (ewritefds) {
1955 ctx->writefds = *ewritefds;
1956 nfds = enfds;
1957 } else {
1958 FD_ZERO(&ctx->writefds);
1959 }
1960 if (eexceptfds) {
1961 ctx->exceptfds = *eexceptfds;
1962 nfds = enfds;
1963 } else {
1964 FD_ZERO(&ctx->exceptfds);
1965 }
1966 for (i = 0; i < ctx->num_sockets; i++) {
1967 if (ctx->sockets[i]->fd + 1 > nfds)
1968 nfds = ctx->sockets[i]->fd + 1;
1969 if (ctx->sockets[i]->flags & COAP_SOCKET_WANT_READ)
1970 FD_SET(ctx->sockets[i]->fd, &ctx->readfds);
1971 if (ctx->sockets[i]->flags & COAP_SOCKET_WANT_WRITE)
1972 FD_SET(ctx->sockets[i]->fd, &ctx->writefds);
1973#if !COAP_DISABLE_TCP
1974 if (ctx->sockets[i]->flags & COAP_SOCKET_WANT_ACCEPT)
1975 FD_SET(ctx->sockets[i]->fd, &ctx->readfds);
1976 if (ctx->sockets[i]->flags & COAP_SOCKET_WANT_CONNECT) {
1977 FD_SET(ctx->sockets[i]->fd, &ctx->writefds);
1978 FD_SET(ctx->sockets[i]->fd, &ctx->exceptfds);
1979 }
1980#endif /* !COAP_DISABLE_TCP */
1981 }
1982
1983 if (timeout_ms == COAP_IO_NO_WAIT) {
1984 tv.tv_usec = 0;
1985 tv.tv_sec = 0;
1986 timeout = 1;
1987 } else if (timeout == 0 && timeout_ms == COAP_IO_WAIT) {
1988 ;
1989 } else {
1990 if (timeout == 0 || (timeout_ms != COAP_IO_WAIT && timeout_ms < timeout))
1991 timeout = timeout_ms;
1992 tv.tv_usec = (timeout % 1000) * 1000;
1993 tv.tv_sec = (long)(timeout / 1000);
1994 }
1995
1996 /* on Windows select will return an error if called without FDs */
1997 if (nfds > 0) {
1998 /* Unlock so that other threads can lock/update ctx */
2000
2001 result = select((int)nfds, &ctx->readfds, &ctx->writefds, &ctx->exceptfds,
2002 timeout > 0 ? &tv : NULL);
2003
2004 coap_lock_lock(return -1);
2005 } else {
2006 goto all_over;
2007 }
2008
2009 if (result < 0) { /* error */
2010#ifdef _WIN32
2011 coap_win_error_to_errno();
2012#endif
2013 if (errno != EINTR) {
2014#if COAP_THREAD_SAFE
2015 if (errno == EBADF) {
2016 coap_log_debug("select: %s\n", coap_socket_strerror());
2017 goto all_over;
2018 }
2019#endif /* COAP_THREAD_SAFE */
2020 coap_log_err("select: %s\n", coap_socket_strerror());
2021 return -1;
2022 }
2023 goto all_over;
2024 }
2025#if COAP_THREAD_SAFE
2026 /* Need to refresh what is available to read / write etc. */
2027 nfds = coap_io_prepare_fds(ctx, enfds, ereadfds, ewritefds, eexceptfds);
2028 tv.tv_usec = 0;
2029 tv.tv_sec = 0;
2030 result = select((int)nfds, &ctx->readfds, &ctx->writefds, &ctx->exceptfds, &tv);
2031 if (result < 0) { /* error */
2032#ifdef _WIN32
2033 coap_win_error_to_errno();
2034#endif
2035 if (errno != EINTR) {
2036 if (errno == EBADF) {
2037 coap_log_debug("select: %s\n", coap_socket_strerror());
2038 goto all_over;
2039 }
2040 coap_log_err("select: %s\n", coap_socket_strerror());
2041 return -1;
2042 }
2043 goto all_over;
2044 }
2045#endif /* COAP_THREAD_SAFE */
2046 if (ereadfds) {
2047 *ereadfds = ctx->readfds;
2048 }
2049 if (ewritefds) {
2050 *ewritefds = ctx->writefds;
2051 }
2052 if (eexceptfds) {
2053 *eexceptfds = ctx->exceptfds;
2054 }
2055
2056 if (result > 0) {
2057 for (i = 0; i < ctx->num_sockets; i++) {
2058 if ((ctx->sockets[i]->flags & COAP_SOCKET_WANT_READ) &&
2059 FD_ISSET(ctx->sockets[i]->fd, &ctx->readfds))
2061#if !COAP_DISABLE_TCP
2062 if ((ctx->sockets[i]->flags & COAP_SOCKET_WANT_ACCEPT) &&
2063 FD_ISSET(ctx->sockets[i]->fd, &ctx->readfds))
2065 if ((ctx->sockets[i]->flags & COAP_SOCKET_WANT_WRITE) &&
2066 FD_ISSET(ctx->sockets[i]->fd, &ctx->writefds))
2068 if ((ctx->sockets[i]->flags & COAP_SOCKET_WANT_CONNECT) &&
2069 (FD_ISSET(ctx->sockets[i]->fd, &ctx->writefds) ||
2070 FD_ISSET(ctx->sockets[i]->fd, &ctx->exceptfds)))
2072#endif /* !COAP_DISABLE_TCP */
2073 }
2074 }
2075
2076 coap_ticks(&now);
2077 coap_io_do_io_lkd(ctx, now);
2078 coap_ticks(&now);
2079 timeout = coap_io_prepare_io_lkd(ctx, ctx->sockets,
2080 (sizeof(ctx->sockets) / sizeof(ctx->sockets[0])),
2081 &ctx->num_sockets, now);
2082 ctx->next_timeout = timeout ? timeout + now : 0;
2083
2084#else /* COAP_EPOLL_SUPPORT */
2085 (void)ereadfds;
2086 (void)ewritefds;
2087 (void)eexceptfds;
2088 (void)enfds;
2089
2090 timeout = coap_io_prepare_epoll_lkd(ctx, before);
2091
2092 do {
2093 struct epoll_event events[COAP_MAX_EPOLL_EVENTS];
2094 int etimeout;
2095
2096 /* Potentially adjust based on what the caller wants */
2097 if (timeout_ms == COAP_IO_NO_WAIT) {
2098 /* Need to return immediately from epoll_wait() */
2099 etimeout = 0;
2100 } else if (timeout == 0 && timeout_ms == COAP_IO_WAIT) {
2101 /*
2102 * Nothing found in coap_io_prepare_epoll_lkd() and COAP_IO_WAIT set,
2103 * so wait forever in epoll_wait().
2104 */
2105 etimeout = -1;
2106 } else {
2107 etimeout = timeout;
2108 if (timeout == 0 || (timeout_ms != COAP_IO_WAIT && timeout_ms < timeout))
2109 etimeout = timeout_ms;
2110 if (etimeout < 0) {
2111 /*
2112 * If timeout > INT_MAX, epoll_wait() cannot wait longer than this as
2113 * it has int timeout parameter
2114 */
2115 etimeout = INT_MAX;
2116 }
2117 }
2118
2119 /* Unlock so that other threads can lock/update ctx */
2121
2122 nfds = epoll_wait(ctx->epfd, events, COAP_MAX_EPOLL_EVENTS, etimeout);
2123 if (nfds < 0) {
2124 if (errno != EINTR) {
2125 coap_log_err("epoll_wait: unexpected error: %s (%d)\n",
2126 coap_socket_strerror(), nfds);
2127 }
2128 coap_lock_lock(return -1);
2129 break;
2130 }
2131
2132 coap_lock_lock(return -1);
2133#if COAP_THREAD_SAFE
2134 /* Need to refresh what is available to read / write etc. */
2135 nfds = epoll_wait(ctx->epfd, events, COAP_MAX_EPOLL_EVENTS, 0);
2136 if (nfds < 0) {
2137 if (errno != EINTR) {
2138 coap_log_err("epoll_wait: unexpected error: %s (%d)\n",
2139 coap_socket_strerror(), nfds);
2140 }
2141 break;
2142 }
2143#endif /* COAP_THREAD_SAFE */
2144
2145 coap_io_do_epoll_lkd(ctx, events, nfds);
2146
2147 /*
2148 * reset to COAP_IO_NO_WAIT (which causes etimeout to become 0)
2149 * incase we have to do another iteration
2150 * (COAP_MAX_EPOLL_EVENTS insufficient)
2151 */
2152 timeout_ms = COAP_IO_NO_WAIT;
2153
2154 /* Keep retrying until less than COAP_MAX_EPOLL_EVENTS are returned */
2155 } while (nfds == COAP_MAX_EPOLL_EVENTS);
2156
2157#endif /* COAP_EPOLL_SUPPORT */
2158#if COAP_SERVER_SUPPORT
2160#endif /* COAP_SERVER_SUPPORT */
2161#if COAP_ASYNC_SUPPORT
2162 /* Check to see if we need to send off any Async requests as delay might
2163 have been updated */
2164 coap_ticks(&now);
2165 coap_check_async(ctx, now, NULL);
2166#endif /* COAP_ASYNC_SUPPORT */
2167
2168#ifndef COAP_EPOLL_SUPPORT
2169all_over:
2170#endif /* COAP_EPOLL_SUPPORT */
2171 coap_ticks(&now);
2172 return (int)(((now - before) * 1000) / COAP_TICKS_PER_SECOND);
2173}
2174
2175volatile int coap_thread_quit = 0;
2176
2177void
2182
2183COAP_API int
2185 coap_io_process_thread_t main_loop_code,
2186 void *main_loop_code_arg, uint32_t timeout_ms,
2187 uint32_t thread_count) {
2188 int ret;
2189
2190 if (!context)
2191 return 0;
2192 coap_lock_lock(return 0);
2193 ret = coap_io_process_loop_lkd(context, main_loop_code,
2194 main_loop_code_arg, timeout_ms,
2195 thread_count);
2197 return ret;
2198}
2199
2200int
2202 coap_io_process_thread_t main_loop_code,
2203 void *main_loop_code_arg, uint32_t timeout_ms,
2204 uint32_t thread_count) {
2205 int ret = 0;;
2206
2207#if COAP_THREAD_SAFE
2208 if (thread_count > 1) {
2209 if (!coap_io_process_configure_threads(context, thread_count - 1))
2210 return 0;
2211 }
2212#else /* COAP_THREAD_SAFE */
2213 thread_count = 1;
2214#endif /* COAP_THREAD_SAFE */
2215 while (!coap_thread_quit) {
2216 if (main_loop_code) {
2217 coap_tick_t begin, end;
2218 uint32_t used_ms;
2219
2220 coap_ticks(&begin);
2221 /*
2222 * main_loop_codecode should not be blocking for any time, and not calling
2223 * coap_io_process().
2224 */
2225 coap_lock_callback_release(main_loop_code(main_loop_code_arg),
2226 /* On re-lock failure */
2227 ret = 0; break);
2228 /*
2229 * Need to delay for the remainder of timeout_ms. In case main_loop_code()
2230 * is time sensitive (e.g Observe subscription to /time), delay to the
2231 * start of the a second boundary
2232 */
2233 coap_ticks(&end);
2234 used_ms = (uint32_t)(end - begin) * 1000 / COAP_TICKS_PER_SECOND;
2235 if (timeout_ms == COAP_IO_NO_WAIT || timeout_ms == COAP_IO_WAIT) {
2236 ret = coap_io_process_lkd(context, timeout_ms);
2237 } else if (timeout_ms > used_ms) {
2238 /* Wait for remaining time rounded up to next second start */
2239 coap_tick_t next_time = end + (timeout_ms - used_ms) * COAP_TICKS_PER_SECOND / 1000;
2240 unsigned int next_sec_us;
2241 unsigned int next_sec_ms;
2242
2243 next_sec_us = (timeout_ms - used_ms) * 1000000 / COAP_TICKS_PER_SECOND + 1000000 -
2244 (coap_ticks_to_rt_us(next_time) % 1000000);
2245 next_sec_ms = (next_sec_us + 999) / 1000;
2246 if (next_sec_ms > timeout_ms && next_sec_ms > 1000)
2247 next_sec_ms -= 1000;
2248 ret = coap_io_process_lkd(context, next_sec_ms ? next_sec_ms : 1);
2249 } else {
2250 /* timeout_ms has expired */
2251 ret = coap_io_process_lkd(context, COAP_IO_NO_WAIT);
2252 }
2253
2254 if (thread_count == 1) {
2255 /*
2256 * Need to delay if only one thread until the remainder of
2257 * timeout_ms is used up. Otherwise, another thread will be
2258 * waiting on coap_io_process() to do any input / timeout work.
2259 */
2260 coap_ticks(&end);
2261 used_ms = (uint32_t)(end - begin) * 1000 / COAP_TICKS_PER_SECOND;
2262 if (timeout_ms > 0 && timeout_ms < used_ms) {
2263 ret = coap_io_process_lkd(context, used_ms - timeout_ms);
2264 } else {
2265 ret = coap_io_process_lkd(context, COAP_IO_NO_WAIT);
2266 }
2267 }
2268 } else {
2269 ret = coap_io_process_lkd(context, timeout_ms);
2270 }
2271 /* coap_io_process_lkd() can return 0 */
2272 if (ret >= 0)
2273 ret = 1;
2274
2275 if (ret < 0) {
2276 ret = 0;
2277 break;
2278 }
2279 }
2280#if COAP_THREAD_SAFE
2282#endif /* COAP_THREAD_SAFE */
2283 coap_thread_quit = 0;
2284 return ret;
2285}
2286
2287#endif /* ! WITH_LWIP && ! WITH_CONTIKI && ! RIOT_VERSION*/
2288
2289COAP_API int
2291 int ret;
2292
2293 coap_lock_lock(return 0);
2294 ret = coap_io_pending_lkd(context);
2296 return ret;
2297}
2298
2299/*
2300 * return 1 I/O pending
2301 * 0 No I/O pending
2302 */
2303int
2305 coap_session_t *s, *rtmp;
2306#if COAP_SERVER_SUPPORT
2307 coap_endpoint_t *ep;
2308#endif /* COAP_SERVER_SUPPORT */
2309
2310 if (!context)
2311 return 0;
2313 if (coap_io_process_lkd(context, COAP_IO_NO_WAIT) < 0)
2314 return 0;
2315
2316 if (context->sendqueue)
2317 return 1;
2318#if COAP_SERVER_SUPPORT
2319 LL_FOREACH(context->endpoint, ep) {
2320 SESSIONS_ITER(ep->sessions, s, rtmp) {
2321 if (s->delayqueue)
2322 return 1;
2323 if (s->lg_xmit)
2324 return 1;
2325 if (s->lg_srcv)
2326 return 1;
2327 }
2328 }
2329#endif /* COAP_SERVER_SUPPORT */
2330#if COAP_CLIENT_SUPPORT
2331 SESSIONS_ITER(context->sessions, s, rtmp) {
2332 if (s->delayqueue)
2333 return 1;
2334 if (s->lg_xmit)
2335 return 1;
2336 if (s->lg_crcv)
2337 return 1;
2338 }
2339#endif /* COAP_CLIENT_SUPPORT */
2340 return 0;
2341}
2342
2343const char *
2345 return strerror(error);
2346}
2347#ifdef _WIN32
2348const char *
2350 coap_win_error_to_errno();
2351 return coap_socket_format_errno(errno);
2352}
2353#else /* _WIN32 */
2354const char *
2356 return coap_socket_format_errno(errno);
2357}
2358#endif /* _WIN32 */
2359
2362#if !defined(WITH_LWIP) && !defined(WITH_CONTIKI)
2363 return sock->fd;
2364#else
2365 (void)(sock);
2366 return COAP_INVALID_SOCKET;
2367#endif
2368}
2369
2372 return sock->flags;
2373}
2374
2375COAP_API void
2377 sock->flags = flags;
2378}
2379
2380#undef SIN6
void coap_address_set_port(coap_address_t *addr, uint16_t port)
Set the port field of addr to port (in host byte order).
int coap_is_bcast(const coap_address_t *a)
Checks if given address a denotes a broadcast address.
void coap_address_init(coap_address_t *addr)
Resets the given coap_address_t object addr to its default values.
int coap_is_mcast(const coap_address_t *a)
Checks if given address a denotes a multicast address.
uint16_t coap_address_get_port(const coap_address_t *addr)
Returns the port from addr in host byte order.
void coap_address_copy(coap_address_t *dst, const coap_address_t *src)
COAP_STATIC_INLINE int coap_address_isany(const coap_address_t *a)
Checks if given address object a denotes the wildcard address.
int coap_debug_send_packet(void)
Check to see whether a packet should be sent or not.
#define COAP_IPV4_SUPPORT
const char * coap_socket_format_errno(int error)
Definition coap_io.c:2344
ssize_t coap_socket_read(coap_socket_t *sock, uint8_t *data, size_t data_len)
Function interface for data stream receiving off a socket.
Definition coap_io.c:704
static int coap_add_fd(coap_fd_t fd, coap_fd_t this_fds[], unsigned int *have_this_fds, unsigned int max_this_fds)
Definition coap_io.c:1704
void coap_socket_close(coap_socket_t *sock)
Function interface to close off a socket.
Definition coap_io.c:390
const char * coap_socket_strerror(void)
Definition coap_io.c:2355
ssize_t coap_socket_recv(coap_socket_t *sock, coap_packet_t *packet)
Function interface for reading data.
Definition coap_io.c:1061
ssize_t coap_socket_send(coap_socket_t *sock, coap_session_t *session, const uint8_t *data, size_t datalen)
Function interface for data transmission.
Definition coap_io.c:860
void coap_packet_get_memmapped(coap_packet_t *packet, unsigned char **address, size_t *length)
Given a packet, set msg and msg_len to an address and length of the packet's data in memory.
Definition coap_io.c:1048
ssize_t coap_socket_write(coap_socket_t *sock, const uint8_t *data, size_t data_len)
Function interface for data stream sending off a socket.
Definition coap_io.c:645
volatile int coap_thread_quit
Definition coap_io.c:2175
void coap_update_io_timer(coap_context_t *context, coap_tick_t delay)
Update when to continue with I/O processing, unless packets come in in the meantime.
Definition coap_io.c:527
#define MSG_NOSIGNAL
#define iov_len_t
Definition coap_io.c:807
#define COAP_SOL_IP
Definition coap_io.c:769
#define coap_closesocket
Definition coap_io.h:48
#define COAP_MAX_EPOLL_EVENTS
Definition coap_io.h:38
uint16_t coap_socket_flags_t
Definition coap_io.h:53
#define COAP_RXBUFFER_SIZE
Definition coap_io.h:29
#define COAP_SOCKET_ERROR
Definition coap_io.h:49
int coap_fd_t
Definition coap_io.h:47
#define COAP_INVALID_SOCKET
Definition coap_io.h:50
#define COAP_SOCKET_MULTICAST
socket is used for multicast communication
void coap_epoll_ctl_add(coap_socket_t *sock, uint32_t events, const char *func)
Epoll specific function to add the state of events that epoll is to track for the appropriate file de...
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)
#define COAP_SOCKET_WANT_ACCEPT
non blocking server socket is waiting for accept
#define COAP_SOCKET_NOT_EMPTY
the socket is not empty
#define COAP_SOCKET_CAN_WRITE
non blocking socket can now write without blocking
#define COAP_SOCKET_BOUND
the socket is bound
#define COAP_SOCKET_WANT_READ
non blocking socket is waiting for reading
#define COAP_SOCKET_CAN_ACCEPT
non blocking server socket can now accept without blocking
int coap_socket_bind_udp(coap_socket_t *sock, const coap_address_t *listen_addr, coap_address_t *bound_addr)
#define COAP_SOCKET_WANT_WRITE
non blocking socket is waiting for writing
#define COAP_SOCKET_CAN_CONNECT
non blocking client socket can now connect without blocking
coap_endpoint_t * coap_malloc_endpoint(void)
void coap_epoll_ctl_mod(coap_socket_t *sock, uint32_t events, const char *func)
Epoll specific function to modify the state of events that epoll is tracking on the appropriate file ...
#define COAP_SOCKET_WANT_CONNECT
non blocking client socket is waiting for connect
void coap_mfree_endpoint(coap_endpoint_t *ep)
#define COAP_SOCKET_CAN_READ
non blocking socket can now read without blocking
#define COAP_SOCKET_CONNECTED
the socket is connected
#define COAP_SOCKET_EMPTY
coap_socket_flags_t values
Library specific build wrapper for coap_internal.h.
#define COAP_API
@ COAP_ENDPOINT
Definition coap_mem.h:45
void * coap_malloc_type(coap_memory_tag_t type, size_t size)
Allocates a chunk of size bytes and returns a pointer to the newly allocated memory.
void coap_free_type(coap_memory_tag_t type, void *p)
Releases the memory that was allocated by coap_malloc_type().
coap_tick_t coap_dtls_get_timeout(coap_session_t *session COAP_UNUSED, coap_tick_t now COAP_UNUSED)
Definition coap_notls.c:229
coap_tick_t coap_dtls_get_context_timeout(void *dtls_context COAP_UNUSED)
Definition coap_notls.c:224
int coap_dtls_handle_timeout(coap_session_t *session COAP_UNUSED)
Definition coap_notls.c:238
#define SESSIONS_ITER_SAFE(e, el, rtmp)
#define SESSIONS_ITER(e, el, rtmp)
#define COAP_DEFAULT_SESSION_TIMEOUT
void coap_io_do_epoll_lkd(coap_context_t *ctx, struct epoll_event *events, size_t nevents)
Process all the epoll events.
Definition coap_net.c:2777
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)
Do the coap_io_process() across thread_count threads.
Definition coap_io.c:2201
int coap_io_pending_lkd(coap_context_t *context)
Check to see if there is any i/o pending for the context.
Definition coap_io.c:2304
void coap_io_do_io_lkd(coap_context_t *ctx, coap_tick_t now)
Processes any outstanding read, write, accept or connect I/O as indicated in the coap_socket_t struct...
Definition coap_net.c:2712
unsigned int coap_io_get_fds_lkd(coap_context_t *ctx, coap_fd_t read_fds[], unsigned int *have_read_fds, unsigned int max_read_fds, coap_fd_t write_fds[], unsigned int *have_write_fds, unsigned int max_write_fds, unsigned int *rem_timeout_ms)
Definition coap_io.c:1720
int coap_io_process_lkd(coap_context_t *ctx, uint32_t timeout_ms)
The main I/O processing function.
Definition coap_io.c:1833
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)
The main message processing loop with additional fds for internal select.
Definition coap_io.c:1926
unsigned int coap_io_prepare_io_lkd(coap_context_t *ctx, coap_socket_t *sockets[], unsigned int max_sockets, unsigned int *num_sockets, coap_tick_t now)
Iterates through all the coap_socket_t structures embedded in endpoints or sessions associated with t...
Definition coap_io.c:1361
unsigned int coap_io_prepare_epoll_lkd(coap_context_t *ctx, coap_tick_t now)
Any now timed out delayed packet is transmitted, along with any packets associated with requested obs...
Definition coap_io.c:1292
COAP_API int coap_io_process(coap_context_t *ctx, uint32_t timeout_ms)
The main I/O processing function.
Definition coap_io.c:1823
COAP_API int coap_io_pending(coap_context_t *context)
Check to see if there is any i/o pending for the context.
Definition coap_io.c:2290
int coap_io_process_configure_threads(coap_context_t *context, uint32_t thread_count)
Configure a defined number of threads to do the alternate coap_io_process() work with traffic load ba...
void coap_io_process_terminate_loop(void)
Terminate all the additional threads created by coap_io_process_loop() and break out of the main thre...
Definition coap_io.c:2178
void coap_io_process_remove_threads(coap_context_t *context)
Release the coap_io_process() worker threads.
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)
Do the coap_io_process() across thread_count threads.
Definition coap_io.c:2184
COAP_API unsigned int coap_io_get_fds(coap_context_t *ctx, coap_fd_t read_fds[], unsigned int *have_read_fds, unsigned int max_read_fds, coap_fd_t write_fds[], unsigned int *have_write_fds, unsigned int max_write_fds, unsigned int *rem_timeout_ms)
Definition coap_io.c:1685
COAP_API unsigned int coap_io_prepare_io(coap_context_t *ctx, coap_socket_t *sockets[], unsigned int max_sockets, unsigned int *num_sockets, coap_tick_t now)
Iterates through all the coap_socket_t structures embedded in endpoints or sessions associated with t...
Definition coap_io.c:1343
#define COAP_IO_NO_WAIT
Definition coap_net.h:733
COAP_API void coap_socket_set_flags(coap_socket_t *sock, coap_socket_flags_t flags)
Set the libcoap internal flags for a socket.
Definition coap_io.c:2376
COAP_API unsigned int coap_io_prepare_epoll(coap_context_t *ctx, coap_tick_t now)
Any now timed out delayed packet is transmitted, along with any packets associated with requested obs...
Definition coap_io.c:1282
COAP_API coap_fd_t coap_socket_get_fd(coap_socket_t *sock)
Get the libcoap internal file descriptor for a socket.
Definition coap_io.c:2361
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)
The main message processing loop with additional fds for internal select.
Definition coap_io.c:1838
#define COAP_IO_WAIT
Definition coap_net.h:732
void(* coap_io_process_thread_t)(void *arg)
Main thread coap_io_process_loop activity.
Definition coap_net.h:914
COAP_API coap_socket_flags_t coap_socket_get_flags(coap_socket_t *sock)
Get the libcoap internal flags for a socket.
Definition coap_io.c:2371
int coap_block_check_lg_crcv_timeouts(coap_session_t *session, coap_tick_t now, coap_tick_t *tim_rem)
int coap_block_check_lg_srcv_timeouts(coap_session_t *session, coap_tick_t now, coap_tick_t *tim_rem)
int coap_block_check_lg_xmit_timeouts(coap_session_t *session, coap_tick_t now, coap_tick_t *tim_rem)
void coap_expire_cache_entries(coap_context_t *context)
Expire coap_cache_entry_t entries.
uint64_t coap_tick_t
This data type represents internal timer ticks with COAP_TICKS_PER_SECOND resolution.
Definition coap_time.h:143
#define COAP_TICKS_PER_SECOND
Use ms resolution on POSIX systems.
Definition coap_time.h:158
#define COAP_MAX_DELAY_TICKS
Definition coap_time.h:221
uint64_t coap_ticks_to_rt_us(coap_tick_t t)
Helper function that converts coap ticks to POSIX wallclock time in us.
int coap_handle_event_lkd(coap_context_t *context, coap_event_t event, coap_session_t *session)
Invokes the event handler of context for the given event and data.
Definition coap_net.c:4880
coap_queue_t * coap_peek_next(coap_context_t *context)
Returns the next pdu to send without removing from sendqeue.
Definition coap_net.c:273
coap_queue_t * coap_pop_next(coap_context_t *context)
Returns the next pdu to send and removes it from the sendqeue.
Definition coap_net.c:281
coap_mid_t coap_retransmit(coap_context_t *context, coap_queue_t *node)
Handles retransmissions of confirmable messages.
Definition coap_net.c:2253
void coap_send_recv_terminate(void)
Terminate any active coap_send_recv() sessions.
Definition coap_net.c:2109
void coap_ticks(coap_tick_t *)
Returns the current value of an internal tick counter.
int coap_dtls_is_context_timeout(void)
Check if timeout is handled per CoAP session or per CoAP context.
Definition coap_notls.c:219
@ COAP_EVENT_SERVER_SESSION_DEL
Called in the CoAP IO loop if a server session is deleted (e.g., due to inactivity or because the max...
Definition coap_event.h:94
@ COAP_EVENT_KEEPALIVE_FAILURE
Triggered when no response to a keep alive (ping) packet.
Definition coap_event.h:132
#define coap_lock_unlock()
Dummy for no thread-safe code.
#define coap_lock_check_locked()
Dummy for no thread-safe code.
#define coap_lock_callback_release(func, failed)
Dummy for no thread-safe code.
#define coap_lock_lock(failed)
Dummy for no thread-safe code.
#define coap_log_debug(...)
Definition coap_debug.h:120
#define coap_log_alert(...)
Definition coap_debug.h:84
#define coap_log_emerg(...)
Definition coap_debug.h:81
const char * coap_session_str(const coap_session_t *session)
Get session description.
#define coap_log_info(...)
Definition coap_debug.h:108
#define coap_log_warn(...)
Definition coap_debug.h:102
#define coap_log_err(...)
Definition coap_debug.h:96
#define coap_log_crit(...)
Definition coap_debug.h:90
int coap_mid_t
coap_mid_t is used to store the CoAP Message ID of a CoAP PDU.
Definition coap_pdu.h:264
#define COAP_INVALID_MID
Indicates an invalid message id.
Definition coap_pdu.h:267
@ COAP_PROTO_DTLS
Definition coap_pdu.h:316
int coap_session_reconnect(coap_session_t *session)
Close the current session (if not already closed) and reconnect to server (client session only).
void coap_session_server_keepalive_failed(coap_session_t *session)
Clear down a session following a keepalive failure.
void coap_session_failed(coap_session_t *session)
Session has failed due to a socket error.
coap_mid_t coap_session_send_ping_lkd(coap_session_t *session)
Send a ping message for the session.
void coap_session_free(coap_session_t *session)
void coap_session_release_lkd(coap_session_t *session)
Decrement reference counter on a session.
coap_session_t * coap_session_reference_lkd(coap_session_t *session)
Increment reference counter on a session.
#define COAP_PROTO_RELIABLE(p)
@ COAP_SESSION_TYPE_SERVER
server-side
@ COAP_SESSION_TYPE_CLIENT
client-side
@ COAP_SESSION_STATE_HANDSHAKE
@ COAP_SESSION_STATE_CSM
@ COAP_SESSION_STATE_ESTABLISHED
@ COAP_SESSION_STATE_NONE
void coap_check_notify_lkd(coap_context_t *context)
Checks all known resources to see if they are dirty and then notifies subscribed observers.
coap_address_t remote
remote address and port
Definition coap_io.h:56
coap_address_t local
local address and port
Definition coap_io.h:57
Multi-purpose address abstraction.
socklen_t size
size of addr
struct sockaddr_in sin
struct coap_sockaddr_un cun
struct sockaddr_in6 sin6
struct sockaddr sa
union coap_address_t::@0 addr
The CoAP stack's global state is stored in a coap_context_t object.
coap_tick_t sendqueue_basetime
The time stamp in the first element of the sendqeue is relative to sendqueue_basetime.
coap_socket_t * sockets[64]
Track different socket information in coap_io_process_with_fds_lkd()
unsigned int reconnect_time
Time to wait before reconnecting a failed client session.
unsigned int num_sockets
Number of sockets being tracked.
coap_session_t * sessions
client sessions
fd_set exceptfds
Used for select call in coap_io_process_with_fds_lkd()
unsigned int ping_timeout
Minimum inactivity time before sending a ping message.
coap_queue_t * sendqueue
uint8_t testing_cids
Change client's source port every testing_cids.
coap_endpoint_t * endpoint
the endpoints used for listening
uint32_t csm_timeout_ms
Timeout for waiting for a CSM from the remote side.
coap_tick_t next_timeout
When the next timeout is to occur.
unsigned int session_timeout
Number of seconds of inactivity after which an unused session will be closed.
Abstraction of virtual endpoint that can be attached to coap_context_t.
coap_context_t * context
endpoint's context
coap_session_t * sessions
hash table or list of active sessions
coap_address_t bind_addr
local interface address
coap_socket_t sock
socket object for the interface, if any
size_t length
length of payload
coap_addr_tuple_t addr_info
local and remote addresses
unsigned char * payload
payload
int ifindex
the interface index
Queue entry.
coap_tick_t t
when to send PDU for the next time
Abstraction of virtual session that can be attached to coap_context_t (client) or coap_endpoint_t (se...
coap_lg_xmit_t * lg_xmit
list of large transmissions
unsigned ref_subscriptions
reference count of current subscriptions
coap_socket_t sock
socket object for the session, if any
coap_session_state_t state
current state of relationship with peer
unsigned ref_proxy_subs
reference count of current proxy subscriptions
coap_addr_tuple_t addr_info
remote/local address info
coap_proto_t proto
protocol used
unsigned ref
reference count from queues
uint8_t negotiated_cid
Set for a client if CID negotiated.
void * tls
security parameters
uint8_t con_active
Active CON request sent.
coap_queue_t * delayqueue
list of delayed messages waiting to be sent
coap_mid_t last_ping_mid
the last keepalive message id that was used in this session
coap_lg_srcv_t * lg_srcv
Server list of expected large receives.
coap_lg_crcv_t * lg_crcv
Client list of expected large receives.
coap_session_type_t type
client or server side socket
coap_context_t * context
session's context
uint8_t session_failed
Set if session failed and can try re-connect.
int ifindex
interface index
char sun_path[COAP_UNIX_PATH_MAX]
coap_session_t * session
Used to determine session owner.
coap_endpoint_t * endpoint
Used by the epoll logic for a listening endpoint.
coap_address_t mcast_addr
remote address and port (multicast track)
coap_socket_flags_t flags
1 or more of COAP_SOCKET* flag values
struct in6_addr ipi6_addr
Definition coap_io.c:749
unsigned int ipi6_ifindex
Definition coap_io.c:750
struct in_addr ipi_spec_dst
Definition coap_io.c:755
struct in_addr ipi_addr
Definition coap_io.c:756
int ipi_ifindex
Definition coap_io.c:754